public void When_Path_Has_Null_Intermediary_Node_Then_Propagates_ProvertyValueChanged_With_HasValue_False()
        {
            // Arrange
            var childOne = new TestObservableObject {Age = 5};
            var childTwo = new TestObservableObject {Age = 17};
            var obj = new TestObservableObject {ObservableChild = childOne};
            var scheduler = new TestScheduler();

            var observer = scheduler.CreateObserver<IPropertyValueChanged<int>>();
            var expected = new[]
            {
                OnNext(000, PropertyValueChanged.CreateWithValue(childOne, "Age", childOne.Age)),
                OnNext(000, PropertyValueChanged.CreateWithValue(childOne, "Age", 20)),
                OnNext(100, PropertyValueChanged.CreateWithoutValue<TestObservableObject, int>(null, "Age")),
                OnNext(300, PropertyValueChanged.CreateWithValue(childTwo, "Age", childTwo.Age)),
            };

            var sut = obj.When(x => x.ObservableChild.Age);

            // Act
            sut.Subscribe(observer);
            obj.ObservableChild.Age = 20;
            scheduler.AdvanceTo(100);
            obj.ObservableChild = null;
            scheduler.AdvanceTo(300);
            obj.ObservableChild = childTwo;

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
 public void AddSource()
 {
     source.OnNext(0);
     source.OnNext(1);
     scheduler.AdvanceTo(1000);
     target.Is(0, 1);
 }
Пример #3
0
        public static void Testing_ExceptionFlow_InjectingControllingSchedulers(Form form, Action <string> notify)
        {
            var modelMock = new Mock <Model>();
            var prices    = new ObservableCollection <decimal>();

            modelMock.SetupGet(m => m.Prices).Returns(prices);
            modelMock.Setup(m => m.GetPriceStream(notify)).Returns(Observable.Never <decimal>());

            var uiScheduler         = new TestScheduler();
            var threadPoolScheduler = new TestScheduler();

            modelMock.Object.Show(uiScheduler, threadPoolScheduler, notify);

            var halfASecondLater   = TimeSpan.FromMilliseconds(500).Ticks;
            var twelveSecondsLater = TimeSpan.FromSeconds(12).Ticks;

            threadPoolScheduler.AdvanceTo(halfASecondLater);
            uiScheduler.AdvanceTo(halfASecondLater);

            Assert.That(modelMock.Object.IsConnected, Is.True);

            threadPoolScheduler.AdvanceTo(twelveSecondsLater);
            uiScheduler.AdvanceTo(twelveSecondsLater);

            Assert.That(modelMock.Object.IsConnected, Is.False);
        }
Пример #4
0
        public void ThroughputAnalyzerShouldCalculateThroughputCorrectly()
        {
            // given
            var testScheduler = new TestScheduler();

            var analysisResultsObserver = testScheduler.CreateObserver <IThroughputAnalysisResult>();

            var interval   = TimeSpan.FromMilliseconds(1);
            var resolution = TimeSpan.FromMilliseconds(10);

            using (Observable.Interval(interval, testScheduler).Take(20).AnalyzeThroughput(resolution, scheduler: testScheduler).Subscribe(analysisResultsObserver))
            {
                analysisResultsObserver.Messages.Count.Should().Be(0);

                // when some time has passed
                testScheduler.AdvanceTo(resolution + interval);

                // then
                analysisResultsObserver.Messages.Count.Should().Be(1);
                analysisResultsObserver.Messages[0].Value.Value.ElapsedTime.Should().Be(resolution);
                analysisResultsObserver.Messages[0].Value.Value.ThroughputPerMillisecond.Should().Be(analysisResultsObserver.Messages[0].Value.Value.Count / analysisResultsObserver.Messages[0].Value.Value.ElapsedTime.TotalMilliseconds);

                // when
                testScheduler.AdvanceTo(resolution + resolution + interval);

                // then
                analysisResultsObserver.Messages.Count.Should().Be(3);

                analysisResultsObserver.Messages[1].Value.Value.ElapsedTime.Should().Be(resolution);
                analysisResultsObserver.Messages[1].Value.Value.ThroughputPerMillisecond.Should().Be(analysisResultsObserver.Messages[1].Value.Value.Count / analysisResultsObserver.Messages[1].Value.Value.ElapsedTime.TotalMilliseconds);

                analysisResultsObserver.Messages.Last().Value.Kind.Should().Be(NotificationKind.OnCompleted);
            }
        }
Пример #5
0
        public void CharBufferUntilTest()
        {
            var str  = "1234aa0000bbaa1111bb4321";
            var list = new List <char>();

            var ts = new TestScheduler();

            var obs = Observable.Create <char>(x =>
            {
                foreach (var c in str)
                {
                    x.OnNext(c);
                }
                return(Disposable.Empty);
            });

            //1
            obs
            .BufferUntil('a', 'b', 200)
            .SelectMany(p => p)
            .Subscribe(list.Add);
            ts.AdvanceTo(str.Length);
            new string(list.ToArray()).Should().Be("aa0000baa1111b");

            //2
            list.Clear();
            obs
            .BufferUntil('4', '3', 200)
            .Retry()
            .SelectMany(p => p)
            .Subscribe(list.Add);
            ts.AdvanceTo(str.Length);
            new string(list.ToArray()).Should().Be("4aa0000bbaa1111bb43");
        }
Пример #6
0
        public void ThroughputAnalyzerShouldCalculateThroughputCorrectlyAndForwardSourceSequence()
        {
            // given
            var testScheduler = new TestScheduler();

            var sourceSequenceObserver            = testScheduler.CreateObserver <long>();
            var throughPutAnalysisResultsObserver = testScheduler.CreateObserver <IThroughputAnalysisResult>();

            var interval   = TimeSpan.FromMilliseconds(1);
            var resolution = TimeSpan.FromMilliseconds(10);

            using (Observable.Interval(interval, testScheduler).Take(20).AnalyzeThroughputWith(throughPutAnalysisResultsObserver, resolution, testScheduler).Subscribe(sourceSequenceObserver))
            {
                throughPutAnalysisResultsObserver.Messages.Count.Should().Be(0);

                // when some time has passed
                testScheduler.AdvanceTo(resolution + interval);

                // then
                throughPutAnalysisResultsObserver.Messages.Count.Should().Be(1);
                throughPutAnalysisResultsObserver.Messages[0].Value.Value.ElapsedTime.Should().Be(resolution);
                throughPutAnalysisResultsObserver.Messages[0].Value.Value.ThroughputPerMillisecond.Should().Be(throughPutAnalysisResultsObserver.Messages[0].Value.Value.Count / throughPutAnalysisResultsObserver.Messages[0].Value.Value.ElapsedTime.TotalMilliseconds);

                // when
                testScheduler.AdvanceTo(resolution + resolution + interval);

                // then
                throughPutAnalysisResultsObserver.Messages.Count.Should().Be(2);

                throughPutAnalysisResultsObserver.Messages[1].Value.Value.ElapsedTime.Should().Be(resolution);
                throughPutAnalysisResultsObserver.Messages[1].Value.Value.ThroughputPerMillisecond.Should().Be(throughPutAnalysisResultsObserver.Messages[1].Value.Value.Count / throughPutAnalysisResultsObserver.Messages[1].Value.Value.ElapsedTime.TotalMilliseconds);
            }
        }
        public void When_Path_Has_Null_Intermediary_Node_Then_Skips_When_Invalid_Path()
        {
            // Arrange
            var childOne = new TestObservableObject {Age = 5};
            var childTwo = new TestObservableObject {Age = 17};
            var obj = new TestObservableObject {ObservableChild = childOne};
            var scheduler = new TestScheduler();

            var observer = scheduler.CreateObserver<int>();
            var expected = new[]
            {
                OnNext(000, childOne.Age),
                OnNext(000, 20),
                OnNext(300, childTwo.Age),
            };

            var sut = obj.WhenValue(x => x.ObservableChild.Age);

            // Act
            sut.Subscribe(observer);
            obj.ObservableChild.Age = 20;
            scheduler.AdvanceTo(100);
            obj.ObservableChild = null;
            scheduler.AdvanceTo(300);
            obj.ObservableChild = childTwo;

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
Пример #8
0
        public void SimpleDelayWithDrop()
        {
            var receivedSignals = new List <int>();
            var subject         = new Subject <int>();
            var scheduler       = new TestScheduler();

            subject.UniqueThrottle(TimeSpan.FromTicks(25), scheduler).Subscribe(x => receivedSignals.Add(x));


            subject.OnNext(1);
            subject.OnNext(1);
            subject.OnNext(1);
            receivedSignals.Count.Should().Be(0);
            scheduler.AdvanceTo(24);
            subject.OnNext(1);
            subject.OnNext(1);
            subject.OnNext(1);
            receivedSignals.Count.Should().Be(0);

            scheduler.AdvanceTo(25);
            receivedSignals.Count.Should().Be(1);

            scheduler.AdvanceTo(50);
            subject.OnNext(1);
            receivedSignals.Count.Should().Be(1);

            scheduler.AdvanceTo(100);
            receivedSignals.Count.Should().Be(2);
        }
Пример #9
0
        public void When_Subscribed_Then_OnNext_Changes()
        {
            // Arrange
            var obj = new TestObservableObject {ObservableChild = new TestObservableObject {Age = 3}};
            var replacementChild = new TestObservableObject {Age = 5};
            var scheduler = new TestScheduler();
            var observer = scheduler.CreateObserver<TestObservableObject>();
            var expected = new[]
            {
                OnNext(000, obj.ObservableChild),
                OnNext(010, replacementChild),
                OnNext(010, replacementChild),
                OnNext(020, replacementChild),
            };

            var sut = obj.WhenAny(x => x.ObservableChild).ForProperty<TestObservableObject>("Age", "Name");

            // Act
            sut.Subscribe(observer);
            scheduler.AdvanceTo(10);
            obj.ObservableChild = replacementChild;
            obj.ObservableChild.Age = 17;
            scheduler.AdvanceTo(20);
            obj.ObservableChild.Name = "Billy";

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
Пример #10
0
        public void ShouldLimitSizeOfBoundCollection()
        {
            _scheduler.AdvanceTo(2);
            _target.Count.Should().Be(2, "Should be 2 item in target collection");

            _scheduler.AdvanceTo(3);
            _scheduler.AdvanceBy(TimeSpan.FromMilliseconds(1).Ticks); //push time forward as size limit is checked for after the event

            _target.Count.Should().Be(2, "Should be 2 item in target collection because of size limit");
        }
        public void ShouldLimitSizeOfBoundCollection()
        {
            _scheduler.AdvanceTo(2);
            Assert.AreEqual(2, _target.Count, "Should be 2 item in target collection");

            _scheduler.AdvanceTo(3);
            Assert.AreEqual(2, _target.Count, "Should be 2 item in target collection because of size limit");

            var expected = new[] { person2, person3 };

            CollectionAssert.AreEquivalent(expected, _target);
        }
        public void ShouldLimitSizeOfBoundCollection()
        {
            _scheduler.AdvanceTo(2);
            _target.Count.Should().Be(2, "Should be 2 item in target collection");

            _scheduler.AdvanceTo(3);
            _target.Count.Should().Be(2, "Should be 2 item in target collection because of size limit");

            var expected = new[] { _person2, _person3 };

            _target.Should().BeEquivalentTo(expected);
        }
Пример #13
0
        public void SendNotification_1EventAfter0SecondThen1After3Minutes_Expect1NotificationSentAfter5Minutes()
        {
            //Arrange
            var eventEmitter = new MvvmLightMessenger();

            var robot = Substitute.For <IRobot>();

            robot.Messenger.Returns(eventEmitter);

            var scheduler      = new TestScheduler();
            var jiraAggregator = new JiraAggregatorSut(robot, scheduler);

            var user = new User {
                displayName = "Laurent Kempé", name = "laurent"
            };

            var addCommentEvent1 = new JiraModel
            {
                issue = new Issue {
                    key = "LK-10", fields = new Fields {
                        reporter = user, assignee = user
                    }
                },
                webhookEvent = "jira:issue_created",
                comment      = new CommentDetails(),
                user         = user
            };

            var addCommentEvent2 = new JiraModel
            {
                issue = new Issue {
                    key = "LK-10", fields = new Fields {
                        reporter = user, assignee = user
                    }
                },
                webhookEvent = "jira:issue_updated",
                comment      = new CommentDetails(),
                user         = user
            };

            //Act
            scheduler.Schedule(TimeSpan.FromSeconds(0), () => eventEmitter.Publish("JiraEvent", addCommentEvent1));
            scheduler.Schedule(TimeSpan.FromSeconds(120), () => eventEmitter.Publish("JiraEvent", addCommentEvent2));

            scheduler.AdvanceTo(TimeSpan.FromSeconds(181).Ticks);
            robot.Received(0).SendNotification("", "", "Message", true);

            scheduler.AdvanceTo(TimeSpan.FromMinutes(5).Ticks);

            //Assert
            robot.Received(1).SendNotification(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), true);
        }
Пример #14
0
        public void CreateDelay_EnsureTestHelperBehavesAsExpected()
        {
            CreateTimer(10).DoOnCompleted(() => _value = 123).ObserveOn(_scheduler).Subscribe();

            AssertValue(0);

            _scheduler.AdvanceTo(5);
            AssertValue(0);

            _scheduler.AdvanceTo(9);
            AssertValue(0);

            _scheduler.AdvanceBy(10);
            AssertValue(123);
        }
Пример #15
0
        public void ShouldReturnValueAfterTime()
        {
            var expected = "FDA";
            var scheduler = new TestScheduler();
            var obs = Typing(expected, 5, scheduler);
            string result = null;
            obs.Subscribe(x => result = x);
            scheduler.AdvanceTo(TimeSpan.FromSeconds(3).Ticks);

            Assert.Equal(null, result);

            scheduler.AdvanceTo(TimeSpan.FromSeconds(6).Ticks);

            Assert.Equal(expected, result);
        }
Пример #16
0
        public void TimeSource100()
        {
            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(100, 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(4, list.Count);
            list.AssertEqual(
                Result(105, 2),
                Result(110, 3),
                Result(115, 0),
                Result(115, 1));
        }
        public void SelectDisposableShouldWork()
        {
            var scheduler = new TestScheduler();
            var disposables = new List<BooleanDisposable>();
            var list = new CompositeDisposable();
            scheduler.CreateColdObservable(
                new Recorded<Notification<long>>(100, Notification.CreateOnNext(0L)),
                new Recorded<Notification<long>>(200, Notification.CreateOnNext(1L)),
                new Recorded<Notification<long>>(300, Notification.CreateOnNext(2L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnNext(3L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnCompleted<long>())
            )
            .SelectDisposable(list, i => {
                var d = new BooleanDisposable();
                disposables.Add(d);
                return d;
            }, (i, _) => i)
            .Subscribe()
            .DisposeWith(list);

            scheduler.AdvanceTo(300);

            disposables.Count.Should().Be(3);

            disposables.Select(d => d.IsDisposed).Should().NotContain(true);

            list.Dispose();

            disposables.Select(d => d.IsDisposed).Should().NotContain(false);

        }
        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);
        }
Пример #19
0
        public void TimeAutoStart()
        {
            TestScheduler scheduler = new TestScheduler();
            var           xs        = scheduler.CreateHotObservable(s_testData);

            var timeSource = new TimeSource <long>(xs, x => new DateTimeOffset(x, TimeSpan.Zero));
            // Note: no start time specified, result should be the same as 101

            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 async Task LastCheckTimeHasToBeCorrect()
        {
            // Arrange
            var testScheduler = new TestScheduler();
            var startTime     = DateTime.Parse("2017-08-13T11:10:00Z").ToUniversalTime();

            testScheduler.AdvanceTo(startTime.Ticks);

            mMockHttpGet.Version = 10001;
            mMockHttpGet.Rules   = new Dictionary <string, RuleDefinition> {
                { "test_rule", new RuleDefinition() }
            };
            mDriver = TweekManagementRulesDriver.StartNew(
                mMockHttpGet.HttpGet,
                new TweekManagementRulesDriverSettings {
                SampleIntervalInMs = (int)TimeSpan.FromHours(0.9).TotalMilliseconds
            },
                null,
                null,
                testScheduler
                );

            // Act
            testScheduler.AdvanceBy(TimeSpan.FromHours(1).Ticks);
            await Task.Delay(10);

            var result = await mDriver.GetAllRules();

            // Assert
            Assert.Equal("10001", mDriver.CurrentLabel);
            Assert.Equal("test_rule", result.Keys.First());
            Assert.Equal(startTime.Hour + 1, mDriver.LastCheckTime.Hour);
        }
        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));
        }
Пример #22
0
        public void TestFakeRunEveryHour()
        {
            // ARRANGE
            FakeMockableAppImplementation app = new(Object);

            app.Initialize();

            // ACT
            TestScheduler.AdvanceBy(TimeSpan.FromHours(1).Ticks);

            var now = TestScheduler.Now;
            var timeOfDayToTrigger = new DateTime(
                now.Year,
                now.Month,
                now.Day,
                2,
                0,
                0
                );

            TestScheduler.AdvanceTo(timeOfDayToTrigger.Ticks);

            // ASSERT
            VerifyEntityTurnOn("binary_sensor.fake_run_every_hour_happened", times: Times.Exactly(2));
        }
Пример #23
0
    public void AllExeptionsAreLogged()
    {
        // ARRANGE
        var testScheduler = new TestScheduler();
        var loggerMock    = new Mock <ILogger <NetDaemonScheduler> >();
        // sets the date to a specific time so we do not get errors in UTC
        var dueTime = new DateTime(2021, 1, 1, 0, 0, 0);

        testScheduler.AdvanceTo(dueTime.Ticks);

        var netDaemonScheduler = new DisposableScheduler(testScheduler).WrapWithLogger(loggerMock.Object);

        netDaemonScheduler.ScheduleCron("* * * * *", () => throw new Exception("hello"));

        // ACT and ASSERT
        testScheduler.AdvanceBy(TimeSpan.FromMinutes(5).Ticks);
        // ASSERT that error is logged once
        loggerMock.Verify(
            x => x.Log(
                LogLevel.Error,
                It.IsAny <EventId>(),
                It.Is <It.IsAnyType>((_, __) => true),
                It.IsAny <Exception>(),
                It.Is <Func <It.IsAnyType, Exception, string> >((_, _) => true)), Times.Exactly(5));
    }
        public void BufferLiveUntilHistoryCompletes()
        {
            var ts = new TestScheduler();

            var history = ts.CreateColdObservable(
                OnNext <ICacheNotification>(3, new DummyNotification {
                EventId = 1
            }),
                OnCompleted <ICacheNotification>(5));

            var live = ts.CreateHotObservable(
                OnNext <ICacheNotification>(4, new DummyNotification {
                EventId = 2
            }));

            var observer = ts.CreateObserver <ICacheNotification>();

            history.Combine(live).Subscribe(observer);

            ts.AdvanceTo(20);

            ReactiveAssert.AreElementsEqual(
                new[]
            {
                OnNext <ICacheNotification>(5, n => n.EventId == 1),
                OnNext <ICacheNotification>(5, n => n.EventId == 2)
            },
                observer.Messages);
        }
        public void HistoryMultipleValues()
        {
            var ts = new TestScheduler();

            var history = ts.CreateColdObservable(
                OnNext <ICacheNotification>(1, new DummyNotification {
                EventId = 1
            }),
                OnNext <ICacheNotification>(4, new DummyNotification {
                EventId = 2
            }),
                OnNext <ICacheNotification>(9, new DummyNotification {
                EventId = 3
            }),
                OnCompleted <ICacheNotification>(10));

            var observer = ts.CreateObserver <ICacheNotification>();

            history.Combine(Observable.Never <ICacheNotification>()).Subscribe(observer);

            ts.AdvanceTo(20);

            ReactiveAssert.AreElementsEqual(
                new[]
            {
                OnNext <ICacheNotification>(10, n => n.EventId == 1),
                OnNext <ICacheNotification>(10, n => n.EventId == 2),
                OnNext <ICacheNotification>(10, n => n.EventId == 3)
            },
                observer.Messages);
        }
Пример #26
0
        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();
        }
