-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TestStore.swift
2593 lines (2469 loc) · 93.1 KB
/
TestStore.swift
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@_spi(Internals) import CasePaths
import Combine
import ConcurrencyExtras
import CustomDump
import Foundation
import XCTestDynamicOverlay
/// A testable runtime for a reducer.
///
/// This object aids in writing expressive and exhaustive tests for features built in the
/// Composable Architecture. It allows you to send a sequence of actions to the store, and each step
/// of the way you must assert exactly how state changed, and how effect emissions were fed back
/// into the system.
///
/// See the dedicated <doc:Testing> article for detailed information on testing.
///
/// ## Exhaustive testing
///
/// By default, ``TestStore`` requires you to exhaustively prove how your feature evolves from
/// sending use actions and receiving actions from effects. There are multiple ways the test store
/// forces you to do this:
///
/// * After each action is sent you must describe precisely how the state changed from before the
/// action was sent to after it was sent.
///
/// If even the smallest piece of data differs the test will fail. This guarantees that you are
/// proving you know precisely how the state of the system changes.
///
/// * Sending an action can sometimes cause an effect to be executed, and if that effect sends an
/// action back into the system, you **must** explicitly assert that you expect to receive that
/// action from the effect, _and_ you must assert how state changed as a result.
///
/// If you try to send another action before you have handled all effect actions, the test will
/// fail. This guarantees that you do not accidentally forget about an effect action, and that
/// the sequence of steps you are describing will mimic how the application behaves in reality.
///
/// * All effects must complete by the time the test case has finished running, and all effect
/// actions must be asserted on.
///
/// If at the end of the assertion there is still an in-flight effect running or an unreceived
/// action, the assertion will fail. This helps exhaustively prove that you know what effects
/// are in flight and forces you to prove that effects will not cause any future changes to your
/// state.
///
/// For example, given a simple counter reducer:
///
/// ```swift
/// @Reducer
/// struct Counter {
/// struct State: Equatable {
/// var count = 0
/// }
///
/// enum Action {
/// case decrementButtonTapped
/// case incrementButtonTapped
/// }
///
/// var body: some Reducer<State, Action> {
/// Reduce { state, action in
/// switch action {
/// case .decrementButtonTapped:
/// state.count -= 1
/// return .none
///
/// case .incrementButtonTapped:
/// state.count += 1
/// return .none
/// }
/// }
/// }
/// }
/// ```
///
/// One can assert against its behavior over time:
///
/// ```swift
/// @MainActor
/// class CounterTests: XCTestCase {
/// func testCounter() async {
/// let store = TestStore(
/// // Given: a counter state of 0
/// initialState: Counter.State(count: 0),
/// ) {
/// Counter()
/// }
///
/// // When: the increment button is tapped
/// await store.send(.incrementButtonTapped) {
/// // Then: the count should be 1
/// $0.count = 1
/// }
/// }
/// }
/// ```
///
/// Note that in the trailing closure of `.send(.incrementButtonTapped)` we are given a single
/// mutable value of the state before the action was sent, and it is our job to mutate the value to
/// match the state after the action was sent. In this case the `count` field changes to `1`.
///
/// If the change made in the closure does not reflect reality, you will get a test failure with a
/// nicely formatted failure message letting you know exactly what went wrong:
///
/// ```swift
/// await store.send(.incrementButtonTapped) {
/// $0.count = 42
/// }
/// ```
///
/// > ❌ Failure: A state change does not match expectation: …
/// >
/// > ```diff
/// > TestStoreFailureTests.State(
/// > - count: 42
/// > + count: 1
/// > )
/// > ```
/// >
/// > (Expected: −, Actual: +)
///
/// For a more complex example, consider the following bare-bones search feature that uses a clock
/// and cancel token to debounce requests:
///
/// ```swift
/// @Reducer
/// struct Search {
/// struct State: Equatable {
/// var query = ""
/// var results: [String] = []
/// }
///
/// enum Action {
/// case queryChanged(String)
/// case searchResponse(Result<[String], Error>)
/// }
///
/// @Dependency(\.apiClient) var apiClient
/// @Dependency(\.continuousClock) var clock
/// private enum CancelID { case search }
///
/// var body: some Reducer<State, Action> {
/// Reduce { state, action in
/// switch action {
/// case let .queryChanged(query):
/// state.query = query
/// return .run { send in
/// try await self.clock.sleep(for: 0.5)
///
/// await send(.searchResponse(Result { try await self.apiClient.search(query) }))
/// }
/// .cancellable(id: CancelID.search, cancelInFlight: true)
///
/// case let .searchResponse(.success(results)):
/// state.results = results
/// return .none
///
/// case .searchResponse(.failure):
/// // Do error handling here.
/// return .none
/// }
/// }
/// }
/// }
/// ```
///
/// It can be fully tested by overriding the `apiClient` and `continuousClock` dependencies with
/// values that are fully controlled and deterministic:
///
/// ```swift
/// // Create a test clock to control the timing of effects
/// let clock = TestClock()
///
/// let store = TestStore(initialState: Search.State()) {
/// Search()
/// } withDependencies: {
/// // Override the clock dependency with the test clock
/// $0.continuousClock = clock
///
/// // Simulate a search response with one item
/// $0.apiClient.search = { _ in
/// ["Composable Architecture"]
/// }
/// )
///
/// // Change the query
/// await store.send(.searchFieldChanged("c") {
/// // Assert that state updates accordingly
/// $0.query = "c"
/// }
///
/// // Advance the clock by enough to get past the debounce
/// await clock.advance(by: 0.5)
///
/// // Assert that the expected response is received
/// await store.receive(\.searchResponse.success) {
/// $0.results = ["Composable Architecture"]
/// }
/// ```
///
/// This test is proving that when the search query changes some search responses are delivered and
/// state updates accordingly.
///
/// If we did not assert that the `searchResponse` action was received, we would get the following
/// test failure:
///
/// > ❌ Failure: The store received 1 unexpected action after this one: …
/// >
/// > ```
/// > Unhandled actions: [
/// > [0]: Search.Action.searchResponse
/// > ]
/// > ```
///
/// This helpfully lets us know that we have no asserted on everything that happened in the feature,
/// which could be hiding a bug from us.
///
/// Or if we had sent another action before handling the effect's action we would have also gotten
/// a test failure:
///
/// > ❌ Failure: Must handle 1 received action before sending an action: …
/// >
/// > ```
/// > Unhandled actions: [
/// > [0]: Search.Action.searchResponse
/// > ]
/// > ```
///
/// All of these types of failures help you prove that you know exactly how your feature evolves as
/// actions are sent into the system. If the library did not produce a test failure in these
/// situations it could be hiding subtle bugs in your code. For example, when the user clears the
/// search query you probably expect that the results are cleared and no search request is executed
/// since there is no query. This can be done like so:
///
/// ```swift
/// await store.send(.queryChanged("")) {
/// $0.query = ""
/// $0.results = []
/// }
///
/// // No need to perform `store.receive` since we do not expect a search
/// // effect to execute.
/// ```
///
/// But, if in the future a bug is introduced causing a search request to be executed even when the
/// query is empty, you will get a test failure because a new effect is being created that is not
/// being asserted on. This is the power of exhaustive testing.
///
/// ## Non-exhaustive testing
///
/// While exhaustive testing can be powerful, it can also be a nuisance, especially when testing how
/// many features integrate together. This is why sometimes you may want to selectively test in a
/// non-exhaustive style.
///
/// > Tip: The concept of "non-exhaustive test store" was first introduced by
/// [Krzysztof Zabłocki][merowing.info] in a [blog post][exhaustive-testing-in-tca] and
/// [conference talk][Composable-Architecture-at-Scale], and then later became integrated into the
/// core library.
///
/// Test stores are exhaustive by default, which means you must assert on every state change, and
/// how ever effect feeds data back into the system, and you must make sure that all effects
/// complete before the test is finished. To turn off exhaustivity you can set ``exhaustivity``
/// to ``Exhaustivity/off``. When that is done the ``TestStore``'s behavior changes:
///
/// * The trailing closures of ``send(_:assert:file:line:)-2co21`` and
/// ``receive(_:timeout:assert:file:line:)-6325h`` no longer need to assert on all state
/// changes. They can assert on any subset of changes, and only if they make an incorrect
/// mutation will a test failure be reported.
/// * The ``send(_:assert:file:line:)-2co21`` and ``receive(_:timeout:assert:file:line:)-6325h``
/// methods are allowed to be called even when actions have been received from effects that have
/// not been asserted on yet. Any pending actions will be cleared.
/// * Tests are allowed to finish with unasserted, received actions and in-flight effects. No test
/// failures will be reported.
///
/// Non-exhaustive stores can be configured to report skipped assertions by configuring
/// ``Exhaustivity/off(showSkippedAssertions:)``. When set to `true` the test store will have the
/// added behavior that any unasserted change causes a grey, informational box to appear next to
/// each assertion detailing the changes that were not asserted against. This allows you to see what
/// information you are choosing to ignore without causing a test failure. It can be useful in
/// tracking down bugs that happen in production but that aren't currently detected in tests.
///
/// This style of testing is most useful for testing the integration of multiple features where you
/// want to focus on just a certain slice of the behavior. Exhaustive testing can still be important
/// to use for leaf node features, where you truly do want to assert on everything happening inside
/// the feature.
///
/// For example, suppose you have a tab-based application where the 3rd tab is a login screen. The
/// user can fill in some data on the screen, then tap the "Submit" button, and then a series of
/// events happens to log the user in. Once the user is logged in, the 3rd tab switches from a
/// login screen to a profile screen, _and_ the selected tab switches to the first tab, which is an
/// activity screen.
///
/// When writing tests for the login feature we will want to do that in the exhaustive style so that
/// we can prove exactly how the feature would behave in production. But, suppose we wanted to write
/// an integration test that proves after the user taps the "Login" button that ultimately the
/// selected tab switches to the first tab.
///
/// In order to test such a complex flow we must test the integration of multiple features, which
/// means dealing with complex, nested state and effects. We can emulate this flow in a test by
/// sending actions that mimic the user logging in, and then eventually assert that the selected
/// tab switched to activity:
///
/// ```swift
/// let store = TestStore(initialState: App.State()) {
/// App()
/// }
///
/// // 1️⃣ Emulate user tapping on submit button.
/// // (You can use case key path syntax to send actions to deeply nested features.)
/// await store.send(\.login.submitButtonTapped) {
/// // 2️⃣ Assert how all state changes in the login feature
/// $0.login?.isLoading = true
/// …
/// }
///
/// // 3️⃣ Login feature performs API request to login, and
/// // sends response back into system.
/// await store.receive(\.login.loginResponse.success) {
/// // 4️⃣ Assert how all state changes in the login feature
/// $0.login?.isLoading = false
/// …
/// }
///
/// // 5️⃣ Login feature sends a delegate action to let parent
/// // feature know it has successfully logged in.
/// await store.receive(\.login.delegate.didLogin) {
/// // 6️⃣ Assert how all of app state changes due to that action.
/// $0.authenticatedTab = .loggedIn(
/// Profile.State(...)
/// )
/// …
/// // 7️⃣ *Finally* assert that the selected tab switches to activity.
/// $0.selectedTab = .activity
/// }
/// ```
///
/// Doing this with exhaustive testing is verbose, and there are a few problems with this:
///
/// * We need to be intimately knowledgeable in how the login feature works so that we can assert
/// on how its state changes and how its effects feed data back into the system.
/// * If the login feature were to change its logic we may get test failures here even though the
/// logic we are actually trying to test doesn't really care about those changes.
/// * This test is very long, and so if there are other similar but slightly different flows we
/// want to test we will be tempted to copy-and-paste the whole thing, leading to lots of
/// duplicated, fragile tests.
///
/// Non-exhaustive testing allows us to test the high-level flow that we are concerned with, that of
/// login causing the selected tab to switch to activity, without having to worry about what is
/// happening inside the login feature. To do this, we can turn off ``TestStore/exhaustivity`` in
/// the test store, and then just assert on what we are interested in:
///
/// ```swift
/// let store = TestStore(App.State()) {
/// App()
/// }
/// store.exhaustivity = .off // ⬅️
///
/// await store.send(\.login.submitButtonTapped)
/// await store.receive(\.login.delegate.didLogin) {
/// $0.selectedTab = .activity
/// }
/// ```
///
/// In particular, we did not assert on how the login's state changed or how the login's effects fed
/// data back into the system. We just assert that when the "Submit" button is tapped that
/// eventually we get the `didLogin` delegate action and that causes the selected tab to flip to
/// activity. Now the login feature is free to make any change it wants to make without affecting
/// this integration test.
///
/// Using ``Exhaustivity/off`` for ``TestStore/exhaustivity`` causes all un-asserted changes to pass
/// without any notification. If you would like to see what test failures are being suppressed
/// without actually causing a failure, you can use ``Exhaustivity/off(showSkippedAssertions:)``:
///
/// ```swift
/// let store = TestStore(initialState: App.State()) {
/// App()
/// }
/// store.exhaustivity = .off(showSkippedAssertions: true) // ⬅️
///
/// await store.send(\.login.submitButtonTapped)
/// await store.receive(\.login.delegate.didLogin) {
/// $0.selectedTab = .profile
/// }
/// ```
///
/// When this is run you will get grey, informational boxes on each assertion where some change
/// wasn't fully asserted on:
///
/// > ◽️ Expected failure: A state change does not match expectation: …
/// >
/// > ```diff
/// > App.State(
/// > authenticatedTab: .loggedOut(
/// > Login.State(
/// > - isLoading: false
/// > + isLoading: true,
/// > …
/// > )
/// > )
/// > )
/// > ```
/// >
/// > Skipped receiving .login(.loginResponse(.success))
/// >
/// > A state change does not match expectation: …
/// >
/// > ```diff
/// > App.State(
/// > - authenticatedTab: .loggedOut(…)
/// > + authenticatedTab: .loggedIn(
/// > + Profile.State(…)
/// > + ),
/// > …
/// > )
/// > ```
/// >
/// > (Expected: −, Actual: +)
///
/// The test still passes, and none of these notifications are test failures. They just let you know
/// what things you are not explicitly asserting against, and can be useful to see when tracking
/// down bugs that happen in production but that aren't currently detected in tests.
///
/// [merowing.info]: https://www.merowing.info
/// [exhaustive-testing-in-tca]: https://www.merowing.info/exhaustive-testing-in-tca/
/// [Composable-Architecture-at-Scale]: https://vimeo.com/751173570
public final class TestStore<State, Action> {
/// The current dependencies of the test store.
///
/// The dependencies define the execution context that your feature runs in. They can be modified
/// throughout the test store's lifecycle in order to influence how your feature produces effects.
///
/// Typically you will override certain dependencies immediately after constructing the test
/// store. For example, if your feature need access to the current date and an API client to do
/// its job, you can override those dependencies like so:
///
/// ```swift
/// let store = TestStore(/* ... */) {
/// $0.apiClient = .mock
/// $0.date = .constant(Date(timeIntervalSinceReferenceDate: 1234567890))
/// }
///
/// // Store assertions here
/// ```
///
/// You can also override dependencies in the middle of the test in order to simulate how the
/// dependency changes as the user performs action. For example, to test the flow of an API
/// request failing at first but then later succeeding, you can do the following:
///
/// ```swift
/// store.dependencies.apiClient = .failing
///
/// store.send(.buttonTapped) { /* ... */ }
/// store.receive(\.searchResponse.failure) { /* ... */ }
///
/// store.dependencies.apiClient = .mock
///
/// store.send(.buttonTapped) { /* ... */ }
/// store.receive(\.searchResponse.success) { /* ... */ }
/// ```
public var dependencies: DependencyValues {
_read { yield self.reducer.dependencies }
_modify { yield &self.reducer.dependencies }
}
/// The current exhaustivity level of the test store.
public var exhaustivity: Exhaustivity = .on
/// Serializes all async work to the main thread for the lifetime of the test store.
public var useMainSerialExecutor: Bool {
get { uncheckedUseMainSerialExecutor }
set { uncheckedUseMainSerialExecutor = newValue }
}
private let originalUseMainSerialExecutor = uncheckedUseMainSerialExecutor
/// The current state of the test store.
///
/// When read from a trailing closure assertion in ``send(_:assert:file:line:)-2co21`` or
/// ``receive(_:timeout:assert:file:line:)-6325h``, it will equal the `inout` state passed to the
/// closure.
public var state: State {
self.reducer.state
}
/// The default timeout used in all methods that take an optional timeout.
///
/// This is the default timeout used in all methods that take an optional timeout, such as
/// ``receive(_:timeout:assert:file:line:)-6325h`` and ``finish(timeout:file:line:)-53gi5``.
public var timeout: UInt64
private let file: StaticString
private let line: UInt
let reducer: TestReducer<State, Action>
private let sharedChangeTracker: SharedChangeTracker
private let store: Store<State, TestReducer<State, Action>.TestAction>
/// Returns `true` if the store's feature has been dismissed.
public fileprivate(set) var isDismissed = false
/// Creates a test store with an initial state and a reducer powering its runtime.
///
/// See <doc:Testing> and the documentation of ``TestStore`` for more information on how to best
/// use a test store.
///
/// - Parameters:
/// - initialState: The state the feature starts in.
/// - reducer: The reducer that powers the runtime of the feature. Unlike
/// ``Store/init(initialState:reducer:withDependencies:)``, this is _not_ a builder closure
/// due to a [Swift bug](https://github.com/apple/swift/issues/72399) that is more likely to
/// affect test store initialization. If you must compose multiple reducers in this closure,
/// wrap them in ``CombineReducers``.
/// - prepareDependencies: A closure that can be used to override dependencies that will be
/// accessed during the test. These dependencies will be used when producing the initial
/// state.
public init<R: Reducer>(
initialState: @autoclosure () -> State,
reducer: () -> R,
withDependencies prepareDependencies: (inout DependencyValues) -> Void = { _ in
},
file: StaticString = #file,
line: UInt = #line
)
where State: Equatable, R.State == State, R.Action == Action {
let sharedChangeTracker = SharedChangeTracker()
let reducer = XCTFailContext.$current.withValue(XCTFailContext(file: file, line: line)) {
Dependencies.withDependencies {
prepareDependencies(&$0)
$0.sharedChangeTrackers.insert(sharedChangeTracker)
} operation: {
TestReducer(Reduce(reducer()), initialState: initialState())
}
}
self.file = file
self.line = line
self.reducer = reducer
self.store = Store(initialState: reducer.state) { reducer }
self.timeout = 1 * NSEC_PER_SEC
self.sharedChangeTracker = sharedChangeTracker
self.useMainSerialExecutor = true
self.reducer.store = self
}
/// Suspends until all in-flight effects have finished, or until it times out.
///
/// Can be used to assert that all effects have finished.
///
/// - Parameter duration: The amount of time to wait before asserting.
@available(iOS 16, macOS 13, tvOS 16, watchOS 9, *)
@MainActor
public func finish(
timeout duration: Duration,
file: StaticString = #file,
line: UInt = #line
) async {
await self.finish(timeout: duration.nanoseconds, file: file, line: line)
}
/// Suspends until all in-flight effects have finished, or until it times out.
///
/// Can be used to assert that all effects have finished.
///
/// > Important: `TestStore.finish()` should only be called once per test store, at the end of the
/// > test. Interacting with a finished test store is undefined.
///
/// - Parameter nanoseconds: The amount of time to wait before asserting.
@_disfavoredOverload
@MainActor
public func finish(
timeout nanoseconds: UInt64? = nil,
file: StaticString = #file,
line: UInt = #line
) async {
self.assertNoReceivedActions(file: file, line: line)
Task.cancel(id: OnFirstAppearID())
let nanoseconds = nanoseconds ?? self.timeout
let start = DispatchTime.now().uptimeNanoseconds
await Task.megaYield()
while !self.reducer.inFlightEffects.isEmpty {
guard start.distance(to: DispatchTime.now().uptimeNanoseconds) < nanoseconds
else {
let timeoutMessage =
nanoseconds != self.timeout
? #"try increasing the duration of this assertion's "timeout""#
: #"configure this assertion with an explicit "timeout""#
let suggestion = """
There are effects in-flight. If the effect that delivers this action uses a \
clock/scheduler (via "receive(on:)", "delay", "debounce", etc.), make sure that you wait \
enough time for it to perform the effect. If you are using a test \
clock/scheduler, advance it so that the effects may complete, or consider using \
an immediate clock/scheduler to immediately perform the effect instead.
If you are not yet using a clock/scheduler, or can not use a clock/scheduler, \
\(timeoutMessage).
"""
XCTFailHelper(
"""
Expected effects to finish, but there are still effects in-flight\
\(nanoseconds > 0 ? " after \(Double(nanoseconds)/Double(NSEC_PER_SEC)) seconds" : "").
\(suggestion)
""",
file: file,
line: line
)
return
}
await Task.yield()
}
self.assertNoSharedChanges(file: file, line: line)
}
deinit {
self.completed()
uncheckedUseMainSerialExecutor = self.originalUseMainSerialExecutor
}
func completed() {
self.assertNoReceivedActions(file: self.file, line: self.line)
Task.cancel(id: OnFirstAppearID())
for effect in self.reducer.inFlightEffects {
XCTFailHelper(
"""
An effect returned for this action is still running. It must complete before the end of \
the test. …
To fix, inspect any effects the reducer returns for this action and ensure that all of \
them complete by the end of the test. There are a few reasons why an effect may not have \
completed:
• If using async/await in your effect, it may need a little bit of time to properly \
finish. To fix you can simply perform "await store.finish()" at the end of your test.
• If an effect uses a clock (or scheduler, via "receive(on:)", "delay", "debounce", etc.), \
make sure that you wait enough time for it to perform the effect. If you are using a test \
clock/scheduler, advance it so that the effects may complete, or consider using an \
immediate clock/scheduler to immediately perform the effect instead.
• If you are returning a long-living effect (timers, notifications, subjects, etc.), \
then make sure those effects are torn down by marking the effect ".cancellable" and \
returning a corresponding cancellation effect ("Effect.cancel") from another action, or, \
if your effect is driven by a Combine subject, send it a completion.
• If you do not wish to assert on these effects, perform "await \
store.skipInFlightEffects()", or consider using a non-exhaustive test store: \
"store.exhaustivity = .off".
""",
file: effect.action.file,
line: effect.action.line
)
}
self.assertNoSharedChanges(file: self.file, line: self.line)
}
private func assertNoReceivedActions(file: StaticString, line: UInt) {
if !self.reducer.receivedActions.isEmpty {
let actions = self.reducer.receivedActions
.map(\.action)
.map { " • " + debugCaseOutput($0, abbreviated: true) }
.joined(separator: "\n")
XCTFailHelper(
"""
The store received \(self.reducer.receivedActions.count) unexpected \
action\(self.reducer.receivedActions.count == 1 ? "" : "s"): …
Unhandled actions:
\(actions)
To fix, explicitly assert against these actions using "store.receive", skip these actions \
by performing "await store.skipReceivedActions()", or consider using a non-exhaustive test \
store: "store.exhaustivity = .off".
""",
file: file,
line: line
)
}
}
private func assertNoSharedChanges(file: StaticString, line: UInt) {
// NB: This existential opening can go away if we can constrain 'State: Equatable' at the
// 'TestStore' level, but for some reason this breaks DocC.
if self.sharedChangeTracker.hasChanges, let stateType = State.self as? any Equatable.Type {
func open<EquatableState: Equatable>(_: EquatableState.Type) {
let store = self as! TestStore<EquatableState, Action>
try? store.expectedStateShouldMatch(
preamble: "Test store finished before asserting against changes to shared state",
postamble: """
Invoke "TestStore.assert" at the end of this test to assert against changes to shared \
state.
""",
expected: store.state,
actual: store.state,
updateStateToExpectedResult: nil,
skipUnnecessaryModifyFailure: true,
file: file,
line: line
)
}
open(stateType)
self.sharedChangeTracker.resetChanges()
}
}
/// Overrides the store's dependencies for a given operation.
///
/// - Parameters:
/// - updateValuesForOperation: A closure for updating the store's dependency values for the
/// duration of the operation.
/// - operation: The operation.
public func withDependencies<R>(
_ updateValuesForOperation: (_ dependencies: inout DependencyValues) throws -> Void,
operation: () throws -> R
) rethrows -> R {
let previous = self.dependencies
defer { self.dependencies = previous }
try updateValuesForOperation(&self.dependencies)
return try operation()
}
/// Overrides the store's dependencies for a given operation.
///
/// - Parameters:
/// - updateValuesForOperation: A closure for updating the store's dependency values for the
/// duration of the operation.
/// - operation: The operation.
@MainActor
public func withDependencies<R>(
_ updateValuesForOperation: (_ dependencies: inout DependencyValues) async throws -> Void,
operation: @MainActor () async throws -> R
) async rethrows -> R {
let previous = self.dependencies
defer { self.dependencies = previous }
try await updateValuesForOperation(&self.dependencies)
return try await operation()
}
/// Overrides the store's exhaustivity for a given operation.
///
/// - Parameters:
/// - exhaustivity: The exhaustivity.
/// - operation: The operation.
public func withExhaustivity<R>(
_ exhaustivity: Exhaustivity,
operation: () throws -> R
) rethrows -> R {
let previous = self.exhaustivity
defer { self.exhaustivity = previous }
self.exhaustivity = exhaustivity
return try operation()
}
/// Overrides the store's exhaustivity for a given operation.
///
/// - Parameters:
/// - exhaustivity: The exhaustivity.
/// - operation: The operation.
@MainActor
public func withExhaustivity<R>(
_ exhaustivity: Exhaustivity,
operation: @MainActor () async throws -> R
) async rethrows -> R {
let previous = self.exhaustivity
defer { self.exhaustivity = previous }
self.exhaustivity = exhaustivity
return try await operation()
}
}
/// A convenience type alias for referring to a test store of a given reducer's domain.
///
/// Instead of specifying two generics:
///
/// ```swift
/// let testStore: TestStore<Feature.State, Feature.Action>
/// ```
///
/// You can specify a single generic:
///
/// ```swift
/// let testStore: TestStoreOf<Feature>
/// ```
public typealias TestStoreOf<R: Reducer> = TestStore<R.State, R.Action>
extension TestStore where State: Equatable {
/// Sends an action to the store and asserts when state changes.
///
/// To assert on how state changes you can provide a trailing closure, and that closure is handed
/// a mutable variable that represents the feature's state _before_ the action was sent. You need
/// to mutate that variable so that it is equal to the feature's state _after_ the action is sent:
///
/// ```swift
/// await store.send(.incrementButtonTapped) {
/// $0.count = 1
/// }
/// await store.send(.decrementButtonTapped) {
/// $0.count = 0
/// }
/// ```
///
/// This method suspends in order to allow any effects to start. For example, if you track an
/// analytics event in an effect when an action is sent, you can assert on that behavior
/// immediately after awaiting `store.send`:
///
/// ```swift
/// @MainActor
/// func testAnalytics() async {
/// let events = LockIsolated<[String]>([])
/// let analytics = AnalyticsClient(
/// track: { event in
/// events.withValue { $0.append(event) }
/// }
/// )
///
/// let store = TestStore(initialState: Feature.State()) {
/// Feature()
/// } withDependencies {
/// $0.analytics = analytics
/// }
///
/// await store.send(.buttonTapped)
///
/// events.withValue { XCTAssertEqual($0, ["Button Tapped"]) }
/// }
/// ```
///
/// This method suspends only for the duration until the effect _starts_ from sending the action.
/// It does _not_ suspend for the duration of the effect.
///
/// In order to suspend for the duration of the effect you can use its return value, a
/// ``TestStoreTask``, which represents the lifecycle of the effect started from sending an
/// action. You can use this value to suspend until the effect finishes, or to force the
/// cancellation of the effect, which is helpful for effects that are tied to a view's lifecycle
/// and not torn down when an action is sent, such as actions sent in SwiftUI's `task` view
/// modifier.
///
/// For example, if your feature kicks off a long-living effect when the view appears by using
/// SwiftUI's `task` view modifier, then you can write a test for such a feature by explicitly
/// canceling the effect's task after you make all assertions:
///
/// ```swift
/// let store = TestStore(/* ... */)
///
/// // Emulate the view appearing
/// let task = await store.send(.task)
///
/// // Assertions
///
/// // Emulate the view disappearing
/// await task.cancel()
/// ```
///
/// - Parameters:
/// - action: An action.
/// - updateStateToExpectedResult: A closure that asserts state changed by sending the action to
/// the store. The mutable state sent to this closure must be modified to match the state of
/// the store after processing the given action. Do not provide a closure if no change is
/// expected.
/// - Returns: A ``TestStoreTask`` that represents the lifecycle of the effect executed when
/// sending the action.
@MainActor
@discardableResult
public func send(
_ action: Action,
assert updateStateToExpectedResult: ((_ state: inout State) throws -> Void)? = nil,
file: StaticString = #file,
line: UInt = #line
) async -> TestStoreTask {
await XCTFailContext.$current.withValue(XCTFailContext(file: file, line: line)) {
guard !self.isDismissed else {
XCTFail("Can't send action to dismissed test store.", file: file, line: line)
return TestStoreTask(rawValue: nil, timeout: self.timeout)
}
if !self.reducer.receivedActions.isEmpty {
var actions = ""
customDump(self.reducer.receivedActions.map(\.action), to: &actions)
XCTFailHelper(
"""
Must handle \(self.reducer.receivedActions.count) received \
action\(self.reducer.receivedActions.count == 1 ? "" : "s") before sending an action: …
Unhandled actions: \(actions)
""",
file: file,
line: line
)
}
switch self.exhaustivity {
case .on:
break
case .off(showSkippedAssertions: true):
await self.skipReceivedActions(strict: false)
case .off(showSkippedAssertions: false):
self.reducer.receivedActions = []
}
let expectedState = self.state
let previousState = self.reducer.state
let previousStackElementID = self.reducer.dependencies.stackElementID.incrementingCopy()
let task = self.sharedChangeTracker.track {
self.store.send(
.init(origin: .send(action), file: file, line: line),
originatingFrom: nil
)
}
if uncheckedUseMainSerialExecutor {
await Task.yield()
} else {
for await _ in self.reducer.effectDidSubscribe.stream {
break
}
}
do {
let currentState = self.state
let currentStackElementID = self.reducer.dependencies.stackElementID
self.reducer.state = previousState
self.reducer.dependencies.stackElementID = previousStackElementID
defer {
self.reducer.state = currentState
self.reducer.dependencies.stackElementID = currentStackElementID
}
try self.expectedStateShouldMatch(
expected: expectedState,
actual: currentState,
updateStateToExpectedResult: updateStateToExpectedResult,
file: file,
line: line
)
} catch {
XCTFail("Threw error: \(error)", file: file, line: line)
}
// NB: Give concurrency runtime more time to kick off effects so users don't need to manually
// instrument their effects.
await Task.megaYield(count: 20)
return .init(rawValue: task, timeout: self.timeout)
}
}
/// Assert against the current state of the store.
///
/// The trailing closure provided is given a mutable argument that represents the current state,
/// and you can provide any mutations you want to the state. If your mutations cause the argument
/// to differ from the current state of the test store, a test failure will be triggered.
///
/// This tool is most useful in non-exhaustive test stores (see
/// <doc:Testing#Non-exhaustive-testing>), which allow you to assert on a subset of the things
/// happening inside your features. For example, you can send an action in a child feature
/// without asserting on how many changes in the system, and then tell the test store to
/// ``finish(timeout:file:line:)-53gi5`` by executing all of its effects, and finally to
/// ``skipReceivedActions(strict:file:line:)-a4ri`` to receive all actions. After that is done you
/// can assert on the final state of the store:
///
/// ```swift
/// store.exhaustivity = .off
/// await store.send(\.child.closeButtonTapped)
/// await store.finish()
/// await store.skipReceivedActions()
/// store.assert {
/// $0.child = nil
/// }
/// ```
///
/// > Note: This helper is only intended to be used with non-exhaustive test stores. It is not
/// needed in exhaustive test stores since any assertion you may make inside the trailing closure
/// has already been handled by a previous `send` or `receive`.
///
/// - Parameters:
/// - updateStateToExpectedResult: A closure that asserts against the current state of the test
/// store.
@MainActor
public func assert(
_ updateStateToExpectedResult: @escaping (_ state: inout State) throws -> Void,
file: StaticString = #file,
line: UInt = #line
) {
XCTFailContext.$current.withValue(XCTFailContext(file: file, line: line)) {
let expectedState = self.state
let currentState = self.reducer.state
do {
try self.expectedStateShouldMatch(
expected: expectedState,
actual: currentState,
updateStateToExpectedResult: updateStateToExpectedResult,
skipUnnecessaryModifyFailure: true,
file: file,
line: line
)
} catch {
XCTFail("Threw error: \(error)", file: file, line: line)
}
}
}
private func expectedStateShouldMatch(
preamble: String = "",
postamble: String = "",
expected: State,
actual: State,
updateStateToExpectedResult: ((inout State) throws -> Void)? = nil,
skipUnnecessaryModifyFailure: Bool = false,
file: StaticString,