// Code generated by smithy-go-codegen DO NOT EDIT.

package awsrestjson

import (
	"bytes"
	"context"
	"github.com/aws/aws-sdk-go-v2/aws"
	protocoltesthttp "github.com/aws/aws-sdk-go-v2/internal/protocoltest"
	"github.com/aws/aws-sdk-go-v2/internal/protocoltest/awsrestjson/types"
	"github.com/aws/smithy-go/middleware"
	smithyprivateprotocol "github.com/aws/smithy-go/private/protocol"
	"github.com/aws/smithy-go/ptr"
	smithyrand "github.com/aws/smithy-go/rand"
	smithytesting "github.com/aws/smithy-go/testing"
	smithyhttp "github.com/aws/smithy-go/transport/http"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"testing"
)

func TestClient_OperationWithNestedStructure_awsRestjson1Serialize(t *testing.T) {
	cases := map[string]struct {
		Params        *OperationWithNestedStructureInput
		ExpectMethod  string
		ExpectURIPath string
		ExpectQuery   []smithytesting.QueryItem
		RequireQuery  []string
		ForbidQuery   []string
		ExpectHeader  http.Header
		RequireHeader []string
		ForbidHeader  []string
		Host          *url.URL
		BodyMediaType string
		BodyAssert    func(io.Reader) error
	}{
		// Client populates nested default values when missing.
		"RestJsonClientPopulatesNestedDefaultValuesWhenMissing": {
			Params: &OperationWithNestedStructureInput{
				TopLevel: &types.TopLevel{
					Dialog: &types.Dialog{
						Language: ptr.String("en"),
					},
					DialogList: []types.Dialog{
						{},
						{
							Farewell: &types.Farewell{},
						},
						{
							Language: ptr.String("it"),
							Greeting: ptr.String("ciao"),
							Farewell: &types.Farewell{
								Phrase: ptr.String("arrivederci"),
							},
						},
					},
					DialogMap: map[string]types.Dialog{
						"emptyDialog": {},
						"partialEmptyDialog": {
							Language: ptr.String("en"),
							Farewell: &types.Farewell{},
						},
						"nonEmptyDialog": {
							Greeting: ptr.String("konnichiwa"),
							Farewell: &types.Farewell{
								Phrase: ptr.String("sayonara"),
							},
						},
					},
				},
			},
			ExpectMethod:  "POST",
			ExpectURIPath: "/OperationWithNestedStructure",
			ExpectQuery:   []smithytesting.QueryItem{},
			ExpectHeader: http.Header{
				"Content-Type": []string{"application/json"},
			},
			BodyMediaType: "application/json",
			BodyAssert: func(actual io.Reader) error {
				return smithytesting.CompareJSONReaderBytes(actual, []byte(`{
			    "topLevel": {
			        "dialog": {
			            "language": "en",
			            "greeting": "hi"
			        },
			        "dialogList": [
			            {
			                "greeting": "hi"
			            },
			            {
			                "greeting": "hi",
			                "farewell": {
			                    "phrase": "bye"
			                }
			            },
			            {
			                "language": "it",
			                "greeting": "ciao",
			                "farewell": {
			                    "phrase": "arrivederci"
			                }
			            }
			        ],
			        "dialogMap": {
			            "emptyDialog": {
			                "greeting": "hi"
			            },
			            "partialEmptyDialog": {
			                "language": "en",
			                "greeting": "hi",
			                "farewell": {
			                    "phrase": "bye"
			                }
			            },
			            "nonEmptyDialog": {
			                "greeting": "konnichiwa",
			                "farewell": {
			                    "phrase": "sayonara"
			                }
			            }
			        }
			    }
			}`))
			},
		},
	}
	for name, c := range cases {
		t.Run(name, func(t *testing.T) {
			if name == "RestJsonClientPopulatesNestedDefaultValuesWhenMissing" {
				t.Skip("disabled test aws.protocoltests.restjson#RestJson aws.protocoltests.restjson#OperationWithNestedStructure")
			}

			actualReq := &http.Request{}
			serverURL := "http://localhost:8888/"
			if c.Host != nil {
				u, err := url.Parse(serverURL)
				if err != nil {
					t.Fatalf("expect no error, got %v", err)
				}
				u.Path = c.Host.Path
				u.RawPath = c.Host.RawPath
				u.RawQuery = c.Host.RawQuery
				serverURL = u.String()
			}
			client := New(Options{
				APIOptions: []func(*middleware.Stack) error{
					func(s *middleware.Stack) error {
						s.Finalize.Clear()
						s.Initialize.Remove(`OperationInputValidation`)
						return nil
					},
				},
				EndpointResolver: EndpointResolverFunc(func(region string, options EndpointResolverOptions) (e aws.Endpoint, err error) {
					e.URL = serverURL
					e.SigningRegion = "us-west-2"
					return e, err
				}),
				HTTPClient:               protocoltesthttp.NewClient(),
				IdempotencyTokenProvider: smithyrand.NewUUIDIdempotencyToken(&smithytesting.ByteLoop{}),
				Region:                   "us-west-2",
			})
			result, err := client.OperationWithNestedStructure(context.Background(), c.Params, func(options *Options) {
				options.APIOptions = append(options.APIOptions, func(stack *middleware.Stack) error {
					return smithyprivateprotocol.AddCaptureRequestMiddleware(stack, actualReq)
				})
			})
			if err != nil {
				t.Fatalf("expect nil err, got %v", err)
			}
			if result == nil {
				t.Fatalf("expect not nil result")
			}
			if e, a := c.ExpectMethod, actualReq.Method; e != a {
				t.Errorf("expect %v method, got %v", e, a)
			}
			if e, a := c.ExpectURIPath, actualReq.URL.RawPath; e != a {
				t.Errorf("expect %v path, got %v", e, a)
			}
			queryItems := smithytesting.ParseRawQuery(actualReq.URL.RawQuery)
			smithytesting.AssertHasQuery(t, c.ExpectQuery, queryItems)
			smithytesting.AssertHasQueryKeys(t, c.RequireQuery, queryItems)
			smithytesting.AssertNotHaveQueryKeys(t, c.ForbidQuery, queryItems)
			smithytesting.AssertHasHeader(t, c.ExpectHeader, actualReq.Header)
			smithytesting.AssertHasHeaderKeys(t, c.RequireHeader, actualReq.Header)
			smithytesting.AssertNotHaveHeaderKeys(t, c.ForbidHeader, actualReq.Header)
			if c.BodyAssert != nil {
				if err := c.BodyAssert(actualReq.Body); err != nil {
					t.Errorf("expect body equal, got %v", err)
				}
			}
		})
	}
}