Пример #27
0
    public void UpToMaxEventsAreBuffered()
    {
        TimeSpan  maxInterval   = TimeSpan.FromTicks(200);
        const int maxBufferSize = 2;
        var       scheduler     = new TestScheduler();
        var       source        = scheduler.CreateColdObservable(
            OnNext(100, 1),
            OnNext(200, 2),
            OnNext(300, 3));

        IList <int>[] expectedBuffers =
        {
            new[] { 1, 2 },
            new[] { 3 }
        };
        var expectedTimes = new[]
        {
            200,     /* Buffer cap reached */
            maxInterval.Ticks + 300
        };
        var results = scheduler.CreateObserver <IList <int> >();

        source.BufferNearEvents(maxInterval, maxBufferSize, scheduler)
        .Subscribe(results);
        scheduler.AdvanceTo(10000);
        results.Messages.AssertEqual(
            OnNext <IList <int> >(expectedTimes[0], buffer => CheckBuffer(expectedBuffers[0], buffer)),
            OnNext <IList <int> >(expectedTimes[1], buffer => CheckBuffer(expectedBuffers[1], buffer)));
    }
Пример #28
0
        public void SendNotification_4SuccessfulAnd1FailedForSameBuildEventSent_ExpectFailedNotificationSentWithCorrectMessage()
        {
            //Arrange
            var eventEmitter = new MvvmLightMessenger();

            var robot = Substitute.For <IRobot>();

            robot.EventEmitter.Returns(eventEmitter);

            var scheduler          = new TestScheduler();
            var teamCityAggregator = new TeamCityAggregatorSut(robot, scheduler);

            var successfulTeamCityBuildModel = new TeamCityModel {
                build = new Build {
                    buildNumber = "10", buildResult = "success"
                }
            };
            var failedTeamCityBuildModel = new TeamCityModel {
                build = new Build {
                    buildNumber = "10", buildResult = "failed"
                }
            };

            //Act
            scheduler.Schedule(TimeSpan.FromMinutes(1), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(1), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(2), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(3), () => eventEmitter.Emit("TeamCityBuild", failedTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(4), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));

            scheduler.AdvanceTo(TimeSpan.FromMinutes(5).Ticks);

            //Assert
            robot.Received(1).SendNotification(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>(), true);
        }
