Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Snatch some of the Apple foundation tests to cover edge cases #20

Open
icanzilb opened this issue Sep 7, 2022 · 1 comment
Open

Snatch some of the Apple foundation tests to cover edge cases #20

icanzilb opened this issue Sep 7, 2022 · 1 comment

Comments

@icanzilb
Copy link
Collaborator

icanzilb commented Sep 7, 2022

Codable tests in the foundation repo:

These should help re-create some of the more difficult to hit scenarios like — when do you need a nested unkeyed container in an unkeyed container? Trying to have a [[Int]] property on a Codable struct doesn't seem to hit that codepath in the encoding container 🤷🏽‍♂️

@DivineDominion
Copy link
Contributor

I really like the test helper and the naming (via https://github.com/apple/swift-corelibs-foundation/blob/main/Tests/Foundation/Tests/TestCodable.swift):

func expectRoundTripEquality<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (Data) throws -> T) throws where T : Equatable  {
    do {
        let data = try encode(value)
        let decoded: T = try decode(data)
        if value != decoded {
            throw NSError(domain: "Decode mismatch", code: 0, userInfo: ["msg": "Decoded \(T.self) <\(decoded)> not equal to original <\(value)>"])
        }
    }
}

func expectRoundTripEqualityThroughJSON<T : Codable>(for value: T) throws where T : Equatable {
    let inf = "INF", negInf = "-INF", nan = "NaN"
    let encode = { (_ value: T) throws -> Data in
        let encoder = JSONEncoder()
        encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: inf,
                                                                      negativeInfinity: negInf,
                                                                      nan: nan)
        return try encoder.encode(value)
    }

    let decode = { (_ data: Data) throws -> T in
        let decoder = JSONDecoder()
        decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: inf,
                                                                        negativeInfinity: negInf,
                                                                        nan: nan)
        return try decoder.decode(T.self, from: data)
    }

    try expectRoundTripEquality(of: value, encode: encode, decode: decode)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants