AnyCodable
AnyCodable copied to clipboard
Improve tests and fix encoding of NSNumber
Changes
- Improve tests
- Some minor changes to remove force unwrapping in tests.
- Existing encoding tests validate that deserialized serialized value is equal to some value. This is different than directly asserting that the serialized value is as expected, and it lets some errors go unnoticed as equality on
NSDictionaryis very permissive. For instance this test will pass:
let dictionary: [String: AnyEncodable] = ["k": true]
let json = try JSONEncoder().encode(dictionary)
let encodedJSONObject = try JSONSerialization.jsonObject(with: json, options: []) as! NSDictionary
let expected = "{ \"k\": 1 }".data(using: .utf8)!
let expectedJSONObject = try JSONSerialization.jsonObject(with: expected, options: []) as! NSDictionary
XCTAssertEqual(encodedJSONObject, expectedJSONObject)
Instead if we compare the serialized value ({ "k": true }) to that of the expectation ({ "k": 1 }) this test will logically fail.
I added util function to ease the comparison of serialized JSON strings.
- Fix serialization of
NSNumber. There were two issues:- We test for
as? Boolbefore testingas? NSNumber. ANSNumbercan always be casted as aBoolso the later case was never hit Swift.Boolare represented as a char type in ObjC and the mapping was incorrect- Add a test for
NSNumber's serialization.
- We test for
- Nit: reduce runtime computations when encoding
NSNumber, which after this fix might be more frequent
Also related: https://github.com/Flight-School/AnyCodable/pull/76, but this PR should do a better job at preventing future regressions