-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import Foundation | ||
import Testing | ||
|
||
@testable import Codec | ||
|
||
struct ResultCodingTests { | ||
enum ResultError: Error, Codable { | ||
case unknownError(String) | ||
} | ||
|
||
enum MyResult<Success: Codable>: 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<String> = .success("Success!") | ||
let failureResult: MyResult<String> = .failure(.unknownError("An unknown error occurred")) | ||
|
||
let encodedSuccess = try JamEncoder.encode(successResult) | ||
let encodedFailure = try JamEncoder.encode(failureResult) | ||
|
||
let decodedSuccess = try JamDecoder.decode(MyResult<String>.self, from: encodedSuccess) | ||
let decodedFailure = try JamDecoder.decode(MyResult<String>.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<String, ResultError>.self, from: invalidData) | ||
} | ||
} | ||
} |