-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlTests.swift
More file actions
496 lines (453 loc) · 19.4 KB
/
Copy pathControlTests.swift
File metadata and controls
496 lines (453 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//
// ControlTests.swift
// AndroidSwiftUICoreTests
//
import Testing
import Foundation
@testable import AndroidSwiftUICore
#if canImport(Observation)
import Observation
@Observable final class ObservableModel { var counter = 0; var name = "" }
#endif
@Suite("Controls and environment")
struct ControlTests {
@Test("Slider emits value, bounds, and a working double callback")
func slider() {
struct Screen: View {
@State var value = 0.5
var body: some View { Slider(value: $value, in: 0...1) }
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(node.props["value"] == .double(0.5))
if case .int(let id)? = node.props["onChange"] {
host.callbacks.invokeDouble(Int64(id), 0.75)
}
node = host.evaluate()
#expect(node.props["value"] == .double(0.75))
}
@Test("TextField round-trips its binding through the string callback")
func textField() {
struct Screen: View {
@State var name = ""
var body: some View { TextField("Name", text: $name) }
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(node.props["text"] == .string(""))
if case .int(let id)? = node.props["onChange"] {
host.callbacks.invokeString(Int64(id), "Coleman")
}
node = host.evaluate()
#expect(node.props["text"] == .string("Coleman"))
}
@Test("focused drives a field's focus and adopts focus the user gives it")
func focusState() {
struct Screen: View {
@State var name = ""
@FocusState var focused = false
var body: some View {
TextField("Name", text: $name).focused($focused)
}
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(isFocused(node) == false)
guard let callback = focusCallback(node) else {
Issue.record("missing focus callback"); return
}
// the user tapping the field reports focus back into the state
host.callbacks.invokeBool(callback, true)
node = host.evaluate()
#expect(isFocused(node) == true)
// and blurring clears it
host.callbacks.invokeBool(focusCallback(node) ?? callback, false)
node = host.evaluate()
#expect(isFocused(node) == false)
}
@Test("focused(equals:) arbitrates between fields and a sibling's blur can't steal focus")
func focusStateEquals() {
enum Field: Hashable { case first, second }
struct Screen: View {
@State var a = ""
@State var b = ""
@FocusState var focus: Field? = nil
var body: some View {
VStack {
TextField("A", text: $a).focused($focus, equals: .first)
TextField("B", text: $b).focused($focus, equals: .second)
}
}
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(isFocused(node.children[0]) == false)
#expect(isFocused(node.children[1]) == false)
guard let firstCallback = focusCallback(node.children[0]),
let secondCallback = focusCallback(node.children[1]) else {
Issue.record("missing focus callbacks"); return
}
// second field takes focus
host.callbacks.invokeBool(secondCallback, true)
node = host.evaluate()
#expect(isFocused(node.children[0]) == false)
#expect(isFocused(node.children[1]) == true)
// the first field's late blur must NOT clear the second field's focus
host.callbacks.invokeBool(firstCallback, false)
node = host.evaluate()
#expect(isFocused(node.children[1]) == true)
}
@Test("ProgressView keeps determinacy and shape independent")
func progressViewStyle() {
// no value, no style: indeterminate, and the interpreter picks circular
let plain = ViewHost(ProgressView()).evaluate()
#expect(plain.props["value"] == nil)
#expect(plain.modifiers.first { $0.kind == "progressViewStyle" } == nil)
// a value is normalized against total
let valued = ViewHost(ProgressView(value: 25.0, total: 100.0)).evaluate()
#expect(valued.props["value"] == .double(0.25))
// a determinate circular bar — impossible before, since shape was
// inferred from determinacy
let circular = ViewHost(ProgressView(value: 0.5).progressViewStyle(.circular)).evaluate()
#expect(circular.props["value"] == .double(0.5))
#expect(circular.modifiers.first { $0.kind == "progressViewStyle" }?.args["style"] == .string("circular"))
// and an indeterminate linear one
let linear = ViewHost(ProgressView().progressViewStyle(.linear)).evaluate()
#expect(linear.props["value"] == nil)
#expect(linear.modifiers.first { $0.kind == "progressViewStyle" }?.args["style"] == .string("linear"))
}
@Test("ProgressView carries a label when given one")
func progressViewLabel() {
let titled = ViewHost(ProgressView("Loading")).evaluate()
#expect(firstTextString(titled) == "Loading")
#expect(titled.props["value"] == nil)
let both = ViewHost(ProgressView("Copying", value: 0.4)).evaluate()
#expect(firstTextString(both) == "Copying")
#expect(both.props["value"] == .double(0.4))
// the builder form takes any view
let built = ViewHost(ProgressView(value: 0.1) { Text("Custom") }).evaluate()
#expect(firstTextString(built) == "Custom")
// and the label-free forms stay label-free
#expect(ViewHost(ProgressView()).evaluate().children.isEmpty)
#expect(ViewHost(ProgressView(value: 0.5)).evaluate().children.isEmpty)
}
@Test("A control style is emitted on the view it is applied to")
func controlStyleEmission() {
let node = ViewHost(Button("Go") {}.buttonStyle(.bordered)).evaluate()
#expect(node.modifiers.first { $0.kind == "buttonStyle" }?.args["style"] == .string("bordered"))
// each control's style is a distinct kind, so they compose rather than
// overwrite one another
let both = ViewHost(
VStack { Text("x") }
.buttonStyle(.plain)
.pickerStyle(.segmented)
).evaluate()
#expect(both.modifiers.first { $0.kind == "buttonStyle" }?.args["style"] == .string("plain"))
#expect(both.modifiers.first { $0.kind == "pickerStyle" }?.args["style"] == .string("segmented"))
#expect(both.modifiers.first { $0.kind == "toggleStyle" } == nil)
}
@Test("A style set on a container is inherited by the controls inside it")
func controlStyleInheritance() {
// The style rides on the container; the interpreter carries it down as
// an environment value, so the buttons themselves carry no style of
// their own — that inheritance is what makes this different from a
// per-node modifier.
let node = ViewHost(
VStack {
Button("One") {}
Button("Two") {}
}
.buttonStyle(.borderedProminent)
).evaluate()
#expect(node.type == "VStack")
#expect(node.modifiers.first { $0.kind == "buttonStyle" }?.args["style"] == .string("borderedProminent"))
#expect(node.children.count == 2)
for child in node.children {
#expect(child.type == "Button")
#expect(child.modifiers.first { $0.kind == "buttonStyle" } == nil)
}
}
@Test("Every control style spelling reaches its own modifier kind")
func controlStyleKinds() {
let toggle = ViewHost(Toggle("t", isOn: .constant(true)).toggleStyle(.checkbox)).evaluate()
#expect(toggle.modifiers.first { $0.kind == "toggleStyle" }?.args["style"] == .string("checkbox"))
let field = ViewHost(TextField("n", text: .constant("")).textFieldStyle(.plain)).evaluate()
#expect(field.modifiers.first { $0.kind == "textFieldStyle" }?.args["style"] == .string("plain"))
}
@Test("Keyboard type and submit label emit their spelling")
func keyboardConfig() {
struct Screen: View {
@State var text = ""
var body: some View {
TextField("Amount", text: $text)
.keyboardType(.decimalPad)
.submitLabel(.search)
}
}
let node = ViewHost(Screen()).evaluate()
#expect(node.modifiers.first { $0.kind == "keyboardType" }?.args["type"] == .string("decimalPad"))
#expect(node.modifiers.first { $0.kind == "submitLabel" }?.args["label"] == .string("search"))
}
@Test("onSubmit registers a callback the field can fire")
func onSubmit() {
var submitted = false
struct Screen: View {
let onSubmit: () -> Void
@State var text = ""
var body: some View {
TextField("Search", text: $text).onSubmit(perform: onSubmit)
}
}
let host = ViewHost(Screen(onSubmit: { submitted = true }))
let node = host.evaluate()
guard case .int(let id)? = node.modifiers.first(where: { $0.kind == "onSubmit" })?.args["action"] else {
Issue.record("missing onSubmit callback"); return
}
host.callbacks.invokeVoid(Int64(id))
#expect(submitted)
}
@Test("Picker emits tagged children and maps the selection string back")
func picker() {
struct Screen: View {
@State var fruit = "Apple"
var body: some View {
Picker("Fruit", selection: $fruit) {
Text("Apple").tag("Apple")
Text("Banana").tag("Banana")
}
}
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(node.props["selection"] == .string("Apple"))
#expect(node.children.count == 2)
// each child carries its tag as a modifier
let tags = node.children.compactMap { child -> String? in
guard let tag = child.modifiers.first(where: { $0.kind == "tag" }),
case .string(let value)? = tag.args["value"] else { return nil }
return value
}
#expect(tags == ["Apple", "Banana"])
if case .int(let id)? = node.props["onChange"] {
host.callbacks.invokeString(Int64(id), "Banana")
}
node = host.evaluate()
#expect(node.props["selection"] == .string("Banana"))
}
@Test("Stepper increments and decrements within bounds, updating its label")
func stepper() {
struct Screen: View {
@State var count = 5
var body: some View { Stepper("Count: \(count)", value: $count, in: 0...10) }
}
let host = ViewHost(Screen())
var node = host.evaluate()
#expect(node.type == "Stepper")
if case .int(let inc)? = node.props["onIncrement"] { host.callbacks.invokeVoid(Int64(inc)) }
node = host.evaluate()
#expect(firstTextString(node) == "Count: 6")
if case .int(let dec)? = node.props["onDecrement"] { host.callbacks.invokeVoid(Int64(dec)) }
node = host.evaluate()
#expect(firstTextString(node) == "Count: 5")
}
@Test("SecureField emits a secure TextField node")
func secureField() {
struct Screen: View {
@State var password = ""
var body: some View { SecureField("Password", text: $password) }
}
let node = ViewHost(Screen()).evaluate()
#expect(node.type == "TextField")
#expect(node.props["secure"] == .bool(true))
}
@Test("Menu emits its label and item children")
func menu() {
let node = ViewHost(Menu("Options") {
Button("First") {}
Button("Second") {}
}).evaluate()
#expect(node.type == "Menu")
#expect(node.props["label"] == .string("Options"))
#expect(node.children.count == 2)
}
@Test("Form nests Sections with their header and rows")
func formSection() {
let node = ViewHost(
Form {
Section("General") {
Text("Wi-Fi")
Text("Bluetooth")
}
}
).evaluate()
#expect(node.type == "Form")
let section = node.children.first
#expect(section?.type == "Section")
#expect(section?.props["header"] == .string("General"))
#expect(section?.children.count == 2)
}
@Test("Environment objects reach @Environment properties in the subtree")
func environmentInjection() {
final class Model { var value = 42 }
struct Child: View {
@Environment(Model.self) var model
var body: some View { Text("value \(model.value)") }
}
struct Screen: View {
let model: Model
var body: some View { Child().environment(model) }
}
let node = ViewHost(Screen(model: Model())).evaluate()
#expect(node.props["text"] == .string("value 42"))
}
#if canImport(Observation)
@Test("@Observable mutation triggers the state-change hook")
func observation() {
struct Screen: View {
let model: ObservableModel
var body: some View { Text("count \(model.counter)") }
}
let model = ObservableModel()
let host = ViewHost(Screen(model: model))
var fired = false
host.onStateChange = { fired = true }
var node = host.evaluate()
#expect(node.props["text"] == .string("count 0"))
model.counter += 1
#expect(fired)
node = host.evaluate()
#expect(node.props["text"] == .string("count 1"))
}
@Test("@Bindable projects a two-way binding into an observable model")
func bindableProjection() {
let model = ObservableModel()
@Bindable var bound = model
let binding = $bound.name
binding.wrappedValue = "hi"
#expect(model.name == "hi")
#expect(binding.wrappedValue == "hi")
}
@Test("A TextField bound via @Bindable writes back to the model")
func bindableTextField() {
struct Screen: View {
@Bindable var model: ObservableModel
var body: some View { TextField("Name", text: $model.name) }
}
let model = ObservableModel()
let host = ViewHost(Screen(model: model))
var node = host.evaluate()
#expect(node.props["text"] == .string(""))
if case .int(let id)? = node.props["onChange"] {
host.callbacks.invokeString(Int64(id), "Coleman")
}
#expect(model.name == "Coleman")
node = host.evaluate()
#expect(node.props["text"] == .string("Coleman"))
}
#endif
@Test("DatePicker emits its selection in milliseconds and round-trips a change")
func datePicker() {
let initial = Date(timeIntervalSince1970: 1_768_435_200) // 2026-01-15T00:00:00Z
let changed = Date(timeIntervalSince1970: 1_772_323_200) // 2026-03-01T00:00:00Z
struct Screen: View {
@State var date: Date
var body: some View { DatePicker("Birthday", selection: $date) }
}
let host = ViewHost(Screen(date: initial))
var node = host.evaluate()
#expect(node.type == "DatePicker")
#expect(node.props["millis"] == .double(initial.timeIntervalSince1970 * 1000))
if case .int(let id)? = node.props["onChange"] {
host.callbacks.invokeDouble(Int64(id), changed.timeIntervalSince1970 * 1000)
}
node = host.evaluate()
#expect(node.props["millis"] == .double(changed.timeIntervalSince1970 * 1000))
}
}
/// Whether a field's `focused` modifier currently claims focus.
private func isFocused(_ node: RenderNode) -> Bool? {
guard let mod = node.modifiers.first(where: { $0.kind == "focused" }),
case .bool(let value)? = mod.args["isFocused"] else { return nil }
return value
}
/// The callback a field's `focused` modifier reports focus changes through.
private func focusCallback(_ node: RenderNode) -> Int64? {
guard let mod = node.modifiers.first(where: { $0.kind == "focused" }),
case .int(let id)? = mod.args["onChange"] else { return nil }
return Int64(id)
}
@Suite("AppStorage")
struct AppStorageTests {
@Test("A stored value survives a fresh wrapper, as it would a relaunch")
func persistsAcrossWrappers() {
AppStorageStore.backend = InMemoryAppStorage()
// first "launch": default, then the user changes it
struct First: View {
@AppStorage("volume") var volume = 5
var body: some View { Text("\(volume)") }
}
let first = First()
#expect(first.volume == 5)
first.volume = 9
// a fresh wrapper reads what was written, not the default
struct Second: View {
@AppStorage("volume") var volume = 5
var body: some View { Text("\(volume)") }
}
#expect(Second().volume == 9)
}
@Test("Each supported type round-trips under its own key")
func supportedTypes() {
AppStorageStore.backend = InMemoryAppStorage()
struct Screen: View {
@AppStorage("on") var on = false
@AppStorage("count") var count = 0
@AppStorage("ratio") var ratio = 0.0
@AppStorage("name") var name = ""
var body: some View { Text(name) }
}
let screen = Screen()
screen.on = true
screen.count = 42
screen.ratio = 0.75
screen.name = "Coleman"
#expect(AppStorageStore.read("on", as: Bool.self) == true)
#expect(AppStorageStore.read("count", as: Int.self) == 42)
#expect(AppStorageStore.read("ratio", as: Double.self) == 0.75)
#expect(AppStorageStore.read("name", as: String.self) == "Coleman")
// keys stay independent
#expect(Screen().count == 42)
#expect(Screen().name == "Coleman")
}
@Test("The projected binding writes through to the store")
func bindingWritesThrough() {
AppStorageStore.backend = InMemoryAppStorage()
struct Screen: View {
@AppStorage("nickname") var nickname = ""
var body: some View { TextField("Name", text: $nickname) }
}
let host = ViewHost(Screen())
let node = host.evaluate()
guard case .int(let id)? = node.props["onChange"] else {
Issue.record("missing field callback"); return
}
host.callbacks.invokeString(Int64(id), "typed in")
#expect(AppStorageStore.read("nickname", as: String.self) == "typed in")
}
@Test("A file-backed store reloads what a previous instance wrote")
func fileBackedRoundTrip() throws {
let directory = NSTemporaryDirectory() + "appstorage-test-\(UInt32.random(in: 0..<100_000))"
try FileManager.default.createDirectory(atPath: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(atPath: directory) }
let first = FileAppStorage(directory: directory)
first.set(7, forKey: "launches")
first.set("dark", forKey: "theme")
// a second instance is what the next launch sees
let second = FileAppStorage(directory: directory)
#expect(second.value(forKey: "launches") as? Int == 7)
#expect(second.value(forKey: "theme") as? String == "dark")
// and removal sticks
second.set(nil, forKey: "theme")
#expect(FileAppStorage(directory: directory).value(forKey: "theme") == nil)
}
}