public void TestInitialFalse() { var notifier = new BooleanNotifier(false); var recorder = new TestScheduler().CreateObserver<bool>(); notifier.Subscribe(recorder); notifier.Value.Is(false); notifier.TurnOn(); notifier.TurnOff(); notifier.Value = true; notifier.Value = true; notifier.Value = false; notifier.TurnOn(); notifier.SwitchValue(); notifier.SwitchValue(); recorder.Messages.Is( OnNext(0, true), OnNext(0, false), OnNext(0, true), OnNext(0, true), OnNext(0, false), OnNext(0, true), OnNext(0, false), OnNext(0, true)); recorder.Messages.Clear(); notifier.TurnOn(); recorder.Messages.Count.Is(0); }
public void ReceiveItemsAfterAnExceptionIsEncountered() { TestScheduler scheduler = new TestScheduler(); IObservable<int> observableA = scheduler.CreateColdObservable<int>(new[] { new Recorded<Notification<int>>(10, Notification.CreateOnError<int>(new InvalidOperationException())) }); IObservable<int> observableB = scheduler.CreateColdObservable<int>(new[] { new Recorded<Notification<int>>(10, Notification.CreateOnNext<int>(314)) }); Queue<IObservable<int>> observables = new Queue<IObservable<int>>(new [] { observableA, observableB }); IObservable<int> observable = A.Fake<IObservable<int>>(); A.CallTo(() => observable.Subscribe(A<IObserver<int>>.Ignored)) .Invokes(call => observables.Dequeue().Subscribe(call.GetArgument<IObserver<int>>(0))); IObserver<Exception> errors = A.Fake<IObserver<Exception>>(); IObserver<int> values = A.Fake<IObserver<int>>(); observable.Retry(errors).Subscribe(values); scheduler.AdvanceBy(20); A.CallTo(() => values.OnNext(314)).MustHaveHappened(Repeated.Exactly.Once); }
public void OAPHShouldRethrowErrors() { var input = new Subject<int>(); var sched = new TestScheduler(); var fixture = new ObservableAsPropertyHelper<int>(input, _ => { }, -5, sched); Assert.Equal(-5, fixture.Value); (new[] { 1, 2, 3, 4 }).Run(x => input.OnNext(x)); sched.Start(); Assert.Equal(4, fixture.Value); input.OnError(new Exception("Die!")); sched.Start(); try { Assert.Equal(4, fixture.Value); } catch { return; } Assert.True(false, "We should've threw there"); }
public void asd() { var scheduler = new TestScheduler(); var observer = new MockObserver<int>(scheduler); Observable.Range(0, 3, Scheduler.Immediate) .Expand(i => (i < 300) ? Observable.Return(i + 100) : Observable.Empty<int>()) .Subscribe(observer); observer.AssertEqual( OnNext(0, 0), OnNext(0, 1), OnNext(0, 2), OnNext(0, 100), OnNext(0, 101), OnNext(0, 102), OnNext(0, 200), OnNext(0, 201), OnNext(0, 202), OnNext(0, 300), OnNext(0, 301), OnNext(0, 302), OnCompleted(0) ); }
public void Test_Where_Error() { var exception = new Exception(); var scheduler = new TestScheduler(); var obs = scheduler.CreateHotObservable<string>( OnNext(150, "Erik"), OnNext(210, "Bart"), OnNext(220, "Matthew"), OnError<string>(230, exception) ); var res = scheduler.Start(() => { return obs.Where(x => x.Length > 4); }); res.Messages.AssertEqual( OnNext(220, "Matthew"), OnError<string>(230, exception) ); obs.Subscriptions.AssertEqual( Subscribe(200, 230) ); }
public void AsyncCommandSmokeTest() { var sched = new TestScheduler(); IObservable<int> async_data; ReactiveAsyncCommand fixture; using (TestUtils.WithTestScheduler(sched)) { fixture = new ReactiveAsyncCommand(null, 1); async_data = fixture .Delay(TimeSpan.FromSeconds(5), RxApp.TaskpoolScheduler) .Select(_ => 5) .Do(_ => fixture.AsyncCompletedNotification.OnNext(new Unit())); } var inflight_results = new List<int>(); fixture.ItemsInflight.Subscribe(inflight_results.Add); var output = new List<int>(); async_data.Subscribe(output.Add); Assert.IsTrue(fixture.CanExecute(null)); fixture.Execute(null); sched.RunToMilliseconds(1005); Assert.IsFalse(fixture.CanExecute(null)); sched.RunToMilliseconds(5005); Assert.IsTrue(fixture.CanExecute(null)); new[] {0,1,0}.AssertAreEqual(inflight_results); new[] {5}.AssertAreEqual(output); }
public void LimitSizeTo() { var subject = new Subject<Person>(); var scheduler = new TestScheduler(); var results = subject.ToObservableChangeSet<Person>(limitSizeTo: 100,scheduler: scheduler).AsAggregator(); var items = Enumerable.Range(1, 200).Select(i => new Person("p" + i.ToString("000"), i)).ToArray(); foreach (var person in items) { subject.OnNext(person); } scheduler.AdvanceBy(100000); Assert.AreEqual(300, results.Messages.Count, "Should be 300 messages"); Assert.AreEqual(200, results.Messages.Sum(x => x.Adds), "Should be 200 adds"); Assert.AreEqual(100, results.Messages.Sum(x => x.Removes), "Should be 100 removes"); Assert.AreEqual(100, results.Data.Count, "Should be 1 item in the cache"); var expected = items.Skip(100).ToArray().OrderBy(p => p.Name).ToArray(); var actual = results.Data.Items.OrderBy(p => p.Name).ToArray(); CollectionAssert.AreEqual(expected, actual,"Only second hundred should be in the cache"); }
public void Test_Select_Success() { var scheduler = new TestScheduler(); // Create an observable, remember subscribe happens at 200 var obs = scheduler.CreateHotObservable<string>( OnNext(150, "Erik"), OnNext(210, "Bart"), OnNext(220, "Matthew"), OnCompleted<string>(230) ); // Start our virtual time scheduler var res = scheduler.Start(() => { return obs.Select(x => x.Length); }); // Check the messages that came through at a specific time res.Messages.AssertEqual( OnNext(210, 4), OnNext(220, 7), OnCompleted<int>(230) ); // Check for when subscribe and unsubscribe obs.Subscriptions.AssertEqual( Subscribe(200, 230) ); }
public void OneLineTest() { var scheduler = new TestScheduler(); var observer = scheduler.CreateObserver<int>(); var sub = new OneLineCacheSubject<int>(); sub.OnNext(1); var d1 = sub.Subscribe(observer); sub.OnNext(2); d1.Dispose(); sub.OnNext(3); sub.OnNext(4); sub.OnNext(5); var d2 = sub.Subscribe(observer); d2.Dispose(); var d3 = sub.Subscribe(observer); sub.OnNext(6); observer.Messages.Select(x => x.Value.Value). Is(new List<int>() {1, 2, 3, 4, 5, 6}); }
public void ReactiveCommandAllFlow() { var testScheduler = new TestScheduler(); var @null = (object)null; var recorder1 = testScheduler.CreateObserver<object>(); var recorder2 = testScheduler.CreateObserver<object>(); var cmd = new ReactiveCommand(); cmd.Subscribe(recorder1); cmd.Subscribe(recorder2); cmd.CanExecute().Is(true); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Execute(); testScheduler.AdvanceBy(10); cmd.Dispose(); cmd.CanExecute().Is(false); cmd.Dispose(); // dispose again recorder1.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted<object>(30)); recorder2.Messages.Is( OnNext(0, @null), OnNext(10, @null), OnNext(20, @null), OnCompleted<object>(30)); }
public void CombineLatestValuesAreAllTrueTest() { var m = ReactivePropertyMode.RaiseLatestValueOnSubscribe; var recorder = new TestScheduler().CreateObserver<bool>(); var x = new ReactiveProperty<bool>(mode: m); var y = new ReactiveProperty<bool>(mode: m); var z = new ReactiveProperty<bool>(mode: m); new[] { x, y, z }.CombineLatestValuesAreAllTrue().Subscribe(recorder); recorder.Messages.First().Is(OnNext(0, false)); x.Value = true; recorder.Messages.Last().Is(OnNext(0, false)); y.Value = true; recorder.Messages.Last().Is(OnNext(0, false)); z.Value = true; recorder.Messages.Last().Is(OnNext(0, true)); y.Value = false; recorder.Messages.Last().Is(OnNext(0, false)); z.Value = false; recorder.Messages.Last().Is(OnNext(0, false)); x.Value = true; recorder.Messages.Last().Is(OnNext(0, false)); z.Value = true; recorder.Messages.Last().Is(OnNext(0, false)); y.Value = true; recorder.Messages.Last().Is(OnNext(0, true)); x.Value = false; recorder.Messages.Last().Is(OnNext(0, false)); y.Value = false; recorder.Messages.Last().Is(OnNext(0, false)); z.Value = false; recorder.Messages.Last().Is(OnNext(0, false)); z.Value = true; recorder.Messages.Last().Is(OnNext(0, false)); }
public void MyTestInitialize() { _scheduler = new TestScheduler(); _source = new SourceList<Person>(); _results = _source.Connect().Buffer(TimeSpan.FromMinutes(1),_scheduler).FlattenBufferResult().AsAggregator(); }
public void FilterBurstsInHotObservable() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(250, 1), OnNext(258, 2), OnNext(262, 3), OnNext(450, -1), OnNext(451, -2), OnNext(460, -3), OnCompleted<int>(500) ); var res = scheduler.Start(() => xs.FilterBursts(TimeSpan.FromTicks(10),scheduler)); res.Messages.AssertEqual( OnNext(250, 1), OnNext(450, -1), OnCompleted<int>(500)); xs.Subscriptions.AssertEqual( Subscribe(Subscribed, 500)); }
public void FilterBurstsWithATestObserver() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(250, 1), OnNext(258, 2), OnNext(262, 3), OnNext(450, -1), OnNext(451, -2), OnNext(460, -3), OnCompleted<int>(500) ); var testObserver = scheduler.CreateObserver<int>(); scheduler.AdvanceTo(200); xs.FilterBursts(TimeSpan.FromTicks(10), scheduler) .Subscribe(testObserver); scheduler.Start(); testObserver.Messages.AssertEqual( OnNext(250, 1), OnNext(450, -1), OnCompleted<int>(500)); xs.Subscriptions.AssertEqual( Subscribe(Subscribed, 500)); }
public void Notify() { var file = Path.GetTempFileName(); File.Delete(file); var info = new FileInfo(file); var scheduler = new TestScheduler(); FileNotification result = null; using (info.WatchFile(TimeSpan.FromSeconds(1), scheduler).Subscribe(x => result = x)) { scheduler.AdvanceBySeconds(1); result.NotificationType.Should().Be(FileNotificationType.Missing); File.AppendAllLines(file, Enumerable.Range(1, 10).Select(i => i.ToString())); scheduler.AdvanceBySeconds(1); result.NotificationType.Should().Be(FileNotificationType.Created); result.NotificationType.Should().NotBe(0); File.AppendAllLines(file, Enumerable.Range(11, 10).Select(i => i.ToString())); scheduler.AdvanceBySeconds(1); result.NotificationType.Should().Be(FileNotificationType.Changed); File.Delete(file); scheduler.AdvanceBySeconds(1); result.NotificationType.Should().Be(FileNotificationType.Missing); } }
public void FilterBurstsInColdObservable() { var scheduler = new TestScheduler(); // A cold observable will begin emitting when the observer subscribes // in this case, each emission defined for the observable will be realtive to the observer subscription time // which by default is 200 (defined in ReactiveTest.Subscribed) var xs = scheduler.CreateColdObservable( OnNext(250, 1), OnNext(258, 2), OnNext(262, 3), OnNext(450, -1), OnNext(451, -2), OnNext(460, -3), OnCompleted<int>(500) ); var res = scheduler.Start(() => xs.FilterBursts(TimeSpan.FromTicks(10), scheduler)); res.Messages.AssertEqual( OnNext(450, 1), OnNext(650, -1), OnCompleted<int>(700)); xs.Subscriptions.AssertEqual( Subscribe(ReactiveTest.Subscribed, 700)); }
public void values_can_be_triggered_by_time_or_count() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( // start #1 (@0) new Recorded<Notification<int>>(10, OnNext(1)), new Recorded<Notification<int>>(12, OnNext(2)), new Recorded<Notification<int>>(14, OnNext(3)), // start #2 (@ 15) new Recorded<Notification<int>>(16, OnNext(4)), new Recorded<Notification<int>>(20, OnNext(5)), new Recorded<Notification<int>>(24, OnNext(6)), new Recorded<Notification<int>>(28, OnNext(7)), // start #3 (@ 28) // start #4 (@ 43) new Recorded<Notification<int>>(50, OnNext(8)), new Recorded<Notification<int>>(51, OnCompleted()) ); var stats = new StatsObserver<IList<int>>(); source.BufferWithTimeOrCount(new TimeSpan(15), 4, scheduler) .Subscribe(stats); scheduler.Run(); Assert.AreEqual(4, stats.NextCount); Assert.AreEqual(3, stats.NextValues[0].Count); Assert.AreEqual(4, stats.NextValues[1].Count); Assert.AreEqual(0, stats.NextValues[2].Count); Assert.AreEqual(1, stats.NextValues[3].Count); }
public void Bug_1261() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(205, 1), OnNext(210, 2), OnNext(215, 3), OnNext(220, 4), OnNext(225, 5), OnNext(230, 6), OnCompleted<int>(230)); var results = scheduler.Start(() => xs.Window(TimeSpan.FromTicks(10), scheduler).Select((x, i) => x.Select(y => i.ToString() + " " + y.ToString()).Concat(Observable.Return(i.ToString() + " end", scheduler))).Merge() ); results.Messages.AssertEqual( OnNext(205, "0 1"), OnNext(210, "0 2"), OnNext(211, "0 end"), OnNext(215, "1 3"), OnNext(220, "1 4"), OnNext(221, "1 end"), OnNext(225, "2 5"), OnNext(230, "2 6"), OnNext(231, "2 end"), OnCompleted<string>(231) ); }
public void TimeSource101() { TestScheduler scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable(s_testData); var timeSource = new TimeSource<long>(xs, x => new DateTimeOffset(x, TimeSpan.Zero)); timeSource.StartTime = new DateTimeOffset(101, TimeSpan.Zero); var counts = from window in timeSource.Window(TimeSpan.FromTicks(5), timeSource.Scheduler) from Count in window.Count() select Count; var list = new List<Timestamped<int>>(); counts .Timestamp(timeSource.Scheduler) .Subscribe(ts => list.Add(ts)); timeSource.Connect(); scheduler.AdvanceTo(120); Assert.AreEqual(3, list.Count); list.AssertEqual( Result(106, 2), Result(111, 3), Result(115, 1)); }
public void MyTestInitialize() { _pausingSubject = new Subject<bool>(); _scheduler = new TestScheduler(); _source = new SourceCache<Person, string>(p => p.Key); _results = _source.Connect().BatchIf(_pausingSubject, _scheduler).AsAggregator(); }
public void ReadsSegmentsCorrectly() { var bytes = Encoding.UTF8.GetBytes( "<log4j:event logger=\"ConsoleApplication1.Program\" level=\"INFO\" timestamp=\"1361281966733\" thread=\"1\">" + " <log4j:message>Istcua orojurf bysgurnl t.</log4j:message>" + " <log4j:properties>" + " <log4j:data name=\"log4japp\" value=\"ConsoleApplication1.exe(6512)\" />" + " <log4j:data name=\"log4jmachinename\" value=\"user1\" />" + " </log4j:properties>" + "</log4j:event>" + "<log4j:event logger=\"ConsoleApplication1.Program\" level=\"WARN\" timestamp=\"1361281966808\" thread=\"1\">" + " <log4j:message>Ebo ohow aco inldrfb pameenegy.</log4j:message>" + " <log4j:properties>" + " <log4j:data name=\"log4japp\" value=\"ConsoleApplication1.exe(6512)\" />" + " <log4j:data name=\"log4jmachinename\" value=\"user2\" />" + " </log4j:properties>" + "</log4j:event>"); var stream = new MemoryStream(bytes); var format = new Log4JXmlLogFormat(); var testScheduler = new TestScheduler(); var observer = testScheduler.CreateObserver<RecordSegment>(); var offset = format.ReadSegments(observer, stream, CancellationToken.None).Result; Assert.Equal(2, observer.Messages.Count); var segments = observer.Messages.Select(x => x.Value.Value).ToArray(); Assert.True(segments.Any(x => x.Offset == 0 && x.Length == 342)); Assert.True(segments.Any(x => x.Offset == 342 && x.Length == 347)); Assert.Equal(stream.Length, offset); }
public void Setup() { _settings = A.Fake<Settings.IValues>(); _commandEndpointFactory = A.Fake<Subject.Network.Command.Endpoint.IFactory>(); _packetEndpointFactory = A.Fake<Subject.Network.Packet.Endpoint.IFactory>(); _commandScheduler = new TestScheduler(); }
public void WhenAHandleToTheFileCanBeObtainedCallSucessMethod() { //Arrange var scheduler = new TestScheduler(); var filePath = Path.GetTempFileName(); var testFolder = Path.GetDirectoryName(filePath); var fileHandlerMock = new Mock<IFileHandler>(); var monitorMock = new Mock<FolderMonitor>(testFolder, fileHandlerMock.Object) { CallBase = true }; var testFile = Path.GetFileName(filePath); fileHandlerMock .Setup(handler => handler.ProcessFile(It.Is<string>(v => v == filePath), It.IsAny<Stream>())) .Callback((string path, Stream s) => { s.Dispose(); File.Delete(path); }) .Verifiable(); var service = monitorMock.Object; service.Interval = TimeSpan.FromSeconds(1); service.RetryCount = 3; service.WatcherObservable = scheduler .CreateHotObservable( OnNext(10, new EventPattern<FileSystemEventArgs>( null, new FileSystemEventArgs(WatcherChangeTypes.Created, testFolder, testFile)))); service.RetryScheduler = scheduler; service.StartMonitoring(); //Act scheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); //Assert fileHandlerMock.VerifyAll(); }
public TestSchedulerService(bool singleUnderlyingScheduler = true) { this.hasSingleUnderlyingScheduler = singleUnderlyingScheduler; this.defaultScheduler = new TestScheduler(); if (singleUnderlyingScheduler) { this.currentThreadScheduler = this.immediateScheduler = this.mainScheduler = this.eventLoopScheduler = this.newThreadScheduler = this.taskPoolScheduler = this.defaultScheduler; } else { this.currentThreadScheduler = new TestScheduler(); this.immediateScheduler = new TestScheduler(); this.mainScheduler = new TestScheduler(); this.eventLoopScheduler = new TestScheduler(); this.newThreadScheduler = new TestScheduler(); this.taskPoolScheduler = new TestScheduler(); } }
public void ConnectableObservable_Connected() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable<int>( OnNext(210, 1), OnNext(220, 2), OnNext(230, 3), OnNext(240, 4), OnCompleted<int>(250) ); var subject = new MySubject(); var conn = new ConnectableObservable<int>(xs, subject); var disconnect = conn.Connect(); var res = scheduler.Start(() => conn); res.Messages.AssertEqual( OnNext(210, 1), OnNext(220, 2), OnNext(230, 3), OnNext(240, 4), OnCompleted<int>(250) ); }
public void WhenAHandleToTheFileCannotBeObtainedCallFailureMethod() { //Arrange var testFolder = Environment.CurrentDirectory; var scheduler = new TestScheduler(); var fileHandlerMock = new Mock<IFileHandler>(); var monitorMock = new Mock<FolderMonitor>(testFolder, fileHandlerMock.Object) { CallBase = true }; var service = monitorMock.Object; service.Interval = TimeSpan.FromSeconds(1); service.RetryCount = 3; service.WatcherObservable = scheduler .CreateHotObservable( OnNext(10, new EventPattern<FileSystemEventArgs>( null, new FileSystemEventArgs(WatcherChangeTypes.Created, testFolder, "test.file")))); service.RetryScheduler = scheduler; service.StartMonitoring(); //Act scheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); //Assert fileHandlerMock.Verify( handler => handler.ReportError(It.Is<string>(v => v == Path.Combine(testFolder, "test.file")), It.Is<Exception>(e => e is FileNotFoundException))); }
public void TaskToObservable_NonVoid_Complete_BeforeSubscribe() { var taskScheduler = new TestTaskScheduler(); var taskFactory = new TaskFactory(taskScheduler); var res = default(ITestableObserver<int>); taskFactory.StartNew(() => { var scheduler = new TestScheduler(); var taskSource = new TaskCompletionSource<int>(); taskSource.Task.ContinueWith(t => { var e = t.Exception; }); scheduler.ScheduleAbsolute(110, () => taskSource.SetResult(42)); res = scheduler.Start(() => taskSource.Task.ToObservable() ); }); res.Messages.AssertEqual( OnNext(200, 42), OnCompleted<int>(200) ); }
public void ScheduleTask_Should_Call_Sample_On_Scheduler() { // Arrange const int count = 5; var scheduler = new TestScheduler(); var settings = new TaskSchedulerSettings { RequestDelay = TimeSpan.FromMilliseconds(250) }; ITaskScheduler taskScheduler = new DelayTaskScheduler(settings, scheduler); // Act var tasks = Enumerable.Range(0, count + 1) .Select(i => Task.Run(() => Task.FromResult(i))) .Select(t => taskScheduler.ScheduleTask(() => t)) .ToArray(); scheduler.AdvanceTo(settings.RequestDelay.Ticks * count); // Assert tasks.Count(t => t.IsCompleted).Should().Be(count); taskScheduler.Dispose(); }
public void Bug_1283() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable( OnNext(100, 1), OnNext(220, 2), OnNext(240, 3), OnNext(300, 4), OnNext(310, 5), OnCompleted<int>(350) ); var results = scheduler.Start(() => xs.Window(TimeSpan.FromTicks(100), scheduler).Select((x, i) => x.Select(y => i.ToString() + " " + y.ToString()).Concat(Observable.Return(i.ToString() + " end", scheduler))).Merge() ); results.Messages.AssertEqual( OnNext(220, "0 2"), OnNext(240, "0 3"), OnNext(300, "0 4"), OnNext(301, "0 end"), OnNext(310, "1 5"), OnNext(351, "1 end"), OnCompleted<string>(351) ); }
public void SameAsRetry_OnError() { var scheduler = new TestScheduler(); var ex = new Exception(); var source = scheduler.CreateColdObservable<int>( OnNext(0, 1), OnNext(0, 2), OnError<int>(0, ex)); var called = 0; var retryRecorder = scheduler.CreateObserver<int>(); source.Retry().Take(5).Subscribe(retryRecorder); var onErrorRecorder = scheduler.CreateObserver<int>(); source.OnErrorRetry((Exception e) => { ++called; }).Take(5).Subscribe(onErrorRecorder); scheduler.Start(); retryRecorder.Messages.Is( OnNext(1, 1), OnNext(1, 2), OnNext(2, 1), OnNext(2, 2), OnNext(3, 1), OnCompleted<int>(3)); var retryResult = retryRecorder.Messages.ToArray(); onErrorRecorder.Messages.Is(retryRecorder.Messages); called.Is(2); }
public TheSignificantTimeChangeProperty() { scheduler = new TestScheduler(); timeService = new TimeService(scheduler); }
public MessageBusInteractTest() : base() { this.scheduler = new TestScheduler(); this.target = this.scheduler.CreateObserver <Statement>(); }
public static void Schedule(this TestScheduler self, TimeSpan ticks, Action action) => self.Schedule(Unit.Default, ticks, (_, __) => { action(); return(Disposable.Empty); });
public BatchFixture() { _scheduler = new TestScheduler(); _source = new SourceList <Person>(); _results = _source.Connect().Buffer(TimeSpan.FromMinutes(1), _scheduler).FlattenBufferResult().AsAggregator(); }
private void reset(DateTimeOffset?now = null) { testScheduler = new TestScheduler(); testScheduler.AdvanceTo((now ?? DateTimeOffset.UtcNow).Ticks); timeService = new TimeService(testScheduler); }
public TheRunAfterDelayMethod() { scheduler = new TestScheduler(); timeService = new TimeService(scheduler); }
public void MostRecent2() { var scheduler = new TestScheduler(); var xs = scheduler.CreateHotObservable <int>( OnNext(210, 1), OnNext(220, 2), OnNext(230, 3), OnNext(240, 4), OnNext(250, 5), OnNext(260, 6), OnNext(270, 7), OnNext(280, 8), OnNext(290, 9), OnCompleted <int>(300) ); var res = xs.MostRecent(0); var e1 = default(IEnumerator <int>); scheduler.ScheduleAbsolute(200, () => { e1 = res.GetEnumerator(); }); var o1 = new List <int>(); scheduler.ScheduleAbsolute(205, () => { Assert.True(e1.MoveNext()); o1.Add(e1.Current); }); scheduler.ScheduleAbsolute(232, () => { Assert.True(e1.MoveNext()); o1.Add(e1.Current); }); scheduler.ScheduleAbsolute(234, () => { Assert.True(e1.MoveNext()); o1.Add(e1.Current); }); scheduler.ScheduleAbsolute(265, () => { Assert.True(e1.MoveNext()); o1.Add(e1.Current); }); scheduler.ScheduleAbsolute(285, () => e1.Dispose()); var e2 = default(IEnumerator); scheduler.ScheduleAbsolute(255, () => { e2 = ((IEnumerable)res).GetEnumerator(); }); var o2 = new List <int>(); scheduler.ScheduleAbsolute(258, () => { Assert.True(e2.MoveNext()); o2.Add((int)e2.Current); }); scheduler.ScheduleAbsolute(262, () => { Assert.True(e2.MoveNext()); o2.Add((int)e2.Current); }); scheduler.ScheduleAbsolute(264, () => { Assert.True(e2.MoveNext()); o2.Add((int)e2.Current); }); scheduler.ScheduleAbsolute(275, () => { Assert.True(e2.MoveNext()); o2.Add((int)e2.Current); }); scheduler.Start(); xs.Subscriptions.AssertEqual( Subscribe(200, 285), Subscribe(255, 300) ); o1.AssertEqual(0, 3, 3, 6); o2.AssertEqual(0, 6, 6, 7); }
public void MultipleSubscriber() { var scheduler = new TestScheduler(); var observer1 = new OneLineCacheSubject <std_msgs.String>(); var observer2 = new OneLineCacheSubject <std_msgs.String>(); var observer3 = new OneLineCacheSubject <std_msgs.String>(); var obs = scheduler.CreateHotObservable( OnNext(10, new std_msgs.String() { data = "abc" }), OnNext(20, new std_msgs.String() { data = "defg" }), OnNext(30, new std_msgs.String() { data = "hijklmn" }) ); var node1 = Ros.InitNodeAsync("test1").Result; var node2 = Ros.InitNodeAsync("test2").Result; var node3 = Ros.InitNodeAsync("test3").Result; var subscriber1 = node1.SubscriberAsync <std_msgs.String>("test_topic").Result; var subscriber2 = node2.SubscriberAsync <std_msgs.String>("test_topic").Result; var publisher = node1.PublisherAsync <std_msgs.String>("test_topic").Result; var subscriber3 = node3.SubscriberAsync <std_msgs.String>("test_topic").Result; publisher.WaitForConnection(TestTimeout); subscriber1.WaitForConnection(TestTimeout); subscriber2.WaitForConnection(TestTimeout); subscriber3.WaitForConnection(TestTimeout); subscriber1.Subscribe(observer1); subscriber2.Subscribe(observer2); subscriber3.Subscribe(observer3); obs.Subscribe(publisher); scheduler.AdvanceBy(10); observer1.Timeout(TestTimeout).First().data.Is("abc"); observer2.Timeout(TestTimeout).First().data.Is("abc"); observer3.Timeout(TestTimeout).First().data.Is("abc"); observer1.Dispose(); scheduler.AdvanceBy(10); AssertEx.Throws <TimeoutException>(() => observer1.Timeout(TestTimeout).First()); observer2.Timeout(TestTimeout).First().data.Is("defg"); observer3.Timeout(TestTimeout).First().data.Is("defg"); observer2.Dispose(); scheduler.AdvanceBy(10); AssertEx.Throws <TimeoutException>(() => observer1.Timeout(TestTimeout).First()); AssertEx.Throws <TimeoutException>(() => observer2.Timeout(TestTimeout).First()); observer3.Timeout(TestTimeout).First().data.Is("hijklmn"); subscriber1.Dispose(); subscriber2.Dispose(); subscriber3.Dispose(); publisher.Dispose(); node1.Dispose(); node2.Dispose(); node3.Dispose(); }
public static ITestableObserver <T> Start <T>(this TestScheduler scheduler, Func <IObservable <T> > create, TimeSpan disposed) { var disposal = disposed.AsTestDisposalTime().Ticks; return(scheduler.Start(create, disposal)); }
[TestInitialize] public void Init() => _scheduler = new TestScheduler();
public void MultiplePublisher() { var scheduler = new TestScheduler(); var observer = new OneLineCacheSubject <std_msgs.String>(); var obs1 = scheduler.CreateHotObservable( OnNext(110, new std_msgs.String() { data = "abc1" }), OnNext(210, new std_msgs.String() { data = "defg1" }), OnNext(310, new std_msgs.String() { data = "hijklmn1" }) ); var obs2 = scheduler.CreateHotObservable( OnNext(120, new std_msgs.String() { data = "abc2" }), OnNext(220, new std_msgs.String() { data = "defg2" }), OnNext(320, new std_msgs.String() { data = "hijklmn2" }) ); var obs3 = scheduler.CreateHotObservable( OnNext(130, new std_msgs.String() { data = "abc3" }), OnNext(230, new std_msgs.String() { data = "defg3" }), OnNext(330, new std_msgs.String() { data = "hijklmn3" }) ); var node1 = Ros.InitNodeAsync("test1").Result; var node2 = Ros.InitNodeAsync("test2").Result; var node3 = Ros.InitNodeAsync("test3").Result; var publisher1 = node1.PublisherAsync <std_msgs.String>("test_topic").Result; var publisher2 = node2.PublisherAsync <std_msgs.String>("test_topic").Result; var subscriber = node1.SubscriberAsync <std_msgs.String>("test_topic").Result; var publisher3 = node3.PublisherAsync <std_msgs.String>("test_topic").Result; publisher1.WaitForConnection(TestTimeout); publisher2.WaitForConnection(TestTimeout); publisher3.WaitForConnection(TestTimeout); subscriber.WaitForConnection(TestTimeout); subscriber.Subscribe(observer); obs1.Subscribe(publisher1); obs2.Subscribe(publisher2); obs3.Subscribe(publisher3); scheduler.AdvanceTo(110); observer.Timeout(TestTimeout).First().data.Is("abc1"); scheduler.AdvanceTo(120); observer.Timeout(TestTimeout).First().data.Is("abc2"); scheduler.AdvanceTo(130); observer.Timeout(TestTimeout).First().data.Is("abc3"); scheduler.AdvanceTo(210); observer.Timeout(TestTimeout).First().data.Is("defg1"); scheduler.AdvanceTo(220); observer.Timeout(TestTimeout).First().data.Is("defg2"); scheduler.AdvanceTo(230); observer.Timeout(TestTimeout).First().data.Is("defg3"); scheduler.AdvanceTo(310); observer.Timeout(TestTimeout).First().data.Is("hijklmn1"); scheduler.AdvanceTo(320); observer.Timeout(TestTimeout).First().data.Is("hijklmn2"); scheduler.AdvanceTo(330); observer.Timeout(TestTimeout).First().data.Is("hijklmn3"); subscriber.Dispose(); publisher1.Dispose(); publisher2.Dispose(); publisher3.Dispose(); node1.Dispose(); node2.Dispose(); node3.Dispose(); }
public TheBarsObservable() { barsObserver = TestScheduler.CreateObserver <BarViewModel[]>(); ViewModel.Bars.Subscribe(barsObserver); }
public void Test() { var notifier = new CountNotifier(10); var recorder = new TestScheduler().CreateObserver <CountChangedStatus>(); notifier.Subscribe(recorder); notifier.Max.Is(10); notifier.Count.Is(0); notifier.Increment(3); notifier.Increment(3); notifier.Increment(3); notifier.Increment(); notifier.Decrement(5); notifier.Decrement(5); recorder.Messages.Is( OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Max), OnNext(0, CountChangedStatus.Decrement), OnNext(0, CountChangedStatus.Decrement), OnNext(0, CountChangedStatus.Empty)); // over max notifier.Increment(10); notifier.Count.Is(10); recorder.Messages.Clear(); notifier.Increment(); notifier.Count.Is(10); recorder.Messages.Count.Is(0); // under zero notifier.Decrement(10); notifier.Count.Is(0); recorder.Messages.Clear(); notifier.Decrement(); notifier.Count.Is(0); recorder.Messages.Count.Is(0); // over inc recorder.Messages.Clear(); notifier.Increment(5); notifier.Increment(15); notifier.Count.Is(10); recorder.Messages.Is( OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Increment), OnNext(0, CountChangedStatus.Max)); // over dec recorder.Messages.Clear(); notifier.Decrement(5); notifier.Decrement(15); notifier.Count.Is(0); recorder.Messages.Is( OnNext(0, CountChangedStatus.Decrement), OnNext(0, CountChangedStatus.Decrement), OnNext(0, CountChangedStatus.Empty)); AssertEx.Throws <ArgumentException>(() => notifier.Increment(-1)); AssertEx.Throws <ArgumentException>(() => notifier.Decrement(-1)); AssertEx.Throws <ArgumentException>(() => new CountNotifier(0)); AssertEx.DoesNotThrow(() => new CountNotifier(1)); }
public void Init() { _cancellationToken = new CancellationToken(); _manualResetEventSlim = new ManualResetEventSlim(false); _testScheduler = new TestScheduler(); _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256")); _peerSettings = Substitute.For <IPeerSettings>(); _peerSettings.PeerId.Returns(PeerIdHelper.GetPeerId()); _deltaDfsReader = Substitute.For <IDeltaDfsReader>(); _deltaDfsReader.TryReadDeltaFromDfs(Arg.Any <Cid>(), out Arg.Any <Delta>()).Returns(x => true); _deltaCache = Substitute.For <IDeltaCache>(); _deltaCache.GenesisHash.Returns("bafk2bzacecji5gcdd6lxsoazgnbg46c3vttjwwkptiw27enachziizhhkir2w".ToCid()); _ledger = Substitute.For <ILedger>(); _peerService = Substitute.For <IPeerService>(); _deltaHashProvider = new DeltaHashProvider(_deltaCache, Substitute.For <IDeltaIndexService>(), Substitute.For <ILogger>()); _deltaIndexService = new DeltaIndexService(new InMemoryRepository <DeltaIndexDao, string>()); _deltaIndexService.Add(new DeltaIndexDao { Cid = _hashProvider.ComputeUtf8MultiHash("0").ToCid(), Height = 0 }); _peerClient = Substitute.For <IPeerClient>(); ModifyPeerClient <LatestDeltaHashRequest>((request, senderPeerIdentifier) => { var deltaHeightResponse = new LatestDeltaHashResponse { DeltaIndex = new DeltaIndex { Cid = _hashProvider.ComputeUtf8MultiHash(_syncTestHeight.ToString()).ToCid().ToArray() .ToByteString(), Height = (uint)_syncTestHeight } }; _deltaHeightReplaySubject.OnNext(new ObserverDto(Substitute.For <IChannelHandlerContext>(), deltaHeightResponse.ToProtocolMessage(senderPeerIdentifier, CorrelationId.GenerateCorrelationId()))); }); ModifyPeerClient <DeltaHistoryRequest>((request, senderPeerIdentifier) => { var data = GenerateSampleData((int)request.Height, (int)request.Range, (int)_syncTestHeight); _deltaIndexService.Add(data.DeltaIndex.Select(x => DeltaIndexDao.ToDao <DeltaIndex>(x, _mapperProvider))); _deltaHistoryReplaySubject.OnNext(new ObserverDto(Substitute.For <IChannelHandlerContext>(), data .ToProtocolMessage(senderPeerIdentifier, CorrelationId.GenerateCorrelationId()))); }); _peerRepository = new PeerRepository(new InMemoryRepository <Peer, string>()); Enumerable.Repeat(new Peer { PeerId = PeerIdHelper.GetPeerId() }, 5).ToList().ForEach(_peerRepository.Add); _deltaHeightReplaySubject = new ReplaySubject <IObserverDto <ProtocolMessage> >(1); _deltaHistoryReplaySubject = new ReplaySubject <IObserverDto <ProtocolMessage> >(1); var mergeMessageStreams = _deltaHeightReplaySubject.AsObservable() .Merge(_deltaHistoryReplaySubject.AsObservable()); _peerService.MessageStream.Returns(mergeMessageStreams); _deltaHashProvider = Substitute.For <IDeltaHashProvider>(); _deltaHashProvider.TryUpdateLatestHash(Arg.Any <Cid>(), Arg.Any <Cid>()).Returns(true); _mapperProvider = new TestMapperProvider(); _userOutput = Substitute.For <IUserOutput>(); _deltaHeightWatcher = new DeltaHeightWatcher(_peerClient, _peerRepository, _peerService, minimumPeers: 0); var dfsService = Substitute.For <IDfsService>(); _peerSyncManager = new PeerSyncManager(_peerClient, _peerRepository, _peerService, _userOutput, _deltaHeightWatcher, Substitute.For <IDfsService>(), 0.7, 0); }
public TheMaximumHoursPerBarObservable() { maximumHoursPerBarObserver = TestScheduler.CreateObserver <int>(); ViewModel.MaximumHoursPerBar.Subscribe(maximumHoursPerBarObserver); }
public static void AdvanceAfterElement <T>(this TestScheduler scheduler, ITestableObservable <T> events, int elementIndex, int timeAfter = 500) { scheduler.AdvanceTo(events.Messages.ElementAt(elementIndex).Time + Time.Tics(timeAfter)); }
public static void AdvanceToEnd <T>(this TestScheduler scheduler, ITestableObservable <T> events) { scheduler.AdvanceTo(events.Messages.Max(x => x.Time)); }
public static void AdvanceJustAfter(this TestScheduler scheduler, int time) { scheduler.AdvanceTo(TimeSpan.FromMilliseconds(time).JustAfter().Ticks); }
public static void AdvanceTo(this TestScheduler scheduler, TimeSpan time) { scheduler.AdvanceTo(time.Ticks); }
public static void AdvanceBy(this TestScheduler @this, TimeSpan time) { Ensure.ArgumentNotNull(@this, nameof(@this)); @this.AdvanceBy(time.Ticks); }
public static void AdvanceJustAfterEnd <T>(this TestScheduler scheduler, ITestableObservable <T> events, int timeAfter = 500) { scheduler.AdvanceTo(events.Messages.Max(x => x.Time) + Time.Tics(timeAfter)); }
public static void ScheduleRelative(this TestScheduler @this, TimeSpan dueTime, Action action) { Ensure.ArgumentNotNull(@this, nameof(@this)); @this.ScheduleRelative(dueTime.Ticks, action); }
public static void ScheduleRelative <TState>(this TestScheduler @this, TState state, TimeSpan dueTime, Func <IScheduler, TState, IDisposable> action) { Ensure.ArgumentNotNull(@this, nameof(@this)); @this.ScheduleRelative(state, dueTime.Ticks, action); }
public static void AdvanceMinimal(this TestScheduler @this) => // not technically minimal, but advancing by a single tick doesn't always work as expected (a bug in Rx?) @this.AdvanceBy(TimeSpan.FromMilliseconds(1));
// because "Start" is an awfully misleading name. See http://kent-boogaart.com/blog/the-peril-of-virtualtimescheduler.start/ public static void AdvanceUntilEmpty(this TestScheduler @this) => @this.Start();
public override void TestInitialize() { base.TestInitialize(); testScheduler = new TestScheduler(); }
public static void AdvanceTo(this TestScheduler @this, DateTime dateTime) { Ensure.ArgumentNotNull(@this, nameof(@this)); @this.AdvanceTo(dateTime.Ticks); }