Пример #29
0
        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));
        }
Пример #30
0
        public void ObservePropertyException()
        {
            var testScheduler = new TestScheduler();
            var recorder      = testScheduler.CreateObserver <string>();
            var commonEx      = new Exception();

            var m = new Model()
            {
                Name = "aaa"
            };

            m.ObserveProperty(x => x.Name)
            .Do(x => recorder.OnNext(x))
            .Do(_ => { throw commonEx; })
            .OnErrorRetry((Exception e) => recorder.OnError(e))
            .Subscribe();

            testScheduler.AdvanceTo(1000);
            m.Name = "bbb";

            recorder.Messages.Is(
                OnNext(0, "aaa"),
                OnError <string>(0, commonEx),
                OnNext(1000, "bbb"),
                OnError <string>(1000, commonEx));
        }
        public void SelectDisposableShouldWork()
        {
            var scheduler   = new TestScheduler();
            var disposables = new List <BooleanDisposable>();
            var list        = new CompositeDisposable();

            scheduler.CreateColdObservable(
                new Recorded <Notification <long> >(100, Notification.CreateOnNext(0L)),
                new Recorded <Notification <long> >(200, Notification.CreateOnNext(1L)),
                new Recorded <Notification <long> >(300, Notification.CreateOnNext(2L)),
                new Recorded <Notification <long> >(400, Notification.CreateOnNext(3L)),
                new Recorded <Notification <long> >(400, Notification.CreateOnCompleted <long>())
                )
            .SelectDisposable(list, i => {
                var d = new BooleanDisposable();
                disposables.Add(d);
                return(d);
            }, (i, _) => i)
            .Subscribe()
            .DisposeWith(list);

            scheduler.AdvanceTo(300);

            disposables.Count.Should().Be(3);

            disposables.Select(d => d.IsDisposed).Should().NotContain(true);

            list.Dispose();

            disposables.Select(d => d.IsDisposed).Should().NotContain(false);
        }
