pointfreeco / swift-custom-dump

A collection of tools for debugging, diffing, and testing your application's data structures.
MIT License
800 stars 89 forks source link

Nested dictionaries are not sorted when using `customDump(_:to:)` #87

Closed sareninden closed 1 year ago

sareninden commented 1 year ago

Describe the bug When using customDump(_:to:) with a plain dictionary eg [String: Int] the keys are sorted correctly. When this dictionary is nested, eg in a struct, the keys are no longer sorted. I noticed this bug when I migrated a project from 0.6.1 to 0.10.2 (seems to occur from 0.10.0 and above).

To Reproduce

import CustomDump
import XCTest

final class DictionarySortedDumpTests: XCTestCase {
    // Works as expected
    func testDictionaryDump() {
        // Given
        let dictionary = ["a": 5, "b": 9, "c": 1, "d": -3, "e": 12]
        let expectedResult = """
[
  "a": 5,
  "b": 9,
  "c": 1,
  "d": -3,
  "e": 12
]
"""

        // When
        var buffer = Buffer()
        customDump(dictionary, to: &buffer)

        // Then
        XCTAssertEqual(buffer.value, expectedResult)
    }

    // Fails for ~(5! - 1) times
    func testNestedDictionaryDump() {
        // Given
        let dictionary = ["a": 5, "b": 9, "c": 1, "d": -3, "e": 12]
        let expectedResult = """
NestedDictionary(
  content: [
    "a": 5,
    "b": 9,
    "c": 1,
    "d": -1,
    "e": 12
  ]
)
"""

        // When
        var buffer = Buffer()
        customDump(NestedDictionary(content: dictionary), to: &buffer)

        // Then
        XCTAssertEqual(buffer.value, expectedResult)
    }
}

private struct Buffer: TextOutputStream {
    private(set) var value: String = ""
    mutating func write(_ string: String) {
        value += string
    }
}

private struct NestedDictionary {
    private let content: [String: Int]

    init(content: [String: Int]) {
        self.content = content
    }
}

Expected behavior I would expect that nested dictionaries are sorted alphabetically like it was in version 0.9.1 and below. The consistent output is important when for example using snapshot testing. Now every time we record new snapshots the files change. But also the compare fails.

Screenshots

Environment

Additional context