github.com/webdestroya/awsmocker@v0.2.6/mocks_common_test.go (about) 1 package awsmocker_test 2 3 import ( 4 "context" 5 "crypto/tls" 6 "io" 7 "net/http" 8 "net/url" 9 "testing" 10 11 "github.com/aws/aws-sdk-go-v2/service/ecs" 12 "github.com/stretchr/testify/require" 13 "github.com/webdestroya/awsmocker" 14 ) 15 16 func TestMockResponse_Error(t *testing.T) { 17 info := awsmocker.Start(t, &awsmocker.MockerOptions{ 18 SkipDefaultMocks: true, 19 Mocks: []*awsmocker.MockedEndpoint{ 20 { 21 Request: &awsmocker.MockedRequest{ 22 Hostname: "test.com", 23 Path: "/err400", 24 }, 25 Response: awsmocker.MockResponse_Error(400, "SomeCode", "SomeMessage"), 26 }, 27 { 28 Request: &awsmocker.MockedRequest{ 29 Hostname: "test.com", 30 Path: "/err401", 31 }, 32 Response: awsmocker.MockResponse_Error(401, "SomeCode2", "SomeMessage"), 33 }, 34 { 35 Request: &awsmocker.MockedRequest{ 36 Hostname: "test.com", 37 Path: "/err0", 38 }, 39 Response: awsmocker.MockResponse_Error(0, "SomeCode0", "SomeMessage"), 40 }, 41 }, 42 }) 43 44 client := &http.Client{ 45 Transport: &http.Transport{ 46 Proxy: func(r *http.Request) (*url.URL, error) { 47 return url.Parse(info.ProxyURL) 48 }, 49 TLSClientConfig: &tls.Config{ 50 InsecureSkipVerify: true, 51 }, 52 }, 53 } 54 55 tables := []struct { 56 method string 57 url string 58 statusCode int 59 expErrorCode string 60 }{ 61 62 {http.MethodGet, "https://test.com/err400", 400, "SomeCode"}, 63 {http.MethodGet, "https://test.com/err401", 401, "SomeCode2"}, 64 {http.MethodGet, "https://test.com/err0", 400, "SomeCode0"}, 65 } 66 67 for _, table := range tables { 68 req, err := http.NewRequest(table.method, table.url, nil) 69 require.NoError(t, err) 70 71 resp, err := client.Do(req) 72 require.NoError(t, err) 73 defer resp.Body.Close() 74 75 require.Equal(t, table.statusCode, resp.StatusCode) 76 77 respBodyRaw, err := io.ReadAll(resp.Body) 78 require.NoError(t, err) 79 80 respBody := string(respBodyRaw) 81 if table.expErrorCode != "" { 82 require.Contains(t, respBody, table.expErrorCode) 83 } 84 } 85 86 } 87 88 func TestMock_Failure(t *testing.T) { 89 info := awsmocker.Start(t, &awsmocker.MockerOptions{ 90 SkipDefaultMocks: true, 91 ReturnAwsConfig: true, 92 Mocks: []*awsmocker.MockedEndpoint{ 93 awsmocker.Mock_Failure("ecs", "ListClusters"), 94 awsmocker.Mock_Failure_WithCode(403, "ecs", "ListServices", "SomeCode", "SomeMessage"), 95 }, 96 }) 97 98 ecsClient := ecs.NewFromConfig(*info.AwsConfig) 99 100 _, err := ecsClient.ListClusters(context.TODO(), &ecs.ListClustersInput{}) 101 require.Error(t, err) 102 require.ErrorContains(t, err, "AccessDenied") 103 104 _, err = ecsClient.ListServices(context.TODO(), &ecs.ListServicesInput{}) 105 require.Error(t, err) 106 require.ErrorContains(t, err, "SomeCode") 107 108 }