Пример #32
0
        public void Subscribe_LastPolled(int numberOfTicks)
        {
            var pollingInterval = TimeSpan.FromMilliseconds(100);

            if (numberOfTicks == 0)
            {
                numberOfTicks++; // Polling is executed before first tick
            }

            var subscriptionTime = pollingInterval.Ticks * (numberOfTicks > 0 ? numberOfTicks : 1);

            var scheduler            = new TestScheduler();
            int cont                 = 0;
            IObservable <int> source = Observable.Create <int>(x =>
            {
                x.OnNext(Interlocked.Increment(ref cont));
                x.OnCompleted();
                return(Disposable.Empty);
            });

            ITestableObserver <int> observer = scheduler.CreateObserver <int>();

            using (var sut = new PollingObservable <int>(source, pollingInterval, scheduler))
            {
                scheduler.AdvanceTo(subscriptionTime);
                using (sut.Subscribe(observer))
                {
                    scheduler.AdvanceBy(1);
                }
            }

            observer.Messages.AssertEqual(
                OnNext <int>(subscriptionTime + 1, x => x == numberOfTicks && cont == numberOfTicks + 1),
                OnCompleted <int>(subscriptionTime + 1));
        }
Пример #33
0
        public void Subscribe_WaitToFirstTick_OneMessage()
        {
            long executionTicks      = TimeSpan.FromMilliseconds(100).Ticks + 1;
            var  scheduler           = new TestScheduler();
            int  cont                = 0;
            IObservable <int> source = Observable.Create <int>(x =>
            {
                scheduler.Sleep(executionTicks - 1);
                x.OnNext(Interlocked.Increment(ref cont));
                x.OnCompleted();
                return(Disposable.Empty);
            });

            ITestableObserver <int> observer = scheduler.CreateObserver <int>();

            using (var sut = new PollingObservable <int>(source, TimeSpan.FromHours(1), scheduler))
                using (sut.Subscribe(observer))
                {
                    scheduler.AdvanceTo(executionTicks);
                }

            observer.Messages.AssertEqual(
                OnNext <int>(executionTicks, x => x == 1),
                OnCompleted <int>(executionTicks));
        }
        public void SetUp()
        {
            _diagnosticsViewModel = new Mock <IDiagnosticsViewModel>();

            _data = new Subject <IEnumerable <DynamicData> >();
            _tabularDataService = new Mock <ITabularDataService>();
            _tabularDataService.Setup(x => x.GetAsync())
            .Returns(_data);

            _columnsChanged     = new Subject <string>();
            _columnsInitialised = new Subject <string>();

            _columnsService = new Mock <IColumnsService>();
            _columnsService.Setup(x => x.Changed)
            .Returns(_columnsChanged);
            _columnsService.Setup(x => x.Initialised)
            .Returns(_columnsInitialised);
            _columnsService.Setup(x => x.InitialiseColumns(It.IsAny <string>(), It.IsAny <IEnumerable <string> >()))
            .Callback <string, IEnumerable <string> >((y, z) =>
            {
                _columnsService.Setup(x => x.VisibleColumns(It.IsAny <string>()))
                .Returns(z);
            });

            _overlayService  = new Mock <IOverlayService>();
            _dateTimeService = new MockDateTimeService(TestScheduler);

            TestScheduler.AdvanceTo(DateTime.Now.Ticks);
        }
