Skip to content

Commit

Permalink
Coding dictionaries (#125)
Browse files Browse the repository at this point in the history
* Add test for empty dictionary and some comments
* removing invalid pre-condition - this is a valid scenarion when encoding an empty dictionary

---------

Co-authored-by: jberling <johan@dynamictype.se>
  • Loading branch information
heckj and jberling authored Feb 27, 2024
1 parent b9d2c8f commit ff4a1f6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ final class AutomergeEncoderImpl {
if codingPath.map({ AnyCodingKey($0) }).starts(with: prefix) {
switch containerType {
case .Key:
precondition(!mapKeysWritten.isEmpty)
// Remove keys that exist in this objectId that weren't
// written during encode. (clean up 'dead' keys from maps)
let extraAutomergeKeys = document.keys(obj: objectIdForContainer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,47 @@ final class AutomergeDictionaryEncodeDecodeTests: XCTestCase {
}

let encoder = AutomergeEncoder(doc: doc)
let decoder = AutomergeDecoder(doc: doc)

var wrapper = Wrapper()
wrapper.exampleDictionary[1] = "one"
wrapper.exampleDictionary[2] = "two"

XCTExpectFailure("Automerge encoder can't encode keys other than strings.")
try encoder.encode(wrapper)
XCTAssertThrowsError(try encoder.encode(wrapper))
// Automerge throws a DocError because it only supports
// Strings as keys for dictionaries.
// DocError(inner: AutomergeUniffi.DocError.WrongObjectType(message: "WrongObjectType"))
}

func testEmptyDictionaryEncode() throws {
// example of Dictionary with keys other than a string

struct Wrapper: Codable, Equatable {
var exampleDictionary: [String: Int] = [:]
}

let encoder = AutomergeEncoder(doc: doc)
let decoder = AutomergeDecoder(doc: doc)
let wrapper = Wrapper()

try encoder.encode(wrapper)
let replica = try decoder.decode(Wrapper.self)
XCTAssertEqual(replica, wrapper)
}

func testEmptyDictionaryEncode() throws {
func testEmptyDictionaryEncodeAtRoot() throws {
let exampleDictionary: [String: Int] = [:]

let encoder = AutomergeEncoder(doc: doc)
let decoder = AutomergeDecoder(doc: doc)

// this fails when you encode an empty dictionary
try encoder.encode(exampleDictionary)

let replica = try decoder.decode([String: Int].self)
XCTAssertEqual(replica, exampleDictionary)
}

func testWorkingDictionaryEncode() throws {
var exampleDictionary: [String: Int] = [:]

exampleDictionary["one"] = 1
Expand Down

0 comments on commit ff4a1f6

Please sign in to comment.