diff --git a/.swiftformat b/.swiftformat index 864dbb8d..ffccb206 100644 --- a/.swiftformat +++ b/.swiftformat @@ -1,6 +1,6 @@ # file options ---swiftversion 5.1 +--swiftversion 5.0 --exclude .build # format options diff --git a/Package.swift b/Package.swift index 0e5823f6..ab076990 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.2 +// swift-tools-version:5.0 import PackageDescription @@ -36,7 +36,6 @@ let package = Package( .product(name: "NIOFoundationCompat", package: "swift-nio"), ]), .testTarget(name: "AWSLambdaRuntimeTests", dependencies: [ - .byName(name: "AWSLambdaRuntimeCore"), .byName(name: "AWSLambdaRuntime"), ]), .target(name: "AWSLambdaEvents", dependencies: []), diff --git a/Sources/AWSLambdaEvents/AWSRegion.swift b/Sources/AWSLambdaEvents/AWSRegion.swift index e884d3a6..dcb7a166 100644 --- a/Sources/AWSLambdaEvents/AWSRegion.swift +++ b/Sources/AWSLambdaEvents/AWSRegion.swift @@ -26,56 +26,56 @@ public struct AWSRegion: RawRepresentable, Equatable { } static var all: [AWSRegion] = [ - Self.ap_northeast_1, - Self.ap_northeast_2, - Self.ap_east_1, - Self.ap_southeast_1, - Self.ap_southeast_2, - Self.ap_south_1, - Self.cn_north_1, - Self.cn_northwest_1, - Self.eu_north_1, - Self.eu_west_1, - Self.eu_west_2, - Self.eu_west_3, - Self.eu_central_1, - Self.us_east_1, - Self.us_east_2, - Self.us_west_1, - Self.us_west_2, - Self.us_gov_east_1, - Self.us_gov_west_1, - Self.ca_central_1, - Self.sa_east_1, - Self.me_south_1, + AWSRegion.ap_northeast_1, + AWSRegion.ap_northeast_2, + AWSRegion.ap_east_1, + AWSRegion.ap_southeast_1, + AWSRegion.ap_southeast_2, + AWSRegion.ap_south_1, + AWSRegion.cn_north_1, + AWSRegion.cn_northwest_1, + AWSRegion.eu_north_1, + AWSRegion.eu_west_1, + AWSRegion.eu_west_2, + AWSRegion.eu_west_3, + AWSRegion.eu_central_1, + AWSRegion.us_east_1, + AWSRegion.us_east_2, + AWSRegion.us_west_1, + AWSRegion.us_west_2, + AWSRegion.us_gov_east_1, + AWSRegion.us_gov_west_1, + AWSRegion.ca_central_1, + AWSRegion.sa_east_1, + AWSRegion.me_south_1, ] - public static var ap_northeast_1: Self { AWSRegion(rawValue: "ap-northeast-1")! } - public static var ap_northeast_2: Self { AWSRegion(rawValue: "ap-northeast-2")! } - public static var ap_east_1: Self { AWSRegion(rawValue: "ap-east-1")! } - public static var ap_southeast_1: Self { AWSRegion(rawValue: "ap-southeast-1")! } - public static var ap_southeast_2: Self { AWSRegion(rawValue: "ap-southeast-2")! } - public static var ap_south_1: Self { AWSRegion(rawValue: "ap-south-1")! } + public static var ap_northeast_1: AWSRegion { return AWSRegion(rawValue: "ap-northeast-1")! } + public static var ap_northeast_2: AWSRegion { return AWSRegion(rawValue: "ap-northeast-2")! } + public static var ap_east_1: AWSRegion { return AWSRegion(rawValue: "ap-east-1")! } + public static var ap_southeast_1: AWSRegion { return AWSRegion(rawValue: "ap-southeast-1")! } + public static var ap_southeast_2: AWSRegion { return AWSRegion(rawValue: "ap-southeast-2")! } + public static var ap_south_1: AWSRegion { return AWSRegion(rawValue: "ap-south-1")! } - public static var cn_north_1: Self { AWSRegion(rawValue: "cn-north-1")! } - public static var cn_northwest_1: Self { AWSRegion(rawValue: "cn-northwest-1")! } + public static var cn_north_1: AWSRegion { return AWSRegion(rawValue: "cn-north-1")! } + public static var cn_northwest_1: AWSRegion { return AWSRegion(rawValue: "cn-northwest-1")! } - public static var eu_north_1: Self { AWSRegion(rawValue: "eu-north-1")! } - public static var eu_west_1: Self { AWSRegion(rawValue: "eu-west-1")! } - public static var eu_west_2: Self { AWSRegion(rawValue: "eu-west-2")! } - public static var eu_west_3: Self { AWSRegion(rawValue: "eu-west-3")! } - public static var eu_central_1: Self { AWSRegion(rawValue: "eu-central-1")! } + public static var eu_north_1: AWSRegion { return AWSRegion(rawValue: "eu-north-1")! } + public static var eu_west_1: AWSRegion { return AWSRegion(rawValue: "eu-west-1")! } + public static var eu_west_2: AWSRegion { return AWSRegion(rawValue: "eu-west-2")! } + public static var eu_west_3: AWSRegion { return AWSRegion(rawValue: "eu-west-3")! } + public static var eu_central_1: AWSRegion { return AWSRegion(rawValue: "eu-central-1")! } - public static var us_east_1: Self { AWSRegion(rawValue: "us-east-1")! } - public static var us_east_2: Self { AWSRegion(rawValue: "us-east-2")! } - public static var us_west_1: Self { AWSRegion(rawValue: "us-west-1")! } - public static var us_west_2: Self { AWSRegion(rawValue: "us-west-2")! } - public static var us_gov_east_1: Self { AWSRegion(rawValue: "us-gov-east-1")! } - public static var us_gov_west_1: Self { AWSRegion(rawValue: "us-gov-west-1")! } + public static var us_east_1: AWSRegion { return AWSRegion(rawValue: "us-east-1")! } + public static var us_east_2: AWSRegion { return AWSRegion(rawValue: "us-east-2")! } + public static var us_west_1: AWSRegion { return AWSRegion(rawValue: "us-west-1")! } + public static var us_west_2: AWSRegion { return AWSRegion(rawValue: "us-west-2")! } + public static var us_gov_east_1: AWSRegion { return AWSRegion(rawValue: "us-gov-east-1")! } + public static var us_gov_west_1: AWSRegion { return AWSRegion(rawValue: "us-gov-west-1")! } - public static var ca_central_1: Self { AWSRegion(rawValue: "ca-central-1")! } - public static var sa_east_1: Self { AWSRegion(rawValue: "sa-east-1")! } - public static var me_south_1: Self { AWSRegion(rawValue: "me-south-1")! } + public static var ca_central_1: AWSRegion { return AWSRegion(rawValue: "ca-central-1")! } + public static var sa_east_1: AWSRegion { return AWSRegion(rawValue: "sa-east-1")! } + public static var me_south_1: AWSRegion { return AWSRegion(rawValue: "me-south-1")! } } extension AWSRegion: Codable { diff --git a/Sources/AWSLambdaEvents/Cloudwatch.swift b/Sources/AWSLambdaEvents/Cloudwatch.swift index 3ef3eb9e..2da263bb 100644 --- a/Sources/AWSLambdaEvents/Cloudwatch.swift +++ b/Sources/AWSLambdaEvents/Cloudwatch.swift @@ -18,12 +18,12 @@ import struct Foundation.Date typealias EventBridge = Cloudwatch public protocol CloudwatchDetail: Decodable { - static var name: String { get } + static var typeName: String { get } } public extension CloudwatchDetail { var detailType: String { - Self.name + return Self.typeName } } @@ -65,7 +65,7 @@ public enum Cloudwatch { self.resources = try container.decode([String].self, forKey: .resources) let detailType = try container.decode(String.self, forKey: .detailType) - guard detailType.lowercased() == Detail.name.lowercased() else { + guard detailType.lowercased() == Detail.typeName.lowercased() else { throw DetailTypeMismatch(name: detailType, type: Detail.self) } @@ -77,13 +77,13 @@ public enum Cloudwatch { public typealias ScheduledEvent = Event public struct Scheduled: CloudwatchDetail { - public static let name = "Scheduled Event" + public static let typeName = "Scheduled Event" } public enum EC2 { public typealias InstanceStateChangeNotificationEvent = Event public struct InstanceStateChangeNotification: CloudwatchDetail { - public static let name = "EC2 Instance State-change Notification" + public static let typeName = "EC2 Instance State-change Notification" public enum State: String, Codable { case running @@ -104,7 +104,7 @@ public enum Cloudwatch { public typealias SpotInstanceInterruptionNoticeEvent = Event public struct SpotInstanceInterruptionNotice: CloudwatchDetail { - public static let name = "EC2 Spot Instance Interruption Warning" + public static let typeName = "EC2 Spot Instance Interruption Warning" public enum Action: String, Codable { case hibernate diff --git a/Sources/AWSLambdaEvents/DynamoDB.swift b/Sources/AWSLambdaEvents/DynamoDB.swift index ebc9f645..63a63a3f 100644 --- a/Sources/AWSLambdaEvents/DynamoDB.swift +++ b/Sources/AWSLambdaEvents/DynamoDB.swift @@ -274,7 +274,7 @@ extension DynamoDB.AttributeValue: Decodable { } extension DynamoDB.AttributeValue: Equatable { - public static func == (lhs: Self, rhs: Self) -> Bool { + public static func == (lhs: DynamoDB.AttributeValue, rhs: DynamoDB.AttributeValue) -> Bool { switch (lhs, rhs) { case (.boolean(let lhs), .boolean(let rhs)): return lhs == rhs @@ -313,7 +313,7 @@ extension DynamoDB { @inlinable public func decode(_ type: T.Type, from image: [String: AttributeValue]) throws -> T { - try self.decode(type, from: .map(image)) + return try self.decode(type, from: .map(image)) } @inlinable public func decode(_ type: T.Type, from value: AttributeValue) @@ -337,7 +337,7 @@ extension DynamoDB { } @inlinable public func decode(_: T.Type) throws -> T { - try T(from: self) + return try T(from: self) } @usableFromInline func container(keyedBy type: Key.Type) throws -> @@ -373,7 +373,7 @@ extension DynamoDB { } @usableFromInline func singleValueContainer() throws -> SingleValueDecodingContainer { - _SingleValueDecodingContainter( + return _SingleValueDecodingContainter( impl: self, codingPath: self.codingPath, value: self.value @@ -397,7 +397,7 @@ extension DynamoDB { var intValue: Int? var stringValue: String { - "Index \(self.intValue!)" + return "Index \(self.intValue!)" } static func == (lhs: ArrayKey, rhs: ArrayKey) -> Bool { @@ -421,7 +421,7 @@ extension DynamoDB { } var allKeys: [K] { - self.dictionary.keys.compactMap { K(stringValue: $0) } + return self.dictionary.keys.compactMap { K(stringValue: $0) } } func contains(_ key: K) -> Bool { @@ -457,51 +457,51 @@ extension DynamoDB { } func decode(_ type: Double.Type, forKey key: K) throws -> Double { - try self.decodeLosslessStringConvertible(key: key) + return try self.decodeLosslessStringConvertible(key: key) } func decode(_ type: Float.Type, forKey key: K) throws -> Float { - try self.decodeLosslessStringConvertible(key: key) + return try self.decodeLosslessStringConvertible(key: key) } func decode(_ type: Int.Type, forKey key: K) throws -> Int { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: UInt.Type, forKey key: K) throws -> UInt { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 { - try self.decodeFixedWidthInteger(key: key) + return try self.decodeFixedWidthInteger(key: key) } func decode(_ type: T.Type, forKey key: K) throws -> T where T: Decodable { @@ -515,15 +515,15 @@ extension DynamoDB { } func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer { - try self.decoderForKey(key).unkeyedContainer() + return try self.decoderForKey(key).unkeyedContainer() } func superDecoder() throws -> Swift.Decoder { - self.impl + return self.impl } func superDecoder(forKey key: K) throws -> Swift.Decoder { - self.impl + return self.impl } private func decoderForKey(_ key: K) throws -> _DecoderImpl { @@ -556,7 +556,7 @@ extension DynamoDB { )) } - @inline(__always) private func decodeFixedWidthInteger(key: Self.Key) + @inline(__always) private func decodeFixedWidthInteger(key: _KeyedDecodingContainer.Key) throws -> T { let value = try getValue(forKey: key) @@ -577,7 +577,7 @@ extension DynamoDB { } @inline(__always) private func decodeLosslessStringConvertible( - key: Self.Key) throws -> T + key: _KeyedDecodingContainer.Key) throws -> T { let value = try getValue(forKey: key) @@ -609,7 +609,7 @@ extension DynamoDB { } func decodeNil() -> Bool { - self.value == .null + return self.value == .null } func decode(_: Bool.Type) throws -> Bool { @@ -629,51 +629,51 @@ extension DynamoDB { } func decode(_: Double.Type) throws -> Double { - try self.decodeLosslessStringConvertible() + return try self.decodeLosslessStringConvertible() } func decode(_: Float.Type) throws -> Float { - try self.decodeLosslessStringConvertible() + return try self.decodeLosslessStringConvertible() } func decode(_: Int.Type) throws -> Int { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: Int8.Type) throws -> Int8 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: Int16.Type) throws -> Int16 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: Int32.Type) throws -> Int32 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: Int64.Type) throws -> Int64 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: UInt.Type) throws -> UInt { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: UInt8.Type) throws -> UInt8 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: UInt16.Type) throws -> UInt16 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: UInt32.Type) throws -> UInt32 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: UInt64.Type) throws -> UInt64 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } func decode(_: T.Type) throws -> T where T: Decodable { @@ -681,7 +681,7 @@ extension DynamoDB { } @inline(__always) private func createTypeMismatchError(type: Any.Type, value: AttributeValue) -> DecodingError { - DecodingError.typeMismatch(type, .init( + return DecodingError.typeMismatch(type, .init( codingPath: self.codingPath, debugDescription: "Expected to decode \(type) but found \(value.debugDataTypeDescription) instead." )) @@ -785,51 +785,51 @@ extension DynamoDB { } mutating func decode(_: Double.Type) throws -> Double { - try self.decodeLosslessStringConvertible() + return try self.decodeLosslessStringConvertible() } mutating func decode(_: Float.Type) throws -> Float { - try self.decodeLosslessStringConvertible() + return try self.decodeLosslessStringConvertible() } mutating func decode(_: Int.Type) throws -> Int { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: Int8.Type) throws -> Int8 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: Int16.Type) throws -> Int16 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: Int32.Type) throws -> Int32 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: Int64.Type) throws -> Int64 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: UInt.Type) throws -> UInt { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: UInt8.Type) throws -> UInt8 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: UInt16.Type) throws -> UInt16 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: UInt32.Type) throws -> UInt32 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: UInt64.Type) throws -> UInt64 { - try self.decodeFixedWidthInteger() + return try self.decodeFixedWidthInteger() } mutating func decode(_: T.Type) throws -> T where T: Decodable { @@ -854,11 +854,11 @@ extension DynamoDB { } mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { - try self.impl.unkeyedContainer() + return try self.impl.unkeyedContainer() } mutating func superDecoder() throws -> Swift.Decoder { - self.impl + return self.impl } @inline(__always) private func createTypeMismatchError(type: Any.Type, value: AttributeValue) -> DecodingError { diff --git a/Sources/AWSLambdaEvents/S3.swift b/Sources/AWSLambdaEvents/S3.swift index 0e7add28..05f30f26 100644 --- a/Sources/AWSLambdaEvents/S3.swift +++ b/Sources/AWSLambdaEvents/S3.swift @@ -22,14 +22,30 @@ public enum S3 { public let eventVersion: String public let eventSource: String public let awsRegion: AWSRegion + // @ISO8601WithFractionalSecondsCoding + private var _eventTime: ISO8601WithFractionalSecondsCoding + public var eventTime: Date { + get { return self._eventTime.wrappedValue } + set { self._eventTime = ISO8601WithFractionalSecondsCoding(wrappedValue: newValue) } + } - @ISO8601WithFractionalSecondsCoding - public var eventTime: Date public let eventName: String public let userIdentity: UserIdentity public let requestParameters: RequestParameters public let responseElements: [String: String] public let s3: Entity + + public enum CodingKeys: String, CodingKey { + case eventVersion + case eventSource + case awsRegion + case _eventTime = "eventTime" + case eventName + case userIdentity + case requestParameters + case responseElements + case s3 + } } public let records: [Record] diff --git a/Sources/AWSLambdaEvents/SES.swift b/Sources/AWSLambdaEvents/SES.swift index 4c5b3719..6d6ee80a 100644 --- a/Sources/AWSLambdaEvents/SES.swift +++ b/Sources/AWSLambdaEvents/SES.swift @@ -43,18 +43,50 @@ public enum SES { public let headersTruncated: Bool public let messageId: String public let source: String - @ISO8601WithFractionalSecondsCoding public var timestamp: Date + // @ISO8601WithFractionalSecondsCoding + private var _timestamp: ISO8601WithFractionalSecondsCoding + public var timestamp: Date { + get { return self._timestamp.wrappedValue } + set { self._timestamp = ISO8601WithFractionalSecondsCoding(wrappedValue: newValue) } + } + + public enum CodingKeys: String, CodingKey { + case commonHeaders + case destination + case headers + case headersTruncated + case messageId + case source + case _timestamp = "timestamp" + } } public struct CommonHeaders: Decodable { public let bcc: [String]? public let cc: [String]? - @RFC5322DateTimeCoding public var date: Date + // @RFC5322DateTimeCoding + private var _date: RFC5322DateTimeCoding + public var date: Date { + get { return self._date.wrappedValue } + set { self._date = RFC5322DateTimeCoding(wrappedValue: newValue) } + } + public let from: [String] public let messageId: String public let returnPath: String? public let subject: String? public let to: [String]? + + public enum CodingKeys: String, CodingKey { + case bcc + case cc + case _date = "date" + case from + case messageId + case returnPath + case subject + case to + } } public struct Header: Decodable { @@ -71,8 +103,27 @@ public enum SES { public let recipients: [String] public let spamVerdict: Verdict public let spfVerdict: Verdict - @ISO8601WithFractionalSecondsCoding public var timestamp: Date + // @ISO8601WithFractionalSecondsCoding + private var _timestamp: ISO8601WithFractionalSecondsCoding + public var timestamp: Date { + get { return self._timestamp.wrappedValue } + set { self._timestamp = ISO8601WithFractionalSecondsCoding(wrappedValue: newValue) } + } + public let virusVerdict: Verdict + + public enum CodingKeys: String, CodingKey { + case action + case dmarcPolicy + case dmarcVerdict + case dkimVerdict + case processingTimeMillis + case recipients + case spamVerdict + case spfVerdict + case _timestamp = "timestamp" + case virusVerdict + } } public struct Action: Decodable { diff --git a/Sources/AWSLambdaEvents/SNS.swift b/Sources/AWSLambdaEvents/SNS.swift index 9db4c8f4..4e7b0f2b 100644 --- a/Sources/AWSLambdaEvents/SNS.swift +++ b/Sources/AWSLambdaEvents/SNS.swift @@ -51,10 +51,14 @@ public enum SNS { public let topicArn: String public let messageAttributes: [String: Attribute] public let signatureVersion: String - - @ISO8601WithFractionalSecondsCoding - public var timestamp: Date public let signingCertURL: String + // @ISO8601WithFractionalSecondsCoding + private var _timestamp: ISO8601WithFractionalSecondsCoding + public var timestamp: Date { + get { return self._timestamp.wrappedValue } + set { self._timestamp = ISO8601WithFractionalSecondsCoding(wrappedValue: newValue) } + } + public let message: String public let unsubscribeUrl: String public let subject: String? @@ -69,7 +73,7 @@ extension SNS.Message: Decodable { case topicArn = "TopicArn" case messageAttributes = "MessageAttributes" case signatureVersion = "SignatureVersion" - case timestamp = "Timestamp" + case _timestamp = "Timestamp" case signingCertURL = "SigningCertUrl" case message = "Message" case unsubscribeUrl = "UnsubscribeUrl" diff --git a/Sources/AWSLambdaEvents/Utils/Base64.swift b/Sources/AWSLambdaEvents/Utils/Base64.swift index 310a6aa5..c1e521da 100644 --- a/Sources/AWSLambdaEvents/Utils/Base64.swift +++ b/Sources/AWSLambdaEvents/Utils/Base64.swift @@ -214,6 +214,6 @@ extension String { func base64decoded(options: Base64.DecodingOptions = []) throws -> [UInt8] { // In Base64, 3 bytes become 4 output characters, and we pad to the nearest multiple // of four. - try Base64.decode(encoded: self, options: options) + return try Base64.decode(encoded: self, options: options) } } diff --git a/Sources/AWSLambdaEvents/Utils/DateWrappers.swift b/Sources/AWSLambdaEvents/Utils/DateWrappers.swift index 3b7fc481..2d2e859c 100644 --- a/Sources/AWSLambdaEvents/Utils/DateWrappers.swift +++ b/Sources/AWSLambdaEvents/Utils/DateWrappers.swift @@ -17,7 +17,7 @@ import class Foundation.DateFormatter import struct Foundation.Locale import struct Foundation.TimeZone -@propertyWrapper +// @propertyWrapper public struct ISO8601Coding: Decodable { public let wrappedValue: Date @@ -28,14 +28,14 @@ public struct ISO8601Coding: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let dateString = try container.decode(String.self) - guard let date = Self.dateFormatter.date(from: dateString) else { + guard let date = ISO8601Coding.dateFormatter.date(from: dateString) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected date to be in ISO8601 date format, but `\(dateString)` is not in the correct format") } self.wrappedValue = date } - private static let dateFormatter: DateFormatter = Self.createDateFormatter() + private static let dateFormatter: DateFormatter = ISO8601Coding.createDateFormatter() private static func createDateFormatter() -> DateFormatter { let formatter = DateFormatter() @@ -46,7 +46,7 @@ public struct ISO8601Coding: Decodable { } } -@propertyWrapper +// @propertyWrapper public struct ISO8601WithFractionalSecondsCoding: Decodable { public let wrappedValue: Date @@ -57,14 +57,14 @@ public struct ISO8601WithFractionalSecondsCoding: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let dateString = try container.decode(String.self) - guard let date = Self.dateFormatter.date(from: dateString) else { + guard let date = ISO8601WithFractionalSecondsCoding.dateFormatter.date(from: dateString) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected date to be in ISO8601 date format with fractional seconds, but `\(dateString)` is not in the correct format") } self.wrappedValue = date } - private static let dateFormatter: DateFormatter = Self.createDateFormatter() + private static let dateFormatter: DateFormatter = ISO8601WithFractionalSecondsCoding.createDateFormatter() private static func createDateFormatter() -> DateFormatter { let formatter = DateFormatter() @@ -75,7 +75,7 @@ public struct ISO8601WithFractionalSecondsCoding: Decodable { } } -@propertyWrapper +// @propertyWrapper public struct RFC5322DateTimeCoding: Decodable { public let wrappedValue: Date @@ -91,14 +91,14 @@ public struct RFC5322DateTimeCoding: Decodable { if let bracket = string.firstIndex(of: "(") { string = String(string[string.startIndex ..< bracket].trimmingCharacters(in: .whitespaces)) } - guard let date = Self.dateFormatter.date(from: string) else { + guard let date = RFC5322DateTimeCoding.dateFormatter.date(from: string) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected date to be in RFC5322 date-time format with fractional seconds, but `\(string)` is not in the correct format") } self.wrappedValue = date } - private static let dateFormatter: DateFormatter = Self.createDateFormatter() + private static let dateFormatter: DateFormatter = RFC5322DateTimeCoding.createDateFormatter() private static func createDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "EEE, d MMM yyy HH:mm:ss z" diff --git a/Sources/AWSLambdaEvents/Utils/HTTP.swift b/Sources/AWSLambdaEvents/Utils/HTTP.swift index 9e0d8f2d..cf0bc116 100644 --- a/Sources/AWSLambdaEvents/Utils/HTTP.swift +++ b/Sources/AWSLambdaEvents/Utils/HTTP.swift @@ -27,15 +27,15 @@ public struct HTTPMethod: RawRepresentable, Equatable { self.rawValue = rawValue } - public static var GET: HTTPMethod { HTTPMethod(rawValue: "GET")! } - public static var POST: HTTPMethod { HTTPMethod(rawValue: "POST")! } - public static var PUT: HTTPMethod { HTTPMethod(rawValue: "PUT")! } - public static var PATCH: HTTPMethod { HTTPMethod(rawValue: "PATCH")! } - public static var DELETE: HTTPMethod { HTTPMethod(rawValue: "DELETE")! } - public static var OPTIONS: HTTPMethod { HTTPMethod(rawValue: "OPTIONS")! } - public static var HEAD: HTTPMethod { HTTPMethod(rawValue: "HEAD")! } - - public static func RAW(value: String) -> HTTPMethod? { HTTPMethod(rawValue: value) } + public static var GET: HTTPMethod { return HTTPMethod(rawValue: "GET")! } + public static var POST: HTTPMethod { return HTTPMethod(rawValue: "POST")! } + public static var PUT: HTTPMethod { return HTTPMethod(rawValue: "PUT")! } + public static var PATCH: HTTPMethod { return HTTPMethod(rawValue: "PATCH")! } + public static var DELETE: HTTPMethod { return HTTPMethod(rawValue: "DELETE")! } + public static var OPTIONS: HTTPMethod { return HTTPMethod(rawValue: "OPTIONS")! } + public static var HEAD: HTTPMethod { return HTTPMethod(rawValue: "HEAD")! } + + public static func RAW(value: String) -> HTTPMethod? { return HTTPMethod(rawValue: value) } } extension HTTPMethod: Codable { @@ -70,76 +70,76 @@ public struct HTTPResponseStatus { self.reasonPhrase = reasonPhrase } - public static var `continue`: HTTPResponseStatus { HTTPResponseStatus(code: 100) } - public static var switchingProtocols: HTTPResponseStatus { HTTPResponseStatus(code: 101) } - public static var processing: HTTPResponseStatus { HTTPResponseStatus(code: 102) } - public static var earlyHints: HTTPResponseStatus { HTTPResponseStatus(code: 103) } - - public static var ok: HTTPResponseStatus { HTTPResponseStatus(code: 200) } - public static var created: HTTPResponseStatus { HTTPResponseStatus(code: 201) } - public static var accepted: HTTPResponseStatus { HTTPResponseStatus(code: 202) } - public static var nonAuthoritativeInformation: HTTPResponseStatus { HTTPResponseStatus(code: 203) } - public static var noContent: HTTPResponseStatus { HTTPResponseStatus(code: 204) } - public static var resetContent: HTTPResponseStatus { HTTPResponseStatus(code: 205) } - public static var partialContent: HTTPResponseStatus { HTTPResponseStatus(code: 206) } - public static var multiStatus: HTTPResponseStatus { HTTPResponseStatus(code: 207) } - public static var alreadyReported: HTTPResponseStatus { HTTPResponseStatus(code: 208) } - public static var imUsed: HTTPResponseStatus { HTTPResponseStatus(code: 226) } - - public static var multipleChoices: HTTPResponseStatus { HTTPResponseStatus(code: 300) } - public static var movedPermanently: HTTPResponseStatus { HTTPResponseStatus(code: 301) } - public static var found: HTTPResponseStatus { HTTPResponseStatus(code: 302) } - public static var seeOther: HTTPResponseStatus { HTTPResponseStatus(code: 303) } - public static var notModified: HTTPResponseStatus { HTTPResponseStatus(code: 304) } - public static var useProxy: HTTPResponseStatus { HTTPResponseStatus(code: 305) } - public static var temporaryRedirect: HTTPResponseStatus { HTTPResponseStatus(code: 307) } - public static var permanentRedirect: HTTPResponseStatus { HTTPResponseStatus(code: 308) } - - public static var badRequest: HTTPResponseStatus { HTTPResponseStatus(code: 400) } - public static var unauthorized: HTTPResponseStatus { HTTPResponseStatus(code: 401) } - public static var paymentRequired: HTTPResponseStatus { HTTPResponseStatus(code: 402) } - public static var forbidden: HTTPResponseStatus { HTTPResponseStatus(code: 403) } - public static var notFound: HTTPResponseStatus { HTTPResponseStatus(code: 404) } - public static var methodNotAllowed: HTTPResponseStatus { HTTPResponseStatus(code: 405) } - public static var notAcceptable: HTTPResponseStatus { HTTPResponseStatus(code: 406) } - public static var proxyAuthenticationRequired: HTTPResponseStatus { HTTPResponseStatus(code: 407) } - public static var requestTimeout: HTTPResponseStatus { HTTPResponseStatus(code: 408) } - public static var conflict: HTTPResponseStatus { HTTPResponseStatus(code: 409) } - public static var gone: HTTPResponseStatus { HTTPResponseStatus(code: 410) } - public static var lengthRequired: HTTPResponseStatus { HTTPResponseStatus(code: 411) } - public static var preconditionFailed: HTTPResponseStatus { HTTPResponseStatus(code: 412) } - public static var payloadTooLarge: HTTPResponseStatus { HTTPResponseStatus(code: 413) } - public static var uriTooLong: HTTPResponseStatus { HTTPResponseStatus(code: 414) } - public static var unsupportedMediaType: HTTPResponseStatus { HTTPResponseStatus(code: 415) } - public static var rangeNotSatisfiable: HTTPResponseStatus { HTTPResponseStatus(code: 416) } - public static var expectationFailed: HTTPResponseStatus { HTTPResponseStatus(code: 417) } - public static var imATeapot: HTTPResponseStatus { HTTPResponseStatus(code: 418) } - public static var misdirectedRequest: HTTPResponseStatus { HTTPResponseStatus(code: 421) } - public static var unprocessableEntity: HTTPResponseStatus { HTTPResponseStatus(code: 422) } - public static var locked: HTTPResponseStatus { HTTPResponseStatus(code: 423) } - public static var failedDependency: HTTPResponseStatus { HTTPResponseStatus(code: 424) } - public static var upgradeRequired: HTTPResponseStatus { HTTPResponseStatus(code: 426) } - public static var preconditionRequired: HTTPResponseStatus { HTTPResponseStatus(code: 428) } - public static var tooManyRequests: HTTPResponseStatus { HTTPResponseStatus(code: 429) } - public static var requestHeaderFieldsTooLarge: HTTPResponseStatus { HTTPResponseStatus(code: 431) } - public static var unavailableForLegalReasons: HTTPResponseStatus { HTTPResponseStatus(code: 451) } - - public static var internalServerError: HTTPResponseStatus { HTTPResponseStatus(code: 500) } - public static var notImplemented: HTTPResponseStatus { HTTPResponseStatus(code: 501) } - public static var badGateway: HTTPResponseStatus { HTTPResponseStatus(code: 502) } - public static var serviceUnavailable: HTTPResponseStatus { HTTPResponseStatus(code: 503) } - public static var gatewayTimeout: HTTPResponseStatus { HTTPResponseStatus(code: 504) } - public static var httpVersionNotSupported: HTTPResponseStatus { HTTPResponseStatus(code: 505) } - public static var variantAlsoNegotiates: HTTPResponseStatus { HTTPResponseStatus(code: 506) } - public static var insufficientStorage: HTTPResponseStatus { HTTPResponseStatus(code: 507) } - public static var loopDetected: HTTPResponseStatus { HTTPResponseStatus(code: 508) } - public static var notExtended: HTTPResponseStatus { HTTPResponseStatus(code: 510) } - public static var networkAuthenticationRequired: HTTPResponseStatus { HTTPResponseStatus(code: 511) } + public static var `continue`: HTTPResponseStatus { return HTTPResponseStatus(code: 100) } + public static var switchingProtocols: HTTPResponseStatus { return HTTPResponseStatus(code: 101) } + public static var processing: HTTPResponseStatus { return HTTPResponseStatus(code: 102) } + public static var earlyHints: HTTPResponseStatus { return HTTPResponseStatus(code: 103) } + + public static var ok: HTTPResponseStatus { return HTTPResponseStatus(code: 200) } + public static var created: HTTPResponseStatus { return HTTPResponseStatus(code: 201) } + public static var accepted: HTTPResponseStatus { return HTTPResponseStatus(code: 202) } + public static var nonAuthoritativeInformation: HTTPResponseStatus { return HTTPResponseStatus(code: 203) } + public static var noContent: HTTPResponseStatus { return HTTPResponseStatus(code: 204) } + public static var resetContent: HTTPResponseStatus { return HTTPResponseStatus(code: 205) } + public static var partialContent: HTTPResponseStatus { return HTTPResponseStatus(code: 206) } + public static var multiStatus: HTTPResponseStatus { return HTTPResponseStatus(code: 207) } + public static var alreadyReported: HTTPResponseStatus { return HTTPResponseStatus(code: 208) } + public static var imUsed: HTTPResponseStatus { return HTTPResponseStatus(code: 226) } + + public static var multipleChoices: HTTPResponseStatus { return HTTPResponseStatus(code: 300) } + public static var movedPermanently: HTTPResponseStatus { return HTTPResponseStatus(code: 301) } + public static var found: HTTPResponseStatus { return HTTPResponseStatus(code: 302) } + public static var seeOther: HTTPResponseStatus { return HTTPResponseStatus(code: 303) } + public static var notModified: HTTPResponseStatus { return HTTPResponseStatus(code: 304) } + public static var useProxy: HTTPResponseStatus { return HTTPResponseStatus(code: 305) } + public static var temporaryRedirect: HTTPResponseStatus { return HTTPResponseStatus(code: 307) } + public static var permanentRedirect: HTTPResponseStatus { return HTTPResponseStatus(code: 308) } + + public static var badRequest: HTTPResponseStatus { return HTTPResponseStatus(code: 400) } + public static var unauthorized: HTTPResponseStatus { return HTTPResponseStatus(code: 401) } + public static var paymentRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 402) } + public static var forbidden: HTTPResponseStatus { return HTTPResponseStatus(code: 403) } + public static var notFound: HTTPResponseStatus { return HTTPResponseStatus(code: 404) } + public static var methodNotAllowed: HTTPResponseStatus { return HTTPResponseStatus(code: 405) } + public static var notAcceptable: HTTPResponseStatus { return HTTPResponseStatus(code: 406) } + public static var proxyAuthenticationRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 407) } + public static var requestTimeout: HTTPResponseStatus { return HTTPResponseStatus(code: 408) } + public static var conflict: HTTPResponseStatus { return HTTPResponseStatus(code: 409) } + public static var gone: HTTPResponseStatus { return HTTPResponseStatus(code: 410) } + public static var lengthRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 411) } + public static var preconditionFailed: HTTPResponseStatus { return HTTPResponseStatus(code: 412) } + public static var payloadTooLarge: HTTPResponseStatus { return HTTPResponseStatus(code: 413) } + public static var uriTooLong: HTTPResponseStatus { return HTTPResponseStatus(code: 414) } + public static var unsupportedMediaType: HTTPResponseStatus { return HTTPResponseStatus(code: 415) } + public static var rangeNotSatisfiable: HTTPResponseStatus { return HTTPResponseStatus(code: 416) } + public static var expectationFailed: HTTPResponseStatus { return HTTPResponseStatus(code: 417) } + public static var imATeapot: HTTPResponseStatus { return HTTPResponseStatus(code: 418) } + public static var misdirectedRequest: HTTPResponseStatus { return HTTPResponseStatus(code: 421) } + public static var unprocessableEntity: HTTPResponseStatus { return HTTPResponseStatus(code: 422) } + public static var locked: HTTPResponseStatus { return HTTPResponseStatus(code: 423) } + public static var failedDependency: HTTPResponseStatus { return HTTPResponseStatus(code: 424) } + public static var upgradeRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 426) } + public static var preconditionRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 428) } + public static var tooManyRequests: HTTPResponseStatus { return HTTPResponseStatus(code: 429) } + public static var requestHeaderFieldsTooLarge: HTTPResponseStatus { return HTTPResponseStatus(code: 431) } + public static var unavailableForLegalReasons: HTTPResponseStatus { return HTTPResponseStatus(code: 451) } + + public static var internalServerError: HTTPResponseStatus { return HTTPResponseStatus(code: 500) } + public static var notImplemented: HTTPResponseStatus { return HTTPResponseStatus(code: 501) } + public static var badGateway: HTTPResponseStatus { return HTTPResponseStatus(code: 502) } + public static var serviceUnavailable: HTTPResponseStatus { return HTTPResponseStatus(code: 503) } + public static var gatewayTimeout: HTTPResponseStatus { return HTTPResponseStatus(code: 504) } + public static var httpVersionNotSupported: HTTPResponseStatus { return HTTPResponseStatus(code: 505) } + public static var variantAlsoNegotiates: HTTPResponseStatus { return HTTPResponseStatus(code: 506) } + public static var insufficientStorage: HTTPResponseStatus { return HTTPResponseStatus(code: 507) } + public static var loopDetected: HTTPResponseStatus { return HTTPResponseStatus(code: 508) } + public static var notExtended: HTTPResponseStatus { return HTTPResponseStatus(code: 510) } + public static var networkAuthenticationRequired: HTTPResponseStatus { return HTTPResponseStatus(code: 511) } } extension HTTPResponseStatus: Equatable { - public static func == (lhs: Self, rhs: Self) -> Bool { - lhs.code == rhs.code + public static func == (lhs: HTTPResponseStatus, rhs: HTTPResponseStatus) -> Bool { + return lhs.code == rhs.code } } @@ -158,7 +158,7 @@ extension HTTPResponseStatus: Codable { extension String { internal var isValidHTTPToken: Bool { - self.utf8.allSatisfy { (char) -> Bool in + return self.utf8.allSatisfy { (char) -> Bool in switch char { case UInt8(ascii: "a") ... UInt8(ascii: "z"), UInt8(ascii: "A") ... UInt8(ascii: "Z"), diff --git a/Sources/AWSLambdaRuntime/Lambda+Codable.swift b/Sources/AWSLambdaRuntime/Lambda+Codable.swift index 495e5a69..65856019 100644 --- a/Sources/AWSLambdaRuntime/Lambda+Codable.swift +++ b/Sources/AWSLambdaRuntime/Lambda+Codable.swift @@ -81,14 +81,14 @@ internal struct CodableVoidClosureWrapper: LambdaHandler { /// Implementation of a`ByteBuffer` to `In` decoding public extension EventLoopLambdaHandler where In: Decodable { func decode(buffer: ByteBuffer) throws -> In { - try self.decoder.decode(In.self, from: buffer) + return try self.decoder.decode(In.self, from: buffer) } } /// Implementation of `Out` to `ByteBuffer` encoding public extension EventLoopLambdaHandler where Out: Encodable { func encode(allocator: ByteBufferAllocator, value: Out) throws -> ByteBuffer? { - try self.encoder.encode(value, using: allocator) + return try self.encoder.encode(value, using: allocator) } } @@ -96,7 +96,7 @@ public extension EventLoopLambdaHandler where Out: Encodable { /// Advanced users that want to inject their own codec can do it by overriding these functions. public extension EventLoopLambdaHandler where In: Decodable { var decoder: LambdaCodableDecoder { - Lambda.defaultJSONDecoder + return Lambda.defaultJSONDecoder } } @@ -104,7 +104,7 @@ public extension EventLoopLambdaHandler where In: Decodable { /// Advanced users that want to inject their own codec can do it by overriding these functions. public extension EventLoopLambdaHandler where Out: Encodable { var encoder: LambdaCodableEncoder { - Lambda.defaultJSONEncoder + return Lambda.defaultJSONEncoder } } @@ -135,13 +135,13 @@ extension JSONEncoder: LambdaCodableEncoder { extension JSONEncoder { /// Convenience method to allow encoding json directly into a `String`. It can be used to encode a payload into an `APIGateway.V2.Response`'s body. public func encodeAsString(_ value: T) throws -> String { - try String(decoding: self.encode(value), as: Unicode.UTF8.self) + return try String(decoding: self.encode(value), as: Unicode.UTF8.self) } } extension JSONDecoder { /// Convenience method to allow decoding json directly from a `String`. It can be used to decode a payload from an `APIGateway.V2.Request`'s body. public func decode(_ type: T.Type, from string: String) throws -> T { - try self.decode(type, from: Data(string.utf8)) + return try self.decode(type, from: Data(string.utf8)) } } diff --git a/Sources/AWSLambdaRuntimeCore/HTTPClient.swift b/Sources/AWSLambdaRuntimeCore/HTTPClient.swift index fcd2a450..e2e3103f 100644 --- a/Sources/AWSLambdaRuntimeCore/HTTPClient.swift +++ b/Sources/AWSLambdaRuntimeCore/HTTPClient.swift @@ -34,20 +34,20 @@ internal final class HTTPClient { } func get(url: String, headers: HTTPHeaders, timeout: TimeAmount? = nil) -> EventLoopFuture { - self.execute(Request(targetHost: self.targetHost, - url: url, - method: .GET, - headers: headers, - timeout: timeout ?? self.configuration.requestTimeout)) + return self.execute(Request(targetHost: self.targetHost, + url: url, + method: .GET, + headers: headers, + timeout: timeout ?? self.configuration.requestTimeout)) } func post(url: String, headers: HTTPHeaders, body: ByteBuffer?, timeout: TimeAmount? = nil) -> EventLoopFuture { - self.execute(Request(targetHost: self.targetHost, - url: url, - method: .POST, - headers: headers, - body: body, - timeout: timeout ?? self.configuration.requestTimeout)) + return self.execute(Request(targetHost: self.targetHost, + url: url, + method: .POST, + headers: headers, + body: body, + timeout: timeout ?? self.configuration.requestTimeout)) } /// cancels the current request if there is one diff --git a/Sources/AWSLambdaRuntimeCore/Lambda+LocalServer.swift b/Sources/AWSLambdaRuntimeCore/Lambda+LocalServer.swift index 48cea94e..a159067f 100644 --- a/Sources/AWSLambdaRuntimeCore/Lambda+LocalServer.swift +++ b/Sources/AWSLambdaRuntimeCore/Lambda+LocalServer.swift @@ -128,7 +128,7 @@ private enum LocalLambda { // this endpoint is called by the client invoking the lambda case (.POST, let url) where url.hasSuffix(self.invocationEndpoint): guard let work = request.body else { - return self.writeResponse(context: context, response: .init(status: .badRequest)) + return self.writeResponse(context: context, status: .badRequest) } let requestID = "\(DispatchTime.now().uptimeNanoseconds)" // FIXME: let promise = context.eventLoop.makePromise(of: Response.self) @@ -136,17 +136,17 @@ private enum LocalLambda { switch result { case .failure(let error): self.logger.error("invocation error: \(error)") - self.writeResponse(context: context, response: .init(status: .internalServerError)) + self.writeResponse(context: context, status: .internalServerError) case .success(let response): self.writeResponse(context: context, response: response) } } let invocation = Invocation(requestID: requestID, request: work, responsePromise: promise) - switch Self.invocationState { + switch HTTPHandler.invocationState { case .waitingForInvocation(let promise): promise.succeed(invocation) case .waitingForLambdaRequest, .waitingForLambdaResponse: - Self.invocations.append(invocation) + HTTPHandler.invocations.append(invocation) } // lambda invocation using the wrong http method @@ -156,14 +156,14 @@ private enum LocalLambda { // /next endpoint is called by the lambda polling for work case (.GET, let url) where url.hasSuffix(Consts.getNextInvocationURLSuffix): // check if our server is in the correct state - guard case .waitingForLambdaRequest = Self.invocationState else { - self.logger.error("invalid invocation state \(Self.invocationState)") - self.writeResponse(context: context, response: .init(status: .unprocessableEntity)) + guard case .waitingForLambdaRequest = HTTPHandler.invocationState else { + self.logger.error("invalid invocation state \(HTTPHandler.invocationState)") + self.writeResponse(context: context, status: .unprocessableEntity) return } // pop the first task from the queue - switch Self.invocations.popFirst() { + switch HTTPHandler.invocations.popFirst() { case .none: // if there is nothing in the queue, // create a promise that we can fullfill when we get a new task @@ -174,14 +174,14 @@ private enum LocalLambda { self.logger.error("invocation error: \(error)") self.writeResponse(context: context, status: .internalServerError) case .success(let invocation): - Self.invocationState = .waitingForLambdaResponse(invocation) + HTTPHandler.invocationState = .waitingForLambdaResponse(invocation) self.writeResponse(context: context, response: invocation.makeResponse()) } } - Self.invocationState = .waitingForInvocation(promise) + HTTPHandler.invocationState = .waitingForInvocation(promise) case .some(let invocation): // if there is a task pending, we can immediatly respond with it. - Self.invocationState = .waitingForLambdaResponse(invocation) + HTTPHandler.invocationState = .waitingForLambdaResponse(invocation) self.writeResponse(context: context, response: invocation.makeResponse()) } @@ -192,9 +192,9 @@ private enum LocalLambda { // the request is malformed, since we were expecting a requestId in the path return self.writeResponse(context: context, status: .badRequest) } - guard case .waitingForLambdaResponse(let invocation) = Self.invocationState else { + guard case .waitingForLambdaResponse(let invocation) = HTTPHandler.invocationState else { // a response was send, but we did not expect to receive one - self.logger.error("invalid invocation state \(Self.invocationState)") + self.logger.error("invalid invocation state \(HTTPHandler.invocationState)") return self.writeResponse(context: context, status: .unprocessableEntity) } guard requestID == invocation.requestID else { @@ -203,9 +203,9 @@ private enum LocalLambda { return self.writeResponse(context: context, status: .badRequest) } - invocation.responsePromise.succeed(.init(status: .ok, body: request.body)) + invocation.responsePromise.succeed(Response(status: .ok, headers: nil, body: request.body)) self.writeResponse(context: context, status: .accepted) - Self.invocationState = .waitingForLambdaRequest + HTTPHandler.invocationState = .waitingForLambdaRequest // :requestID/error endpoint is called by the lambda posting an error response case (.POST, let url) where url.hasSuffix(Consts.postErrorURLSuffix): @@ -214,9 +214,9 @@ private enum LocalLambda { // the request is malformed, since we were expecting a requestId in the path return self.writeResponse(context: context, status: .badRequest) } - guard case .waitingForLambdaResponse(let invocation) = Self.invocationState else { + guard case .waitingForLambdaResponse(let invocation) = HTTPHandler.invocationState else { // a response was send, but we did not expect to receive one - self.logger.error("invalid invocation state \(Self.invocationState)") + self.logger.error("invalid invocation state \(HTTPHandler.invocationState)") return self.writeResponse(context: context, status: .unprocessableEntity) } guard requestID == invocation.requestID else { @@ -225,9 +225,9 @@ private enum LocalLambda { return self.writeResponse(context: context, status: .badRequest) } - invocation.responsePromise.succeed(.init(status: .internalServerError, body: request.body)) + invocation.responsePromise.succeed(Response(status: .internalServerError, headers: nil, body: request.body)) self.writeResponse(context: context, status: .accepted) - Self.invocationState = .waitingForLambdaRequest + HTTPHandler.invocationState = .waitingForLambdaRequest // unknown call default: @@ -236,7 +236,7 @@ private enum LocalLambda { } func writeResponse(context: ChannelHandlerContext, status: HTTPResponseStatus) { - self.writeResponse(context: context, response: .init(status: status)) + self.writeResponse(context: context, response: Response(status: status, headers: nil, body: nil)) } func writeResponse(context: ChannelHandlerContext, response: Response) { diff --git a/Sources/AWSLambdaRuntimeCore/Lambda+String.swift b/Sources/AWSLambdaRuntimeCore/Lambda+String.swift index 9d37356a..bf11536c 100644 --- a/Sources/AWSLambdaRuntimeCore/Lambda+String.swift +++ b/Sources/AWSLambdaRuntimeCore/Lambda+String.swift @@ -47,12 +47,12 @@ extension Lambda { // for testing internal static func run(configuration: Configuration = .init(), closure: @escaping StringClosure) -> Result { - self.run(configuration: configuration, handler: StringClosureWrapper(closure)) + return self.run(configuration: configuration, handler: StringClosureWrapper(closure)) } // for testing internal static func run(configuration: Configuration = .init(), closure: @escaping StringVoidClosure) -> Result { - self.run(configuration: configuration, handler: StringVoidClosureWrapper(closure)) + return self.run(configuration: configuration, handler: StringVoidClosureWrapper(closure)) } } diff --git a/Sources/AWSLambdaRuntimeCore/Lambda.swift b/Sources/AWSLambdaRuntimeCore/Lambda.swift index 5dc27648..0cb3cb0b 100644 --- a/Sources/AWSLambdaRuntimeCore/Lambda.swift +++ b/Sources/AWSLambdaRuntimeCore/Lambda.swift @@ -78,12 +78,12 @@ public enum Lambda { // for testing and internal use internal static func run(configuration: Configuration = .init(), handler: Handler) -> Result { - self.run(configuration: configuration, factory: { $0.eventLoop.makeSucceededFuture(handler) }) + return self.run(configuration: configuration, factory: { $0.eventLoop.makeSucceededFuture(handler) }) } // for testing and internal use internal static func run(configuration: Configuration = .init(), factory: @escaping (InitializationContext) throws -> Handler) -> Result { - self.run(configuration: configuration, factory: { context -> EventLoopFuture in + return self.run(configuration: configuration, factory: { context -> EventLoopFuture in let promise = context.eventLoop.makePromise(of: Handler.self) // if we have a callback based handler factory, we offload the creation of the handler // onto the default offload queue, to ensure that the eventloop is never blocked. diff --git a/Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift b/Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift index 9b9ec8fb..884a1263 100644 --- a/Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift +++ b/Sources/AWSLambdaRuntimeCore/LambdaConfiguration.swift @@ -40,7 +40,7 @@ extension Lambda { } var description: String { - "\(General.self)(logLevel: \(self.logLevel))" + return "\(General.self)(logLevel: \(self.logLevel))" } } @@ -57,7 +57,7 @@ extension Lambda { } var description: String { - "\(Lifecycle.self)(id: \(self.id), maxTimes: \(self.maxTimes), stopSignal: \(self.stopSignal))" + return "\(Lifecycle.self)(id: \(self.id), maxTimes: \(self.maxTimes), stopSignal: \(self.stopSignal))" } } @@ -79,12 +79,12 @@ extension Lambda { } var description: String { - "\(RuntimeEngine.self)(ip: \(self.ip), port: \(self.port), keepAlive: \(self.keepAlive), requestTimeout: \(String(describing: self.requestTimeout))" + return "\(RuntimeEngine.self)(ip: \(self.ip), port: \(self.port), keepAlive: \(self.keepAlive), requestTimeout: \(String(describing: self.requestTimeout))" } } var description: String { - "\(Configuration.self)\n \(self.general))\n \(self.lifecycle)\n \(self.runtimeEngine)" + return "\(Configuration.self)\n \(self.general))\n \(self.lifecycle)\n \(self.runtimeEngine)" } } } diff --git a/Sources/AWSLambdaRuntimeCore/LambdaContext.swift b/Sources/AWSLambdaRuntimeCore/LambdaContext.swift index ab30dd7b..1e347030 100644 --- a/Sources/AWSLambdaRuntimeCore/LambdaContext.swift +++ b/Sources/AWSLambdaRuntimeCore/LambdaContext.swift @@ -118,7 +118,7 @@ extension Lambda { } public var debugDescription: String { - "\(Self.self)(requestID: \(self.requestID), traceID: \(self.traceID), invokedFunctionARN: \(self.invokedFunctionARN), cognitoIdentity: \(self.cognitoIdentity ?? "nil"), clientContext: \(self.clientContext ?? "nil"), deadline: \(self.deadline))" + return "\(Context.self)(requestID: \(self.requestID), traceID: \(self.traceID), invokedFunctionARN: \(self.invokedFunctionARN), cognitoIdentity: \(self.cognitoIdentity ?? "nil"), clientContext: \(self.clientContext ?? "nil"), deadline: \(self.deadline))" } } } diff --git a/Sources/AWSLambdaRuntimeCore/LambdaHandler.swift b/Sources/AWSLambdaRuntimeCore/LambdaHandler.swift index 16eba1cb..d81391d5 100644 --- a/Sources/AWSLambdaRuntimeCore/LambdaHandler.swift +++ b/Sources/AWSLambdaRuntimeCore/LambdaHandler.swift @@ -46,7 +46,7 @@ internal extension Lambda { public extension LambdaHandler { /// The queue on which `handle` is invoked on. var offloadQueue: DispatchQueue { - Lambda.defaultOffloadQueue + return Lambda.defaultOffloadQueue } /// `LambdaHandler` is offloading the processing to a `DispatchQueue` @@ -164,7 +164,7 @@ public extension EventLoopLambdaHandler { /// Implementation of `ByteBuffer` to `Void` decoding public extension EventLoopLambdaHandler where Out == Void { func encode(allocator: ByteBufferAllocator, value: Void) throws -> ByteBuffer? { - nil + return nil } } @@ -196,7 +196,7 @@ public protocol ByteBufferLambdaHandler { public extension ByteBufferLambdaHandler { func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture { - context.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } diff --git a/Sources/AWSLambdaRuntimeCore/LambdaLifecycle.swift b/Sources/AWSLambdaRuntimeCore/LambdaLifecycle.swift index ec609901..217894a3 100644 --- a/Sources/AWSLambdaRuntimeCore/LambdaLifecycle.swift +++ b/Sources/AWSLambdaRuntimeCore/LambdaLifecycle.swift @@ -62,7 +62,7 @@ extension Lambda { /// /// - Returns: An `EventLoopFuture` that is fulfilled after the Lambda lifecycle has fully shutdown. public var shutdownFuture: EventLoopFuture { - self.shutdownPromise.futureResult + return self.shutdownPromise.futureResult } /// Start the `Lifecycle`. diff --git a/Sources/AWSLambdaRuntimeCore/LambdaRunner.swift b/Sources/AWSLambdaRuntimeCore/LambdaRunner.swift index 96bae6ed..2a27faaa 100644 --- a/Sources/AWSLambdaRuntimeCore/LambdaRunner.swift +++ b/Sources/AWSLambdaRuntimeCore/LambdaRunner.swift @@ -118,7 +118,7 @@ private extension Lambda.Context { extension EventLoopFuture { // callback does not have side effects, failing with original result func peekError(_ callback: @escaping (Error) -> Void) -> EventLoopFuture { - self.flatMapError { error in + return self.flatMapError { error in callback(error) return self } @@ -126,7 +126,7 @@ extension EventLoopFuture { // callback does not have side effects, failing with original result func peekError(_ callback: @escaping (Error) -> EventLoopFuture) -> EventLoopFuture { - self.flatMapError { error in + return self.flatMapError { error in let promise = self.eventLoop.makePromise(of: Value.self) callback(error).whenComplete { _ in promise.completeWith(self) @@ -136,7 +136,7 @@ extension EventLoopFuture { } func mapResult(_ callback: @escaping (Result) -> NewValue) -> EventLoopFuture { - self.map { value in + return self.map { value in callback(.success(value)) }.flatMapErrorThrowing { error in callback(.failure(error)) diff --git a/Sources/AWSLambdaRuntimeCore/Utils.swift b/Sources/AWSLambdaRuntimeCore/Utils.swift index 5e7ffa6e..a86f6d7a 100644 --- a/Sources/AWSLambdaRuntimeCore/Utils.swift +++ b/Sources/AWSLambdaRuntimeCore/Utils.swift @@ -67,7 +67,7 @@ internal extension DispatchWallTime { } var millisSinceEpoch: Int64 { - Int64(bitPattern: self.rawValue) / -1_000_000 + return Int64(bitPattern: self.rawValue) / -1_000_000 } } diff --git a/Sources/AWSLambdaTesting/Lambda+Testing.swift b/Sources/AWSLambdaTesting/Lambda+Testing.swift index 981ca736..df005b6c 100644 --- a/Sources/AWSLambdaTesting/Lambda+Testing.swift +++ b/Sources/AWSLambdaTesting/Lambda+Testing.swift @@ -61,13 +61,13 @@ extension Lambda { public static func test(_ closure: @escaping Lambda.StringClosure, with event: String, using config: TestConfig = .init()) throws -> String { - try Self.test(StringClosureWrapper(closure), with: event, using: config) + return try Lambda.test(StringClosureWrapper(closure), with: event, using: config) } public static func test(_ closure: @escaping Lambda.StringVoidClosure, with event: String, using config: TestConfig = .init()) throws { - _ = try Self.test(StringVoidClosureWrapper(closure), with: event, using: config) + _ = try Lambda.test(StringVoidClosureWrapper(closure), with: event, using: config) } public static func test( @@ -75,7 +75,7 @@ extension Lambda { with event: In, using config: TestConfig = .init() ) throws -> Out { - try Self.test(CodableClosureWrapper(closure), with: event, using: config) + return try Lambda.test(CodableClosureWrapper(closure), with: event, using: config) } public static func test( @@ -83,7 +83,7 @@ extension Lambda { with event: In, using config: TestConfig = .init() ) throws { - _ = try Self.test(CodableVoidClosureWrapper(closure), with: event, using: config) + _ = try Lambda.test(CodableVoidClosureWrapper(closure), with: event, using: config) } public static func test( @@ -110,4 +110,36 @@ extension Lambda { }.wait() } } + +// FIXME: required in swift 5 +private struct StringClosureWrapper: LambdaHandler { + typealias In = String + typealias Out = String + + private let closure: Lambda.StringClosure + + init(_ closure: @escaping Lambda.StringClosure) { + self.closure = closure + } + + func handle(context: Lambda.Context, event: In, callback: @escaping (Result) -> Void) { + self.closure(context, event, callback) + } +} + +// FIXME: required in swift 5 +private struct StringVoidClosureWrapper: LambdaHandler { + typealias In = String + typealias Out = Void + + private let closure: Lambda.StringVoidClosure + + init(_ closure: @escaping Lambda.StringVoidClosure) { + self.closure = closure + } + + func handle(context: Lambda.Context, event: In, callback: @escaping (Result) -> Void) { + self.closure(context, event, callback) + } +} #endif diff --git a/Sources/CodableSample/main.swift b/Sources/CodableSample/main.swift index 59cc8dee..a4bb0375 100644 --- a/Sources/CodableSample/main.swift +++ b/Sources/CodableSample/main.swift @@ -31,7 +31,7 @@ struct Handler: EventLoopLambdaHandler { func handle(context: Lambda.Context, event: Request) -> EventLoopFuture { // as an example, respond with the input event's reversed body - context.eventLoop.makeSucceededFuture(Response(body: String(event.body.reversed()))) + return context.eventLoop.makeSucceededFuture(Response(body: String(event.body.reversed()))) } } diff --git a/Sources/StringSample/main.swift b/Sources/StringSample/main.swift index 452160f9..d2d61997 100644 --- a/Sources/StringSample/main.swift +++ b/Sources/StringSample/main.swift @@ -22,7 +22,7 @@ struct Handler: EventLoopLambdaHandler { func handle(context: Lambda.Context, event: String) -> EventLoopFuture { // as an example, respond with the event's reversed body - context.eventLoop.makeSucceededFuture(String(event.reversed())) + return context.eventLoop.makeSucceededFuture(String(event.reversed())) } } diff --git a/Tests/AWSLambdaEventsTests/APIGatewayTests.swift b/Tests/AWSLambdaEventsTests/APIGatewayTests.swift index 37cba98a..70564917 100644 --- a/Tests/AWSLambdaEventsTests/APIGatewayTests.swift +++ b/Tests/AWSLambdaEventsTests/APIGatewayTests.swift @@ -67,7 +67,7 @@ class APIGatewayTests: XCTestCase { var data: Data? XCTAssertNoThrow(data = try JSONEncoder().encode(resp)) var json: JSONResponse? - XCTAssertNoThrow(json = try JSONDecoder().decode(JSONResponse.self, from: XCTUnwrap(data))) + XCTAssertNoThrow(json = try JSONDecoder().decode(JSONResponse.self, from: data!)) XCTAssertEqual(json?.statusCode, resp.statusCode.code) XCTAssertEqual(json?.body, resp.body) diff --git a/Tests/AWSLambdaEventsTests/CloudwatchTests.swift b/Tests/AWSLambdaEventsTests/CloudwatchTests.swift index b931e020..cff2e1ec 100644 --- a/Tests/AWSLambdaEventsTests/CloudwatchTests.swift +++ b/Tests/AWSLambdaEventsTests/CloudwatchTests.swift @@ -17,7 +17,7 @@ import XCTest class CloudwatchTests: XCTestCase { static func eventBody(type: String, details: String) -> String { - """ + return """ { "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", "detail-type": "\(type)", @@ -34,7 +34,7 @@ class CloudwatchTests: XCTestCase { } func testScheduledEventFromJSON() { - let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.Scheduled.name, details: "{}") + let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.Scheduled.typeName, details: "{}") let data = eventBody.data(using: .utf8)! var maybeEvent: Cloudwatch.ScheduledEvent? XCTAssertNoThrow(maybeEvent = try JSONDecoder().decode(Cloudwatch.ScheduledEvent.self, from: data)) @@ -52,7 +52,7 @@ class CloudwatchTests: XCTestCase { } func testEC2InstanceStateChangeNotificationEventFromJSON() { - let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.InstanceStateChangeNotification.name, + let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.InstanceStateChangeNotification.typeName, details: "{ \"instance-id\": \"0\", \"state\": \"stopping\" }") let data = eventBody.data(using: .utf8)! var maybeEvent: Cloudwatch.EC2.InstanceStateChangeNotificationEvent? @@ -73,7 +73,7 @@ class CloudwatchTests: XCTestCase { } func testEC2SpotInstanceInterruptionNoticeEventFromJSON() { - let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.SpotInstanceInterruptionNotice.name, + let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.SpotInstanceInterruptionNotice.typeName, details: "{ \"instance-id\": \"0\", \"instance-action\": \"terminate\" }") let data = eventBody.data(using: .utf8)! var maybeEvent: Cloudwatch.EC2.SpotInstanceInterruptionNoticeEvent? @@ -95,12 +95,12 @@ class CloudwatchTests: XCTestCase { func testCustomEventFromJSON() { struct Custom: CloudwatchDetail { - public static let name = "Custom" + public static let typeName = "Custom" let name: String } - let eventBody = CloudwatchTests.eventBody(type: Custom.name, details: "{ \"name\": \"foo\" }") + let eventBody = CloudwatchTests.eventBody(type: Custom.typeName, details: "{ \"name\": \"foo\" }") let data = eventBody.data(using: .utf8)! var maybeEvent: Cloudwatch.Event? XCTAssertNoThrow(maybeEvent = try JSONDecoder().decode(Cloudwatch.Event.self, from: data)) @@ -127,7 +127,7 @@ class CloudwatchTests: XCTestCase { } func testTypeMismatch() { - let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.InstanceStateChangeNotification.name, + let eventBody = CloudwatchTests.eventBody(type: Cloudwatch.EC2.InstanceStateChangeNotification.typeName, details: "{ \"instance-id\": \"0\", \"state\": \"stopping\" }") let data = eventBody.data(using: .utf8)! XCTAssertThrowsError(try JSONDecoder().decode(Cloudwatch.ScheduledEvent.self, from: data)) { error in diff --git a/Tests/AWSLambdaEventsTests/Utils/DateWrapperTests.swift b/Tests/AWSLambdaEventsTests/Utils/DateWrapperTests.swift index 35b1a474..b2f0af3f 100644 --- a/Tests/AWSLambdaEventsTests/Utils/DateWrapperTests.swift +++ b/Tests/AWSLambdaEventsTests/Utils/DateWrapperTests.swift @@ -18,21 +18,21 @@ import XCTest class DateWrapperTests: XCTestCase { func testISO8601CodingWrapperSuccess() { struct TestEvent: Decodable { - @ISO8601Coding - var date: Date + // @ISO8601Coding + var date: ISO8601Coding } let json = #"{"date":"2020-03-26T16:53:05Z"}"# var event: TestEvent? XCTAssertNoThrow(event = try JSONDecoder().decode(TestEvent.self, from: json.data(using: .utf8)!)) - XCTAssertEqual(event?.date, Date(timeIntervalSince1970: 1_585_241_585)) + XCTAssertEqual(event?.date.wrappedValue, Date(timeIntervalSince1970: 1_585_241_585)) } func testISO8601CodingWrapperFailure() { struct TestEvent: Decodable { - @ISO8601Coding - var date: Date + // @ISO8601Coding + var date: ISO8601Coding } let date = "2020-03-26T16:53:05" // missing Z at end @@ -50,21 +50,21 @@ class DateWrapperTests: XCTestCase { func testISO8601WithFractionalSecondsCodingWrapperSuccess() { struct TestEvent: Decodable { - @ISO8601WithFractionalSecondsCoding - var date: Date + // @ISO8601WithFractionalSecondsCoding + var date: ISO8601WithFractionalSecondsCoding } let json = #"{"date":"2020-03-26T16:53:05.123Z"}"# var event: TestEvent? XCTAssertNoThrow(event = try JSONDecoder().decode(TestEvent.self, from: json.data(using: .utf8)!)) - XCTAssertEqual(event?.date, Date(timeIntervalSince1970: 1_585_241_585.123)) + XCTAssertEqual(event?.date.wrappedValue, Date(timeIntervalSince1970: 1_585_241_585.123)) } func testISO8601WithFractionalSecondsCodingWrapperFailure() { struct TestEvent: Decodable { - @ISO8601WithFractionalSecondsCoding - var date: Date + // @ISO8601WithFractionalSecondsCoding + var date: ISO8601WithFractionalSecondsCoding } let date = "2020-03-26T16:53:05Z" // missing fractional seconds @@ -82,47 +82,47 @@ class DateWrapperTests: XCTestCase { func testRFC5322DateTimeCodingWrapperSuccess() { struct TestEvent: Decodable { - @RFC5322DateTimeCoding - var date: Date + // @RFC5322DateTimeCoding + var date: RFC5322DateTimeCoding } let json = #"{"date":"Thu, 5 Apr 2012 23:47:37 +0200"}"# var event: TestEvent? XCTAssertNoThrow(event = try JSONDecoder().decode(TestEvent.self, from: json.data(using: .utf8)!)) - XCTAssertEqual(event?.date.description, "2012-04-05 21:47:37 +0000") + XCTAssertEqual(event?.date.wrappedValue.description, "2012-04-05 21:47:37 +0000") } func testRFC5322DateTimeCodingWrapperWithExtraTimeZoneSuccess() { struct TestEvent: Decodable { - @RFC5322DateTimeCoding - var date: Date + // @RFC5322DateTimeCoding + var date: RFC5322DateTimeCoding } let json = #"{"date":"Fri, 26 Jun 2020 03:04:03 -0500 (CDT)"}"# var event: TestEvent? XCTAssertNoThrow(event = try JSONDecoder().decode(TestEvent.self, from: json.data(using: .utf8)!)) - XCTAssertEqual(event?.date.description, "2020-06-26 08:04:03 +0000") + XCTAssertEqual(event?.date.wrappedValue.description, "2020-06-26 08:04:03 +0000") } func testRFC5322DateTimeCodingWrapperWithAlphabeticTimeZoneSuccess() { struct TestEvent: Decodable { - @RFC5322DateTimeCoding - var date: Date + // @RFC5322DateTimeCoding + var date: RFC5322DateTimeCoding } let json = #"{"date":"Fri, 26 Jun 2020 03:04:03 CDT"}"# var event: TestEvent? XCTAssertNoThrow(event = try JSONDecoder().decode(TestEvent.self, from: json.data(using: .utf8)!)) - XCTAssertEqual(event?.date.description, "2020-06-26 08:04:03 +0000") + XCTAssertEqual(event?.date.wrappedValue.description, "2020-06-26 08:04:03 +0000") } func testRFC5322DateTimeCodingWrapperFailure() { struct TestEvent: Decodable { - @RFC5322DateTimeCoding - var date: Date + // @RFC5322DateTimeCoding + var date: RFC5322DateTimeCoding } let date = "Thu, 5 Apr 2012 23:47 +0200" // missing seconds diff --git a/Tests/AWSLambdaEventsTests/XCTestManifests.swift b/Tests/AWSLambdaEventsTests/XCTestManifests.swift new file mode 100644 index 00000000..897575e6 --- /dev/null +++ b/Tests/AWSLambdaEventsTests/XCTestManifests.swift @@ -0,0 +1,165 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftAWSLambdaRuntime open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if !canImport(ObjectiveC) +import XCTest + +extension ALBTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__ALBTests = [ + ("testRequestWithSingleValueHeadersEvent", testRequestWithSingleValueHeadersEvent), + ] +} + +extension APIGatewayTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__APIGatewayTests = [ + ("testRequestDecodingExampleGetRequest", testRequestDecodingExampleGetRequest), + ("testRequestDecodingTodoPostRequest", testRequestDecodingTodoPostRequest), + ("testResponseEncoding", testResponseEncoding), + ] +} + +extension APIGatewayV2Tests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__APIGatewayV2Tests = [ + ("testRequestDecodingExampleGetRequest", testRequestDecodingExampleGetRequest), + ] +} + +extension Base64Tests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__Base64Tests = [ + ("testBase64DecodingAllTheBytesSequentially", testBase64DecodingAllTheBytesSequentially), + ("testBase64DecodingArrayOfNulls", testBase64DecodingArrayOfNulls), + ("testBase64DecodingWithInvalidLength", testBase64DecodingWithInvalidLength), + ("testBase64DecodingWithPoop", testBase64DecodingWithPoop), + ("testBase64UrlDecodingAllTheBytesSequentially", testBase64UrlDecodingAllTheBytesSequentially), + ("testDecodeEmptyString", testDecodeEmptyString), + ("testNSStringToDecode", testNSStringToDecode), + ] +} + +extension CloudwatchTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__CloudwatchTests = [ + ("testCustomEventFromJSON", testCustomEventFromJSON), + ("testEC2InstanceStateChangeNotificationEventFromJSON", testEC2InstanceStateChangeNotificationEventFromJSON), + ("testEC2SpotInstanceInterruptionNoticeEventFromJSON", testEC2SpotInstanceInterruptionNoticeEventFromJSON), + ("testScheduledEventFromJSON", testScheduledEventFromJSON), + ("testTypeMismatch", testTypeMismatch), + ("testUnregistredType", testUnregistredType), + ] +} + +extension DateWrapperTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__DateWrapperTests = [ + ("testISO8601CodingWrapperFailure", testISO8601CodingWrapperFailure), + ("testISO8601CodingWrapperSuccess", testISO8601CodingWrapperSuccess), + ("testISO8601WithFractionalSecondsCodingWrapperFailure", testISO8601WithFractionalSecondsCodingWrapperFailure), + ("testISO8601WithFractionalSecondsCodingWrapperSuccess", testISO8601WithFractionalSecondsCodingWrapperSuccess), + ("testRFC5322DateTimeCodingWrapperFailure", testRFC5322DateTimeCodingWrapperFailure), + ("testRFC5322DateTimeCodingWrapperSuccess", testRFC5322DateTimeCodingWrapperSuccess), + ("testRFC5322DateTimeCodingWrapperWithAlphabeticTimeZoneSuccess", testRFC5322DateTimeCodingWrapperWithAlphabeticTimeZoneSuccess), + ("testRFC5322DateTimeCodingWrapperWithExtraTimeZoneSuccess", testRFC5322DateTimeCodingWrapperWithExtraTimeZoneSuccess), + ] +} + +extension DynamoDBTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__DynamoDBTests = [ + ("testAttributeValueBinaryDecoding", testAttributeValueBinaryDecoding), + ("testAttributeValueBinarySetDecoding", testAttributeValueBinarySetDecoding), + ("testAttributeValueBoolDecoding", testAttributeValueBoolDecoding), + ("testAttributeValueEmptyDecoding", testAttributeValueEmptyDecoding), + ("testAttributeValueEquatable", testAttributeValueEquatable), + ("testAttributeValueListDecoding", testAttributeValueListDecoding), + ("testAttributeValueMapDecoding", testAttributeValueMapDecoding), + ("testAttributeValueNullDecoding", testAttributeValueNullDecoding), + ("testAttributeValueNumberDecoding", testAttributeValueNumberDecoding), + ("testAttributeValueNumberSetDecoding", testAttributeValueNumberSetDecoding), + ("testAttributeValueStringDecoding", testAttributeValueStringDecoding), + ("testAttributeValueStringSetDecoding", testAttributeValueStringSetDecoding), + ("testDecoderSimple", testDecoderSimple), + ("testEventFromJSON", testEventFromJSON), + ] +} + +extension S3Tests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__S3Tests = [ + ("testSimpleEventFromJSON", testSimpleEventFromJSON), + ] +} + +extension SESTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__SESTests = [ + ("testSimpleEventFromJSON", testSimpleEventFromJSON), + ] +} + +extension SNSTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__SNSTests = [ + ("testSimpleEventFromJSON", testSimpleEventFromJSON), + ] +} + +extension SQSTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__SQSTests = [ + ("testSimpleEventFromJSON", testSimpleEventFromJSON), + ] +} + +public func __allTests() -> [XCTestCaseEntry] { + return [ + testCase(ALBTests.__allTests__ALBTests), + testCase(APIGatewayTests.__allTests__APIGatewayTests), + testCase(APIGatewayV2Tests.__allTests__APIGatewayV2Tests), + testCase(Base64Tests.__allTests__Base64Tests), + testCase(CloudwatchTests.__allTests__CloudwatchTests), + testCase(DateWrapperTests.__allTests__DateWrapperTests), + testCase(DynamoDBTests.__allTests__DynamoDBTests), + testCase(S3Tests.__allTests__S3Tests), + testCase(SESTests.__allTests__SESTests), + testCase(SNSTests.__allTests__SNSTests), + testCase(SQSTests.__allTests__SQSTests), + ] +} +#endif diff --git a/Tests/AWSLambdaRuntimeCoreTests/Lambda+StringTest.swift b/Tests/AWSLambdaRuntimeCoreTests/Lambda+StringTest.swift index 8e880296..9fe0ef50 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/Lambda+StringTest.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/Lambda+StringTest.swift @@ -87,7 +87,7 @@ class StringLambdaTest: XCTestCase { typealias Out = String func handle(context: Lambda.Context, event: String) -> EventLoopFuture { - context.eventLoop.makeSucceededFuture(event) + return context.eventLoop.makeSucceededFuture(event) } } @@ -107,7 +107,7 @@ class StringLambdaTest: XCTestCase { typealias Out = Void func handle(context: Lambda.Context, event: String) -> EventLoopFuture { - context.eventLoop.makeSucceededFuture(()) + return context.eventLoop.makeSucceededFuture(()) } } @@ -127,7 +127,7 @@ class StringLambdaTest: XCTestCase { typealias Out = String func handle(context: Lambda.Context, event: String) -> EventLoopFuture { - context.eventLoop.makeFailedFuture(TestError("boom")) + return context.eventLoop.makeFailedFuture(TestError("boom")) } } @@ -211,7 +211,7 @@ private struct Behavior: LambdaServerBehavior { } func getInvocation() -> GetInvocationResult { - .success((requestId: self.requestId, event: self.event)) + return .success((requestId: self.requestId, event: self.event)) } func processResponse(requestId: String, response: String?) -> Result { diff --git a/Tests/AWSLambdaRuntimeCoreTests/LambdaLifecycleTest.swift b/Tests/AWSLambdaRuntimeCoreTests/LambdaLifecycleTest.swift index a485530d..6da8c225 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/LambdaLifecycleTest.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/LambdaLifecycleTest.swift @@ -54,11 +54,11 @@ class LambdaLifecycleTest: XCTestCase { } func handle(context: Lambda.Context, event: ByteBuffer) -> EventLoopFuture { - self.handler(context, event) + return self.handler(context, event) } func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture { - self.shutdown(context) + return self.shutdown(context) } } @@ -122,7 +122,7 @@ class LambdaLifecycleTest: XCTestCase { struct BadBehavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .failure(.internalServerError) + return .failure(.internalServerError) } func processResponse(requestId: String, response: String?) -> Result { diff --git a/Tests/AWSLambdaRuntimeCoreTests/LambdaRunnerTest.swift b/Tests/AWSLambdaRuntimeCoreTests/LambdaRunnerTest.swift index dd87eb61..7256ce9e 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/LambdaRunnerTest.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/LambdaRunnerTest.swift @@ -21,7 +21,7 @@ class LambdaRunnerTest: XCTestCase { let requestId = UUID().uuidString let event = "hello" func getInvocation() -> GetInvocationResult { - .success((self.requestId, self.event)) + return .success((self.requestId, self.event)) } func processResponse(requestId: String, response: String?) -> Result { @@ -48,7 +48,7 @@ class LambdaRunnerTest: XCTestCase { static let error = "boom" let requestId = UUID().uuidString func getInvocation() -> GetInvocationResult { - .success((requestId: self.requestId, event: "hello")) + return .success((requestId: self.requestId, event: "hello")) } func processResponse(requestId: String, response: String?) -> Result { diff --git a/Tests/AWSLambdaRuntimeCoreTests/LambdaRuntimeClientTest.swift b/Tests/AWSLambdaRuntimeCoreTests/LambdaRuntimeClientTest.swift index 94c8ac62..a68db83c 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/LambdaRuntimeClientTest.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/LambdaRuntimeClientTest.swift @@ -44,7 +44,7 @@ class LambdaRuntimeClientTest: XCTestCase { func testGetInvocationServerInternalError() { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .failure(.internalServerError) + return .failure(.internalServerError) } func processResponse(requestId: String, response: String?) -> Result { @@ -70,7 +70,7 @@ class LambdaRuntimeClientTest: XCTestCase { func testGetInvocationServerNoBodyError() { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .success(("1", "")) + return .success(("1", "")) } func processResponse(requestId: String, response: String?) -> Result { @@ -97,7 +97,7 @@ class LambdaRuntimeClientTest: XCTestCase { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { // no request id -> no context - .success(("", "hello")) + return .success(("", "hello")) } func processResponse(requestId: String, response: String?) -> Result { @@ -123,11 +123,11 @@ class LambdaRuntimeClientTest: XCTestCase { func testProcessResponseInternalServerError() { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .success((requestId: "1", event: "event")) + return .success((requestId: "1", event: "event")) } func processResponse(requestId: String, response: String?) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } func processError(requestId: String, error: ErrorResponse) -> Result { @@ -148,7 +148,7 @@ class LambdaRuntimeClientTest: XCTestCase { func testProcessErrorInternalServerError() { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .success((requestId: "1", event: "event")) + return .success((requestId: "1", event: "event")) } func processResponse(requestId: String, response: String?) -> Result { @@ -157,7 +157,7 @@ class LambdaRuntimeClientTest: XCTestCase { } func processError(requestId: String, error: ErrorResponse) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } func processInitError(error: ErrorResponse) -> Result { @@ -188,7 +188,7 @@ class LambdaRuntimeClientTest: XCTestCase { } func processInitError(error: ErrorResponse) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } } XCTAssertThrowsError(try runLambda(behavior: Behavior(), factory: { $0.eventLoop.makeFailedFuture(TestError("boom")) })) { error in @@ -227,13 +227,13 @@ class LambdaRuntimeClientTest: XCTestCase { var inboundHeader: HTTPServerRequestPart? XCTAssertNoThrow(inboundHeader = try server.readInbound()) - guard case .head(let head) = try? XCTUnwrap(inboundHeader) else { XCTFail("Expected to get a head first"); return } + guard case .head(let head) = inboundHeader! else { XCTFail("Expected to get a head first"); return } XCTAssertEqual(head.headers["lambda-runtime-function-error-type"], ["Unhandled"]) XCTAssertEqual(head.headers["user-agent"], ["Swift-Lambda/Unknown"]) var inboundBody: HTTPServerRequestPart? XCTAssertNoThrow(inboundBody = try server.readInbound()) - guard case .body(let body) = try? XCTUnwrap(inboundBody) else { XCTFail("Expected body after head"); return } + guard case .body(let body) = inboundBody! else { XCTFail("Expected body after head"); return } XCTAssertEqual(try JSONDecoder().decode(ErrorResponse.self, from: body).errorMessage, "boom") XCTAssertEqual(try server.readInbound(), .end(nil)) @@ -263,17 +263,17 @@ class LambdaRuntimeClientTest: XCTestCase { XCTAssertNoThrow(inv = try Lambda.Invocation(headers: header)) guard let invocation = inv else { return } - let result = client.reportResults(logger: logger, invocation: invocation, result: Result.failure(TestError("boom"))) + let result = client.reportResults(logger: logger, invocation: invocation, result: .failure(TestError("boom"))) var inboundHeader: HTTPServerRequestPart? XCTAssertNoThrow(inboundHeader = try server.readInbound()) - guard case .head(let head) = try? XCTUnwrap(inboundHeader) else { XCTFail("Expected to get a head first"); return } + guard case .head(let head) = inboundHeader! else { XCTFail("Expected to get a head first"); return } XCTAssertEqual(head.headers["lambda-runtime-function-error-type"], ["Unhandled"]) XCTAssertEqual(head.headers["user-agent"], ["Swift-Lambda/Unknown"]) var inboundBody: HTTPServerRequestPart? XCTAssertNoThrow(inboundBody = try server.readInbound()) - guard case .body(let body) = try? XCTUnwrap(inboundBody) else { XCTFail("Expected body after head"); return } + guard case .body(let body) = inboundBody! else { XCTFail("Expected body after head"); return } XCTAssertEqual(try JSONDecoder().decode(ErrorResponse.self, from: body).errorMessage, "boom") XCTAssertEqual(try server.readInbound(), .end(nil)) @@ -303,11 +303,11 @@ class LambdaRuntimeClientTest: XCTestCase { XCTAssertNoThrow(inv = try Lambda.Invocation(headers: header)) guard let invocation = inv else { return } - let result = client.reportResults(logger: logger, invocation: invocation, result: Result.success(nil)) + let result = client.reportResults(logger: logger, invocation: invocation, result: .success(nil)) var inboundHeader: HTTPServerRequestPart? XCTAssertNoThrow(inboundHeader = try server.readInbound()) - guard case .head(let head) = try? XCTUnwrap(inboundHeader) else { XCTFail("Expected to get a head first"); return } + guard case .head(let head) = inboundHeader! else { XCTFail("Expected to get a head first"); return } XCTAssertFalse(head.headers.contains(name: "lambda-runtime-function-error-type")) XCTAssertEqual(head.headers["user-agent"], ["Swift-Lambda/Unknown"]) diff --git a/Tests/AWSLambdaRuntimeCoreTests/LambdaTest.swift b/Tests/AWSLambdaRuntimeCoreTests/LambdaTest.swift index 30fed618..077d9ba0 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/LambdaTest.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/LambdaTest.swift @@ -116,7 +116,7 @@ class LambdaTest: XCTestCase { } func processInitError(error: ErrorResponse) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } } @@ -216,15 +216,15 @@ class LambdaTest: XCTestCase { struct Behavior: LambdaServerBehavior { func getInvocation() -> GetInvocationResult { - .failure(.internalServerError) + return .failure(.internalServerError) } func processResponse(requestId: String, response: String?) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } func processError(requestId: String, error: ErrorResponse) -> Result { - .failure(.internalServerError) + return .failure(.internalServerError) } func processInitError(error: ErrorResponse) -> Result { @@ -306,7 +306,7 @@ private struct Behavior: LambdaServerBehavior { } func getInvocation() -> GetInvocationResult { - .success((requestId: self.requestId, event: self.event)) + return .success((requestId: self.requestId, event: self.event)) } func processResponse(requestId: String, response: String?) -> Result { @@ -356,6 +356,6 @@ struct FailedBootstrapBehavior: LambdaServerBehavior { } func processInitError(error: ErrorResponse) -> Result { - .success(()) + return .success(()) } } diff --git a/Tests/AWSLambdaRuntimeCoreTests/Utils.swift b/Tests/AWSLambdaRuntimeCoreTests/Utils.swift index e7160307..86418ac3 100644 --- a/Tests/AWSLambdaRuntimeCoreTests/Utils.swift +++ b/Tests/AWSLambdaRuntimeCoreTests/Utils.swift @@ -83,13 +83,13 @@ struct TestError: Error, Equatable, CustomStringConvertible { internal extension Date { var millisSinceEpoch: Int64 { - Int64(self.timeIntervalSince1970 * 1000) + return Int64(self.timeIntervalSince1970 * 1000) } } extension Lambda.RuntimeError: Equatable { public static func == (lhs: Lambda.RuntimeError, rhs: Lambda.RuntimeError) -> Bool { // technically incorrect, but good enough for our tests - String(describing: lhs) == String(describing: rhs) + return String(describing: lhs) == String(describing: rhs) } } diff --git a/Tests/AWSLambdaRuntimeCoreTests/XCTestManifests.swift b/Tests/AWSLambdaRuntimeCoreTests/XCTestManifests.swift new file mode 100644 index 00000000..eaa2580e --- /dev/null +++ b/Tests/AWSLambdaRuntimeCoreTests/XCTestManifests.swift @@ -0,0 +1,120 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftAWSLambdaRuntime open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if !canImport(ObjectiveC) +import XCTest + +extension LambdaLifecycleTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__LambdaLifecycleTest = [ + ("testLambdaResultIfShutsdownIsUnclean", testLambdaResultIfShutsdownIsUnclean), + ("testShutdownFutureIsFulfilledWithStartUpError", testShutdownFutureIsFulfilledWithStartUpError), + ("testShutdownIsCalledWhenLambdaShutsdown", testShutdownIsCalledWhenLambdaShutsdown), + ] +} + +extension LambdaRunnerTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__LambdaRunnerTest = [ + ("testFailure", testFailure), + ("testSuccess", testSuccess), + ] +} + +extension LambdaRuntimeClientTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__LambdaRuntimeClientTest = [ + ("testBootstrapFailure", testBootstrapFailure), + ("testErrorResponseToJSON", testErrorResponseToJSON), + ("testFailure", testFailure), + ("testGetInvocationServerInternalError", testGetInvocationServerInternalError), + ("testGetInvocationServerMissingHeaderRequestIDError", testGetInvocationServerMissingHeaderRequestIDError), + ("testGetInvocationServerNoBodyError", testGetInvocationServerNoBodyError), + ("testInitializationErrorReport", testInitializationErrorReport), + ("testInvocationErrorReport", testInvocationErrorReport), + ("testInvocationSuccessResponse", testInvocationSuccessResponse), + ("testProcessErrorInternalServerError", testProcessErrorInternalServerError), + ("testProcessInitErrorOnBootstrapFailure", testProcessInitErrorOnBootstrapFailure), + ("testProcessResponseInternalServerError", testProcessResponseInternalServerError), + ("testSuccess", testSuccess), + ] +} + +extension LambdaTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__LambdaTest = [ + ("testBigEvent", testBigEvent), + ("testBootstrapFailure", testBootstrapFailure), + ("testBootstrapFailure2", testBootstrapFailure2), + ("testBootstrapFailureAndReportErrorFailure", testBootstrapFailureAndReportErrorFailure), + ("testBootstrapOnce", testBootstrapOnce), + ("testDeadline", testDeadline), + ("testDisconnect", testDisconnect), + ("testFailure", testFailure), + ("testGetRemainingTime", testGetRemainingTime), + ("testKeepAliveServer", testKeepAliveServer), + ("testNoKeepAliveServer", testNoKeepAliveServer), + ("testServerFailure", testServerFailure), + ("testStartStopInDebugMode", testStartStopInDebugMode), + ("testSuccess", testSuccess), + ("testTimeout", testTimeout), + ] +} + +extension StringLambdaTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__StringLambdaTest = [ + ("testBootstrapFailure", testBootstrapFailure), + ("testCallbackFailure", testCallbackFailure), + ("testCallbackSuccess", testCallbackSuccess), + ("testClosureFailure", testClosureFailure), + ("testClosureSuccess", testClosureSuccess), + ("testEventLoopFailure", testEventLoopFailure), + ("testEventLoopSuccess", testEventLoopSuccess), + ("testVoidCallbackSuccess", testVoidCallbackSuccess), + ("testVoidClosureSuccess", testVoidClosureSuccess), + ("testVoidEventLoopSuccess", testVoidEventLoopSuccess), + ] +} + +extension UtilsTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__UtilsTest = [ + ("testGenerateXRayTraceID", testGenerateXRayTraceID), + ] +} + +public func __allTests() -> [XCTestCaseEntry] { + return [ + testCase(LambdaLifecycleTest.__allTests__LambdaLifecycleTest), + testCase(LambdaRunnerTest.__allTests__LambdaRunnerTest), + testCase(LambdaRuntimeClientTest.__allTests__LambdaRuntimeClientTest), + testCase(LambdaTest.__allTests__LambdaTest), + testCase(StringLambdaTest.__allTests__StringLambdaTest), + testCase(UtilsTest.__allTests__UtilsTest), + ] +} +#endif diff --git a/Tests/AWSLambdaRuntimeTests/Lambda+CodeableTest.swift b/Tests/AWSLambdaRuntimeTests/Lambda+CodeableTest.swift index 9aa3f72a..ac9eb6fa 100644 --- a/Tests/AWSLambdaRuntimeTests/Lambda+CodeableTest.swift +++ b/Tests/AWSLambdaRuntimeTests/Lambda+CodeableTest.swift @@ -42,7 +42,7 @@ class CodableLambdaTest: XCTestCase { } XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) - XCTAssertNoThrow(outputBuffer = try closureWrapper.handle(context: self.newContext(), event: XCTUnwrap(inputBuffer)).wait()) + XCTAssertNoThrow(outputBuffer = try closureWrapper.handle(context: self.newContext(), event: inputBuffer!).wait()) XCTAssertNil(outputBuffer) } @@ -58,22 +58,22 @@ class CodableLambdaTest: XCTestCase { } XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) - XCTAssertNoThrow(outputBuffer = try closureWrapper.handle(context: self.newContext(), event: XCTUnwrap(inputBuffer)).wait()) - XCTAssertNoThrow(response = try JSONDecoder().decode(Response.self, from: XCTUnwrap(outputBuffer))) + XCTAssertNoThrow(outputBuffer = try closureWrapper.handle(context: self.newContext(), event: inputBuffer!).wait()) + XCTAssertNoThrow(response = try JSONDecoder().decode(Response.self, from: outputBuffer!)) XCTAssertEqual(response?.requestId, request.requestId) } // convencience method func newContext() -> Lambda.Context { - Lambda.Context(requestID: UUID().uuidString, - traceID: "abc123", - invokedFunctionARN: "aws:arn:", - deadline: .now() + .seconds(3), - cognitoIdentity: nil, - clientContext: nil, - logger: Logger(label: "test"), - eventLoop: self.eventLoopGroup.next(), - allocator: ByteBufferAllocator()) + return Lambda.Context(requestID: UUID().uuidString, + traceID: "abc123", + invokedFunctionARN: "aws:arn:", + deadline: .now() + .seconds(3), + cognitoIdentity: nil, + clientContext: nil, + logger: Logger(label: "test"), + eventLoop: self.eventLoopGroup.next(), + allocator: ByteBufferAllocator()) } } diff --git a/Tests/AWSLambdaRuntimeTests/XCTestManifests.swift b/Tests/AWSLambdaRuntimeTests/XCTestManifests.swift new file mode 100644 index 00000000..3c82598f --- /dev/null +++ b/Tests/AWSLambdaRuntimeTests/XCTestManifests.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftAWSLambdaRuntime open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if !canImport(ObjectiveC) +import XCTest + +extension CodableLambdaTest { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__CodableLambdaTest = [ + ("testCodableClosureWrapper", testCodableClosureWrapper), + ("testCodableVoidClosureWrapper", testCodableVoidClosureWrapper), + ] +} + +public func __allTests() -> [XCTestCaseEntry] { + return [ + testCase(CodableLambdaTest.__allTests__CodableLambdaTest), + ] +} +#endif diff --git a/Tests/AWSLambdaTestingTests/XCTestManifests.swift b/Tests/AWSLambdaTestingTests/XCTestManifests.swift new file mode 100644 index 00000000..7617283d --- /dev/null +++ b/Tests/AWSLambdaTestingTests/XCTestManifests.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftAWSLambdaRuntime open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if !canImport(ObjectiveC) +import XCTest + +extension LambdaTestingTests { + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__LambdaTestingTests = [ + ("testAsyncLongRunning", testAsyncLongRunning), + ("testCodableClosure", testCodableClosure), + ("testCodableVoidClosure", testCodableVoidClosure), + ("testConfigValues", testConfigValues), + ("testEventLoopLambdaHandler", testEventLoopLambdaHandler), + ("testFailure", testFailure), + ("testLambdaHandler", testLambdaHandler), + ] +} + +public func __allTests() -> [XCTestCaseEntry] { + return [ + testCase(LambdaTestingTests.__allTests__LambdaTestingTests), + ] +} +#endif diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 58f2ccfd..ed45af14 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftAWSLambdaRuntime open source project // -// Copyright (c) 2017-2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors +// Copyright (c) 2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -12,4 +12,17 @@ // //===----------------------------------------------------------------------===// -preconditionFailure("use `swift test --enable-test-discovery`") +import XCTest + +import AWSLambdaEventsTests +import AWSLambdaRuntimeCoreTests +import AWSLambdaRuntimeTests +import AWSLambdaTestingTests + +var tests = [XCTestCaseEntry]() +tests += AWSLambdaEventsTests.__allTests() +tests += AWSLambdaRuntimeCoreTests.__allTests() +tests += AWSLambdaRuntimeTests.__allTests() +tests += AWSLambdaTestingTests.__allTests() + +XCTMain(tests) diff --git a/docker/docker-compose.1804.50.yaml b/docker/docker-compose.1804.50.yaml new file mode 100644 index 00000000..9b6e306f --- /dev/null +++ b/docker/docker-compose.1804.50.yaml @@ -0,0 +1,21 @@ +version: "3" + +services: + + runtime-setup: + image: swift-aws-lambda:18.04-5.0 + build: + dockerfile: Dockerfile.ubuntu + args: + ubuntu_version: "bionic" + swift_version: "5.0" + + test: + image: swift-aws-lambda:18.04-5.0 + command: /bin/bash -cl "swift test -Xswiftc -warnings-as-errors $${SANITIZER_ARG-}" + + test-samples: + image: swift-aws-lambda:18.04-5.0 + + shell: + image: swift-aws-lambda:18.04-5.0 diff --git a/docker/docker-compose.1804.51.yaml b/docker/docker-compose.1804.51.yaml new file mode 100644 index 00000000..aee289e5 --- /dev/null +++ b/docker/docker-compose.1804.51.yaml @@ -0,0 +1,20 @@ +version: "3" + +services: + + runtime-setup: + image: swift-aws-lambda:18.04-5.1 + build: + dockerfile: Dockerfile.ubuntu + args: + ubuntu_version: "bionic" + swift_version: "5.1" + + test: + image: swift-aws-lambda:18.04-5.1 + + test-samples: + image: swift-aws-lambda:18.04-5.1 + + shell: + image: swift-aws-lambda:18.04-5.1