Пример #35
0
    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);
    }
Пример #36
0
        static void TestSchedulerEx()
        {
            var scheduler = new TestScheduler();

            scheduler.Schedule(() => Console.WriteLine("A")); //Schedule immediately
            scheduler.Schedule(TimeSpan.FromTicks(10), () => Console.WriteLine("B"));
            scheduler.Schedule(TimeSpan.FromTicks(20), () => Console.WriteLine("C"));
            Console.WriteLine("scheduler.AdvanceTo(1);");
            scheduler.AdvanceTo(1);
            Console.WriteLine("scheduler.AdvanceTo(10);");
            scheduler.AdvanceTo(10);
            Console.WriteLine("scheduler.AdvanceTo(15);");
            scheduler.AdvanceTo(15);
            Console.WriteLine("scheduler.AdvanceTo(20);");
            scheduler.AdvanceTo(20);
        }
Пример #37
0
            public async Task WorksIfProviderHasMultipleSuggestions()
            {
                var scheduler   = new TestScheduler();
                var provider    = Substitute.For <ISuggestionProvider>();
                var suggestions = new[]
                {
                    createSuggestion("te1"),
                    createSuggestion("te2"),
                    createSuggestion("te3")
                };
                var observableContent = suggestions
                                        .Select(suggestion => createRecorded(1, suggestion))
                                        .ToArray();
                var observable = scheduler
                                 .CreateColdObservable(observableContent);

                provider.GetSuggestions().Returns(observable);
                var container = new SuggestionProviderContainer(provider);
                var viewmodel = new SuggestionsViewModel(container);

                await viewmodel.Initialize();

                scheduler.AdvanceTo(1);

                viewmodel.Suggestions.Should().HaveCount(suggestions.Length)
                .And.Contain(suggestions);
            }
