AnyCodable icon indicating copy to clipboard operation
AnyCodable copied to clipboard

Improve tests and fix encoding of NSNumber

Open gsabran opened this issue 1 year ago • 1 comments

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 NSDictionary is 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? Bool before testing as? NSNumber. A NSNumber can always be casted as a Bool so the later case was never hit
    • Swift.Bool are represented as a char type in ObjC and the mapping was incorrect
    • Add a test for NSNumber's serialization.
  • Nit: reduce runtime computations when encoding NSNumber, which after this fix might be more frequent

gsabran avatar Aug 06 '24 22:08 gsabran

Also related: https://github.com/Flight-School/AnyCodable/pull/76, but this PR should do a better job at preventing future regressions

gsabran avatar Aug 06 '24 22:08 gsabran