diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/CHANGELOG.md b/sdk/resourcemanager/resourcegraph/armresourcegraph/CHANGELOG.md index 1cbcc680a763..a27deb574086 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/CHANGELOG.md +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 0.8.0 (2023-06-13) + +### Features Added + +- Support for test fakes and OpenTelemetry trace spans. + ## 0.7.1 (2023-04-14) ### Bug Fixes diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/README.md b/sdk/resourcemanager/resourcegraph/armresourcegraph/README.md index 5476d33dd210..7f5690deef0c 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/README.md +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/README.md @@ -60,6 +60,31 @@ A client groups a set of related APIs, providing access to its functionality. C client := clientFactory.NewClient() ``` +## Fakes +The `fake` package provides implementations for fake servers that can be used for testing. +To create a fake server, declare an instance of the required fake server type(s). +```go +myFakeServer := fake.Server{} +``` +Next, provide func implementations for the methods you wish to fake. +The named return variables can be used to simplify return value construction. +```go +myFakeServer.Resources = func(ctx context.Context, query armresourcegraph.QueryRequest, options *armresourcegraph.ClientResourcesOptions) (resp azfake.Responder[armresourcegraph.ClientResourcesResponse], errResp azfake.ErrorResponder) { + // TODO: resp.SetResponse(/* your fake ClientResourcesResponse response */) + return +} +``` +You connect the fake server to a client instance during construction through the optional transport. +Use `NewTokenCredential()` from `azcore/fake` to obtain a fake credential. +```go +import azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +client, err := armresourcegraph.NewClient("subscriptionID", azfake.NewTokenCredential(), &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewServerTransport(&myFakeServer), + }, +}) +``` + ## Provide Feedback If you encounter bugs or have suggestions, please @@ -82,4 +107,4 @@ This project has adopted the For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any -additional questions or comments. \ No newline at end of file +additional questions or comments. diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/autorest.md b/sdk/resourcemanager/resourcegraph/armresourcegraph/autorest.md index cc85bec615e0..e887d72974fc 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/autorest.md +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/autorest.md @@ -8,6 +8,9 @@ require: - https://github.com/Azure/azure-rest-api-specs/blob/d55b8005f05b040b852c15e74a0f3e36494a15e1/specification/resourcegraph/resource-manager/readme.md - https://github.com/Azure/azure-rest-api-specs/blob/d55b8005f05b040b852c15e74a0f3e36494a15e1/specification/resourcegraph/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 0.7.1 - -``` \ No newline at end of file +module: github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph +module-version: 0.8.0 +azcore-version: 1.7.0-beta.2 +generate-fakes: true +inject-spans: true +``` diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/build.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/build.go index c90165324fbd..60a8b924c059 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/build.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/build.go @@ -2,6 +2,6 @@ // Licensed under the MIT License. See License.txt in the project root for license information. // This file enables 'go generate' to regenerate this specific SDK -//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/resourcegraph/armresourcegraph +//go:generate pwsh ../../../../eng/scripts/build.ps1 -goExtension "@autorest/go@4.0.0-preview.51" -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/resourcegraph/armresourcegraph package armresourcegraph diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/client.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/client.go index 04ea8bff79ef..46057d4fd827 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/client.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/client.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph @@ -45,18 +44,25 @@ func NewClient(credential azcore.TokenCredential, options *arm.ClientOptions) (* // - query - Request specifying query and its options. // - options - ClientResourcesOptions contains the optional parameters for the Client.Resources method. func (client *Client) Resources(ctx context.Context, query QueryRequest, options *ClientResourcesOptions) (ClientResourcesResponse, error) { + var err error + const operationName = "Client.Resources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() req, err := client.resourcesCreateRequest(ctx, query, options) if err != nil { return ClientResourcesResponse{}, err } - resp, err := client.internal.Pipeline().Do(req) + httpResp, err := client.internal.Pipeline().Do(req) if err != nil { return ClientResourcesResponse{}, err } - if !runtime.HasStatusCode(resp, http.StatusOK) { - return ClientResourcesResponse{}, runtime.NewResponseError(resp) + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientResourcesResponse{}, err } - return client.resourcesHandleResponse(resp) + resp, err := client.resourcesHandleResponse(httpResp) + return resp, err } // resourcesCreateRequest creates the Resources request. @@ -70,7 +76,10 @@ func (client *Client) resourcesCreateRequest(ctx context.Context, query QueryReq reqQP.Set("api-version", "2021-06-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - return req, runtime.MarshalAsJSON(req, query) + if err := runtime.MarshalAsJSON(req, query); err != nil { + return nil, err + } + return req, nil } // resourcesHandleResponse handles the Resources response. @@ -89,18 +98,25 @@ func (client *Client) resourcesHandleResponse(resp *http.Response) (ClientResour // - request - Request specifying the query and its options. // - options - ClientResourcesHistoryOptions contains the optional parameters for the Client.ResourcesHistory method. func (client *Client) ResourcesHistory(ctx context.Context, request ResourcesHistoryRequest, options *ClientResourcesHistoryOptions) (ClientResourcesHistoryResponse, error) { + var err error + const operationName = "Client.ResourcesHistory" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() req, err := client.resourcesHistoryCreateRequest(ctx, request, options) if err != nil { return ClientResourcesHistoryResponse{}, err } - resp, err := client.internal.Pipeline().Do(req) + httpResp, err := client.internal.Pipeline().Do(req) if err != nil { return ClientResourcesHistoryResponse{}, err } - if !runtime.HasStatusCode(resp, http.StatusOK) { - return ClientResourcesHistoryResponse{}, runtime.NewResponseError(resp) + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientResourcesHistoryResponse{}, err } - return client.resourcesHistoryHandleResponse(resp) + resp, err := client.resourcesHistoryHandleResponse(httpResp) + return resp, err } // resourcesHistoryCreateRequest creates the ResourcesHistory request. @@ -114,7 +130,10 @@ func (client *Client) resourcesHistoryCreateRequest(ctx context.Context, request reqQP.Set("api-version", "2021-06-01-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} - return req, runtime.MarshalAsJSON(req, request) + if err := runtime.MarshalAsJSON(req, request); err != nil { + return nil, err + } + return req, nil } // resourcesHistoryHandleResponse handles the ResourcesHistory response. diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/client_factory.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/client_factory.go index 7c576c719a5e..9abcebc38f58 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/client_factory.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/client_factory.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/constants.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/constants.go index fd8addc81179..d56b6438ebd8 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/constants.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/constants.go @@ -3,15 +3,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) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph const ( moduleName = "armresourcegraph" - moduleVersion = "v0.7.1" + moduleVersion = "v0.8.0" ) // AuthorizationScopeFilter - Defines what level of authorization resources should be returned based on the which subscriptions @@ -19,19 +18,19 @@ const ( type AuthorizationScopeFilter string const ( - AuthorizationScopeFilterAtScopeAndBelow AuthorizationScopeFilter = "AtScopeAndBelow" + AuthorizationScopeFilterAtScopeAboveAndBelow AuthorizationScopeFilter = "AtScopeAboveAndBelow" AuthorizationScopeFilterAtScopeAndAbove AuthorizationScopeFilter = "AtScopeAndAbove" + AuthorizationScopeFilterAtScopeAndBelow AuthorizationScopeFilter = "AtScopeAndBelow" AuthorizationScopeFilterAtScopeExact AuthorizationScopeFilter = "AtScopeExact" - AuthorizationScopeFilterAtScopeAboveAndBelow AuthorizationScopeFilter = "AtScopeAboveAndBelow" ) // PossibleAuthorizationScopeFilterValues returns the possible values for the AuthorizationScopeFilter const type. func PossibleAuthorizationScopeFilterValues() []AuthorizationScopeFilter { return []AuthorizationScopeFilter{ - AuthorizationScopeFilterAtScopeAndBelow, + AuthorizationScopeFilterAtScopeAboveAndBelow, AuthorizationScopeFilterAtScopeAndAbove, + AuthorizationScopeFilterAtScopeAndBelow, AuthorizationScopeFilterAtScopeExact, - AuthorizationScopeFilterAtScopeAboveAndBelow, } } @@ -39,23 +38,23 @@ func PossibleAuthorizationScopeFilterValues() []AuthorizationScopeFilter { type ColumnDataType string const ( - ColumnDataTypeString ColumnDataType = "string" + ColumnDataTypeBoolean ColumnDataType = "boolean" + ColumnDataTypeDatetime ColumnDataType = "datetime" ColumnDataTypeInteger ColumnDataType = "integer" ColumnDataTypeNumber ColumnDataType = "number" - ColumnDataTypeBoolean ColumnDataType = "boolean" ColumnDataTypeObject ColumnDataType = "object" - ColumnDataTypeDatetime ColumnDataType = "datetime" + ColumnDataTypeString ColumnDataType = "string" ) // PossibleColumnDataTypeValues returns the possible values for the ColumnDataType const type. func PossibleColumnDataTypeValues() []ColumnDataType { return []ColumnDataType{ - ColumnDataTypeString, + ColumnDataTypeBoolean, + ColumnDataTypeDatetime, ColumnDataTypeInteger, ColumnDataTypeNumber, - ColumnDataTypeBoolean, ColumnDataTypeObject, - ColumnDataTypeDatetime, + ColumnDataTypeString, } } @@ -79,15 +78,15 @@ func PossibleFacetSortOrderValues() []FacetSortOrder { type ResultFormat string const ( - ResultFormatTable ResultFormat = "table" ResultFormatObjectArray ResultFormat = "objectArray" + ResultFormatTable ResultFormat = "table" ) // PossibleResultFormatValues returns the possible values for the ResultFormat const type. func PossibleResultFormatValues() []ResultFormat { return []ResultFormat{ - ResultFormatTable, ResultFormatObjectArray, + ResultFormatTable, } } @@ -95,14 +94,14 @@ func PossibleResultFormatValues() []ResultFormat { type ResultTruncated string const ( - ResultTruncatedTrue ResultTruncated = "true" ResultTruncatedFalse ResultTruncated = "false" + ResultTruncatedTrue ResultTruncated = "true" ) // PossibleResultTruncatedValues returns the possible values for the ResultTruncated const type. func PossibleResultTruncatedValues() []ResultTruncated { return []ResultTruncated{ - ResultTruncatedTrue, ResultTruncatedFalse, + ResultTruncatedTrue, } } diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/internal.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/internal.go new file mode 100644 index 000000000000..e9c8222f2199 --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/internal.go @@ -0,0 +1,78 @@ +//go:build go1.18 +// +build go1.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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "io" + "net/http" + "reflect" +) + +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 getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +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, err +} + +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 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 contains[T comparable](s []T, v T) bool { + for _, vv := range s { + if vv == v { + return true + } + } + return false +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/operations_server.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/operations_server.go new file mode 100644 index 000000000000..0cd2315cd0de --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/operations_server.go @@ -0,0 +1,86 @@ +//go:build go1.18 +// +build go1.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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +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/resourcemanager/resourcegraph/armresourcegraph" + "net/http" +) + +// OperationsServer is a fake server for instances of the armresourcegraph.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armresourcegraph.OperationsClientListOptions) (resp azfake.PagerResponder[armresourcegraph.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armresourcegraph.OperationsClient by way of the +// undefined.Transporter field. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{srv: srv} +} + +// OperationsServerTransport connects instances of armresourcegraph.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *azfake.PagerResponder[armresourcegraph.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")} + } + + var resp *http.Response + var err error + + switch method { + case "OperationsClient.NewListPager": + resp, err = o.dispatchNewListPager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +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")} + } + if o.newListPager == nil { + resp := o.srv.NewListPager(nil) + o.newListPager = &resp + } + resp, err := server.PagerResponderNext(o.newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(o.newListPager) { + o.newListPager = nil + } + return resp, nil +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/polymorphic_helpers.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/polymorphic_helpers.go new file mode 100644 index 000000000000..e3d660c72816 --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/polymorphic_helpers.go @@ -0,0 +1,56 @@ +//go:build go1.18 +// +build go1.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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "encoding/json" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph" +) + +func unmarshalFacetClassification(rawMsg json.RawMessage) (armresourcegraph.FacetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b armresourcegraph.FacetClassification + switch m["resultType"] { + case "FacetError": + b = &armresourcegraph.FacetError{} + case "FacetResult": + b = &armresourcegraph.FacetResult{} + default: + b = &armresourcegraph.Facet{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFacetClassificationArray(rawMsg json.RawMessage) ([]armresourcegraph.FacetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]armresourcegraph.FacetClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFacetClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/server.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/server.go new file mode 100644 index 000000000000..efaf008dc84c --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/server.go @@ -0,0 +1,117 @@ +//go:build go1.18 +// +build go1.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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +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/resourcemanager/resourcegraph/armresourcegraph" + "net/http" +) + +// Server is a fake server for instances of the armresourcegraph.Client type. +type Server struct { + // Resources is the fake for method Client.Resources + // HTTP status codes to indicate success: http.StatusOK + Resources func(ctx context.Context, query armresourcegraph.QueryRequest, options *armresourcegraph.ClientResourcesOptions) (resp azfake.Responder[armresourcegraph.ClientResourcesResponse], errResp azfake.ErrorResponder) + + // ResourcesHistory is the fake for method Client.ResourcesHistory + // HTTP status codes to indicate success: http.StatusOK + ResourcesHistory func(ctx context.Context, request armresourcegraph.ResourcesHistoryRequest, options *armresourcegraph.ClientResourcesHistoryOptions) (resp azfake.Responder[armresourcegraph.ClientResourcesHistoryResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of armresourcegraph.Client by way of the +// undefined.Transporter field. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{srv: srv} +} + +// ServerTransport connects instances of armresourcegraph.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")} + } + + var resp *http.Response + var err error + + switch method { + case "Client.Resources": + resp, err = s.dispatchResources(req) + case "Client.ResourcesHistory": + resp, err = s.dispatchResourcesHistory(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (s *ServerTransport) dispatchResources(req *http.Request) (*http.Response, error) { + if s.srv.Resources == nil { + return nil, &nonRetriableError{errors.New("fake for method Resources not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[armresourcegraph.QueryRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Resources(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).QueryResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchResourcesHistory(req *http.Request) (*http.Response, error) { + if s.srv.ResourcesHistory == nil { + return nil, &nonRetriableError{errors.New("fake for method ResourcesHistory not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[armresourcegraph.ResourcesHistoryRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.ResourcesHistory(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + 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 +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/time_rfc3339.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/time_rfc3339.go new file mode 100644 index 000000000000..45fe10cbc6df --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake/time_rfc3339.go @@ -0,0 +1,86 @@ +//go:build go1.18 +// +build go1.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) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} + +func populateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*timeRFC3339)(t) +} + +func unpopulateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || strings.EqualFold(string(data), "null") { + return nil + } + var aux timeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/fake_example_test.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake_example_test.go new file mode 100644 index 000000000000..adff1a119537 --- /dev/null +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/fake_example_test.go @@ -0,0 +1,79 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armresourcegraph_test + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph/fake" +) + +func ExampleServer() { + // first, create an instance of the fake server for the client you wish to test. + // the type name of the server will be similar to the corresponding client, with + // the suffix "Server" instead of "Client". + fakeServer := fake.Server{ + + // next, provide implementations for the APIs you wish to fake. + // this fake corresponds to the Client.Resources() API. + Resources: func(ctx context.Context, query armresourcegraph.QueryRequest, options *armresourcegraph.ClientResourcesOptions) (resp azfake.Responder[armresourcegraph.ClientResourcesResponse], errResp azfake.ErrorResponder) { + // the values of ctx, query, and options come from the API call. + + // the named return values resp and errResp are used to construct the response + // and are meant to be mutually exclusive. if both responses have been constructed, + // the error response is selected. + + // use resp to set the desired response + queryResp := armresourcegraph.ClientResourcesResponse{} + queryResp.Count = to.Ptr[int64](12345) + resp.SetResponse(http.StatusOK, queryResp, nil) + + // to simulate the failure case, use errResp + //errResp.SetResponseError(http.StatusBadRequest, "ThisIsASimulatedError") + + return + }, + } + + // now create the corresponding client, connecting the fake server via the client options + client, err := armresourcegraph.NewClient(azfake.NewTokenCredential(), &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewServerTransport(&fakeServer), + }, + }) + if err != nil { + log.Fatal(err) + } + + // call the API. the provided values will be passed to the fake's implementation. + // the response or error values returned by the API call are from the fake. + resp, err := client.Resources(context.TODO(), armresourcegraph.QueryRequest{ + Query: to.Ptr("fake query"), + }, nil) + if err != nil { + log.Fatal(err) + } + + fmt.Println(*resp.Count) + + // APIs that haven't been faked will return an error + _, err = client.ResourcesHistory(context.TODO(), armresourcegraph.ResourcesHistoryRequest{}, nil) + + fmt.Println(err.Error()) + + // Output: + // 12345 + // fake for method ResourcesHistory not implemented +} diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/go.mod b/sdk/resourcemanager/resourcegraph/armresourcegraph/go.mod index c53311d0784c..227155ebbf1a 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/go.mod +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/go.mod @@ -3,19 +3,19 @@ module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armre go 1.18 require ( - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.4.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0-beta.2 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.2 ) require ( - github.com/Azure/azure-sdk-for-go/sdk/internal v1.2.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v0.9.0 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/google/uuid v1.3.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect golang.org/x/crypto v0.6.0 // indirect - golang.org/x/net v0.7.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/net v0.8.0 // indirect + golang.org/x/sys v0.6.0 // indirect + golang.org/x/text v0.8.0 // indirect ) diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/go.sum b/sdk/resourcemanager/resourcegraph/armresourcegraph/go.sum index 8ba445a8c4da..b9280dc6acaf 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/go.sum +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/go.sum @@ -1,9 +1,9 @@ -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.4.0 h1:rTnT/Jrcm+figWlYz4Ixzt0SJVR2cMC8lvZcimipiEY= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.4.0/go.mod h1:ON4tFdPTwRcgWEaVDrN3584Ef+b7GgSJaXxe5fW9t4M= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0-beta.2 h1:C3zKsGguxcLd8a2uEytB8+TFtBGd75bXRxEs0QBwsv0= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0-beta.2/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.2 h1:uqM+VoHjVH6zdlkLF2b6O0ZANcHoj3rO0PoQ3jglUJA= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.2/go.mod h1:twTKAa1E6hLmSDjLhaCkbTMQKc7p/rNLU40rLxGEOCI= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.2.0 h1:leh5DwKv6Ihwi+h60uHtn6UWAxBbZ0q8DwQVMzf61zw= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.2.0/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 h1:sXr+ck84g/ZlZUOZiNELInmMgOsuGwdjjVkEIde0OtY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= github.com/AzureAD/microsoft-authentication-library-for-go v0.9.0 h1:UE9n9rkJF62ArLb1F3DEjRt8O3jLwMWdSoypKV4f3MU= github.com/AzureAD/microsoft-authentication-library-for-go v0.9.0/go.mod h1:kgDmCTgBzIEPFElEF+FK0SdjAor06dRq2Go927dnQ6o= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -20,12 +20,12 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= -golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/models.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/models.go index 810f2c632234..8f7c54392e70 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/models.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/models.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/models_serde.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/models_serde.go index d1eea349eda3..193a2d4c0b51 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/models_serde.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/models_serde.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/operations_client.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/operations_client.go index 15eb850177bb..72e68d3d957d 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/operations_client.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/operations_client.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph @@ -48,6 +47,7 @@ func (client *OperationsClient) NewListPager(options *OperationsClientListOption return false }, Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") req, err := client.listCreateRequest(ctx, options) if err != nil { return OperationsClientListResponse{}, err @@ -61,6 +61,7 @@ func (client *OperationsClient) NewListPager(options *OperationsClientListOption } return client.listHandleResponse(resp) }, + Tracer: client.internal.Tracer(), }) } diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/polymorphic_helpers.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/polymorphic_helpers.go index c81f32e50bf7..ff55449e4191 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/polymorphic_helpers.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/polymorphic_helpers.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph @@ -28,7 +27,10 @@ func unmarshalFacetClassification(rawMsg json.RawMessage) (FacetClassification, default: b = &Facet{} } - return b, json.Unmarshal(rawMsg, b) + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil } func unmarshalFacetClassificationArray(rawMsg json.RawMessage) ([]FacetClassification, error) { diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/response_types.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/response_types.go index 806d53a389e4..389220289d60 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/response_types.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/response_types.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph diff --git a/sdk/resourcemanager/resourcegraph/armresourcegraph/time_rfc3339.go b/sdk/resourcemanager/resourcegraph/armresourcegraph/time_rfc3339.go index ee3b84d2e6a9..dd11cb29364d 100644 --- a/sdk/resourcemanager/resourcegraph/armresourcegraph/time_rfc3339.go +++ b/sdk/resourcemanager/resourcegraph/armresourcegraph/time_rfc3339.go @@ -3,9 +3,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. // Changes may cause incorrect behavior and will be lost if the code is regenerated. -// DO NOT EDIT. package armresourcegraph