Пример #38
0
        public void B1E1ParsePackageTest()
        {
            var ts = new TestScheduler();

            var source = new byte[]
            {
                0, 0, 11, 23, 12,

                254, 0, 255,

                254, 1, 1, 255,

                22,

                254, 2, 2, 2, 255, 33, 5, 0
            };
            var rst = new List <byte[]>();

            source.ToObservable(ts)
            .ParsePackage <byte>(254, 255)
            .Subscribe(p => rst.Add(p));

            ts.AdvanceTo(source.Length);
            var expect = new List <byte[]>
            {
                new byte[] { 0 },
                new byte[] { 1, 1 },
                new byte[] { 2, 2, 2 }
            };

            rst.Should().BeEquivalentTo(expect);
        }
 public void SetUp()
 {
     testScheduler = new TestScheduler();
     testScheduler.AdvanceTo(DateTimeOffset.UtcNow.Ticks);
     nodes = TestNode.CreateCluster(scheduler: testScheduler);
     nodes.Start();
     leader = nodes.WaitForLeader(testScheduler).Result;
 }
Пример #40
0
 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");
 }
Пример #41
0
        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 SetUp()
        {
            testScheduler = new TestScheduler();
            testScheduler.AdvanceTo(DateTimeOffset.UtcNow.Ticks);
            nodes = TestNode.CreateCluster(scheduler: testScheduler);
            nodes.Start();
            leader = nodes.WaitForLeader(testScheduler).Result;

            darkNode = nodes.First(n => n != leader) as TestNode;
            darkNode.SleepOnAppendEntries = true;
        }
        public void SimpleDelay()
        {
            var receivedSignals = new List<int>();
            var subject = new Subject<int>();
            var scheduler = new TestScheduler();
            subject.UniqueThrottle(TimeSpan.FromTicks(25), scheduler).Subscribe(x => receivedSignals.Add(x));


            subject.OnNext(1);
            receivedSignals.Count.Should().Be(0);

            scheduler.AdvanceTo(24);
            receivedSignals.Count.Should().Be(0);

            scheduler.AdvanceTo(25);
            receivedSignals.Count.Should().Be(1);

            scheduler.AdvanceTo(100);
            receivedSignals.Count.Should().Be(1);
        }
        public void AsyncGetTest()
        {
            var input = new[] { 1, 1, 1, 1, 1 };
            var sched = new TestScheduler();

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x*5).Delay(delay, sched), 5, 2, null, sched);

            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.Equal(0, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1200)));
            Assert.Equal(25, result);

            sched.Start();
            Assert.Equal(25, result);
        }
Пример #45
0
        public void SendNotification_1EventAfter0SecondThen1After3Minutes_Expect1NotificationSentAfter5Minutes()
        {
            //Arrange
            var eventEmitter = new MvvmLightMessenger();

            var robot = Substitute.For<IRobot>();
            robot.EventEmitter.Returns(eventEmitter);

            var scheduler = new TestScheduler();
            var jiraAggregator = new JiraAggregatorSut(robot, scheduler);

            var user = new User { displayName = "Laurent Kempé", name = "laurent" };

            var addCommentEvent1 = new JiraModel
            {
                issue = new Issue { key = "LK-10", fields = new Fields { reporter = user, assignee = user } },
                webhookEvent = "jira:issue_created",
                comment = new CommentDetails(),
                user = user
            };

            var addCommentEvent2 = new JiraModel
            {
                issue = new Issue { key = "LK-10", fields = new Fields { reporter = user, assignee = user } },
                webhookEvent = "jira:issue_updated",
                comment = new CommentDetails(),
                user = user
            };

            //Act
            scheduler.Schedule(TimeSpan.FromSeconds(0), () => eventEmitter.Emit("JiraEvent", addCommentEvent1));
            scheduler.Schedule(TimeSpan.FromSeconds(120), () => eventEmitter.Emit("JiraEvent", addCommentEvent2));

            scheduler.AdvanceTo(TimeSpan.FromSeconds(181).Ticks);
            robot.Received(0).SendNotification("", "", "Message", true);

            scheduler.AdvanceTo(TimeSpan.FromMinutes(5).Ticks);

            //Assert
            robot.Received(1).SendNotification(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), true);
        }
        public void EnsureCacheDoesNotBlockOnRelease()
        {
            var input = new[] { 1, 2 };
            var sched = new TestScheduler();
            var releaseCount = 0;

            var delay = TimeSpan.FromSeconds(1.0);
            //set the cache to only hold one value, which forces an eviction of an inflight request from the inner cache
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x * 5).Delay(delay, sched), 1, 2, x=>releaseCount+=1, sched);


            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1000)));
            Assert.Equal(0,releaseCount);
            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1001)));
            Assert.Equal(1, releaseCount);
           

        }
