示例工程 17-reflection-keypaths

17-reflection-keypaths/Tests/Ch17KitTests/KeyPathTests.swift

swift · 2.1 KB

import Testing
 
@testable import Ch17Kit
 
@Suite("KeyPath 与动态成员")
struct KeyPathTests {
    func makePerson() -> Person {
        Person(
            name: "ada",
            age: 36,
            address: Address(city: "Beijing", zip: "100000"),
            nickname: nil
        )
    }
 
    @Test func keyPathReadsAndWrites() {
        var person = makePerson()
        #expect(KeyPathLab.value(person, at: \.name) == "ada")
        KeyPathLab.set(&person, \.age, to: 40)
        #expect(person.age == 40)
    }
 
    @Test func sortingUsesKeyPath() {
        let people = [
            Person(name: "bob", age: 20, address: Address(city: "A", zip: "1"), nickname: nil),
            Person(name: "ann", age: 30, address: Address(city: "B", zip: "2"), nickname: nil),
        ]
        #expect(KeyPathLab.sortedByAge(people).map(\.name) == ["bob", "ann"])
    }
 
    @Test func storedKeyPathIsUsable() {
        #expect(KeyPathLab.value(makePerson(), at: KeyPathLab.ageKeyPath) == 36)
    }
 
    @Test func dynamicMemberReadsAndWrites() {
        var settings = StringSettings(["theme": "light"])
        #expect(settings.theme == "light")
        settings.theme = "dark"
        settings.font = "mono"
        #expect(settings.theme == "dark")
        #expect(settings.allKeys == ["font", "theme"])
        #expect(settings.missing == nil)
    }
 
    @Test func dynamicCallableForwardsArguments() {
        #expect(Sum()(1, 2, 3, 4) == 10)
        #expect(Sum()() == 0)
    }
}
 
@Suite("身份")
struct IdentityTests {
    @Test func sameReferenceCountsOnce() {
        let node = Node(value: 1)
        let alias = node
        let other = Node(value: 1)
        #expect(IdentityLab.distinctCount([node, alias, other]) == 2)
    }
 
    @Test func identityIgnoresEqualValues() {
        let first = Node(value: 1)
        let second = Node(value: 1)
        #expect(!IdentityLab.containsSameInstance([first], as: second))
        #expect(IdentityLab.containsSameInstance([first], as: first))
    }
 
    @Test func keyPathIsAnEightByteHandle() {
        #expect(MemoryLayout<KeyPath<Person, Int>>.size == 8)
    }
}