Defaults/Tests/DefaultsTests/DefaultsSwiftUITests.swift

66 lines
1.8 KiB
Swift
Raw Normal View History

import Foundation
import SwiftUI
2024-09-26 05:17:26 +08:00
import Testing
import Defaults
2024-09-26 05:17:26 +08:00
private let suite_ = createSuite()
#if os(macOS)
typealias XColor = NSColor
#else
typealias XColor = UIColor
#endif
extension Defaults.Keys {
2024-09-26 05:17:26 +08:00
fileprivate static let hasUnicorn = Key<Bool>("swiftui_hasUnicorn", default: false, suite: suite_)
fileprivate static let user = Key<User>("swiftui_user", default: User(username: "Hank", password: "123456"), suite: suite_)
fileprivate static let setInt = Key<Set<Int>>("swiftui_setInt", default: Set(1...3), suite: suite_)
fileprivate static let color = Key<Color>("swiftui_color", default: .black, suite: suite_)
}
struct ContentView: View {
@Default(.hasUnicorn) var hasUnicorn
@Default(.user) var user
@Default(.setInt) var setInt
@Default(.color) var color
var body: some View {
Text("User \(user.username) has Unicorn: \(String(hasUnicorn))")
.foregroundColor(color)
Toggle("Toggle Unicorn", isOn: $hasUnicorn)
}
}
2024-09-26 05:17:26 +08:00
@Suite(.serialized)
final class DefaultsSwiftUITests {
init() {
Defaults.removeAll(suite: suite_)
}
2024-09-26 05:17:26 +08:00
deinit {
Defaults.removeAll(suite: suite_)
}
2024-09-26 05:17:26 +08:00
@Test
func testSwiftUIObserve() {
let view = ContentView()
2024-09-26 05:17:26 +08:00
#expect(!view.hasUnicorn)
#expect(view.user.username == "Hank")
#expect(view.setInt.count == 3)
#expect(XColor(view.color) == XColor(Color.black))
view.user = User(username: "Chen", password: "123456")
view.hasUnicorn.toggle()
view.setInt.insert(4)
view.color = Color(.sRGB, red: 100, green: 100, blue: 100, opacity: 1)
2024-09-26 05:17:26 +08:00
#expect(view.hasUnicorn)
#expect(view.user.username == "Chen")
#expect(view.setInt == Set(1...4))
#expect(!Default(.hasUnicorn).defaultValue)
#expect(!Default(.hasUnicorn).isDefaultValue)
#expect(XColor(view.color) != XColor(Color.black))
#expect(XColor(view.color) == XColor(Color(.sRGB, red: 100, green: 100, blue: 100, opacity: 1)))
}
}