Skip to content

Commit

Permalink
update Results test
Browse files Browse the repository at this point in the history
  • Loading branch information
MacOMNI committed Dec 5, 2024
1 parent 3f4d9c9 commit 99fcaf8
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions Codec/Tests/CodecTests/ResultTests.swift
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")

Check warning on line 29 in Codec/Tests/CodecTests/ResultTests.swift

View check run for this annotation

Codecov / codecov/patch

Codec/Tests/CodecTests/ResultTests.swift#L26-L29

Added lines #L26 - L29 were not covered by tests
}
}

// 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)
}
}
}

0 comments on commit 99fcaf8

Please sign in to comment.