LocalData/Tests/LocalDataTests/AnyCodableTests.swift
Matt Bruce e27e2e38bb Tests AnyCodableTests.swift, AnyStorageKeyTests.swift, AuditTests.swift (+8 more)
Summary:
- Tests: AnyCodableTests.swift, AnyStorageKeyTests.swift, AuditTests.swift, EncryptionLogicTests.swift, FileStorageHelperTests.swift (+6 more)
- Added symbols: struct NonCodable, struct StringKey, typealias Value, struct AuditCatalog, struct TestKey, struct RawProvider (+11 more)

Stats:
- 11 files changed, 698 insertions(+)
2026-01-18 14:53:29 -06:00

56 lines
1.9 KiB
Swift

import Foundation
import Testing
@testable import LocalData
@Suite struct AnyCodableTests {
@Test func encodeDecodePrimitives() throws {
let values: [Any] = [true, 42, 3.14, "hello"]
for value in values {
let anyCodable = AnyCodable(value)
let data = try JSONEncoder().encode(anyCodable)
let decoded = try JSONDecoder().decode(AnyCodable.self, from: data)
if let b = value as? Bool { #expect(decoded.value as? Bool == b) }
else if let i = value as? Int { #expect(decoded.value as? Int == i) }
else if let d = value as? Double { #expect(decoded.value as? Double == d) }
else if let s = value as? String { #expect(decoded.value as? String == s) }
}
}
@Test func encodeDecodeComplex() throws {
let dictionary: [String: Any] = [
"bool": true,
"int": 123,
"string": "test",
"array": [1, 2, 3],
"nested": ["key": "value"]
]
let anyCodable = AnyCodable(dictionary)
let data = try JSONEncoder().encode(anyCodable)
let decoded = try JSONDecoder().decode(AnyCodable.self, from: data)
guard let result = decoded.value as? [String: Any] else {
Issue.record("Decoded value is not a dictionary")
return
}
#expect(result["bool"] as? Bool == true)
#expect(result["int"] as? Int == 123)
#expect(result["string"] as? String == "test")
#expect((result["array"] as? [Int]) == [1, 2, 3])
#expect((result["nested"] as? [String: String]) == ["key": "value"])
}
@Test func throwsOnInvalidValue() {
struct NonCodable {}
let anyCodable = AnyCodable(NonCodable())
#expect(throws: EncodingError.self) {
_ = try JSONEncoder().encode(anyCodable)
}
}
}