Additional testing

This commit is contained in:
Cory Benfield committed 2020-07-05 17:11:02 +01:00
1 parent 49370cd8db
commit e6e0c68caf
8 files changed
+271 -32

No files matched your search

@@ -42,7 +42,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -50,7 +50,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -58,7 +58,7 @@ extension DictionaryKeyedContainer: KeyedDecodingContainerProtocol {
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -47,7 +47,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -55,7 +55,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -63,7 +63,7 @@ extension KeyedInnerListDecoder: KeyedDecodingContainerProtocol {
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -47,7 +47,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -55,7 +55,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -63,7 +63,7 @@ extension KeyedItemDecoder: KeyedDecodingContainerProtocol {
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -42,7 +42,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol {
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -50,7 +50,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol {
}
func nestedContainer<NestedKey: CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -58,7 +58,7 @@ extension ParametersDecoder: KeyedDecodingContainerProtocol {
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
try self.decoder.push(_StructuredHeaderCodingKey(key))
try self.decoder.push(_StructuredHeaderCodingKey(key, keyDecodingStrategy: self.decoder.keyDecodingStrategy))
defer {
self.decoder.pop()
}
@@ -13,13 +13,50 @@
//===----------------------------------------------------------------------===//
public struct StructuredFieldDecoder {
public var keyDecodingStrategy: KeyDecodingStrategy?
public init() { }
}
extension StructuredFieldDecoder {
public struct KeyDecodingStrategy: Hashable {
fileprivate enum Base: Hashable {
case lowercase
}
fileprivate var base: Base
/// Lowercase all coding keys before searching for them in keyed containers such as
/// dictionaries or parameters.
public static let lowercase = KeyDecodingStrategy(base: .lowercase)
}
}
extension StructuredFieldDecoder {
public func decode<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
return try type.init(from: decoder)
}
public func decodeDictionaryField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseDictionaryField()
return try type.init(from: decoder)
}
public func decodeListField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseListField()
return try type.init(from: decoder)
}
public func decodeItemField<StructuredField: Decodable, BaseData: RandomAccessCollection>(_ type: StructuredField.Type = StructuredField.self, from data: BaseData) throws -> StructuredField where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
let parser = StructuredFieldParser(data)
let decoder = _StructuredFieldDecoder(parser, keyDecodingStrategy: self.keyDecodingStrategy)
try decoder.parseItemField()
return try type.init(from: decoder)
}
}
@@ -31,9 +68,12 @@ class _StructuredFieldDecoder<BaseData: RandomAccessCollection> where BaseData.E
// our way down with values, but doing that is a CoWy nightmare from which we cannot escape.
private var _codingStack: [CodingStackEntry]
init(_ parser: StructuredFieldParser<BaseData>) {
var keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?
init(_ parser: StructuredFieldParser<BaseData>, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) {
self.parser = parser
self._codingStack = []
self.keyDecodingStrategy = keyDecodingStrategy
}
}
@@ -59,13 +99,10 @@ extension _StructuredFieldDecoder: Decoder {
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
if self.currentElement == nil {
// First parse, this is a dictionary.
// TODO: This assumption is wrong. Item and List headers may appear here if users want
// their parameters. We have to check for those cases.
let parsed = try self.parser.parseDictionaryField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .dictionary(parsed)))
// First parse. This may be a dictionary, but depending on the keys this may also be list or item.
// We can't really detect this (Key isn't caseiterable) so we just kinda have to hope. Users can tell
// us with alternative methods if we're wrong.
try self.parseDictionaryField()
}
switch self.currentElement! {
@@ -86,16 +123,13 @@ extension _StructuredFieldDecoder: Decoder {
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
if self.currentElement == nil {
// First parse, this is a list header.
let parsed = try self.parser.parseListField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .list(parsed)))
try self.parseListField()
}
// We have unkeyed containers for lists, inner lists, and bare inner lists.
switch self.currentElement! {
case .list(let items):
fatalError("Not yet implemented")
return TopLevelListDecoder(items, decoder: self)
case .innerList(let innerList):
return BareInnerListDecoder(innerList.bareInnerList, decoder: self)
case .bareInnerList(let bareInnerList):
@@ -109,10 +143,7 @@ extension _StructuredFieldDecoder: Decoder {
func singleValueContainer() throws -> SingleValueDecodingContainer {
if self.currentElement == nil {
// First parse, this is a an item header.
let parsed = try self.parser.parseItemField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .item(parsed)))
try self.parseItemField()
}
// We have single value containers for items and bareItems.
@@ -125,6 +156,30 @@ extension _StructuredFieldDecoder: Decoder {
throw StructuredHeaderError.invalidTypeForItem
}
}
func parseDictionaryField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseDictionaryField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .dictionary(parsed)))
}
func parseListField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseListField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .list(parsed)))
}
func parseItemField() throws {
precondition(self._codingStack.isEmpty)
let parsed = try self.parser.parseItemField()
// We unconditionally add to the base of the coding stack here. This element is never popped off.
self._codingStack.append(CodingStackEntry(key: .init(stringValue: ""), element: .item(parsed)))
}
}
extension _StructuredFieldDecoder {
@@ -26,8 +26,16 @@ struct _StructuredHeaderCodingKey : CodingKey {
self.intValue = intValue
}
init<Key: CodingKey>(_ key: Key) {
self.stringValue = key.stringValue
init<Key: CodingKey>(_ key: Key, keyDecodingStrategy: StructuredFieldDecoder.KeyDecodingStrategy?) {
switch keyDecodingStrategy {
case .none:
self.stringValue = key.stringValue
case .some(.lowercase):
self.stringValue = key.stringValue.lowercased()
default:
preconditionFailure("Invalid key decoding strategy")
}
self.intValue = key.intValue
}
}
@@ -0,0 +1,109 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
struct TopLevelListDecoder<BaseData: RandomAccessCollection> where BaseData.Element == UInt8, BaseData.SubSequence: Hashable {
private var list: [ItemOrInnerList<BaseData.SubSequence>]
private var currentOffset: Int
private var decoder: _StructuredFieldDecoder<BaseData>
init(_ list: [ItemOrInnerList<BaseData.SubSequence>], decoder: _StructuredFieldDecoder<BaseData>) {
self.list = list
self.currentOffset = 0
self.decoder = decoder
}
}
extension TopLevelListDecoder: UnkeyedDecodingContainer {
var codingPath: [CodingKey] {
return self.decoder.codingPath
}
var count: Int? {
return self.list.count
}
var isAtEnd: Bool {
return self.currentOffset == self.list.count
}
var currentIndex: Int {
return self.currentOffset
}
mutating func decodeNil() throws -> Bool {
// We never decode nil.
return false
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
// This is a request to decode a scalar. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
}
let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset)
defer {
self.currentOffset += 1
}
try self.decoder.push(codingKey)
defer {
self.decoder.pop()
}
return try type.init(from: self.decoder)
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
// This is a request to decode a full item. We decode the next entry and increment the index.
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
}
let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset)
defer {
self.currentOffset += 1
}
try self.decoder.push(codingKey)
defer {
self.decoder.pop()
}
return try self.decoder.container(keyedBy: type)
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !self.isAtEnd else {
throw StructuredHeaderError.indexOutOfRange
}
let codingKey = _StructuredHeaderCodingKey(intValue: self.currentOffset)
defer {
self.currentOffset += 1
}
try self.decoder.push(codingKey)
defer {
self.decoder.pop()
}
return try self.decoder.unkeyedContainer()
}
mutating func superDecoder() throws -> Decoder {
// No inheritance here folks
throw StructuredHeaderError.invalidTypeForItem
}
}
@@ -121,4 +121,71 @@ final class StructuredFieldDecoderTests: XCTestCase {
XCTAssertThrowsError(try StructuredFieldDecoder().decode(Bool.self, from: Array(headerField.utf8)))
XCTAssertThrowsError(try StructuredFieldDecoder().decode(String.self, from: Array(intField.utf8)))
}
func testDecodingTopLevelItemWithParameters() throws {
struct IntWithParams: Codable, Equatable {
var item: Int
var parameters: [String: String]
}
let headerField = "5;bar=baz"
let expected = IntWithParams(item: 5, parameters: ["bar": "baz"])
XCTAssertEqual(expected, try StructuredFieldDecoder().decodeItemField(from: Array(headerField.utf8)))
}
func testDecodingTopLevelList() throws {
let headerField = "foo, bar, baz"
let expected = ["foo", "bar", "baz"]
XCTAssertEqual(expected, try StructuredFieldDecoder().decodeListField(from: Array(headerField.utf8)))
XCTAssertEqual(expected, try StructuredFieldDecoder().decode(from: Array(headerField.utf8)))
}
func testDecodingLowercaseKeyStrategy() throws {
struct Camel: Codable, Equatable {
var hasHump: Bool
}
let headerField = "hashump"
let expected = Camel(hasHump: true)
var decoder = StructuredFieldDecoder()
decoder.keyDecodingStrategy = .lowercase
XCTAssertEqual(expected, try decoder.decodeDictionaryField(from: Array(headerField.utf8)))
}
func testDecodingLowercaseKeyStrategyParameters() throws {
struct CamelParameters: Codable, Equatable {
var hasHump: Bool
}
struct Camel: Codable, Equatable {
var item: String
var parameters: CamelParameters
}
let headerField = "dromedary;hashump"
let expected = Camel(item: "dromedary", parameters: .init(hasHump: true))
var decoder = StructuredFieldDecoder()
decoder.keyDecodingStrategy = .lowercase
XCTAssertEqual(expected, try decoder.decodeItemField(from: Array(headerField.utf8)))
}
func testDecodingKeyMissingFromDictionary() throws {
struct MissingKey: Codable {
var foo: Int
}
let headerField = "bar=baz"
XCTAssertThrowsError(try StructuredFieldDecoder().decodeDictionaryField(MissingKey.self, from: Array(headerField.utf8)))
}
func testDecodingKeyAsItemWantedInnerList() throws {
struct MissingInnerList: Codable {
var innerlist: [String]
}
let headerField = "innerlist=x"
XCTAssertThrowsError(try StructuredFieldDecoder().decodeDictionaryField(MissingInnerList.self, from: Array(headerField.utf8)))
}
}