Пример #47
0
        public void SequenceValueIs8After8SimulatedSeconds()
        {
            var scheduler = new TestScheduler();
            var seq = new MonotonicTick(scheduler);

            int value = 0;

            seq.Ticker.Subscribe(x => value = x);

            scheduler.AdvanceTo(8500 * TimeSpan.TicksPerMillisecond);

            Assert.Equal(8, value);
        }
        public void ObservePropertyFalse()
        {
            var testScheduler = new TestScheduler();
            var recorder = testScheduler.CreateObserver<string>();

            var m = new Model() { Name = "aaa" };
            m.ObserveProperty(x => x.Name, false).Subscribe(recorder);

            testScheduler.AdvanceTo(1000);
            m.Name = "bbb";

            recorder.Messages.Is(
                OnNext(1000, "bbb"));
        }
        public void CacheShouldQueueOnceWeHitOurConcurrentLimit()
        {
            var input = new[] { 1, 2, 3, 4, 1 };
            var sched = new TestScheduler();

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x => Observable.Return(x*5).Delay(delay, sched), 5, 2, null, sched);

            int result = 0;
            input.ToObservable(sched).SelectMany<int, int>(x => (IObservable<int>)fixture.AsyncGet(x)).Subscribe(x => result += x);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.Equal(0, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1500)));
            Assert.Equal(1*5 + 2*5 + 1*5, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(2500)));
            Assert.Equal(1*5 + 2*5 + 3*5 + 4*5 + 1*5, result);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(5000)));
            Assert.Equal(1*5 + 2*5 + 3*5 + 4*5 + 1*5, result);
        }
Пример #50
0
        public void When_Completed_Task_ToRex_Then_Projects_Results_Into_Rex()
        {
            // Arrange
            var scheduler = new TestScheduler();
            var observer = scheduler.CreateObserver<Rex<int>>();

            // Act
            scheduler.AdvanceTo(10);
            TaskEx.FromResult(10).ToRex().Subscribe(observer);
            scheduler.Start();

            // Assert
            observer.Messages.AssertEqual(
                OnNext(10, Rex.Result(10)),
                OnCompleted<Rex<int>>(10)
                );
        }
Пример #51
0
        public void AcceptAsync_Success()
        {
            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var scheduler = new TestScheduler();

            MAsyncSocketExtensions.AcceptAsObservableSocketEndPoint =
                (t1, t2) => scheduler.CreateHotObservable(OnNext(10, sock));

            var observer = scheduler.CreateObserver<Socket>();

            var client = new TcpRosListener(0);

            var result = client.AcceptAsync().Subscribe(observer);

            scheduler.AdvanceTo(10);

            observer.Messages.Is(OnNext(10, sock));
        }
        public void When_Subscribe_Via_Interface_To_Poco_Source_Then_OnNext_Initial_Value_Only()
        {
            // Arrange
            var obj = new TestPoco {Age = 3} as ITestObject;
            var scheduler = new TestScheduler();
            var observer = scheduler.CreateObserver<IPropertyValueChanged<int>>();
            var expected = new[]
            {
                OnNext(000, PropertyValueChanged.CreateWithValue(obj, "Age", 3)),
            };

            var sut = obj.When(x => x.Age);

            // Act
            sut.Subscribe(observer);
            scheduler.AdvanceTo(10);
            obj.Age = 5;

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
        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 ObservePropertyException()
        {
            var testScheduler = new TestScheduler();
            var recorder = testScheduler.CreateObserver<string>();
            var commonEx = new Exception();

            var m = new Model() { Name = "aaa" };
            m.ObserveProperty(x => x.Name)
                .Do(x => recorder.OnNext(x))
                .Do(_ => { throw commonEx; })
                .OnErrorRetry((Exception e) => recorder.OnError(e))
                .Subscribe();

            testScheduler.AdvanceTo(1000);
            m.Name = "bbb";

            recorder.Messages.Is(
                OnNext(0, "aaa"),
                OnError<string>(0, commonEx),
                OnNext(1000, "bbb"),
                OnError<string>(1000, commonEx));
        }
        public void CacheShouldEatExceptionsAndMarshalThemToObservable()
        {
            /* This is a bit tricky:
             *
             * 5,2 complete at t=1000 simultaneously
             * 10,0 get queued up, 0 fails immediately (delay() doesn't delay the OnError),
             *    so 10 completes at t=2000
             * The 7 completes at t=3000
             */
            var input = new[] { 5, 2, 10, 0/*boom!*/, 7 };
            var sched = new TestScheduler();

            Observable.Throw<int>(new Exception("Foo")).Subscribe(x => {
                Console.WriteLine(x);
            }, ex => {
                Console.WriteLine(ex);
            }, () => {
                Console.WriteLine("Completed");
            });

            var delay = TimeSpan.FromSeconds(1.0);
            var fixture = new ObservableAsyncMRUCache<int, int>(x =>
                (x == 0 ? Observable.Throw<int>(new Exception("Boom!")) : Observable.Return(10 * x)).Delay(delay, sched), 5, 2, null, sched);

            Exception exception = null;
            int completed = 0;
            input.ToObservable()
                .SelectMany(x => fixture.AsyncGet(x))
                .Subscribe(x => {
                    this.Log().InfoFormat("Result = {0}", x);
                    completed++;
                }, ex => exception = exception ?? ex);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(500)));
            Assert.Null(exception);
            Assert.Equal(0, completed);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(1500)));
            Assert.NotNull(exception);
            Assert.Equal(2, completed);

            sched.AdvanceTo(sched.FromTimeSpan(TimeSpan.FromMilliseconds(7500)));
            Assert.NotNull(exception);
            Assert.Equal(4, completed);
            this.Log().Info(exception);
        }
        public void When_Subscribe_Then_Returns_Default_Value_At_Time_Of_Subscribe_And_Subsequent_Values()
        {
            // Arrange
            var obj = new TestObservableObject() {Age = 2};
            var scheduler = new TestScheduler();
            var observer = scheduler.CreateObserver<IPropertyChanged<TestObservableObject>>();
            var expected = new[]
            {
                OnNext(00, PropertyChanged.Create(obj)),
                OnNext(20, PropertyChanged.Create(obj, "Age")),
                OnNext(30, PropertyChanged.Create(obj, "Age")),
                OnNext(40, PropertyChanged.Create(obj, "Name")),
            };

            var sut = new NotifyPropertyChangedObservable<TestObservableObject>(obj.ToPropertyValueChangedObservable());

            // Act
            sut.Subscribe(observer);
            scheduler.AdvanceTo(20);
            obj.Age = 3;
            scheduler.AdvanceTo(30);
            obj.Age = 7;
            scheduler.AdvanceTo(40);
            obj.Name = "Fi";

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
        public void When_Subscribe_Twice_Then_Correct_Notifications_For_Both_Observers()
        {
            // Arrange
            var obj = new TestObservableObject {Age = 3};
            var scheduler = new TestScheduler();
            var firstObserver = scheduler.CreateObserver<IPropertyChanged<TestObservableObject>>();
            var secondObserver = scheduler.CreateObserver<IPropertyChanged<TestObservableObject>>();
            var firstObservserExpected = new[]
            {
                OnNext(0, PropertyChanged.Create(obj)),
                OnNext(0, PropertyChanged.Create(obj, "Age")),
                OnNext(20, PropertyChanged.Create(obj, "Age")),
                OnNext(50, PropertyChanged.Create(obj, "Age")),
            };

            var secondObservserExpected = new[]
            {
                OnNext(50, PropertyChanged.Create(obj)),
                OnNext(50, PropertyChanged.Create(obj, "Age")),
            };

            var sut = new NotifyPropertyChangedObservable<TestObservableObject>(obj.ToPropertyValueChangedObservable());

            // Act
            sut.Subscribe(firstObserver);
            obj.Age = 5;
            scheduler.AdvanceTo(20);
            obj.Age = 6;
            scheduler.AdvanceTo(50);
            sut.Subscribe(secondObserver);
            obj.Age = 7;

            // Assert
            Assert.AreEqual(firstObservserExpected, firstObserver.Messages);
            Assert.AreEqual(secondObservserExpected, secondObserver.Messages);
        }
Пример #58
0
        public void SendNotification_4SuccessfulAnd1FailedForSameBuildEventSent_ExpectFailedNotificationSentWithCorrectMessage()
        {
            //Arrange
            var eventEmitter = new MvvmLightMessenger();

            var robot = Substitute.For<IRobot>();
            robot.EventEmitter.Returns(eventEmitter);

            var scheduler = new TestScheduler();
            var teamCityAggregator = new TeamCityAggregatorSut(robot, scheduler);

            var successfulTeamCityBuildModel = new TeamCityModel { build = new Build { buildNumber = "10", buildResult = "success" } };
            var failedTeamCityBuildModel = new TeamCityModel { build = new Build { buildNumber = "10", buildResult = "failed" } };

            //Act
            scheduler.Schedule(TimeSpan.FromMinutes(1), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(1), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(2), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(3), () => eventEmitter.Emit("TeamCityBuild", failedTeamCityBuildModel));
            scheduler.Schedule(TimeSpan.FromMinutes(4), () => eventEmitter.Emit("TeamCityBuild", successfulTeamCityBuildModel));

            scheduler.AdvanceTo(TimeSpan.FromMinutes(5).Ticks);

            //Assert
            robot.Received(1).SendNotification(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), true);
        }
