forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactiveCommandTest.cs
459 lines (370 loc) · 16.3 KB
/
ReactiveCommandTest.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using Microsoft.Reactive.Testing;
using ReactiveUI.Testing;
using Microsoft.Reactive.Testing;
using ReactiveUI.Xaml;
using Xunit;
#if MONO
using Mono.Reactive.Testing;
#else
#endif
namespace ReactiveUI.Tests
{
public abstract class ReactiveCommandInterfaceTest
{
protected abstract IReactiveCommand createCommand(IObservable<bool> canExecute, IScheduler scheduler = null);
protected abstract IReactiveCommand createRelayCommand(Func<object, bool> canExecute,
IScheduler scheduler = null);
[Fact]
public void CompletelyDefaultReactiveCommandShouldFire()
{
var sched = new TestScheduler();
var fixture = createCommand(null, sched);
Assert.True(fixture.CanExecute(null));
string result = null;
fixture.Subscribe(x => result = x as string);
fixture.Execute("Test");
sched.Start();
Assert.Equal("Test", result);
fixture.Execute("Test2");
sched.Start();
Assert.Equal("Test2", result);
}
[Fact]
public void ObservableCanExecuteShouldShowUpInCommand()
{
var input = new[] {true, false, false, true, false, true};
var result = (new TestScheduler()).With(sched => {
var can_execute = new Subject<bool>();
var fixture = createCommand(can_execute, sched);
var changes_as_observable = fixture.CanExecuteObservable.CreateCollection();
int change_event_count = 0;
fixture.CanExecuteChanged += (o, e) => { change_event_count++; };
input.Run(x => {
can_execute.OnNext(x);
sched.Start();
Assert.Equal(x, fixture.CanExecute(null));
});
// N.B. We check against '5' instead of 6 because we're supposed to
// suppress changes that aren't actually changes i.e. false => false
sched.AdvanceToMs(10*1000);
return changes_as_observable;
});
input.DistinctUntilChanged().AssertAreEqual(result.ToList());
}
[Fact]
public void ObservableCanExecuteFuncShouldShowUpInCommand()
{
int counter = 0;
var fixture = createRelayCommand(_ => (counter%2 == 0));
var changes_as_observable = fixture.CanExecuteObservable.CreateCollection();
int change_event_count = 0;
fixture.CanExecuteChanged += (o, e) => { change_event_count++; };
Enumerable.Range(0, 6).Run(x => {
Assert.Equal(x%2 == 0, fixture.CanExecute(null));
counter++;
});
Assert.Equal(6, changes_as_observable.Count);
}
[Fact]
public void ObservableExecuteFuncShouldBeObservableAndAct()
{
var executed_params = new List<object>();
var fixture = createCommand(null);
fixture.Subscribe(x => executed_params.Add(x));
var observed_params = new ReplaySubject<object>();
fixture.Subscribe(observed_params.OnNext, observed_params.OnError, observed_params.OnCompleted);
var range = Enumerable.Range(0, 5);
range.Run(x => fixture.Execute(x));
range.AssertAreEqual(executed_params.OfType<int>());
range.ToObservable()
.Zip(observed_params, (expected, actual) => new {expected, actual})
.Do(Console.WriteLine)
.Subscribe(x => Assert.Equal(x.expected, x.actual));
}
[Fact]
public void MultipleSubscribesShouldntResultInMultipleNotifications()
{
var input = new[] {1, 2, 1, 2};
var sched = new TestScheduler();
var fixture = createCommand(null, sched);
var odd_list = new List<int>();
var even_list = new List<int>();
fixture.Where(x => ((int)x)%2 != 0).Subscribe(x => odd_list.Add((int)x));
fixture.Where(x => ((int)x)%2 == 0).Subscribe(x => even_list.Add((int)x));
input.Run(x => fixture.Execute(x));
sched.AdvanceToMs(1000);
new[] {1, 1}.AssertAreEqual(odd_list);
new[] {2, 2}.AssertAreEqual(even_list);
}
[Fact]
public void CanExecuteExceptionShouldntPermabreakCommands()
{
var canExecute = new Subject<bool>();
var fixture = createCommand(canExecute);
var exceptions = new List<Exception>();
var canExecuteStates = new List<bool>();
fixture.CanExecuteObservable.Subscribe(canExecuteStates.Add);
fixture.ThrownExceptions.Subscribe(exceptions.Add);
canExecute.OnNext(false);
Assert.False(fixture.CanExecute(null));
canExecute.OnNext(true);
Assert.True(fixture.CanExecute(null));
canExecute.OnError(new Exception("Aieeeee!"));
// The command should just latch at whatever its previous state was
// before the exception
Assert.True(fixture.CanExecute(null));
Assert.Equal(1, exceptions.Count);
Assert.Equal("Aieeeee!", exceptions[0].Message);
Assert.Equal(false, canExecuteStates[canExecuteStates.Count - 2]);
Assert.Equal(true, canExecuteStates[canExecuteStates.Count - 1]);
}
[Fact]
public void NoSubscriberOfThrownExceptionsEqualsDeath()
{
(new TestScheduler()).With(sched => {
var canExecute = new Subject<bool>();
var fixture = createCommand(canExecute);
canExecute.OnNext(true);
canExecute.OnError(new Exception("Aieeeee!"));
bool failed = true;
try {
sched.Start();
Assert.True(fixture.CanExecute(null));
} catch (Exception ex) {
failed = (ex.InnerException.Message != "Aieeeee!");
}
Assert.False(failed);
});
}
}
public class ReactiveCommandTest : ReactiveCommandInterfaceTest
{
protected override IReactiveCommand createCommand(IObservable<bool> canExecute, IScheduler scheduler = null)
{
return new ReactiveCommand(canExecute, scheduler);
}
protected override IReactiveCommand createRelayCommand(Func<object, bool> canExecute,
IScheduler scheduler = null)
{
return ReactiveCommand.Create(canExecute, null, scheduler);
}
public class TheCreateCommandMethod
{
[Fact]
public void CreatesCommandThatHandlesThrownExceptions()
{
var command = ReactiveCommand.Create(_ => true, _ => { throw new Exception(); });
Assert.NotNull(command.ThrownExceptions);
bool handled = false;
command.ThrownExceptions.Subscribe(e => handled = true);
command.Execute(null);
Assert.True(handled);
}
}
}
public class ReactiveAsyncCommandBaseTest : ReactiveCommandInterfaceTest
{
protected override IReactiveCommand createCommand(IObservable<bool> canExecute, IScheduler scheduler = null)
{
return new ReactiveAsyncCommand(canExecute, 1, scheduler);
}
protected override IReactiveCommand createRelayCommand(Func<object, bool> canExecute,
IScheduler scheduler = null)
{
return ReactiveAsyncCommand.Create(x => 1, x => { }, canExecute, 1, scheduler);
}
}
public class ReactiveAsyncCommandTest
{
[Fact]
public void RegisterAsyncFunctionSmokeTest()
{
(new TestScheduler()).With(sched => {
var fixture = new ReactiveAsyncCommand(null, 1);
ReactiveCollection<int> results;
results = fixture.RegisterAsyncObservable(_ =>
Observable.Return(5).Delay(TimeSpan.FromSeconds(5), sched)).CreateCollection();
var inflightResults = fixture.ItemsInflight.CreateCollection();
sched.AdvanceToMs(10);
Assert.True(fixture.CanExecute(null));
fixture.Execute(null);
sched.AdvanceToMs(1005);
Assert.False(fixture.CanExecute(null));
sched.AdvanceToMs(5100);
Assert.True(fixture.CanExecute(null));
new[] {0, 1, 0}.AssertAreEqual(inflightResults);
new[] {5}.AssertAreEqual(results);
});
}
[Fact]
public void RegisterMemoizedFunctionSmokeTest()
{
var input = new[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 2};
var output = new[] {5, 5, 5, 5, 5, 10, 10, 10, 10, 10};
var sched = new EventLoopScheduler();
var results = new List<Timestamped<int>>();
var start = sched.Now;
sched.With(_ => {
var fixture = new ReactiveAsyncCommand(null, 5, sched);
fixture.RegisterMemoizedFunction(x => {
Thread.Sleep(1000);
return ((int)x)*5;
}, 50, null, sched)
.Timestamp()
.Subscribe(x => results.Add(x));
Assert.True(fixture.CanExecute(1));
foreach (var i in input) {
Assert.True(fixture.CanExecute(i));
fixture.Execute(i);
}
Thread.Sleep(2500);
});
Assert.Equal(10, results.Count);
results.Select(x => x.Timestamp - start)
.Run(x => { });
output.AssertAreEqual(results.Select(x => x.Value));
Assert.False(results.Any(x => x.Timestamp - start > new TimeSpan(0, 0, 3)));
}
[Fact]
public void MultipleSubscribersShouldntDecrementRefcountBelowZero()
{
(new TestScheduler()).With(sched => {
var fixture = new ReactiveAsyncCommand();
var results = new List<int>();
bool[] subscribers = new[] {false, false, false, false, false};
var output = fixture.RegisterAsyncObservable(_ =>
Observable.Return(5).Delay(TimeSpan.FromMilliseconds(5000), sched));
output.Subscribe(x => results.Add(x));
Enumerable.Range(0, 5).Run(x => output.Subscribe(_ => subscribers[x] = true));
Assert.True(fixture.CanExecute(null));
fixture.Execute(null);
sched.AdvanceToMs(2000);
Assert.False(fixture.CanExecute(null));
sched.AdvanceToMs(6000);
Assert.True(fixture.CanExecute(null));
Assert.True(results.Count == 1);
Assert.True(results[0] == 5);
Assert.True(subscribers.All(x => x));
});
}
[Fact]
public void MultipleResultsFromObservableShouldntDecrementRefcountBelowZero()
{
(new TestScheduler()).With(sched => {
int latestInFlight = 0;
var fixture = new ReactiveAsyncCommand(null, 1, sched);
var results = fixture
.RegisterAsyncObservable(_ => new[] {1, 2, 3}.ToObservable())
.CreateCollection();
fixture.ItemsInflight.Subscribe(x => latestInFlight = x);
fixture.Execute(1);
sched.Start();
Assert.Equal(3, results.Count);
Assert.Equal(0, latestInFlight);
});
}
[Fact]
public void RAFShouldActuallyRunOnTheTaskpool()
{
var deferred = RxApp.DeferredScheduler;
var taskpool = RxApp.TaskpoolScheduler;
try {
var testDeferred = new CountingTestScheduler(Scheduler.Immediate);
var testTaskpool = new CountingTestScheduler(Scheduler.NewThread);
RxApp.DeferredScheduler = testDeferred;
RxApp.TaskpoolScheduler = testTaskpool;
var fixture = new ReactiveAsyncCommand();
var result = fixture.RegisterAsyncFunction(x => {
Thread.Sleep(1000);
return (int)x*5;
});
fixture.Execute(1);
Assert.Equal(5, result.First());
Assert.True(testDeferred.ScheduledItems.Count >= 1);
Assert.True(testTaskpool.ScheduledItems.Count >= 1);
} finally {
RxApp.DeferredScheduler = deferred;
RxApp.TaskpoolScheduler = taskpool;
}
}
[Fact]
public void RAOShouldActuallyRunOnTheTaskpool()
{
var deferred = RxApp.DeferredScheduler;
var taskpool = RxApp.TaskpoolScheduler;
try {
var testDeferred = new CountingTestScheduler(Scheduler.Immediate);
var testTaskpool = new CountingTestScheduler(Scheduler.NewThread);
RxApp.DeferredScheduler = testDeferred;
RxApp.TaskpoolScheduler = testTaskpool;
var fixture = new ReactiveAsyncCommand();
var result = fixture.RegisterAsyncObservable(x =>
Observable.Return((int)x*5).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler));
fixture.Execute(1);
Assert.Equal(5, result.First());
Assert.True(testDeferred.ScheduledItems.Count >= 1);
Assert.True(testTaskpool.ScheduledItems.Count >= 1);
} finally {
RxApp.DeferredScheduler = deferred;
RxApp.TaskpoolScheduler = taskpool;
}
}
[Fact]
public void CanExecuteShouldChangeOnInflightOp()
{
(new TestScheduler()).With(sched => {
var canExecute = sched.CreateHotObservable(
sched.OnNextAt(0, true),
sched.OnNextAt(250, false),
sched.OnNextAt(500, true),
sched.OnNextAt(750, false),
sched.OnNextAt(1000, true),
sched.OnNextAt(1100, false)
);
var fixture = new ReactiveAsyncCommand(canExecute);
int calculatedResult = -1;
bool latestCanExecute = false;
fixture.RegisterAsyncObservable(x =>
Observable.Return((int)x*5).Delay(TimeSpan.FromMilliseconds(900), RxApp.DeferredScheduler))
.Subscribe(x => calculatedResult = x);
fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x);
// CanExecute should be true, both input observable is true
// and we don't have anything inflight
sched.AdvanceToMs(10);
Assert.True(fixture.CanExecute(1));
Assert.True(latestCanExecute);
// Invoke a command 10ms in
fixture.Execute(1);
// At 300ms, input is false
sched.AdvanceToMs(300);
Assert.False(fixture.CanExecute(1));
Assert.False(latestCanExecute);
// At 600ms, input is true, but the command is still running
sched.AdvanceToMs(600);
Assert.False(fixture.CanExecute(1));
Assert.False(latestCanExecute);
// After we've completed, we should still be false, since from
// 750ms-1000ms the input observable is false
sched.AdvanceToMs(900);
Assert.False(fixture.CanExecute(1));
Assert.False(latestCanExecute);
Assert.Equal(-1, calculatedResult);
sched.AdvanceToMs(1010);
Assert.True(fixture.CanExecute(1));
Assert.True(latestCanExecute);
Assert.Equal(calculatedResult, 5);
sched.AdvanceToMs(1200);
Assert.False(fixture.CanExecute(1));
Assert.False(latestCanExecute);
});
}
}
}