public void IsActive_is_true_when_subscription_is_made_and_false_when_disposed() { var testScheduler = new TestScheduler(); var result = false; var busyLatch = new BusyLatch(); busyLatch.IsActive .ObserveOn(testScheduler) .Subscribe(x => result = x); var subscription = busyLatch .Subscribe(_ => { }); testScheduler.AdvanceBy(1); Assert.That(result, Is.True); subscription.Dispose(); testScheduler.AdvanceBy(1); Assert.That(result, Is.False); }
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 OnExecuteを動かしてみる2() { var comp = new TestTargetComponent(); var testScheduler = new TestScheduler(); var recorder = testScheduler.CreateObserver<ReturnCode_t>(); comp.ExecutionContextScheduler = testScheduler; // コンポーネントを活性化 comp.ActivateAsync().ToObservable().Subscribe(recorder); // 時間がたっていないので何も起きていない comp.ExecuteCounter.Is(0); recorder.Messages.Count.Is(0); // 時間を進める testScheduler.AdvanceBy(100); // 活性化に成功したことを確認 recorder.Messages.Count.Is(2); recorder.Messages.First().Value.Value.Is(ReturnCode_t.RTC_OK); comp.ExecuteCounter.Is(0); // 時間を5秒進める testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); // OnExecuteは1秒に1回呼ばれる comp.ExecuteCounter.Is(5); }
public void TimerTestStart2() { var testScheduler = new TestScheduler(); var recorder = testScheduler.CreateObserver<long>(); var timer = new ReactiveTimer(TimeSpan.FromSeconds(1), testScheduler); timer.Subscribe(recorder); timer.Start(); testScheduler.AdvanceTo(TimeSpan.FromSeconds(3).Ticks + 1); recorder.Messages.Is( OnNext(TimeSpan.FromSeconds(0).Ticks + 1, 0L), OnNext(TimeSpan.FromSeconds(1).Ticks + 1, 1L), OnNext(TimeSpan.FromSeconds(2).Ticks + 1, 2L), OnNext(TimeSpan.FromSeconds(3).Ticks + 1, 3L)); timer.Stop(); recorder.Messages.Clear(); testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); recorder.Messages.Count.Is(0); }
public void CancelTest() { var testScheduler = new TestScheduler(); var recorder = testScheduler.CreateObserver<int>(); var notifier = new ScheduledNotifier<int>(testScheduler); notifier.Subscribe(recorder); var noCancel1 = notifier.Report(10, TimeSpan.FromMinutes(1)); var cancel1 = notifier.Report(20, TimeSpan.FromMinutes(3)); cancel1.Dispose(); recorder.Messages.Count.Is(0); testScheduler.AdvanceBy(TimeSpan.FromMinutes(5).Ticks); recorder.Messages.Count.Is(1); recorder.Messages[0].Is(OnNext(TimeSpan.FromMinutes(1).Ticks, 10)); var lastTime = recorder.Messages.Last().Time; recorder.Messages.Clear(); var origin = new DateTimeOffset(1999, 1, 1, 1, 1, 1, TimeSpan.Zero); var noCancel2 = notifier.Report(30, origin.AddMinutes(1)); var cancel2 = notifier.Report(40, origin.AddMinutes(3)); cancel2.Dispose(); testScheduler.AdvanceTo(origin.AddMinutes(5).Ticks); recorder.Messages.Is( OnNext(origin.AddMinutes(1).Ticks, 30)); }
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 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 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 when_used_with_TakeUntil_IsActive_is_true_then_false() { var testScheduler = new TestScheduler(); var result = false; var busyLatch = new BusyLatch(); busyLatch.IsActive .ObserveOn(testScheduler) .Subscribe(x => result = x); Observable.Range(0, 1) .TakeUntil(busyLatch) .Subscribe(x => { }); testScheduler.AdvanceBy(1); Assert.That(result, Is.True); testScheduler.AdvanceBy(1); Assert.That(result, Is.False); }
public void TargetComponentの入出力チェック() { var scheduler = new TestScheduler(); // OutPortから出力されたデータを蓄えるためのもの。 var recorder = scheduler.CreateObserver<TimedLong>(); // InPortにデータを入力するためのもの。1秒ごとにデータを送る。 var publisher = scheduler.CreateHotObservable( OnNext(TimeSpan.FromSeconds(1).Ticks, new TimedLong() {Data = 1}), OnNext(TimeSpan.FromSeconds(2).Ticks, new TimedLong() {Data = 2}), OnNext(TimeSpan.FromSeconds(3).Ticks, new TimedLong() {Data = 3}), OnNext(TimeSpan.FromSeconds(4).Ticks, new TimedLong() {Data = 4}), OnNext(TimeSpan.FromSeconds(5).Ticks, new TimedLong() {Data = 5}) ); var comp = new TargetComponent(); // コンポーネントのスケジューラをTestSchedulerに差し替える comp.ExecutionContextScheduler = scheduler; // 入出力ポートに接続 comp.InPort.Connect(publisher); comp.OutPort.Connect(recorder); // コンポーネントを活性化 var retRecorder = scheduler.CreateObserver<ReturnCode_t>(); comp.ActivateAsync().ToObservable().Subscribe(retRecorder); scheduler.AdvanceBy(100); retRecorder.Messages.Count.Is(2); retRecorder.Messages.First().Value.Value.Is(ReturnCode_t.RTC_OK); // 時間を5秒進める scheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); // 入力データの値が2倍されて出力されていることを確認 recorder.Messages.Count.Is(5); ReactiveAssert.AreElementsEqual( recorder.Messages.Select(x => x.Value.Value), new[] { new TimedLong() {Data = 2}, new TimedLong() {Data = 4}, new TimedLong() {Data = 6}, new TimedLong() {Data = 8}, new TimedLong() {Data = 10} }); }
public void TestScheduler_Usage() { var scheduler = new TestScheduler(); var wasExecuted = false; scheduler.Schedule(() => wasExecuted = true); Assert.IsFalse(wasExecuted); scheduler.AdvanceBy(1); //execute 1 tick of queued actions Assert.IsTrue(wasExecuted); }
public void delay_cancels_the_delay_if_subscription_is_disposed() { var scheduler = new TestScheduler(); var sut = new DelayServiceBuilder() .WithScheduler(scheduler) .Build(); var executed = false; var delayResult = sut .Delay(TimeSpan.FromSeconds(5)) .Subscribe(_ => executed = true); scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); Assert.False(executed); delayResult.Dispose(); scheduler.AdvanceBy(TimeSpan.FromSeconds(5)); Assert.False(executed); }
public void Replay_SeveralPoints_ObservesSectionsAtCorrectIntervalThenCompletes() { bool completed = false; var scheduler = new TestScheduler(); var testPoints = new[] { new GpxPoint(47.644548m, -122.326897m, 4.46m, DateTime.Parse("2009-10-17T18:37:26Z")), new GpxPoint(47.644548m, -122.326897m, 4.94m, DateTime.Parse("2009-10-17T18:37:31Z")), new GpxPoint(47.644548m, -122.326897m, 6.87m, DateTime.Parse("2009-10-17T18:37:34Z")) }; var observedSections = new List<GpxSection>(); testPoints.Replay(scheduler) .Subscribe(onNext: observedSections.Add, onError: _ => Assert.Fail(), onCompleted: () => completed = true); scheduler.AdvanceBy(1); Assert.That(observedSections.Count, Is.EqualTo(1)); Assert.That(observedSections[0].Start, Is.SameAs(testPoints[0])); Assert.That(observedSections[0].End, Is.SameAs(testPoints[1])); Assert.That(completed, Is.False); // Nothing for the time between the first two points scheduler.AdvanceBy(TimeSpan.TicksPerSecond * 4); Assert.That(observedSections.Count, Is.EqualTo(1)); Assert.That(completed, Is.False); scheduler.AdvanceBy(TimeSpan.TicksPerSecond); Assert.That(observedSections.Count, Is.EqualTo(2)); Assert.That(observedSections[1].Start, Is.SameAs(testPoints[1])); Assert.That(observedSections[1].End, Is.SameAs(testPoints[2])); Assert.That(completed, Is.False); // Waits for the time between the last two points before completing scheduler.AdvanceBy(TimeSpan.TicksPerSecond * 2); Assert.That(observedSections.Count, Is.EqualTo(2)); Assert.That(completed, Is.False); scheduler.AdvanceBy(TimeSpan.TicksPerSecond); Assert.That(completed, Is.True); }
public void Clock() { var scheduler = new TestScheduler (); Assert.AreEqual (0, scheduler.Clock, "#1"); // default scheduler.AdvanceBy (TimeSpan.FromDays (1).Ticks); Assert.AreEqual (TimeSpan.FromDays (1).Ticks, scheduler.Clock, "#2"); var dt = new DateTimeOffset (2012, 1, 1, 0, 0, 0, TimeSpan.Zero); scheduler.AdvanceTo (dt.Ticks); Assert.AreEqual (dt, new DateTimeOffset (scheduler.Clock, TimeSpan.Zero), "#3"); }
public void elections_are_ran_shortly_after_node_startup() { var testScheduler = new TestScheduler(); testScheduler.AdvanceTo(DateTimeOffset.UtcNow.Ticks); var nodes = TestNode.CreateCluster(scheduler: testScheduler); nodes.Start(); testScheduler.AdvanceBy(TestNode.ElectionTimeout.Ticks); nodes.Should().ContainSingle(n => n.State == State.Leader || n.State == State.Candidate); }
public void Should_Get_Commits_Every_10_seconds() { var someRepo = new Repo(); TestScheduler testScheduler = new TestScheduler(); var sut = new RepoWatcher(_browserMock.Object, someRepo, testScheduler); _browserMock.Verify(x => x.GetCommits(someRepo), Times.Never); testScheduler.AdvanceBy(TimeSpan.FromSeconds(10).Ticks); _browserMock.Verify(x => x.GetCommits(someRepo), Times.Once); }
public void Feature_starts_in_an_unavailable_state_if_no_instance_is_provided() { var feature = new Feature<string>(); var scheduler = new TestScheduler(); bool wasAvailable = false; feature.Availability.Timeout(TimeSpan.FromMinutes(5), scheduler).Subscribe(i => wasAvailable = i, ex => { }); scheduler.AdvanceBy(TimeSpan.FromDays(1).Ticks); Assert.That(wasAvailable, Is.False); }
public void TimerTest1() { var testScheduler = new TestScheduler(); var recorder = testScheduler.CreateObserver<long>(); var timer = new ReactiveTimer(TimeSpan.FromSeconds(1), testScheduler); timer.Subscribe(recorder); timer.Start(TimeSpan.FromSeconds(10)); testScheduler.AdvanceTo(TimeSpan.FromSeconds(13).Ticks); recorder.Messages.Is( OnNext(TimeSpan.FromSeconds(10).Ticks, 0L), OnNext(TimeSpan.FromSeconds(11).Ticks, 1L), OnNext(TimeSpan.FromSeconds(12).Ticks, 2L), OnNext(TimeSpan.FromSeconds(13).Ticks, 3L)); recorder.Messages.Clear(); timer.Stop(); testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); recorder.Messages.Count.Is(0); timer.Start(); var reStartClock = testScheduler.Clock + 1; testScheduler.AdvanceBy(TimeSpan.FromSeconds(3).Ticks + 1); recorder.Messages.Is( OnNext(reStartClock, 4L), OnNext(reStartClock + TimeSpan.FromSeconds(1).Ticks, 5L), OnNext(reStartClock + TimeSpan.FromSeconds(2).Ticks, 6L), OnNext(reStartClock + TimeSpan.FromSeconds(3).Ticks, 7L)); recorder.Messages.Clear(); timer.Reset(); testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); recorder.Messages.Count.Is(0); timer.Dispose(); recorder.Messages.Is(OnCompleted<long>(testScheduler.Clock)); timer.Dispose(); // dispose again }
public void OnExecuteを動かしてみる() { var comp = new SimpleComponent("test"); var testScheduler = new TestScheduler(); var recorder = testScheduler.CreateObserver<ReturnCode_t>(); comp.ExecutionContextScheduler = testScheduler; // OnExecuteが呼ばれるたびにカウンタをインクリメント var executeCounter = 0; comp.OnExecute = _ => { executeCounter = executeCounter + 1; return ReturnCode_t.RTC_OK; }; // コンポーネントを活性化 comp.ActivateAsync().ToObservable().Subscribe(recorder); // 時間がたっていないので何も起きていない executeCounter.Is(0); recorder.Messages.Count.Is(0); // 時間を進める testScheduler.AdvanceBy(100); // 活性化に成功したことを確認 recorder.Messages.Count.Is(2); recorder.Messages.First().Value.Value.Is(ReturnCode_t.RTC_OK); executeCounter.Is(0); // 時間を5秒進める testScheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); // OnExecuteは1秒に1回呼ばれる executeCounter.Is(5); }
public void delay_returns_observable_that_ticks_after_specified_delay() { var scheduler = new TestScheduler(); var sut = new DelayServiceBuilder() .WithScheduler(scheduler) .Build(); var completed = false; sut .Delay(TimeSpan.FromSeconds(5)) .Subscribe(_ => completed = true); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(2)); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(3)); Assert.True(completed); }
public void managed_memory_value_is_default_value_when_diagnostics_service_memory_errors() { // ARRANGE var viewModel = new DiagnosticsViewModel(_diagnosticService.Object, SchedulerService); // ACT _memorySubject.OnError(new Exception("blah!")); TestScheduler.AdvanceBy(TimeSpan.FromSeconds(1)); // ASSERT Assert.That(viewModel.ManagedMemory, Is.EqualTo(Constants.UI.Diagnostics.DefaultManagedMemoryString)); }
public async Task ShouldBackoffInCaseOfSeveralExceptions() { var testScheduler = new TestScheduler(); IFailureContext actualFailureContext = null; Task Throwing() => throw new InvalidOperationException("Boom"); var scheduledTask = testScheduler.Schedule(TimeSpan.FromSeconds(50), ct => Throwing(), (failureContext, ct) => { actualFailureContext = failureContext; return(Task.CompletedTask); }, TimeSpan.FromSeconds(180)); await testScheduler.AdvanceBy(TimeSpan.FromSeconds(51)); await testScheduler.AdvanceBy(TimeSpan.FromSeconds(51)); actualFailureContext.Should().NotBeNull(); actualFailureContext.Exception.Should().NotBeNull(); actualFailureContext.FailCount.Should().Be(2); actualFailureContext.CurrentPeriod.Should().Be(TimeSpan.FromSeconds(100)); await testScheduler.AdvanceBy(TimeSpan.FromSeconds(51)); actualFailureContext.FailCount.Should().Be(2); await testScheduler.AdvanceBy(TimeSpan.FromSeconds(50)); actualFailureContext.Exception.Should().NotBeNull(); actualFailureContext.FailCount.Should().Be(3); actualFailureContext.CurrentPeriod.Should().Be(TimeSpan.FromSeconds(180)); await scheduledTask.Cancel(); }
public void AndStopRetryingAfterASuccessFullLoginApiCall() { var observer = TestScheduler.CreateObserver <ITogglDataSource>(); var userIsMissingApiTokenException = new UserIsMissingApiTokenException(Substitute.For <IRequest>(), Substitute.For <IResponse>()); Api.User.Get().Returns(Observable.Throw <IUser>(userIsMissingApiTokenException), Observable.Return(User)); TestScheduler.Start(); LoginManager.Login(Email, Password).Subscribe(observer); TestScheduler.AdvanceBy(TimeSpan.FromDays(1).Ticks); Api.User.Received(2).Get(); }
public void ChangesNotLostIfConsumerIsRunningOnDifferentThread() { var producerScheduler = new TestScheduler(); var consumerScheduler = new TestScheduler(); //Note consumer is running on a different scheduler _source.Connect().BatchIf(_pausingSubject, producerScheduler).ObserveOn(consumerScheduler).Bind(out var target).AsAggregator(); _source.AddOrUpdate(new Person("A", 1)); producerScheduler.AdvanceBy(1); consumerScheduler.AdvanceBy(1); target.Count.Should().Be(1, "There should be 1 message"); _pausingSubject.OnNext(true); producerScheduler.AdvanceBy(1); consumerScheduler.AdvanceBy(1); _source.AddOrUpdate(new Person("B", 2)); producerScheduler.AdvanceBy(1); consumerScheduler.AdvanceBy(1); target.Count.Should().Be(1, "There should be 1 message"); _pausingSubject.OnNext(false); producerScheduler.AdvanceBy(1); //Target doesnt get the messages until its scheduler runs, but the //messages shouldnt be lost target.Count.Should().Be(1, "There should be 1 message"); consumerScheduler.AdvanceBy(1); target.Count.Should().Be(2, "There should be 2 message"); }
public void Should_capture_changes_every_second() { var scheduler = new TestScheduler(); scheduler.Start(); Console.WriteLine(scheduler.IsEnabled); var temp = Path.GetTempPath(); var file = Path.Combine(temp, Guid.NewGuid() + "__" + Guid.NewGuid()); var subject = Listener.Register(temp); var capture = new List<string>(); var subscription = subject.Subscribe(capture.Add); File.WriteAllText(file, "foo"); File.Delete(file); CollectionAssert.IsEmpty(capture); scheduler.AdvanceBy(TimeSpan.FromMilliseconds(500).Ticks); CollectionAssert.IsEmpty(capture); scheduler.AdvanceBy(TimeSpan.FromMilliseconds(600).Ticks); CollectionAssert.IsNotEmpty(capture); CollectionAssert.Contains(capture, file); var currentCount = capture.Count; subscription.Dispose(); File.WriteAllText(file, "foo"); File.Delete(file); scheduler.AdvanceBy(TimeSpan.FromSeconds(10).Ticks); Assert.AreEqual(currentCount, capture.Count); foreach (var c in capture) { Console.WriteLine(c); } }
public async ThreadingTask MarksTheActionNavigatedAwayBeforeStopButtonForOnboardingPurposes(bool useDefaultMode) { OnboardingStorage.StopButtonWasTappedBefore.Returns(Observable.Return(false)); await ViewModel.Initialize(); subject.OnNext(null); TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks); ViewModel.StartTimeEntry.Execute(useDefaultMode); TestScheduler.Start(); OnboardingStorage.DidNotReceive().SetNavigatedAwayFromMainViewAfterStopButton(); }
public void Replay_NoPoints_CompletesImmediately() { bool completed = false; var scheduler = new TestScheduler(); Enumerable.Empty<GpxPoint>().Replay(scheduler) .Subscribe(onNext:_ => Assert.Fail(), onError:_ => Assert.Fail(), onCompleted:() => completed = true); scheduler.AdvanceBy(1); Assert.That(completed, Is.True); }
public void cpu_value_is_formatted_when_diagnostics_service_pumps_cpu() { // ARRANGE var viewModel = new DiagnosticsViewModel(_diagnosticService.Object, SchedulerService); // ACT _cpuSubject.OnNext(42); TestScheduler.AdvanceBy(TimeSpan.FromSeconds(1)); // ASSERT Assert.That(viewModel.Cpu, Is.EqualTo("CPU: 42 %")); }
public void PhaseChanges_Should_Be_Synchronised_Across_Instances() { var secondProviderStartOffset = CycleConfiguration.Default.CycleDuration.Divide(3); _testScheduler.AdvanceBy(secondProviderStartOffset.Ticks); var spy2 = Substitute.For <IObserver <IPhase> >(); using (var cycleProvider2 = new CycleEventsProvider(CycleConfiguration.Default, _dateTimeProvider, _schedulerProvider, _deltaHashProvider, _logger)) using (cycleProvider2.PhaseChanges.Take(50 - PhaseCountPerCycle) .Subscribe(p => { _output.WriteLine( $"{_stopWatch.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture)} % 2 -- {p}"); spy2.OnNext(p); }, () => { _output.WriteLine( // ReSharper disable once InterpolatedStringExpressionIsNotIFormattable $"% 2 -- completed after {_stopWatch.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture):g}"); spy2.OnCompleted(); })) { _testScheduler.Start(); _spy.Received(1).OnCompleted(); spy2.Received(1).OnCompleted(); var receivedPhases = GetReceivedPhases(_spy); receivedPhases.Count.Should().Be(50); var receivedPhases2 = GetReceivedPhases(spy2); receivedPhases2.Count.Should().Be(50 - PhaseCountPerCycle); (receivedPhases2.First().UtcStartTime - receivedPhases.First().UtcStartTime) .TotalMilliseconds.Should().BeApproximately( CycleConfiguration.Default.CycleDuration.TotalMilliseconds, 0.0001d, "the provider should start on the second cycle"); foreach (var phases in receivedPhases.Skip(PhaseCountPerCycle) .Zip(receivedPhases2, (a, b) => new Tuple <IPhase, IPhase>(a, b))) { (phases.Item1.UtcStartTime - phases.Item2.UtcStartTime).TotalMilliseconds .Should().BeApproximately(0, 0.0001d, "phases should be in sync"); phases.Item1.Name.Should().Be(phases.Item2.Name); phases.Item1.Status.Should().Be(phases.Item1.Status); } } }
public void OnlyCallProcessOnlyOnceEvenIfItThrows() { //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(); throw new Exception(); }) .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 try { scheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); } catch (Exception) { } //CleanUp File.Delete(filePath); //Assert fileHandlerMock.Verify(handler => handler.ProcessFile(It.Is <string>(v => v == filePath), It.IsAny <Stream>()), Times.Once); fileHandlerMock.Verify(handler => handler.ReportError(It.IsAny <string>(), It.IsAny <Exception>()), Times.Once); }
public void default_strategy_is_exponential_backoff_to_a_maximum_of_three_minutes() { var repetitions = 0; var scheduler = new TestScheduler(); var source = Observable .Defer( () => { ++repetitions; return(Observable.Return(Unit.Default)); }); var sut = source .RepeatWithBackoff(100, scheduler: scheduler) .Subscribe( _ => { }, ex => { }); Assert.Equal(1, repetitions); var @try = 1; for (var i = 0; i < 7; ++i) { scheduler.AdvanceBy(TimeSpan.FromSeconds(Math.Pow(2, @try)) - TimeSpan.FromMilliseconds(1)); Assert.Equal(@try, repetitions); scheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); Assert.Equal(++@try, repetitions); } // we've reached the 3 minute maximum delay for (var i = 0; i < 5; ++i) { scheduler.AdvanceBy(TimeSpan.FromMinutes(3) - TimeSpan.FromMilliseconds(1)); Assert.Equal(@try, repetitions); scheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); Assert.Equal(++@try, repetitions); } }
public void PresetAndAdvance_Test() { // arrange var hotSource = _scheduler.CreateHotObservable( OnNext(ONE_MINUTE_TICKS * 2, "A"), OnNext(ONE_MINUTE_TICKS * 3, "B"), OnNext(ONE_MINUTE_TICKS * 4, "C"), OnNext(ONE_MINUTE_TICKS * 5, "D"), OnNext(ONE_MINUTE_TICKS * 10, "E"), OnCompleted <string>(ONE_MINUTE_TICKS * 11)); var observer = _scheduler.CreateObserver <int>(); // System under test var xs = from w in hotSource.Window(TimeSpan.FromMinutes(3), _scheduler) from sum in w.Sum(f => f[0]) select sum; // act xs.Subscribe(observer); _scheduler.AdvanceTo(ONE_MINUTE_TICKS * 6 + 1); observer.Messages.AssertEqual( OnNext <int>(ONE_MINUTE_TICKS * 3, 'A' + 'B'), OnNext <int>(ONE_MINUTE_TICKS * 6, 'C' + 'D') ); _scheduler.AdvanceBy(ONE_MINUTE_TICKS * 5); observer.Messages.AssertEqual( OnNext <int>(ONE_MINUTE_TICKS * 3, 'A' + 'B'), OnNext <int>(ONE_MINUTE_TICKS * 6, 'C' + 'D'), OnNext <int>(ONE_MINUTE_TICKS * 9, 0), // empty window OnNext <int>(ONE_MINUTE_TICKS * 11, 'E'), OnCompleted <int>(ONE_MINUTE_TICKS * 11) ); }
public void TestStartAndStopRandomOrders() { var testScheduler = new TestScheduler(); var mockExchangeClient = new MockClient(1, testScheduler); var orderStream = mockExchangeClient.OrderStream; var orderBookStream = mockExchangeClient.OrderBookStream; var resultOrders = new List <ExchangeOrder>(); var resultOrderBooks = new List <IOrderBook>(); var orderStreamSubscription = orderStream.Subscribe(resultOrders.Add); var orderBookStreamSubscription = orderBookStream.Subscribe(resultOrderBooks.Add); mockExchangeClient.Connect(); mockExchangeClient.StartRandomOrders(); testScheduler.AdvanceBy(1000000000); //count the number of items pushed while randomorders started int orderCountBeforeStart = resultOrders.Count; int orderBookCountBeforeStart = resultOrderBooks.Count; mockExchangeClient.StopRandomOrders(); mockExchangeClient.Disconnect(); //advance the time scheduler testScheduler.AdvanceBy(1000000000); //count the number of items pushed while randomorders stopped int orderCountAfterStop = resultOrders.Count; int orderBookCountAfterStop = resultOrderBooks.Count; //No items should have been pushed Assert.AreEqual(orderCountBeforeStart, orderCountAfterStop); Assert.AreEqual(orderBookCountBeforeStart, orderBookCountAfterStop); }
public void EventStore_polling_replays_new_events_inserted_after_previous_catchup_completed() { Events.Write(3); var scheduler = new TestScheduler(); var projector = new Projector <Order.ItemAdded>(() => new ReadModels1DbContext()) { OnUpdate = (work, e) => { } }; var statusReports = new List <ReadModelCatchupStatus>(); using (var catchup = CreateReadModelCatchup <ReadModels1DbContext>(projector)) { catchup.Progress .ForEachAsync(s => { statusReports.Add(s); Console.WriteLine(s); }); catchup.PollEventStore(TimeSpan.FromSeconds(5), scheduler); // Advance to trigger the first catchup scheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); // Trigger an empty batch replay scheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); Events.Write(2); // Advance to trigger the polling catchup scheduler.AdvanceBy(TimeSpan.FromSeconds(9).Ticks); statusReports.Count(s => s.IsStartOfBatch) .Should().Be(3); } }
public void T01_Consecutive() { var observer1 = testScheduler.CreateObserver <string>(); var observer2 = testScheduler.CreateObserver <string>(); var observable = testScheduler.CreateColdObservable( OnNext(100, "1"), OnCompleted <string>(1000) ); var sharedObservable = observable.ToAsyncSource(Duration.MaxValue, SystemClock.Instance); sharedObservable.SubscribeOn(testScheduler).Subscribe(observer1); testScheduler.AdvanceBy(1000); sharedObservable.SubscribeOn(testScheduler).Subscribe(observer2); testScheduler.Start(); var expected = new[] { //OnNext(101, "1"), OnNext(1001, "1"), OnCompleted <string>(1001) }; Assert.Equal(expected.ToList(), observer1.Messages); expected = new[] { OnNext(1001, "1"), OnCompleted <string>(1001) }; Assert.Equal(expected.ToList(), observer2.Messages); Assert.Equal(1, observable.Subscriptions.Count); Write(observable.Subscriptions.Stringify()); }
public async Task RulesUpdated_OnRulesChangeEventHasBeenFired() { // Arrange var testScheduler = new TestScheduler(); testScheduler.Stop(); var timesCalled = 0; var clientMock = new Mock <IRulesClient>(); var settings = new MinioRulesDriverSettings { SampleIntervalInMs = 10 }; var driver = new MinioRulesDriver(clientMock.Object, settings, null, testScheduler); driver.OnRulesChange += rules => Interlocked.Increment(ref timesCalled); clientMock.Setup(x => x.GetRuleset(It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(new Dictionary <string, RuleDefinition>())); // Act clientMock.Setup(x => x.GetVersion(It.IsAny <CancellationToken>())).Returns(Task.FromResult("10001")); testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(11).Ticks); await Task.Delay(10); clientMock.Setup(x => x.GetVersion(It.IsAny <CancellationToken>())).Returns(Task.FromResult("10002")); testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(11).Ticks); await Task.Delay(10); clientMock.Setup(x => x.GetVersion(It.IsAny <CancellationToken>())).Returns(Task.FromResult("10003")); testScheduler.AdvanceBy(TimeSpan.FromMilliseconds(11).Ticks); await Task.Delay(10); // Assert Assert.Equal("10003", driver.CurrentLabel); Assert.Equal(3, timesCalled); }
public void exposes_log_messages() { // ARRANGE LogHelper.ReconfigureLoggerToLevel(LogLevel.Error); var logger = LogManager.GetCurrentClassLogger(); var message1 = string.Format("Message 1 - {0}", Guid.NewGuid()); var message2 = string.Format("Message 2 - {0}", Guid.NewGuid()); var viewModel = new DiagnosticsViewModel(_diagnosticService.Object, _schedulerService); _logSubject.OnNext(message1); _logSubject.OnNext(message2); _testScheduler.AdvanceBy(Constants.DiagnosticsLogInterval + Constants.DiagnosticsLogInterval); //ACT var log = viewModel.Log.ToArray(); //ASSERT Assert.That(log.Count(x => x.Contains(message1)) == 1, Is.True); Assert.That(log.Count(x => x.Contains(message2)) == 1, Is.True); }
public void CurrentSection_AfterLoadingGpxAndWaiting_IsUpdatedAtTheCorrectTimes() { var vm = InitialiseViewModel(); // Log property updates var propertyUpdates = new List <string>(); vm.Changed.Subscribe(x => propertyUpdates.Add(x.PropertyName)); Assert.That(ExecuteLoadGpxDataCommandAsync(vm).Result, Is.True); scheduler.AdvanceBy(1); Assert.That(propertyUpdates.Count, Is.EqualTo(1)); Assert.That(propertyUpdates[0], Is.EqualTo("CurrentSection")); vm.CurrentSection.AssertSection(47.644548m, -122.326897m, 4.46m, "2009-10-17T18:37:26Z", 47.644548m, -122.326897m, 4.94m, "2009-10-17T18:37:31Z"); scheduler.AdvanceBy(TimeSpan.TicksPerSecond * 5); Assert.That(propertyUpdates.Count, Is.EqualTo(2)); Assert.That(propertyUpdates[1], Is.EqualTo("CurrentSection")); vm.CurrentSection.AssertSection(47.644548m, -122.326897m, 4.94m, "2009-10-17T18:37:31Z", 47.644548m, -122.326897m, 6.87m, "2009-10-17T18:37:34Z"); }
public async Task WhenChangedUsesTheGetProjectsAutocompleteSuggestionsInteractor() { var text = "Some text"; await ViewModel.Initialize(); TestScheduler.Start(); ViewModel.FilterText.OnNext(text); TestScheduler.AdvanceBy(TimeSpan.FromSeconds(60).Ticks); InteractorFactory .Received() .GetProjectsAutocompleteSuggestions(Arg.Is <IList <string> >( words => words.SequenceEqual(text.SplitToQueryWords()))); }
public void SelectsTheColorPassedAsTheParameter() { var passedColor = Colors.DefaultProjectColors.Skip(3).First(); var parameters = ColorParameters.Create(passedColor, false); var observer = TestScheduler.CreateObserver <IEnumerable <SelectableColorViewModel> >(); ViewModel.Initialize(parameters); ViewModel.SelectableColors.Subscribe(observer); TestScheduler.AdvanceBy(EnoughTicksToEmitTheThrottledColor); observer.LastEmittedValue() .Single(c => c.Selected) .Color.Should().Be(passedColor); }
public void Stream() { ITestableObserver <RatingRecord> observer = scheduler.CreateObserver <RatingRecord>(); instance.Ratings.Subscribe(observer); instance.AddRating(new RatingRecord { Id = "1", Date = new DateTime(2016, 01, 10), Rating = 10 }); scheduler.AdvanceBy(100); instance.Dispose(); observer.Messages.AssertEqual( OnNext <RatingRecord>(0, item => true), OnCompleted <RatingRecord>(100)); }
public void DuplicateWithinDurationIsSupressed() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( OnNext(100, "a"), OnNext(200, "a")); var duration = TimeSpan.FromTicks(250); var results = scheduler.CreateObserver <string>(); source.DistinctUntilChanged(duration, scheduler).Subscribe(results); scheduler.AdvanceBy(1000); results.Messages.AssertEqual( OnNext(100, "a")); }
public void ActivityOverdue() { var scheduler = new TestScheduler(); var activity = new CookingActivity(scheduler) { TotalTime = TimeSpan.FromSeconds(5) }; var vm = new CookingActivityViewModel(activity); vm.StartCommand.Execute(null); scheduler.AdvanceBy(TimeSpan.FromSeconds(2).Ticks); Assert.IsFalse(vm.IsOverdue); StringAssert.DoesNotContain("-", vm.RemainingTime); scheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks); Assert.IsTrue(vm.IsOverdue); StringAssert.Contains("-", vm.RemainingTime); }
public void TestFakeRunDaily() { // ARRANGE FakeMockableAppImplementation app = new(Object); app.Initialize(); // ACT TestScheduler.AdvanceBy(TimeSpan.FromDays(1).Ticks); TestScheduler.AdvanceBy(TimeSpan.FromDays(1).Ticks); // ASSERT VerifyEntityTurnOn("binary_sensor.fake_run_daily_happened", times: Times.Exactly(2)); }
public void TestFakeRunEveryStopsTimerWhenDisposed() { // ARRANGE FakeMockableAppImplementation app = new(Object); app.Initialize(); // ACT TestScheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); TestScheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); // ASSERT VerifyEntityTurnOn("binary_sensor.fake_run_stops_when_disposed", times: Times.Exactly(1)); }
public void ShouldDonateStopTimerIntent() { var secondTimeEntry = Substitute.For <IThreadSafeTimeEntry>(); ViewModel.StopTimeEntry.Execute(Arg.Any <TimeEntryStopOrigin>()); TestScheduler.Start(); TestScheduler.Stop(); subject.OnNext(secondTimeEntry); TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks); ViewModel.StopTimeEntry.Execute(Arg.Any <TimeEntryStopOrigin>()); TestScheduler.Start(); IntentDonationService.Received().DonateStopCurrentTimeEntry(); }
public void can_add_hidden_column() { // ARRANGE var viewModel = new ColumnPickerViewModel(_identifier, _columnService.Object, SchedulerService); TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); // ACT viewModel.Left.First().IsSelected = true; // ASSERT Assert.That(viewModel.AddCommand.CanExecute(null), Is.True); }
public void BufferWhileShouldBufferWhilePredicateIsTrue(int start, int count) { // given var testScheduler = new TestScheduler(); var observable = System.Reactive.Linq.Observable.Range(start, count).ObserveOn(testScheduler).BufferWhile(() => true); var observer = testScheduler.CreateObserver<IList<int>>(); observable.Subscribe(observer); // when below range end testScheduler.AdvanceBy(count); // then observer.Messages.Count.Should().Be(0); }
public void no_buttons_enabled_when_populated() { // ARRANGE // ACT var viewModel = new ColumnPickerViewModel(_identifier, _columnService.Object, SchedulerService); TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); // ASSERT Assert.That(viewModel.AddCommand.CanExecute(null), Is.False); Assert.That(viewModel.RemoveCommand.CanExecute(null), Is.False); Assert.That(viewModel.MoveupCommand.CanExecute(null), Is.False); Assert.That(viewModel.MovedownCommand.CanExecute(null), Is.False); }
public void AddsFifteenItemsToTheListOfSelectableColorsIfTheUserIsPro() { var someColor = new Color(23, 45, 125); var parameters = ColorParameters.Create(someColor, true); var observer = TestScheduler.CreateObserver <IEnumerable <SelectableColorViewModel> >(); ViewModel.Initialize(parameters); ViewModel.SelectableColors.Subscribe(observer); TestScheduler.AdvanceBy(EnoughTicksToEmitTheThrottledColor); observer.LastEmittedValue() .Should().HaveCount(15); }
public void delay_returns_observable_that_ticks_after_specified_delay() { var scheduler = new TestScheduler(); var sut = new DelayServiceBuilder() .WithScheduler(scheduler) .Build(); var completed = false; sut .Delay(TimeSpan.FromSeconds(5)) .Subscribe(_ => completed = true); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(2)); Assert.False(completed); scheduler.AdvanceBy(TimeSpan.FromSeconds(3)); Assert.True(completed); }
public void SelectsThePassedColorIfThePassedColorIsNotPartOfTheDefaultColorsAndWorkspaceIsPro() { var someColor = new Color(23, 45, 125); var parameters = ColorParameters.Create(someColor, true); var observer = TestScheduler.CreateObserver <IEnumerable <SelectableColorViewModel> >(); ViewModel.Initialize(parameters); ViewModel.SelectableColors.Subscribe(observer); TestScheduler.AdvanceBy(EnoughTicksToEmitTheThrottledColor); observer.LastEmittedValue() .Single(c => c.Selected) .Color.Should().Be(someColor); }
public void can_not_move_first_column_up() { // ARRANGE var viewModel = new ColumnPickerViewModel(_identifier, _columnService.Object, SchedulerService); TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(1)); // ACT viewModel.Right.First().IsSelected = true; // ASSERT Assert.That(viewModel.MoveupCommand.CanExecute(null), Is.False); }
public void It_Should_Process_An_Error_Observable() { // Arrange var scheduler = new TestScheduler(); var heardMessages = new List<LogMessage>(); var exceptions = new List<Exception>(); var subscription = CreateSubscription( scheduler, MockDataTask(CreateErrorMessage(999, "Test Error")), msg => heardMessages.Add(msg), ex => exceptions.Add(ex)); // Act scheduler.AdvanceBy(TestSchedulerTickInterval); scheduler.AdvanceBy(TestSchedulerTickInterval); subscription.Dispose(); // Assert Assert.That(exceptions, Has.Count.EqualTo(2)); Assert.That(heardMessages, Has.Count.EqualTo(0)); }
public void It_Should_Flatten_Lists_Of_Records_Into_An_Observable() { // Arrange var scheduler = new TestScheduler(); var heardMessages = new List<LogMessage>(); var exceptions = new List<Exception>(); var subscription = CreateSubscription( scheduler, MockDataTask(CreateTestRecords(2)), msg => heardMessages.Add(msg), ex => exceptions.Add(ex)); // Act scheduler.AdvanceBy(TestSchedulerTickInterval); scheduler.AdvanceBy(TestSchedulerTickInterval); subscription.Dispose(); // Assert Assert.That(exceptions, Has.Count.EqualTo(0)); Assert.That(heardMessages, Has.Count.EqualTo(4)); }
public void ContentFileRenamedShouldTriggerEvent() { var fileSystem = new FileSystem(); var scheduler = new TestScheduler(); var solution = Solution.Load(TestDataGenerator.SolutionPath, TestDataGenerator.Get, fileSystem, scheduler); var solutionChangedEventArgs = SolutionChangedEventArgs.Empty; solution.Changed += (sender, args) => solutionChangedEventArgs = args; fileSystem.Rename(string.Empty, @"x:\Test\Foo.Tests\FooTypeTests.cs"); scheduler.AdvanceBy(1.Seconds()); solutionChangedEventArgs.ChangedProjects.Count.ShouldBe(1); solutionChangedEventArgs.ChangedProjects.ShouldContain(TestDataGenerator.FooTestsProjectPath); }
public void TestScheduler() { var scheduler = new TestScheduler(); int val = 0; var observable = Observable.Return(42) .Delay(TimeSpan.FromSeconds(10), scheduler); observable.Subscribe(v => val = v); scheduler.AdvanceBy(TimeSpan.FromSeconds(15).Ticks); val.Should().Be(42); }
public void CallOnErrorWhenAnExceptionIsEncountered() { TestScheduler scheduler = new TestScheduler(); IObservable<int> observable = scheduler.CreateColdObservable<int>(new [] { new Recorded<Notification<int>>(10, Notification.CreateOnError<int>(new InvalidOperationException())) }); IObserver<Exception> errors = A.Fake<IObserver<Exception>>(); observable.Retry(errors).Subscribe(); scheduler.AdvanceBy(10); A.CallTo(() => errors.OnNext(A<Exception>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); }
public void ShouldNotAttemptToSaveIfNoMessages() { IElasticClient elasticClient = A.Fake<IElasticClient>(); TestScheduler testScheduler = new TestScheduler(); IMonitorFactory<TestMessage> factory = new ElasticSearchMonitorFactory<TestMessage>("indexName", new List<Type>(), "instanceName", TimeSpan.FromSeconds(1), testScheduler, elasticClient); IMonitor<TestMessage> monitor = factory.Create("SomeName"); Assert.That(monitor, Is.Not.Null); testScheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); A.CallTo(() => elasticClient.Bulk(A<IBulkRequest>._)).MustNotHaveHappened(); }
public void ShouldAttemptToSaveIfMessagesReceived() { IElasticClient elasticClient = A.Fake<IElasticClient>(); TestScheduler testScheduler = new TestScheduler(); IMonitorFactory<TestMessage> factory = new ElasticSearchMonitorFactory<TestMessage>("indexName", new List<Type>(), "instanceName", TimeSpan.FromSeconds(1), testScheduler, elasticClient); IMonitor<TestMessage> monitor = factory.Create("SomeName"); monitor.MessageReceived(new TestMessage(), TimeSpan.FromMilliseconds(1)); testScheduler.AdvanceBy(TimeSpan.FromMinutes(1).Ticks); A.CallTo(() => elasticClient.Bulk(A<IBulkRequest>._)).MustHaveHappened(Repeated.Exactly.Once); }