|
| 1 | +// Copyright 2023 (c) Andrea Scuderi - https://github.com/swift-serverless |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import AWSLambdaEvents |
| 16 | +import AWSLambdaRuntime |
| 17 | +@testable import AWSLambdaRuntimeCore |
| 18 | +import AWSLambdaTesting |
| 19 | +import Logging |
| 20 | +import NIO |
| 21 | + |
| 22 | +extension Lambda { |
| 23 | + public static func test<Handler: LambdaHandler>( |
| 24 | + _ handlerType: Handler.Type, |
| 25 | + with event: Handler.Event, |
| 26 | + using config: TestConfig = .init() |
| 27 | + ) async throws -> Handler.Output { |
| 28 | + let logger = Logger(label: "test") |
| 29 | + let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) |
| 30 | + defer { |
| 31 | + try! eventLoopGroup.syncShutdownGracefully() |
| 32 | + } |
| 33 | + let eventLoop = eventLoopGroup.next() |
| 34 | + |
| 35 | + let initContext = LambdaInitializationContext.__forTestsOnly( |
| 36 | + logger: logger, |
| 37 | + eventLoop: eventLoop |
| 38 | + ) |
| 39 | + |
| 40 | + let context = LambdaContext.__forTestsOnly( |
| 41 | + requestID: config.requestID, |
| 42 | + traceID: config.traceID, |
| 43 | + invokedFunctionARN: config.invokedFunctionARN, |
| 44 | + timeout: config.timeout, |
| 45 | + logger: logger, |
| 46 | + eventLoop: eventLoop |
| 47 | + ) |
| 48 | + let handler = try await Handler(context: initContext) |
| 49 | + defer { |
| 50 | + let eventLoop = initContext.eventLoop.next() |
| 51 | + try? initContext.terminator.terminate(eventLoop: eventLoop).wait() |
| 52 | + } |
| 53 | + return try await handler.handle(event, context: context) |
| 54 | + } |
| 55 | +} |
0 commit comments