Пример #59
0
		public void when_user_login_fails_too_fast_then_locks_account ()
		{
			var seconds = TimeSpan.FromSeconds(1).Ticks;
			var events = new EventStream();

			// Here we use the test scheduler to simulate time passing by
			// because we have a dependency on time because of the Buffer
			// method.
			var scheduler = new TestScheduler();
			var observable = scheduler.CreateColdObservable(
				// Two users attempt to log in, 4 times in a row
				new Recorded<Notification<LoginFailure>>(10 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })),
				new Recorded<Notification<LoginFailure>>(10 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })),
				new Recorded<Notification<LoginFailure>>(20 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })),
				new Recorded<Notification<LoginFailure>>(20 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })),
				new Recorded<Notification<LoginFailure>>(30 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })),
				new Recorded<Notification<LoginFailure>>(30 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })),
				new Recorded<Notification<LoginFailure>>(40 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })),
				new Recorded<Notification<LoginFailure>>(40 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })),

				// User 2 attempts one more time within the 1' window
				new Recorded<Notification<LoginFailure>>(45 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })),

				// User 1 pulls out the paper where he wrote his pwd ;), so he takes longer
				new Recorded<Notification<LoginFailure>>(75 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 }))
			);

			// This subscription bridges the scheduler-driven
			// observable with our event stream, causing us
			// to publish events as they are "raised" by the
			// test scheduler.
			observable.Subscribe (failure => events.Push (failure));

			var query = events.Of<LoginFailure>()
				// Sliding windows 1' long, every 10''
				.Buffer(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10), scheduler)
				// From all failure values
				.SelectMany(failures => failures
					// Group the failures by user
					.GroupBy(failure => failure.UserId)
					// Only grab those failures with more than 5 in the 1' window
					.Where(group => group.Count() >= 5)
					// Return the user id that failed to log in
					.Select(group => group.Key));

			var blocked = new List<int>();

			using (var subscription = query.Subscribe (userId => blocked.Add (userId))) {
				// Here we could advance the scheduler half way and test intermediate
				// state if needed. We go all the way past the end of our login failures.
				scheduler.AdvanceTo (100 * seconds);
			}

			// We should have only user # 2 in the list.
			Assert.False (blocked.Contains (1));
			Assert.True (blocked.Contains (2));
		}
        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));
        }