From 50a57836cc507b3a50c418147b7bdccbbccd7cef Mon Sep 17 00:00:00 2001 From: Dj Date: Mon, 3 Aug 2026 12:51:21 -0700 Subject: [PATCH] Fix serialization test bugs and enable Go 1.27 compat --- .github/workflows/lint.yml | 8 +-- .github/workflows/tests.yml | 4 +- cfn/event_test.go | 6 +- cfn/response.go | 4 +- cfn/wrap_test.go | 4 +- cmd/build-lambda-zip/main.go | 5 +- cmd/build-lambda-zip/main_test.go | 10 +-- events/activemq_test.go | 2 +- events/alb_test.go | 8 +-- events/apigw_test.go | 47 +++++++------- events/appsync_test.go | 14 ++--- events/autoscaling_test.go | 2 +- events/chime_bot_test.go | 2 +- events/clientvpn_test.go | 6 +- events/cloudwatch_events_test.go | 2 +- events/codebuild_test.go | 4 +- events/codedeploy_test.go | 4 +- events/codepipeline_cloudwatch_test.go | 4 +- events/codepipeline_job_test.go | 6 +- events/codepipeline_test.go | 6 +- events/cognito_test.go | 42 ++++++------- events/config_test.go | 6 +- events/connect_test.go | 2 +- events/dynamodb_test.go | 4 +- events/ecr_image_action_test.go | 2 +- events/ecr_scan_test.go | 2 +- events/ecs_container_instance_test.go | 2 +- events/example_s3_test.go | 4 +- events/firehose_test.go | 2 +- events/iot_1_click_test.go | 2 +- events/iot_button_test.go | 2 +- events/iot_preprovision_hook_test.go | 10 +-- events/iot_test.go | 10 +-- events/kafka_test.go | 2 +- events/kinesis_analytics_test.go | 2 +- events/kinesis_test.go | 4 +- events/lambda_function_urls_test.go | 9 +-- events/lex_test.go | 4 +- events/rabbitmq_test.go | 2 +- events/s3_object_lambda_test.go | 2 +- events/s3_test.go | 2 +- events/ses_test.go | 2 +- events/sns_test.go | 2 +- events/sqs_test.go | 2 +- events/test/assert.go | 8 +-- events/test/assert_test.go | 85 ++++++++++++++++++++++++++ events/test/jsonsyntax.go | 13 ++-- events/test/jsonsyntax_test.go | 84 +++++++++++++++++++++++++ events/test/readjson.go | 6 +- events/test/readjson_test.go | 38 ++++++++++++ events/test/testdata/event.json | 1 + lambda/errors.go | 4 +- lambda/extensions_api_client.go | 9 ++- lambda/handler.go | 3 +- lambda/handler_test.go | 9 ++- lambda/invoke_loop_gte_go122_test.go | 24 +++++++- lambda/invoke_loop_test.go | 6 +- lambda/runtime_api_client.go | 3 +- lambda/runtime_api_client_test.go | 5 +- lambda/sigterm_test.go | 49 ++++++++++++--- lambdaurl/http_handler_test.go | 7 +-- 61 files changed, 445 insertions(+), 180 deletions(-) create mode 100644 events/test/assert_test.go create mode 100644 events/test/jsonsyntax_test.go create mode 100644 events/test/readjson_test.go create mode 100644 events/test/testdata/event.json diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index fb54d23d..501977b1 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -16,11 +16,11 @@ jobs: name: run golangci-golint on the project runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7 with: go-version: 'stable' - name: golangci-golint - uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # v9 + uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9 with: - version: v2.9.0 + version: v2.13.1 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 47c3a7bd..c94e320a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,6 +11,7 @@ jobs: fail-fast: false matrix: go: + - "1.27" - "1.26" - "1.25" - "1.24" @@ -22,9 +23,6 @@ jobs: - "1.18" - "1.17" - "1.16" - - "1.15" - - "1.14" - - "1.13" steps: - name: Set up Go ${{ matrix.go }} diff --git a/cfn/event_test.go b/cfn/event_test.go index 9d22ad01..73080d0b 100644 --- a/cfn/event_test.go +++ b/cfn/event_test.go @@ -4,7 +4,7 @@ package cfn import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -13,7 +13,7 @@ import ( func TestCloudFormationEventMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cloudformation-event.json") + inputJSON, err := os.ReadFile("./testdata/cloudformation-event.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -34,5 +34,5 @@ func TestCloudFormationEventMarshaling(t *testing.T) { } func TestCloudFormationMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, Event{}) + test.TestMalformedJson(t, &Event{}) } diff --git a/cfn/response.go b/cfn/response.go index 375ddcb8..5b786f5f 100644 --- a/cfn/response.go +++ b/cfn/response.go @@ -6,7 +6,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" //nolint: staticcheck + "io" "log" "net/http" ) @@ -67,7 +67,7 @@ func (r *Response) sendWith(client httpClient) error { return err } - body, err = ioutil.ReadAll(res.Body) + body, err = io.ReadAll(res.Body) if err != nil { return err } diff --git a/cfn/wrap_test.go b/cfn/wrap_test.go index 7eadbd1a..f2a664b3 100644 --- a/cfn/wrap_test.go +++ b/cfn/wrap_test.go @@ -8,7 +8,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" //nolint: staticcheck + "io" "net/http" "testing" @@ -209,7 +209,7 @@ func TestWrappedSendFailure(t *testing.T) { func extractResponseBody(t *testing.T, req *http.Request) Response { assert.NotContains(t, req.Header, "Content-Type") - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) assert.NoError(t, err) var response Response err = json.Unmarshal(body, &response) diff --git a/cmd/build-lambda-zip/main.go b/cmd/build-lambda-zip/main.go index 80a45334..799ce5ef 100644 --- a/cmd/build-lambda-zip/main.go +++ b/cmd/build-lambda-zip/main.go @@ -6,7 +6,6 @@ import ( "archive/zip" "flag" "fmt" - "io/ioutil" //nolint: staticcheck "log" "os" "path/filepath" @@ -82,7 +81,7 @@ func compressExeAndArgs(outZipPath string, exePath string, args []string) error zipWriter := zip.NewWriter(zipFile) defer zipWriter.Close() - data, err := ioutil.ReadFile(exePath) + data, err := os.ReadFile(exePath) if err != nil { return err } @@ -97,7 +96,7 @@ func compressExeAndArgs(outZipPath string, exePath string, args []string) error if err != nil { return err } - data, err := ioutil.ReadFile(arg) + data, err := os.ReadFile(arg) if err != nil { return err } diff --git a/cmd/build-lambda-zip/main_test.go b/cmd/build-lambda-zip/main_test.go index 6def4c49..ae2c823f 100644 --- a/cmd/build-lambda-zip/main_test.go +++ b/cmd/build-lambda-zip/main_test.go @@ -5,7 +5,7 @@ package main import ( "archive/zip" "fmt" - "io/ioutil" //nolint: staticcheck + "io" "os" "os/exec" "path" @@ -34,7 +34,7 @@ func TestSizes(t *testing.T) { } testDir, err := os.Getwd() require.NoError(t, err) - tempDir, err := ioutil.TempDir("/tmp", "build-lambda-zip") + tempDir, err := os.MkdirTemp("/tmp", "build-lambda-zip") require.NoError(t, err) for _, test := range cases { require.NoError(t, os.Chdir(testDir)) @@ -66,7 +66,7 @@ func TestSizes(t *testing.T) { } func TestCompressExeAndArgs(t *testing.T) { - tempDir, err := ioutil.TempDir("/tmp", "build-lambda-zip") + tempDir, err := os.MkdirTemp("/tmp", "build-lambda-zip") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -117,7 +117,7 @@ func TestCompressExeAndArgs(t *testing.T) { link, err := bootstrap.Open() require.NoError(t, err) defer link.Close() - linkTarget, err := ioutil.ReadAll(link) + linkTarget, err := io.ReadAll(link) require.NoError(t, err) assert.Equal(t, filepath.Base(filePaths[0]), string(linkTarget)) }) @@ -148,7 +148,7 @@ func TestCompressExeAndArgs(t *testing.T) { f, err := zf.Open() require.NoError(t, err) defer f.Close() - content, err := ioutil.ReadAll(f) + content, err := io.ReadAll(f) require.NoError(t, err) assert.Equal(t, fmt.Sprintf("Hello file %d!", expectedIndex), string(content), "in file: %s", zf.Name) expectedIndex++ diff --git a/events/activemq_test.go b/events/activemq_test.go index 7b967893..5f04b597 100644 --- a/events/activemq_test.go +++ b/events/activemq_test.go @@ -43,5 +43,5 @@ func TestActiveMQEventMarshaling(t *testing.T) { } func TestActiveMQMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ActiveMQEvent{}) + test.TestMalformedJson(t, &ActiveMQEvent{}) } diff --git a/events/alb_test.go b/events/alb_test.go index 56d5b963..84757a47 100644 --- a/events/alb_test.go +++ b/events/alb_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -16,7 +16,7 @@ func TestALBTargetRequestMarshaling(t *testing.T) { for _, filename := range inputFiles { // read json from file - inputJSON, err := ioutil.ReadFile(filename) + inputJSON, err := os.ReadFile(filename) if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -37,13 +37,13 @@ func TestALBTargetRequestMarshaling(t *testing.T) { } func TestALBTargetRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ALBTargetGroupRequest{}) + test.TestMalformedJson(t, &ALBTargetGroupRequest{}) } func TestALBTargetResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/alb-lambda-target-response.json") + inputJSON, err := os.ReadFile("./testdata/alb-lambda-target-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } diff --git a/events/apigw_test.go b/events/apigw_test.go index 651718ab..9db86d78 100644 --- a/events/apigw_test.go +++ b/events/apigw_test.go @@ -5,8 +5,9 @@ package events import ( "encoding/json" "errors" - "io/ioutil" //nolint: staticcheck + "io" "net/http" + "os" "strings" "testing" @@ -18,7 +19,7 @@ import ( func TestApiGatewayRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -57,13 +58,13 @@ func TestApiGatewayRequestMarshaling(t *testing.T) { } func TestApiGatewayRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayProxyRequest{}) + test.TestMalformedJson(t, &APIGatewayProxyRequest{}) } func TestApiGatewayResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-response.json") + inputJSON, err := os.ReadFile("./testdata/apigw-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -84,7 +85,7 @@ func TestApiGatewayResponseMarshaling(t *testing.T) { } func TestApiGatewayResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayProxyResponse{}) + test.TestMalformedJson(t, &APIGatewayProxyResponse{}) } func TestAPIGatewayProxyStreamingResponseMarshaling(t *testing.T) { @@ -122,7 +123,7 @@ func TestAPIGatewayProxyStreamingResponseMarshaling(t *testing.T) { }, } { t.Run(test.name, func(t *testing.T) { - response, err := ioutil.ReadAll(test.response) + response, err := io.ReadAll(test.response) require.NoError(t, err) sep := "\x00\x00\x00\x00\x00\x00\x00\x00" responseParts := strings.Split(string(response), sep) @@ -164,7 +165,7 @@ func TestAPIGatewayProxyStreamingResponsePropogatesInnerClose(t *testing.T) { func TestApiGatewayCustomAuthorizerRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-custom-auth-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -187,7 +188,7 @@ func TestApiGatewayCustomAuthorizerRequestMarshaling(t *testing.T) { func TestApiGatewayCustomAuthorizerRequestTypeRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-request-type-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-custom-auth-request-type-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -208,17 +209,17 @@ func TestApiGatewayCustomAuthorizerRequestTypeRequestMarshaling(t *testing.T) { } func TestApiGatewayCustomAuthorizerRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerRequest{}) + test.TestMalformedJson(t, &APIGatewayCustomAuthorizerRequest{}) } func TestApiGatewayCustomAuthorizerRequestTypeRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerRequestTypeRequest{}) + test.TestMalformedJson(t, &APIGatewayCustomAuthorizerRequestTypeRequest{}) } func TestApiGatewayWebsocketRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-websocket-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-websocket-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -241,7 +242,7 @@ func TestApiGatewayWebsocketRequestMarshaling(t *testing.T) { func TestApiGatewayWebsocketRequestSendMessageMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-websocket-request-send-message.json") + inputJSON, err := os.ReadFile("./testdata/apigw-websocket-request-send-message.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -264,7 +265,7 @@ func TestApiGatewayWebsocketRequestSendMessageMarshaling(t *testing.T) { func TestApiGatewayWebsocketRequestDisconnectMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-websocket-request-disconnect.json") + inputJSON, err := os.ReadFile("./testdata/apigw-websocket-request-disconnect.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -285,13 +286,13 @@ func TestApiGatewayWebsocketRequestDisconnectMarshaling(t *testing.T) { } func TestApiGatewayWebsocketRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayWebsocketProxyRequest{}) + test.TestMalformedJson(t, &APIGatewayWebsocketProxyRequest{}) } func TestApiGatewayCustomAuthorizerResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-response.json") + inputJSON, err := os.ReadFile("./testdata/apigw-custom-auth-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -373,13 +374,13 @@ func TestAPIGatewayV2CustomAuthorizerSimpleResponseMarshalling(t *testing.T) { } func TestApiGatewayCustomAuthorizerResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerResponse{}) + test.TestMalformedJson(t, &APIGatewayCustomAuthorizerResponse{}) } func TestApiGatewayRestApiOpenApiRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-restapi-openapi-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-restapi-openapi-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -408,7 +409,7 @@ func TestApiGatewayRestApiOpenApiRequestMarshaling(t *testing.T) { func TestApiGatewayV2HTTPRequestJWTAuthorizerMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-request-jwt-authorizer.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-request-jwt-authorizer.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -443,7 +444,7 @@ func TestApiGatewayV2HTTPRequestJWTAuthorizerMarshaling(t *testing.T) { func TestApiGatewayV2HTTPRequestLambdaAuthorizerMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-request-lambda-authorizer.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-request-lambda-authorizer.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -478,7 +479,7 @@ func TestApiGatewayV2HTTPRequestLambdaAuthorizerMarshaling(t *testing.T) { func TestApiGatewayV2HTTPRequestIAMMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-request-iam.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-request-iam.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -537,7 +538,7 @@ func TestApiGatewayV2HTTPRequestIAMMarshaling(t *testing.T) { func TestApiGatewayV2HTTPRequestNoAuthorizerMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-request-no-authorizer.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-request-no-authorizer.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -570,7 +571,7 @@ func TestApiGatewayV2HTTPRequestNoAuthorizerMarshaling(t *testing.T) { } func TestApiGatewayV2CustomAuthorizerV1RequestMarshaling(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-custom-authorizer-v1-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-custom-authorizer-v1-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -591,7 +592,7 @@ func TestApiGatewayV2CustomAuthorizerV1RequestMarshaling(t *testing.T) { } func TestApiGatewayV2CustomAuthorizerV2RequestMarshaling(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/apigw-v2-custom-authorizer-v2-request.json") + inputJSON, err := os.ReadFile("./testdata/apigw-v2-custom-authorizer-v2-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } diff --git a/events/appsync_test.go b/events/appsync_test.go index 2e179261..647d2335 100644 --- a/events/appsync_test.go +++ b/events/appsync_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -10,7 +10,7 @@ import ( ) func TestAppSyncIdentity_IAM(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/appsync-identity-iam.json") + inputJSON, err := os.ReadFile("./testdata/appsync-identity-iam.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -29,7 +29,7 @@ func TestAppSyncIdentity_IAM(t *testing.T) { } func TestAppSyncIdentity_Cognito(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/appsync-identity-cognito.json") + inputJSON, err := os.ReadFile("./testdata/appsync-identity-cognito.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -48,7 +48,7 @@ func TestAppSyncIdentity_Cognito(t *testing.T) { } func TestAppSyncLambdaAuthorizerRequestMarshalling(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/appsync-lambda-auth-request.json") + inputJSON, err := os.ReadFile("./testdata/appsync-lambda-auth-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -67,11 +67,11 @@ func TestAppSyncLambdaAuthorizerRequestMarshalling(t *testing.T) { } func TestAppSyncLambdaAuthorizerRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, AppSyncLambdaAuthorizerRequest{}) + test.TestMalformedJson(t, &AppSyncLambdaAuthorizerRequest{}) } func TestAppSyncLambdaAuthorizerResponseMarshalling(t *testing.T) { - inputJSON, err := ioutil.ReadFile("./testdata/appsync-lambda-auth-response.json") + inputJSON, err := os.ReadFile("./testdata/appsync-lambda-auth-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -90,5 +90,5 @@ func TestAppSyncLambdaAuthorizerResponseMarshalling(t *testing.T) { } func TestAppSyncLambdaAuthorizerResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, AppSyncLambdaAuthorizerResponse{}) + test.TestMalformedJson(t, &AppSyncLambdaAuthorizerResponse{}) } diff --git a/events/autoscaling_test.go b/events/autoscaling_test.go index a41541d8..d5712037 100644 --- a/events/autoscaling_test.go +++ b/events/autoscaling_test.go @@ -37,5 +37,5 @@ func TestAutoScalingEventMarshaling(t *testing.T) { } func TestAutoScalingMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, AutoScalingEvent{}) + test.TestMalformedJson(t, &AutoScalingEvent{}) } diff --git a/events/chime_bot_test.go b/events/chime_bot_test.go index 3caba67e..e898ee32 100644 --- a/events/chime_bot_test.go +++ b/events/chime_bot_test.go @@ -135,5 +135,5 @@ func TestChimeBotEventMarshaling(t *testing.T) { } func TestChimeBotMarshalingMalformedJSON(t *testing.T) { - test.TestMalformedJson(t, ChimeBotEvent{}) + test.TestMalformedJson(t, &ChimeBotEvent{}) } diff --git a/events/clientvpn_test.go b/events/clientvpn_test.go index aae58d59..c46abc7a 100644 --- a/events/clientvpn_test.go +++ b/events/clientvpn_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -11,7 +11,7 @@ import ( func TestClientVPNConnectionHandlerRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/clientvpn-connectionhandler-request.json") + inputJSON, err := os.ReadFile("./testdata/clientvpn-connectionhandler-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -32,5 +32,5 @@ func TestClientVPNConnectionHandlerRequestMarshaling(t *testing.T) { } func TestClientVPNConnectionHandlerRequestMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ClientVPNConnectionHandlerRequest{}) + test.TestMalformedJson(t, &ClientVPNConnectionHandlerRequest{}) } diff --git a/events/cloudwatch_events_test.go b/events/cloudwatch_events_test.go index 3f49caba..c364bb86 100644 --- a/events/cloudwatch_events_test.go +++ b/events/cloudwatch_events_test.go @@ -32,5 +32,5 @@ func TestCloudwatchScheduledEventIdempotency(t *testing.T) { } func TestCloudwatchScheduledEventRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CloudWatchEvent{}) + test.TestMalformedJson(t, &CloudWatchEvent{}) } diff --git a/events/codebuild_test.go b/events/codebuild_test.go index d0e1b693..6d25c1fb 100644 --- a/events/codebuild_test.go +++ b/events/codebuild_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "time" @@ -301,7 +301,7 @@ func TestUnmarshalCodeBuildEvent(t *testing.T) { } for _, testcase := range tests { - data, err := ioutil.ReadFile(testcase.input) + data, err := os.ReadFile(testcase.input) require.NoError(t, err) var actual CodeBuildEvent diff --git a/events/codedeploy_test.go b/events/codedeploy_test.go index c363f77d..5cd1cb59 100644 --- a/events/codedeploy_test.go +++ b/events/codedeploy_test.go @@ -3,7 +3,7 @@ package events import ( "encoding/json" "github.com/stretchr/testify/require" - "io/ioutil" //nolint: staticcheck + "os" "testing" "time" ) @@ -67,7 +67,7 @@ func TestUnmarshalCodeDeployEvent(t *testing.T) { } for _, testcase := range tests { - data, err := ioutil.ReadFile(testcase.input) + data, err := os.ReadFile(testcase.input) require.NoError(t, err) var actual CodeDeployEvent diff --git a/events/codepipeline_cloudwatch_test.go b/events/codepipeline_cloudwatch_test.go index 13321980..7cf85ed5 100644 --- a/events/codepipeline_cloudwatch_test.go +++ b/events/codepipeline_cloudwatch_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "time" @@ -89,7 +89,7 @@ func TestUnmarshalCodePipelineEvent(t *testing.T) { } for _, testcase := range tests { - data, err := ioutil.ReadFile(testcase.input) + data, err := os.ReadFile(testcase.input) require.NoError(t, err) var actual CodePipelineCloudWatchEvent diff --git a/events/codepipeline_job_test.go b/events/codepipeline_job_test.go index c78bfa0d..cfca0a12 100644 --- a/events/codepipeline_job_test.go +++ b/events/codepipeline_job_test.go @@ -3,7 +3,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -13,7 +13,7 @@ import ( func TestCodePipeLineJobEventMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/codepipeline-job-event.json") + inputJSON, err := os.ReadFile("./testdata/codepipeline-job-event.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -34,5 +34,5 @@ func TestCodePipeLineJobEventMarshaling(t *testing.T) { } func TestCodePipelineJobEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CodePipelineJobEvent{}) + test.TestMalformedJson(t, &CodePipelineJobEvent{}) } diff --git a/events/codepipeline_test.go b/events/codepipeline_test.go index cb7e0e6a..36c312cf 100644 --- a/events/codepipeline_test.go +++ b/events/codepipeline_test.go @@ -3,7 +3,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -13,7 +13,7 @@ import ( func TestCodePipeLineEventMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/codepipeline-job-event.json") + inputJSON, err := os.ReadFile("./testdata/codepipeline-job-event.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -34,5 +34,5 @@ func TestCodePipeLineEventMarshaling(t *testing.T) { } func TestCodePipelineEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CodePipelineEvent{}) + test.TestMalformedJson(t, &CodePipelineEvent{}) } diff --git a/events/cognito_test.go b/events/cognito_test.go index 7a18e601..823e1bdb 100644 --- a/events/cognito_test.go +++ b/events/cognito_test.go @@ -3,7 +3,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -13,7 +13,7 @@ import ( func TestCognitoEventMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -34,13 +34,13 @@ func TestCognitoEventMarshaling(t *testing.T) { } func TestCognitoMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEvent{}) + test.TestMalformedJson(t, &CognitoEvent{}) } func TestCognitoEventUserPoolsPreSignupMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-presignup.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-presignup.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -61,13 +61,13 @@ func TestCognitoEventUserPoolsPreSignupMarshaling(t *testing.T) { } func TestCognitoUserPoolsPreSignupMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsPreSignup{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsPreSignup{}) } func TestCognitoEventUserPoolsPreAuthenticationMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-preauthentication.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-preauthentication.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -88,13 +88,13 @@ func TestCognitoEventUserPoolsPreAuthenticationMarshaling(t *testing.T) { } func TestCognitoUserPoolsPreAuthenticationMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsPreAuthentication{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsPreAuthentication{}) } func TestCognitoEventUserPoolsPostConfirmationMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-postconfirmation.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-postconfirmation.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -115,12 +115,12 @@ func TestCognitoEventUserPoolsPostConfirmationMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsPreTokenGenMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsPreTokenGen{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsPreTokenGen{}) } func TestCognitoEventUserPoolsPreTokenGenMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-pretokengen.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-pretokengen.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -142,7 +142,7 @@ func TestCognitoEventUserPoolsPreTokenGenMarshaling(t *testing.T) { func TestCognitoEventUserPoolsPreTokenGenV2Marshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-pretokengen-v2.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-pretokengen-v2.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -164,7 +164,7 @@ func TestCognitoEventUserPoolsPreTokenGenV2Marshaling(t *testing.T) { func TestCognitoEventUserPoolsPreTokenGenV2_0Marshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-pretokengen-v2_0.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-pretokengen-v2_0.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -190,7 +190,7 @@ func TestCognitoEventUserPoolsDefineAuthChallengeMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsDefineAuthChallengeMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsDefineAuthChallenge{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsDefineAuthChallenge{}) } func TestCognitoEventUserPoolsCreateAuthChallengeMarshaling(t *testing.T) { @@ -199,7 +199,7 @@ func TestCognitoEventUserPoolsCreateAuthChallengeMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsCreateAuthChallengeMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsCreateAuthChallenge{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsCreateAuthChallenge{}) } func TestCognitoEventUserPoolsVerifyAuthChallengeMarshaling(t *testing.T) { @@ -208,13 +208,13 @@ func TestCognitoEventUserPoolsVerifyAuthChallengeMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsVerifyAuthChallengeMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsVerifyAuthChallenge{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsVerifyAuthChallenge{}) } func TestCognitoEventUserPoolsPostAuthenticationMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-postauthentication.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-postauthentication.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -235,12 +235,12 @@ func TestCognitoEventUserPoolsPostAuthenticationMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsMigrateUserMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsMigrateUser{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsMigrateUser{}) } func TestCognitoEventUserPoolsMigrateUserMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-migrateuser.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-migrateuser.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -261,7 +261,7 @@ func TestCognitoEventUserPoolsMigrateUserMarshaling(t *testing.T) { func TestCognitoEventUserPoolsCustomMessageMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-custommessage.json") + inputJSON, err := os.ReadFile("./testdata/cognito-event-userpools-custommessage.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -282,7 +282,7 @@ func TestCognitoEventUserPoolsCustomMessageMarshaling(t *testing.T) { } func TestCognitoUserPoolsCustomMessageMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsCustomMessage{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsCustomMessage{}) } func TestCognitoEventUserPoolsInboundFederationOIDCMarshaling(t *testing.T) { @@ -296,5 +296,5 @@ func TestCognitoEventUserPoolsInboundFederationSAMLMarshaling(t *testing.T) { } func TestCognitoEventUserPoolsInboundFederationMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsInboundFederation{}) + test.TestMalformedJson(t, &CognitoEventUserPoolsInboundFederation{}) } diff --git a/events/config_test.go b/events/config_test.go index 57b31123..9a9b593a 100644 --- a/events/config_test.go +++ b/events/config_test.go @@ -3,7 +3,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -12,7 +12,7 @@ import ( func TestConfigEventMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/config-event.json") + inputJSON, err := os.ReadFile("./testdata/config-event.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -33,5 +33,5 @@ func TestConfigEventMarshaling(t *testing.T) { } func TestConfigMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ConfigEvent{}) + test.TestMalformedJson(t, &ConfigEvent{}) } diff --git a/events/connect_test.go b/events/connect_test.go index 723f99f3..cc8dd748 100644 --- a/events/connect_test.go +++ b/events/connect_test.go @@ -32,5 +32,5 @@ func TestConnectMarshaling(t *testing.T) { } func TestConnectMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ConnectEvent{}) + test.TestMalformedJson(t, &ConnectEvent{}) } diff --git a/events/dynamodb_test.go b/events/dynamodb_test.go index e364cb02..cce0d052 100644 --- a/events/dynamodb_test.go +++ b/events/dynamodb_test.go @@ -32,7 +32,7 @@ func TestDynamoDBEventMarshaling(t *testing.T) { } func TestDynamoDBEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, DynamoDBEvent{}) + test.TestMalformedJson(t, &DynamoDBEvent{}) } func TestDynamoDBTimeWindowEventMarshaling(t *testing.T) { @@ -56,5 +56,5 @@ func TestDynamoDBTimeWindowEventMarshaling(t *testing.T) { } func TestDynamoDBTimeWindowEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, DynamoDBTimeWindowEvent{}) + test.TestMalformedJson(t, &DynamoDBTimeWindowEvent{}) } diff --git a/events/ecr_image_action_test.go b/events/ecr_image_action_test.go index 180e8030..2177ff35 100644 --- a/events/ecr_image_action_test.go +++ b/events/ecr_image_action_test.go @@ -52,5 +52,5 @@ func TestECRImageActionEventMarshaling(t *testing.T) { } func TestECRPushMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ECRImageActionEvent{}) + test.TestMalformedJson(t, &ECRImageActionEvent{}) } diff --git a/events/ecr_scan_test.go b/events/ecr_scan_test.go index 2029dbd5..a71f1895 100644 --- a/events/ecr_scan_test.go +++ b/events/ecr_scan_test.go @@ -52,5 +52,5 @@ func TestECRScanEventMarshaling(t *testing.T) { } func TestECRScanMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ECRScanEvent{}) + test.TestMalformedJson(t, &ECRScanEvent{}) } diff --git a/events/ecs_container_instance_test.go b/events/ecs_container_instance_test.go index 1e7229ac..5c845eb2 100644 --- a/events/ecs_container_instance_test.go +++ b/events/ecs_container_instance_test.go @@ -90,5 +90,5 @@ func ptr(s string) *string { } func TestECSContainerInstanceMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ECSContainerInstanceEvent{}) + test.TestMalformedJson(t, &ECSContainerInstanceEvent{}) } diff --git a/events/example_s3_test.go b/events/example_s3_test.go index d64f6a94..7d2f1cc7 100644 --- a/events/example_s3_test.go +++ b/events/example_s3_test.go @@ -6,7 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "github.com/aws/aws-lambda-go/events" @@ -32,7 +32,7 @@ func ExampleS3ObjectLambdaEvent() { return err } defer resp.Body.Close() - bodyBytes, err := ioutil.ReadAll(resp.Body) + bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/events/firehose_test.go b/events/firehose_test.go index 46409965..28d7ed5f 100644 --- a/events/firehose_test.go +++ b/events/firehose_test.go @@ -72,5 +72,5 @@ func toUpperHandler(ctx context.Context, evnt KinesisFirehoseEvent) KinesisFireh } func TestKinesisFirehoseMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisFirehoseEvent{}) + test.TestMalformedJson(t, &KinesisFirehoseEvent{}) } diff --git a/events/iot_1_click_test.go b/events/iot_1_click_test.go index 7f4ffc94..f91e4038 100644 --- a/events/iot_1_click_test.go +++ b/events/iot_1_click_test.go @@ -30,5 +30,5 @@ func TestIoTOneClickEventMalformedJson(t *testing.T) { } func TestIoTOneClickEventMarshaling(t *testing.T) { - test.TestMalformedJson(t, IoTOneClickEvent{}) + test.TestMalformedJson(t, &IoTOneClickEvent{}) } diff --git a/events/iot_button_test.go b/events/iot_button_test.go index 583cb43d..aa0671e6 100644 --- a/events/iot_button_test.go +++ b/events/iot_button_test.go @@ -30,5 +30,5 @@ func TestIoTButtonMalformedJson(t *testing.T) { } func TestIoTButtonEventMarshaling(t *testing.T) { - test.TestMalformedJson(t, IoTButtonEvent{}) + test.TestMalformedJson(t, &IoTButtonEvent{}) } diff --git a/events/iot_preprovision_hook_test.go b/events/iot_preprovision_hook_test.go index 09d7e490..ac9ea012 100644 --- a/events/iot_preprovision_hook_test.go +++ b/events/iot_preprovision_hook_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -11,7 +11,7 @@ import ( func TestIoTPreProvisionHookRequest(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/iot-preprovision-hook-request.json") + inputJSON, err := os.ReadFile("./testdata/iot-preprovision-hook-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -32,13 +32,13 @@ func TestIoTPreProvisionHookRequest(t *testing.T) { } func TestIoTPreProvisionHookRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, IoTPreProvisionHookRequest{}) + test.TestMalformedJson(t, &IoTPreProvisionHookRequest{}) } func TestIoTPreProvisionHookResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/iot-preprovision-hook-response.json") + inputJSON, err := os.ReadFile("./testdata/iot-preprovision-hook-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -59,5 +59,5 @@ func TestIoTPreProvisionHookResponseMarshaling(t *testing.T) { } func TestIoTPreProvisionHookResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, IoTPreProvisionHookResponse{}) + test.TestMalformedJson(t, &IoTPreProvisionHookResponse{}) } diff --git a/events/iot_test.go b/events/iot_test.go index 38cf84e9..b730de3a 100644 --- a/events/iot_test.go +++ b/events/iot_test.go @@ -2,7 +2,7 @@ package events import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/aws/aws-lambda-go/events/test" @@ -11,7 +11,7 @@ import ( func TestIoTCoreCustomAuthorizerRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/iot-custom-auth-request.json") + inputJSON, err := os.ReadFile("./testdata/iot-custom-auth-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -32,13 +32,13 @@ func TestIoTCoreCustomAuthorizerRequestMarshaling(t *testing.T) { } func TestIoTCoreCustomAuthorizerRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, IoTCoreCustomAuthorizerRequest{}) + test.TestMalformedJson(t, &IoTCoreCustomAuthorizerRequest{}) } func TestIoTCoreCustomAuthorizerResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/iot-custom-auth-response.json") + inputJSON, err := os.ReadFile("./testdata/iot-custom-auth-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -59,5 +59,5 @@ func TestIoTCoreCustomAuthorizerResponseMarshaling(t *testing.T) { } func TestIoTCoreCustomAuthorizerResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, IoTCoreCustomAuthorizerResponse{}) + test.TestMalformedJson(t, &IoTCoreCustomAuthorizerResponse{}) } diff --git a/events/kafka_test.go b/events/kafka_test.go index f4ad6577..bc170dec 100644 --- a/events/kafka_test.go +++ b/events/kafka_test.go @@ -60,5 +60,5 @@ func TestKafkaEventMarshaling(t *testing.T) { } func TestKafkaMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KafkaEvent{}) + test.TestMalformedJson(t, &KafkaEvent{}) } diff --git a/events/kinesis_analytics_test.go b/events/kinesis_analytics_test.go index 14e91fe1..5f9ce62f 100644 --- a/events/kinesis_analytics_test.go +++ b/events/kinesis_analytics_test.go @@ -18,7 +18,7 @@ func TestKinesisAnalyticsOutputDeliveryResponseMarshaling(t *testing.T) { } func TestKinesisOutputDeliveryEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisAnalyticsOutputDeliveryEvent{}) + test.TestMalformedJson(t, &KinesisAnalyticsOutputDeliveryEvent{}) } func testKinesisAnalyticsOutputMarshaling(t *testing.T, inputEvent interface{}, jsonFile string) { diff --git a/events/kinesis_test.go b/events/kinesis_test.go index 4ec2bbb1..5c96271f 100644 --- a/events/kinesis_test.go +++ b/events/kinesis_test.go @@ -31,7 +31,7 @@ func TestKinesisEventMarshaling(t *testing.T) { } func TestKinesisMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisEvent{}) + test.TestMalformedJson(t, &KinesisEvent{}) } func TestKinesisTimeWindowEventMarshaling(t *testing.T) { @@ -55,5 +55,5 @@ func TestKinesisTimeWindowEventMarshaling(t *testing.T) { } func TestKinesisTimeWindowEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisTimeWindowEvent{}) + test.TestMalformedJson(t, &KinesisTimeWindowEvent{}) } diff --git a/events/lambda_function_urls_test.go b/events/lambda_function_urls_test.go index cbc15f45..d37bac5e 100644 --- a/events/lambda_function_urls_test.go +++ b/events/lambda_function_urls_test.go @@ -5,8 +5,9 @@ package events import ( "encoding/json" "errors" - "io/ioutil" //nolint: staticcheck + "io" "net/http" + "os" "strings" "testing" @@ -17,7 +18,7 @@ import ( func TestLambdaFunctionURLResponseMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/lambda-urls-response.json") + inputJSON, err := os.ReadFile("./testdata/lambda-urls-response.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -40,7 +41,7 @@ func TestLambdaFunctionURLResponseMarshaling(t *testing.T) { func TestLambdaFunctionURLRequestMarshaling(t *testing.T) { // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/lambda-urls-request.json") + inputJSON, err := os.ReadFile("./testdata/lambda-urls-request.json") if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -94,7 +95,7 @@ func TestLambdaFunctionURLStreamingResponseMarshaling(t *testing.T) { }, } { t.Run(test.name, func(t *testing.T) { - response, err := ioutil.ReadAll(test.response) + response, err := io.ReadAll(test.response) require.NoError(t, err) sep := "\x00\x00\x00\x00\x00\x00\x00\x00" responseParts := strings.Split(string(response), sep) diff --git a/events/lex_test.go b/events/lex_test.go index efda78ef..afeea1dd 100644 --- a/events/lex_test.go +++ b/events/lex_test.go @@ -41,9 +41,9 @@ func TestLexResponseMarshaling(t *testing.T) { } func TestLexMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, LexEvent{}) + test.TestMalformedJson(t, &LexEvent{}) } func TestLexResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, LexResponse{}) + test.TestMalformedJson(t, &LexResponse{}) } diff --git a/events/rabbitmq_test.go b/events/rabbitmq_test.go index 9935479f..b37d16ff 100644 --- a/events/rabbitmq_test.go +++ b/events/rabbitmq_test.go @@ -40,5 +40,5 @@ func TestRabbitMQEventMarshaling(t *testing.T) { } func TestRabbitMQMarshalingMalformedJSON(t *testing.T) { - test.TestMalformedJson(t, RabbitMQEvent{}) + test.TestMalformedJson(t, &RabbitMQEvent{}) } diff --git a/events/s3_object_lambda_test.go b/events/s3_object_lambda_test.go index 66e40ac7..0a65b843 100644 --- a/events/s3_object_lambda_test.go +++ b/events/s3_object_lambda_test.go @@ -40,5 +40,5 @@ func TestS3ObjectLambdaEventMarshaling(t *testing.T) { } func TestS3ObjectLambdaMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, S3ObjectLambdaEvent{}) + test.TestMalformedJson(t, &S3ObjectLambdaEvent{}) } diff --git a/events/s3_test.go b/events/s3_test.go index 8ec48fbf..979dac02 100644 --- a/events/s3_test.go +++ b/events/s3_test.go @@ -54,7 +54,7 @@ func TestS3TestEventMarshaling(t *testing.T) { } func TestS3MarshalingMalformedJSON(t *testing.T) { - test.TestMalformedJson(t, S3Event{}) + test.TestMalformedJson(t, &S3Event{}) } func TestS3GlacierEventMarshaling(t *testing.T) { diff --git a/events/ses_test.go b/events/ses_test.go index d0da6c7a..9537c983 100644 --- a/events/ses_test.go +++ b/events/ses_test.go @@ -39,5 +39,5 @@ func TestSESEventMarshaling(t *testing.T) { } func TestSESMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, SimpleEmailEvent{}) + test.TestMalformedJson(t, &SimpleEmailEvent{}) } diff --git a/events/sns_test.go b/events/sns_test.go index e084062c..4f0fe621 100644 --- a/events/sns_test.go +++ b/events/sns_test.go @@ -31,7 +31,7 @@ func TestSnsEventMarshaling(t *testing.T) { } func TestSnsMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, SNSEvent{}) + test.TestMalformedJson(t, &SNSEvent{}) } func TestCloudWatchAlarmSNSPayloadMarshaling(t *testing.T) { diff --git a/events/sqs_test.go b/events/sqs_test.go index b207d7b1..506ec035 100644 --- a/events/sqs_test.go +++ b/events/sqs_test.go @@ -31,5 +31,5 @@ func TestSqsEventMarshaling(t *testing.T) { } func TestSqsMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, SQSEvent{}) + test.TestMalformedJson(t, &SQSEvent{}) } diff --git a/events/test/assert.go b/events/test/assert.go index 25c9c28f..00942359 100644 --- a/events/test/assert.go +++ b/events/test/assert.go @@ -2,15 +2,15 @@ package test import ( "encoding/json" - "io/ioutil" //nolint: staticcheck + "os" "testing" "github.com/stretchr/testify/assert" ) // nolint: staticcheck -func AssertJsonFile(t *testing.T, file string, o interface{}) { - inputJSON, err := ioutil.ReadFile(file) +func AssertJsonFile(t testing.TB, file string, o interface{}) { + inputJSON, err := os.ReadFile(file) if err != nil { t.Errorf("could not open test file. details: %v", err) } @@ -18,7 +18,7 @@ func AssertJsonFile(t *testing.T, file string, o interface{}) { } // nolint: staticcheck -func AssertJsonBytes(t *testing.T, inputJSON []byte, o interface{}) { +func AssertJsonBytes(t testing.TB, inputJSON []byte, o interface{}) { // de-serialize if err := json.Unmarshal(inputJSON, o); err != nil { t.Errorf("could not unmarshal event. details: %v", err) diff --git a/events/test/assert_test.go b/events/test/assert_test.go new file mode 100644 index 00000000..89f399ca --- /dev/null +++ b/events/test/assert_test.go @@ -0,0 +1,85 @@ +// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +package test + +import ( + "path/filepath" + "testing" +) + +type sampleEvent struct { + Name string `json:"name"` + Age int `json:"age"` +} + +// unmarshalableEvent unmarshals cleanly from an empty JSON object but cannot be +// marshaled back to JSON because channels are an unsupported type. It is used to +// exercise the marshal-error branch of AssertJsonBytes. +type unmarshalableEvent struct { + C chan int `json:"c"` +} + +func TestAssertJsonBytes(t *testing.T) { + // Round-trips valid JSON through Unmarshal/Marshal and asserts equality. + inputJSON := []byte(`{"name":"test","age":5}`) + var o sampleEvent + AssertJsonBytes(t, inputJSON, &o) + + if o.Name != "test" || o.Age != 5 { + t.Errorf("AssertJsonBytes did not deserialize as expected: %+v", o) + } +} + +func TestAssertJsonBytesUnmarshalError(t *testing.T) { + // Malformed JSON should trigger the unmarshal-error branch. + mock := &mockTB{TB: t} + target := make(map[string]interface{}) + AssertJsonBytes(mock, []byte(`{bad json`), &target) + + if !containsError(mock.errors, "could not unmarshal event. details: %v") { + t.Errorf("expected unmarshal error, got: %v", mock.errors) + } +} + +func TestAssertJsonBytesMarshalError(t *testing.T) { + // A value that unmarshals from {} but cannot be marshaled should trigger the + // marshal-error branch. + mock := &mockTB{TB: t} + o := &unmarshalableEvent{} + AssertJsonBytes(mock, []byte(`{}`), o) + + if !containsError(mock.errors, "could not marshal event. details: %v") { + t.Errorf("expected marshal error, got: %v", mock.errors) + } +} + +func TestAssertJsonFile(t *testing.T) { + // Reads a JSON fixture and asserts it round-trips cleanly. + var o sampleEvent + AssertJsonFile(t, filepath.Join("testdata", "event.json"), &o) + + if o.Name != "test" || o.Age != 5 { + t.Errorf("AssertJsonFile did not deserialize as expected: %+v", o) + } +} + +func TestAssertJsonFileMissing(t *testing.T) { + // A missing file should trigger the open-error branch. + mock := &mockTB{TB: t} + var o sampleEvent + AssertJsonFile(mock, filepath.Join("testdata", "does-not-exist.json"), &o) + + if !containsError(mock.errors, "could not open test file. details: %v") { + t.Errorf("expected open error, got: %v", mock.errors) + } +} + +// containsError reports whether the given format string appears in errs. +func containsError(errs []string, format string) bool { + for _, e := range errs { + if e == format { + return true + } + } + return false +} diff --git a/events/test/jsonsyntax.go b/events/test/jsonsyntax.go index a0d2b823..a734dff6 100644 --- a/events/test/jsonsyntax.go +++ b/events/test/jsonsyntax.go @@ -4,22 +4,27 @@ package test import ( "encoding/json" + "errors" "testing" ) +// unmarshalJSON is the function used by TestMalformedJson to deserialize JSON. +// It defaults to json.Unmarshal and can be overridden in tests within this package. +var unmarshalJSON = json.Unmarshal + // nolint: staticcheck -func TestMalformedJson(t *testing.T, objectToDeserialize interface{}) { +func TestMalformedJson(t testing.TB, objectToDeserialize interface{}) { // 1. read JSON from file inputJson := GetMalformedJson() // 2. de-serialize into Go object - err := json.Unmarshal(inputJson, objectToDeserialize) + err := unmarshalJSON(inputJson, objectToDeserialize) if err == nil { t.Errorf("unmarshal should have failed but succeeded instead") } - _, isSyntaxError := err.(*json.SyntaxError) - if !isSyntaxError { + var syntaxError *json.SyntaxError + if !errors.As(err, &syntaxError) { t.Errorf("unmarshal should have returned a json.SyntaxError") } } diff --git a/events/test/jsonsyntax_test.go b/events/test/jsonsyntax_test.go new file mode 100644 index 00000000..460bd6d9 --- /dev/null +++ b/events/test/jsonsyntax_test.go @@ -0,0 +1,84 @@ +// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +package test + +import ( + "encoding/json" + "errors" + "testing" +) + +// mockTB implements testing.TB to capture Errorf calls. +type mockTB struct { + testing.TB + errors []string +} + +func (m *mockTB) Errorf(format string, args ...interface{}) { + m.errors = append(m.errors, format) +} + +func (m *mockTB) Helper() {} + +func TestMalformedJsonSyntaxError(t *testing.T) { + // Default behavior: malformed JSON produces json.SyntaxError, no Errorf called. + mock := &mockTB{} + target := make(map[string]interface{}) + TestMalformedJson(mock, &target) + + if len(mock.errors) != 0 { + t.Errorf("expected no errors, got: %v", mock.errors) + } +} + +func TestMalformedJsonUnmarshalSucceeds(t *testing.T) { + // When unmarshal unexpectedly returns nil, both Errorf calls should fire. + original := unmarshalJSON + unmarshalJSON = func([]byte, interface{}) error { + return nil + } + defer func() { unmarshalJSON = original }() + + mock := &mockTB{} + TestMalformedJson(mock, nil) + + if len(mock.errors) != 2 { + t.Fatalf("expected 2 errors, got %d: %v", len(mock.errors), mock.errors) + } + if mock.errors[0] != "unmarshal should have failed but succeeded instead" { + t.Errorf("unexpected first error message: %s", mock.errors[0]) + } + if mock.errors[1] != "unmarshal should have returned a json.SyntaxError" { + t.Errorf("unexpected second error message: %s", mock.errors[1]) + } +} + +func TestMalformedJsonNonSyntaxError(t *testing.T) { + // When unmarshal returns a non-SyntaxError, the second Errorf should fire. + original := unmarshalJSON + unmarshalJSON = func([]byte, interface{}) error { + return errors.New("some other error") + } + defer func() { unmarshalJSON = original }() + + mock := &mockTB{} + TestMalformedJson(mock, nil) + + if len(mock.errors) != 1 { + t.Fatalf("expected 1 error, got %d: %v", len(mock.errors), mock.errors) + } + if mock.errors[0] != "unmarshal should have returned a json.SyntaxError" { + t.Errorf("unexpected error message: %s", mock.errors[0]) + } +} + +func TestMalformedJsonDefaultUsesStdlib(t *testing.T) { + // Verify the default unmarshalJSON is json.Unmarshal. + mock := &mockTB{} + var target json.RawMessage + TestMalformedJson(mock, &target) + + if len(mock.errors) != 0 { + t.Errorf("expected no errors with default json.Unmarshal, got: %v", mock.errors) + } +} diff --git a/events/test/readjson.go b/events/test/readjson.go index bb742192..dd2ad7c1 100644 --- a/events/test/readjson.go +++ b/events/test/readjson.go @@ -1,13 +1,13 @@ package test import ( - "io/ioutil" //nolint: staticcheck + "os" "testing" ) // ReadJSONFromFile reads a given input file to JSON -func ReadJSONFromFile(t *testing.T, inputFile string) []byte { - inputJSON, err := ioutil.ReadFile(inputFile) +func ReadJSONFromFile(t testing.TB, inputFile string) []byte { + inputJSON, err := os.ReadFile(inputFile) if err != nil { t.Errorf("could not open test file. details: %v", err) } diff --git a/events/test/readjson_test.go b/events/test/readjson_test.go new file mode 100644 index 00000000..932672c9 --- /dev/null +++ b/events/test/readjson_test.go @@ -0,0 +1,38 @@ +// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +package test + +import ( + "encoding/json" + "path/filepath" + "testing" +) + +func TestReadJSONFromFile(t *testing.T) { + // Read a known fixture and confirm the bytes deserialize as expected. + got := ReadJSONFromFile(t, filepath.Join("testdata", "event.json")) + + var o sampleEvent + if err := json.Unmarshal(got, &o); err != nil { + t.Fatalf("ReadJSONFromFile returned invalid JSON: %v", err) + } + if o.Name != "test" || o.Age != 5 { + t.Errorf("ReadJSONFromFile returned unexpected content: %s", got) + } +} + +func TestReadJSONFromFileMissing(t *testing.T) { + // A missing file should trigger Errorf and return nil. + mock := &mockTB{} + got := ReadJSONFromFile(mock, filepath.Join("testdata", "does-not-exist.json")) + + if got != nil { + t.Errorf("expected nil content for missing file, got: %s", got) + } + if len(mock.errors) != 1 { + t.Fatalf("expected 1 error for missing file, got %d: %v", len(mock.errors), mock.errors) + } + if mock.errors[0] != "could not open test file. details: %v" { + t.Errorf("unexpected error message: %s", mock.errors[0]) + } +} diff --git a/events/test/testdata/event.json b/events/test/testdata/event.json new file mode 100644 index 00000000..1d54f2a8 --- /dev/null +++ b/events/test/testdata/event.json @@ -0,0 +1 @@ +{"name":"test","age":5} diff --git a/lambda/errors.go b/lambda/errors.go index 5d482d04..e7f68c36 100644 --- a/lambda/errors.go +++ b/lambda/errors.go @@ -10,7 +10,7 @@ import ( func getErrorType(err interface{}) string { errorType := reflect.TypeOf(err) - if errorType.Kind() == reflect.Ptr { + if errorType.Kind() == reflect.Ptr { //nolint:govet return errorType.Elem().Name() } return errorType.Name() @@ -21,7 +21,7 @@ func lambdaErrorResponse(invokeError error) *messages.InvokeResponse_Error { return &ive } var errorName string - if errorType := reflect.TypeOf(invokeError); errorType.Kind() == reflect.Ptr { + if errorType := reflect.TypeOf(invokeError); errorType.Kind() == reflect.Ptr { //nolint:govet errorName = errorType.Elem().Name() } else { errorName = errorType.Name() diff --git a/lambda/extensions_api_client.go b/lambda/extensions_api_client.go index c9703891..1e8b7618 100644 --- a/lambda/extensions_api_client.go +++ b/lambda/extensions_api_client.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" //nolint: staticcheck "net/http" ) @@ -18,8 +17,8 @@ const ( type extensionAPIEventType string const ( - extensionInvokeEvent extensionAPIEventType = "INVOKE" //nolint:deadcode,unused,varcheck - extensionShutdownEvent extensionAPIEventType = "SHUTDOWN" //nolint:deadcode,unused,varcheck + extensionInvokeEvent extensionAPIEventType = "INVOKE" //nolint:unused + extensionShutdownEvent extensionAPIEventType = "SHUTDOWN" //nolint:unused ) type extensionAPIClient struct { @@ -53,7 +52,7 @@ func (c *extensionAPIClient) register(name string, events ...extensionAPIEventTy return "", fmt.Errorf("failed to register extension: %v", err) } defer res.Body.Close() - _, _ = io.Copy(ioutil.Discard, res.Body) + _, _ = io.Copy(io.Discard, res.Body) if res.StatusCode != http.StatusOK { return "", fmt.Errorf("failed to register extension, got response status: %d %s", res.StatusCode, http.StatusText(res.StatusCode)) @@ -78,7 +77,7 @@ func (c *extensionAPIClient) next(id string) (response extensionEventResponse, e return } defer res.Body.Close() - _, _ = io.Copy(ioutil.Discard, res.Body) + _, _ = io.Copy(io.Discard, res.Body) if res.StatusCode != http.StatusOK { err = fmt.Errorf("failed to register extension, got response status: %d %s", res.StatusCode, http.StatusText(res.StatusCode)) diff --git a/lambda/handler.go b/lambda/handler.go index 8df580d4..f87012b0 100644 --- a/lambda/handler.go +++ b/lambda/handler.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" // nolint:staticcheck "reflect" "strings" "sync" @@ -208,7 +207,7 @@ func (h handlerFunc) Invoke(ctx context.Context, payload []byte) ([]byte, error) case *bytes.Buffer: return response.Bytes(), nil } - b, err := ioutil.ReadAll(response) + b, err := io.ReadAll(response) if err != nil { return nil, err } diff --git a/lambda/handler_test.go b/lambda/handler_test.go index bca7a30e..f92667a4 100644 --- a/lambda/handler_test.go +++ b/lambda/handler_test.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" //nolint: staticcheck "reflect" "strings" "testing" @@ -400,7 +399,7 @@ func TestInvokes(t *testing.T) { }, { name: "types that are not json serializable result in an error", - expected: expected{``, errors.New("json: error calling MarshalJSON for type struct { lambda.arbitraryJSON }: barf")}, + expected: expected{``, errors.New("json: error calling MarshalJSON")}, handler: func() (interface{}, error) { return struct { arbitraryJSON @@ -430,7 +429,7 @@ func TestInvokes(t *testing.T) { t.Run("via Handler.Invoke", func(t *testing.T) { response, err := lambdaHandler.Invoke(context.TODO(), []byte(testCase.input)) if testCase.expected.err != nil { - assert.EqualError(t, err, testCase.expected.err.Error()) + assert.ErrorContains(t, err, testCase.expected.err.Error()) } else { assert.NoError(t, err) assert.Equal(t, testCase.expected.val, string(response)) @@ -439,11 +438,11 @@ func TestInvokes(t *testing.T) { t.Run("via handlerOptions.handlerFunc", func(t *testing.T) { response, err := lambdaHandler.handlerFunc(context.TODO(), []byte(testCase.input)) if testCase.expected.err != nil { - assert.EqualError(t, err, testCase.expected.err.Error()) + assert.ErrorContains(t, err, testCase.expected.err.Error()) } else { assert.NoError(t, err) require.NotNil(t, response) - responseBytes, err := ioutil.ReadAll(response) + responseBytes, err := io.ReadAll(response) assert.NoError(t, err) assert.Equal(t, testCase.expected.val, string(responseBytes)) } diff --git a/lambda/invoke_loop_gte_go122_test.go b/lambda/invoke_loop_gte_go122_test.go index 83284562..b6b6f8d8 100644 --- a/lambda/invoke_loop_gte_go122_test.go +++ b/lambda/invoke_loop_gte_go122_test.go @@ -155,6 +155,13 @@ func TestConcurrencyWithRIE(t *testing.T) { handlerBuild.Env = append(os.Environ(), "GOOS=linux") require.NoError(t, handlerBuild.Run()) + // Pre-pull the container image so that pull latency doesn't count against + // the per-subtest readiness deadline. + pull := exec.Command(containerCmd, "pull", "public.ecr.aws/lambda/provided:al2023") + pull.Stdout = os.Stderr + pull.Stderr = os.Stderr + require.NoError(t, pull.Run()) + nInvokes := 10 concurrency := 3 sleepMs := 1000 @@ -189,7 +196,22 @@ func TestConcurrencyWithRIE(t *testing.T) { require.NoError(t, cmd.Start()) t.Cleanup(func() { _ = cmd.Process.Kill() }) - time.Sleep(5 * time.Second) // Wait for container to start and pull image if needed + // Poll until the container's RIE is accepting TCP connections. + const pollInterval = 100 * time.Millisecond + addr := fmt.Sprintf("127.0.0.1:%d", port) + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + conn, dialErr := net.DialTimeout("tcp", addr, pollInterval) + if dialErr == nil { + conn.Close() + break + } + time.Sleep(pollInterval) + } + + // Give the RIE a moment to fully initialize its HTTP handler after + // the TCP listener is up. + time.Sleep(500 * time.Millisecond) client := &http.Client{Timeout: 15 * time.Second} invokeURL := fmt.Sprintf("http://127.0.0.1:%d/2015-03-31/functions/function/invocations", port) diff --git a/lambda/invoke_loop_test.go b/lambda/invoke_loop_test.go index 4c305564..83888de2 100644 --- a/lambda/invoke_loop_test.go +++ b/lambda/invoke_loop_test.go @@ -437,8 +437,10 @@ func (invalidPayload) MarshalJSON() ([]byte, error) { func TestSafeMarshal_SerializationError(t *testing.T) { payload := safeMarshal(invalidPayload{}) - want := `{"errorMessage":"json: error calling MarshalJSON for type lambda.invalidPayload: some error that contains '\"'","errorType":"Runtime.SerializationError"}` - assert.Equal(t, want, string(payload)) + wantType := "Runtime.SerializationError" + wantPayload := "lambda.invalidPayload" + assert.Contains(t, string(payload), wantType) + assert.Contains(t, string(payload), wantPayload) } type requestRecord struct { diff --git a/lambda/runtime_api_client.go b/lambda/runtime_api_client.go index 0fa12b4f..7607e49f 100644 --- a/lambda/runtime_api_client.go +++ b/lambda/runtime_api_client.go @@ -10,7 +10,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" //nolint: staticcheck "log" "net/http" "runtime" @@ -153,7 +152,7 @@ func (c *runtimeAPIClient) post(url string, body io.Reader, contentType string, return fmt.Errorf("failed to POST to %s: got unexpected status code: %d", url, resp.StatusCode) } - _, err = io.Copy(ioutil.Discard, resp.Body) + _, err = io.Copy(io.Discard, resp.Body) if err != nil { return fmt.Errorf("something went wrong reading the POST response from %s: %v", url, err) } diff --git a/lambda/runtime_api_client_test.go b/lambda/runtime_api_client_test.go index 96b4b7e3..36baebc2 100644 --- a/lambda/runtime_api_client_test.go +++ b/lambda/runtime_api_client_test.go @@ -6,7 +6,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" //nolint: staticcheck "net/http" "net/http/httptest" "strings" @@ -79,7 +78,7 @@ func TestClientDoneAndError(t *testing.T) { w.WriteHeader(http.StatusNotFound) return } - body, _ := ioutil.ReadAll(r.Body) + body, _ := io.ReadAll(r.Body) if strings.HasSuffix(r.URL.Path, "/error") { capturedErrors = append(capturedErrors, body) } else if strings.HasSuffix(r.URL.Path, "/response") { @@ -126,7 +125,7 @@ func TestStatusCodes(t *testing.T) { url := fmt.Sprintf("status-%d", i) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = ioutil.ReadAll(io.Reader(r.Body)) + _, _ = io.ReadAll(io.Reader(r.Body)) w.WriteHeader(i) })) diff --git a/lambda/sigterm_test.go b/lambda/sigterm_test.go index 5894ed16..ef86db16 100644 --- a/lambda/sigterm_test.go +++ b/lambda/sigterm_test.go @@ -6,7 +6,6 @@ package lambda import ( "fmt" "io" - "io/ioutil" //nolint: staticcheck "net" "net/http" "os" @@ -37,6 +36,13 @@ func TestEnableSigterm(t *testing.T) { handlerBuild.Env = append(os.Environ(), "GOOS=linux") require.NoError(t, handlerBuild.Run()) + // Pre-pull the container image so that pull latency doesn't count against + // the per-subtest readiness deadline. + pull := exec.Command(containerCmd, "pull", "public.ecr.aws/lambda/provided:al2023") + pull.Stdout = os.Stderr + pull.Stderr = os.Stderr + require.NoError(t, pull.Run()) + for name, opts := range map[string]struct { envVars []string assertLogs func(t *testing.T, logs string) @@ -65,7 +71,7 @@ func TestEnableSigterm(t *testing.T) { cmdArgs := []string{"run", "--rm", "-v", testDir + ":/var/runtime:ro,delegated", "-p", fmt.Sprintf("%d:8080", port), - "-e", "AWS_LAMBDA_FUNCTION_TIMEOUT=2"} + "-e", "AWS_LAMBDA_FUNCTION_TIMEOUT=4"} for _, env := range opts.envVars { cmdArgs = append(cmdArgs, "-e", env) } @@ -87,19 +93,48 @@ func TestEnableSigterm(t *testing.T) { require.NoError(t, cmd.Start()) t.Cleanup(func() { _ = cmd.Process.Kill() }) - time.Sleep(5 * time.Second) // Wait for container to start + // Monitor the container process for early exit + cmdDone := make(chan error, 1) + go func() { + cmdDone <- cmd.Wait() + }() + + // Poll until the container's RIE is accepting TCP connections. + // We only do TCP dialing here — NOT HTTP requests — to avoid + // sending multiple requests, which can result in failures. + const pollInterval = 100 * time.Millisecond + addr := fmt.Sprintf("127.0.0.1:%d", port) + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + select { + case err := <-cmdDone: + <-logDone + require.Failf(t, "container exited before becoming ready", "exit error: %v\nlogs:\n%s", err, logBuf.String()) + default: + } + conn, dialErr := net.DialTimeout("tcp", addr, pollInterval) + if dialErr == nil { + conn.Close() + break + } + time.Sleep(pollInterval) + } + + // Give the RIE a moment to fully initialize its HTTP handler after + // the TCP listener is up. + time.Sleep(500 * time.Millisecond) - client := &http.Client{Timeout: 5 * time.Second} + client := &http.Client{Timeout: 10 * time.Second} invokeURL := fmt.Sprintf("http://127.0.0.1:%d/2015-03-31/functions/function/invocations", port) resp, err := client.Post(invokeURL, "application/json", strings.NewReader("{}")) require.NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) assert.NoError(t, err) - assert.Equal(t, "Task timed out after 2.00 seconds", string(body)) + assert.Equal(t, "Task timed out after 4.00 seconds", string(body)) _ = cmd.Process.Kill() - _ = cmd.Wait() + <-cmdDone <-logDone logs := logBuf.String() diff --git a/lambdaurl/http_handler_test.go b/lambdaurl/http_handler_test.go index d4d990b7..c45853ae 100644 --- a/lambdaurl/http_handler_test.go +++ b/lambdaurl/http_handler_test.go @@ -10,7 +10,6 @@ import ( _ "embed" "encoding/json" "io" - "io/ioutil" //nolint: staticcheck "log" "net/http" "os" @@ -182,7 +181,7 @@ func TestWrap(t *testing.T) { ctx := context.WithValue(context.Background(), detectContentTypeContextKey{}, params.detectContentType) res, err := handler(ctx, &req) require.NoError(t, err) - resultBodyBytes, err := ioutil.ReadAll(res) + resultBodyBytes, err := io.ReadAll(res) require.NoError(t, err) resultHeaderBytes, resultBodyBytes, ok := bytes.Cut(resultBodyBytes, []byte{0, 0, 0, 0, 0, 0, 0, 0}) require.True(t, ok) @@ -240,7 +239,7 @@ func TestStartViaEmulator(t *testing.T) { var logs string done := make(chan interface{}) // closed on completion of log flush go func() { - logBytes, err := ioutil.ReadAll(stdout) + logBytes, err := io.ReadAll(stdout) require.NoError(t, err) logs = string(logBytes) close(done) @@ -255,7 +254,7 @@ func TestStartViaEmulator(t *testing.T) { resp, err := client.Post(rieInvokeAPI, "application/json", strings.NewReader("{}")) require.NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) assert.NoError(t, err) expected := "{\"statusCode\":200,\"headers\":{\"Content-Type\":\"text/html; charset=utf-8\"}}\x00\x00\x00\x00\x00\x00\x00\x00\n\n\nHello World!\n\n\n"