func TestClient_OperationWithNestedStructure_awsRestjson1Deserialize(t *testing.T) {
	cases := map[string]struct {
		StatusCode    int
		Header        http.Header
		BodyMediaType string
		Body          []byte
		ExpectResult  *OperationWithNestedStructureOutput
	}{
		// Client populates nested default values when missing in response body.
		"RestJsonClientPopulatesNestedDefaultsWhenMissingInResponseBody": {
			StatusCode: 200,
			Header: http.Header{
				"Content-Type": []string{"application/json"},
			},
			BodyMediaType: "application/json",
			Body: []byte(`{
			    "dialog": {
			        "language": "en"
			    },
			    "dialogList": [
			        {
			        },
			        {
			            "farewell": {}
			        },
			        {
			            "language": "it",
			            "greeting": "ciao",
			            "farewell": {
			                "phrase": "arrivederci"
			            }
			        }
			    ],
			    "dialogMap": {
			        "emptyDialog": {
			        },
			        "partialEmptyDialog": {
			            "language": "en",
			            "farewell": {}
			        },
			        "nonEmptyDialog": {
			            "greeting": "konnichiwa",
			            "farewell": {
			                "phrase": "sayonara"
			            }
			        }
			    }
			}`),
			ExpectResult: &OperationWithNestedStructureOutput{
				Dialog: &types.Dialog{
					Language: ptr.String("en"),
					Greeting: ptr.String("hi"),
				},
				DialogList: []types.Dialog{
					{
						Greeting: ptr.String("hi"),
					},
					{
						Greeting: ptr.String("hi"),
						Farewell: &types.Farewell{
							Phrase: ptr.String("bye"),
						},
					},
					{
						Language: ptr.String("it"),
						Greeting: ptr.String("ciao"),
						Farewell: &types.Farewell{
							Phrase: ptr.String("arrivederci"),
						},
					},
				},
				DialogMap: map[string]types.Dialog{
					"emptyDialog": {
						Greeting: ptr.String("hi"),
					},
					"partialEmptyDialog": {
						Language: ptr.String("en"),
						Greeting: ptr.String("hi"),
						Farewell: &types.Farewell{
							Phrase: ptr.String("bye"),
						},
					},
					"nonEmptyDialog": {
						Greeting: ptr.String("konnichiwa"),
						Farewell: &types.Farewell{
							Phrase: ptr.String("sayonara"),
						},
					},
				},
			},
		},
	}
	for name, c := range cases {
		t.Run(name, func(t *testing.T) {
			if name == "RestJsonClientPopulatesNestedDefaultsWhenMissingInResponseBody" {
				t.Skip("disabled test aws.protocoltests.restjson#RestJson aws.protocoltests.restjson#OperationWithNestedStructure")
			}

			serverURL := "http://localhost:8888/"
			client := New(Options{
				HTTPClient: smithyhttp.ClientDoFunc(func(r *http.Request) (*http.Response, error) {
					headers := http.Header{}
					for k, vs := range c.Header {
						for _, v := range vs {
							headers.Add(k, v)
						}
					}
					if len(c.BodyMediaType) != 0 && len(headers.Values("Content-Type")) == 0 {
						headers.Set("Content-Type", c.BodyMediaType)
					}
					response := &http.Response{
						StatusCode: c.StatusCode,
						Header:     headers,
						Request:    r,
					}
					if len(c.Body) != 0 {
						response.ContentLength = int64(len(c.Body))
						response.Body = ioutil.NopCloser(bytes.NewReader(c.Body))
					} else {

						response.Body = http.NoBody
					}
					return response, nil
				}),
				APIOptions: []func(*middleware.Stack) error{
					func(s *middleware.Stack) error {
						s.Finalize.Clear()
						s.Initialize.Remove(`OperationInputValidation`)
						return nil
					},
				},
				EndpointResolver: EndpointResolverFunc(func(region string, options EndpointResolverOptions) (e aws.Endpoint, err error) {
					e.URL = serverURL
					e.SigningRegion = "us-west-2"
					return e, err
				}),
				IdempotencyTokenProvider: smithyrand.NewUUIDIdempotencyToken(&smithytesting.ByteLoop{}),
				Region:                   "us-west-2",
			})
			var params OperationWithNestedStructureInput
			result, err := client.OperationWithNestedStructure(context.Background(), &params)
			if err != nil {
				t.Fatalf("expect nil err, got %v", err)
			}
			if result == nil {
				t.Fatalf("expect not nil result")
			}
			if err := smithytesting.CompareValues(c.ExpectResult, result); err != nil {
				t.Errorf("expect c.ExpectResult value match:\n%v", err)
			}
		})
	}
}
