diff --git a/Codec/Tests/CodecTests/ResultTests.swift b/Codec/Tests/CodecTests/ResultTests.swift new file mode 100644 index 00000000..b3178711 --- /dev/null +++ b/Codec/Tests/CodecTests/ResultTests.swift @@ -0,0 +1,68 @@ +import Foundation +import Testing + +@testable import Codec + +struct ResultCodingTests { + enum ResultError: Error, Codable { + case unknownError(String) + } + + enum MyResult: Codable { + case success(Success) + case failure(ResultError) + + private enum CodingKeys: String, CodingKey { + case success, failure + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + if container.contains(.success) { + let value = try container.decode(Success.self, forKey: .success) + self = .success(value) + } else if container.contains(.failure) { + let error = try container.decode(ResultError.self, forKey: .failure) + self = .failure(error) + } else { + throw DecodingError.dataCorruptedError(forKey: .failure, in: container, debugDescription: "Invalid data format") + } + } + + // Encodable implementation + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + switch self { + case let .success(value): + try container.encode(value, forKey: .success) + case let .failure(error): + try container.encode(error, forKey: .failure) + } + } + } + + @Test func result() throws { + let successResult: MyResult = .success("Success!") + let failureResult: MyResult = .failure(.unknownError("An unknown error occurred")) + + let encodedSuccess = try JamEncoder.encode(successResult) + let encodedFailure = try JamEncoder.encode(failureResult) + + let decodedSuccess = try JamDecoder.decode(MyResult.self, from: encodedSuccess) + let decodedFailure = try JamDecoder.decode(MyResult.self, from: encodedFailure) + #expect(decodedFailure != nil) + #expect(decodedSuccess != nil) + } + + @Test func invalidVariant() throws { + // Invalid variant value (e.g. value 2) + let invalidData = Data([0x02] + "Invalid variant".utf8) + + // Expect decoding to fail and return nil + #expect(throws: Error.self) { + _ = try JamDecoder.decode(Result.self, from: invalidData) + } + } +}