public void SameAsRetry_OnCompleted()
        {
            var scheduler = new TestScheduler();
            var source = scheduler.CreateHotObservable<int>(
                OnNext(0, 1),
                OnNext(0, 2),
                OnCompleted<int>(0),
                OnNext(0, 3));

            var called = 0;
            var retryRecorder = scheduler.CreateObserver<int>();
            source.Retry().Subscribe(retryRecorder);
            var onErrorRecorder = scheduler.CreateObserver<int>();
            source.OnErrorRetry((Exception e) => { ++called; }).Subscribe(onErrorRecorder);

            scheduler.Start();

            retryRecorder.Messages.Is(
                OnNext(1, 1),
                OnNext(1, 2),
                OnCompleted<int>(1));

            onErrorRecorder.Messages.Is(retryRecorder.Messages);
            called.Is(0);
        }
        public void AddRangeNotifiesAsResetInsteadOfIndividualItemsWhenItemCountAboveThresholdTest(int lowerLimit, int upperLimit)
        {
            // given
            var rangeToAdd = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).ToList();
            var testScheduler = new TestScheduler();
            var testObserverCollectionChanges = testScheduler.CreateObserver<IObservableCollectionChange<int>>();
            var testObserverResets = testScheduler.CreateObserver<Unit>();

            using (var observableList = new ObservableList<int>())
            {
                // when
                observableList.ThresholdAmountWhenChangesAreNotifiedAsReset = 0;

                observableList.CollectionChanges.Subscribe(testObserverCollectionChanges);
                observableList.Resets.Subscribe(testObserverResets);

                testScheduler.Schedule(TimeSpan.FromTicks(100), () => { observableList.AddRange(rangeToAdd); });
                testScheduler.Start();

                // then
                var shouldBeReset = rangeToAdd.Count >= observableList.ThresholdAmountWhenChangesAreNotifiedAsReset;
                testObserverCollectionChanges.Messages.Count.Should().Be(shouldBeReset ? 1 : rangeToAdd.Count);
                testObserverCollectionChanges.Messages.Should()
                    .Match(recordedMessages =>
                        recordedMessages.All(message => message.Value.Value.ChangeType == (shouldBeReset ? ObservableCollectionChangeType.Reset : ObservableCollectionChangeType.ItemAdded)));

                testObserverResets.Messages.Count.Should().Be(shouldBeReset ? 1 : 0);
            }
        }
        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 SameAsRetry_OnError()
        {
            var scheduler = new TestScheduler();
            var ex = new Exception();
            var source = scheduler.CreateColdObservable<int>(
                OnNext(0, 1),
                OnNext(0, 2),
                OnError<int>(0, ex));

            var called = 0;
            var retryRecorder = scheduler.CreateObserver<int>();
            source.Retry().Take(5).Subscribe(retryRecorder);
            var onErrorRecorder = scheduler.CreateObserver<int>();
            source.OnErrorRetry((Exception e) => { ++called; }).Take(5).Subscribe(onErrorRecorder);

            scheduler.Start();

            retryRecorder.Messages.Is(
                OnNext(1, 1),
                OnNext(1, 2),
                OnNext(2, 1),
                OnNext(2, 2),
                OnNext(3, 1),
                OnCompleted<int>(3));

            var retryResult = retryRecorder.Messages.ToArray();

            onErrorRecorder.Messages.Is(retryRecorder.Messages);
            called.Is(2);
        }
Exemplo n.º 5
0
        public void Infinite()
        {
            var scheduler = new TestScheduler();

            var xs = scheduler.CreateHotObservable(
                OnNext(70, 1),
                OnNext(110, 2),
                OnNext(220, 3),
                OnNext(270, 4),
                OnNext(340, 5),
                OnNext(410, 6),
                OnNext(520, 7),
                OnNext(630, 8),
                OnNext(710, 9),
                OnNext(870, 10),
                OnNext(940, 11),
                OnNext(1020, 12)
            );

            var subject = default(AsyncSubject<int>);
            var subscription = default(IDisposable);

            var results1 = scheduler.CreateObserver<int>();
            var subscription1 = default(IDisposable);

            var results2 = scheduler.CreateObserver<int>();
            var subscription2 = default(IDisposable);

            var results3 = scheduler.CreateObserver<int>();
            var subscription3 = default(IDisposable);

            scheduler.ScheduleAbsolute(100, () => subject = new AsyncSubject<int>());
            scheduler.ScheduleAbsolute(200, () => subscription = xs.Subscribe(subject));
            scheduler.ScheduleAbsolute(1000, () => subscription.Dispose());

            scheduler.ScheduleAbsolute(300, () => subscription1 = subject.Subscribe(results1));
            scheduler.ScheduleAbsolute(400, () => subscription2 = subject.Subscribe(results2));
            scheduler.ScheduleAbsolute(900, () => subscription3 = subject.Subscribe(results3));

            scheduler.ScheduleAbsolute(600, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(700, () => subscription2.Dispose());
            scheduler.ScheduleAbsolute(800, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(950, () => subscription3.Dispose());

            scheduler.Start();

            results1.Messages.AssertEqual(
            );

            results2.Messages.AssertEqual(
            );

            results3.Messages.AssertEqual(
            );
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        public void OneLineTest()
        {
            var scheduler = new TestScheduler();

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

            var sub = new OneLineCacheSubject<int>();

            sub.OnNext(1);

            var d1 = sub.Subscribe(observer);
            sub.OnNext(2);

            d1.Dispose();

            sub.OnNext(3);
            sub.OnNext(4);
            sub.OnNext(5);

            var d2 = sub.Subscribe(observer);

            d2.Dispose();

            var d3 = sub.Subscribe(observer);
            sub.OnNext(6);

            observer.Messages.Select(x => x.Value.Value).
                Is(new List<int>() {1, 2, 3, 4, 5, 6});
        }
        public void 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);
        }
Exemplo n.º 9
0
        public void CreatColdObservable_LongWay()
        {
            var testScheduler = new TestScheduler();

            ITestableObservable<int> coldObservable = testScheduler.CreateColdObservable<int>(
                // This is the long way to configure emissions. see below for a shorter one
                new Recorded<Notification<int>>(20, Notification.CreateOnNext<int>(1)),
                new Recorded<Notification<int>>(40, Notification.CreateOnNext<int>(2)),
                new Recorded<Notification<int>>(60, Notification.CreateOnCompleted<int>())
                );

            // Creating an observer that captures the emission it recieves
            var testableObserver = testScheduler.CreateObserver<int>();

            // Subscribing the observer, but until TestSchduler is started, emissions
            // are not be emitted
            coldObservable
                .Subscribe(testableObserver);

            // Starting the TestScheduler means that only now emissions that were configured
            // will be emitted
            testScheduler.Start();

            // Asserting that every emitted value was recieved by the observer at the
            // same time it was emitted
            coldObservable.Messages
                .AssertEqual(testableObserver.Messages);

            // Asserting that the observer was subscribed at Scheduler inital time
            coldObservable.Subscriptions.AssertEqual(
                Subscribe(0));
        }
Exemplo n.º 10
0
        public void CreatColdObservable_ShortWay()
        {
            var testScheduler = new TestScheduler();
            ITestableObservable<int> coldObservable =
                testScheduler.CreateColdObservable<int>(
                    // Inheritting your test class from ReactiveTest opens the following
                    // factory methods that make your code much more fluent
                    OnNext(20, 1),
                    OnNext(40, 2),
                    OnNext(60, 2),
                    OnCompleted<int>(900)
                    );

            // Creating an observer that captures the emission it recieves
            var testableObserver = testScheduler.CreateObserver<int>();

            // Subscribing the observer, but until TestSchduler is started, emissions
            // are not be emitted
            coldObservable
                .Subscribe(testableObserver);

            // Starting the TestScheduler means that only now emissions that were configured
            // will be emitted
            testScheduler.Start();

            // Asserting that every emitted value was recieved by the observer at the
            // same time it was emitted
            coldObservable.Messages
                .AssertEqual(testableObserver.Messages);

            // Asserting that the observer was subscribed at Scheduler inital time
            coldObservable.Subscriptions.AssertEqual(
                Subscribe(0));
        }
Exemplo n.º 11
0
        public void When_Subscribe_With_Two_Node_Path_To_Property_And_Modify_Node_One_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<IPropertyChanged<TestObservableObject>>();
            var expected = new[]
            {
                OnNext(000, PropertyChanged.Create(obj.ObservableChild)),
                OnNext(010, PropertyChanged.Create(replacementChild)),
                OnNext(010, PropertyChanged.Create(replacementChild, "Age")),
            };

            var sut = obj.WhenAny(x => x.ObservableChild);

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

            // Assert
            Assert.AreEqual(expected, observer.Messages);
        }
        public void TestOffset()
        {
            var testScheduler = new TestScheduler();
            var recorder = testScheduler.CreateObserver<int>();

            var notifier = new ScheduledNotifier<int>(testScheduler);
            notifier.Subscribe(recorder);

            var origin = new DateTimeOffset(1999, 1, 1, 1, 1, 1, TimeSpan.Zero);

            notifier.Report(1);
            notifier.Report(2);
            notifier.Report(3, origin);
            notifier.Report(4, origin.AddDays(10));
            notifier.Report(5, origin.AddYears(1));
            notifier.Report(6);

            testScheduler.Start();

            recorder.Messages.Is(
                OnNext(1, 1),
                OnNext(1, 2),
                OnNext(1, 6),
                OnNext(origin.Ticks, 3),
                OnNext(origin.AddDays(10).Ticks, 4),
                OnNext(origin.AddYears(1).Ticks, 5));
        }
Exemplo n.º 13
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);
        }
        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));
        }
Exemplo n.º 15
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);
        }
        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);
        }
        public async Task should_be_able_do_necessary_update_while_do_on_error_async()
        {
            var scheduler = new TestScheduler();

            var count = 0;
            var raw = Observable.Defer(() =>
            {
                count++;
                if (count == 4)
                {
                    return Observable.Throw<int>(new Exception("Count=4"));
                }

                return Observable.Return(count);
            }).Repeat();

            var observer = scheduler.CreateObserver<int>();
            using (raw.DoOnErrorAsync(async ex =>
            {
                await TestTask(ex);
            }).Subscribe(observer))
            {
                await Task.Delay(5000);
                Assert.AreEqual(4, observer.Messages.Count);
                Assert.AreEqual(3, observer.Messages.Where(m => m.Value.Kind == System.Reactive.NotificationKind.OnNext).Count());
                Assert.AreEqual(1, observer.Messages.Where(m => m.Value.Kind == System.Reactive.NotificationKind.OnError).Count());
            }
        }
        public void Test()
        {
            var testScheduler = new TestScheduler();
            var recorder = testScheduler.CreateObserver<int>();

            var notifier = new ScheduledNotifier<int>(testScheduler);
            notifier.Subscribe(recorder);

            notifier.Report(1);
            notifier.Report(2);
            notifier.Report(3, TimeSpan.FromMinutes(10));
            notifier.Report(4, TimeSpan.FromMinutes(1));
            notifier.Report(5, TimeSpan.FromMinutes(5));
            notifier.Report(6);

            testScheduler.Start();

            recorder.Messages.Is(
                OnNext(1, 1),
                OnNext(1, 2),
                OnNext(1, 6),
                OnNext(TimeSpan.FromMinutes(1).Ticks, 4),
                OnNext(TimeSpan.FromMinutes(5).Ticks, 5),
                OnNext(TimeSpan.FromMinutes(10).Ticks, 3));
        }
Exemplo n.º 19
0
        public void ReadsSegmentsCorrectly()
        {
            var bytes = Encoding.UTF8.GetBytes(
                "<log4j:event logger=\"ConsoleApplication1.Program\" level=\"INFO\" timestamp=\"1361281966733\" thread=\"1\">" +
                "  <log4j:message>Istcua orojurf bysgurnl t.</log4j:message>" +
                "  <log4j:properties>" +
                "    <log4j:data name=\"log4japp\" value=\"ConsoleApplication1.exe(6512)\" />" +
                "    <log4j:data name=\"log4jmachinename\" value=\"user1\" />" +
                "  </log4j:properties>" +
                "</log4j:event>" +
                "<log4j:event logger=\"ConsoleApplication1.Program\" level=\"WARN\" timestamp=\"1361281966808\" thread=\"1\">" +
                "  <log4j:message>Ebo ohow aco inldrfb pameenegy.</log4j:message>" +
                "  <log4j:properties>" +
                "    <log4j:data name=\"log4japp\" value=\"ConsoleApplication1.exe(6512)\" />" +
                "    <log4j:data name=\"log4jmachinename\" value=\"user2\" />" +
                "  </log4j:properties>" +
                "</log4j:event>");

            var stream = new MemoryStream(bytes);
            var format = new Log4JXmlLogFormat();
            var testScheduler = new TestScheduler();
            var observer = testScheduler.CreateObserver<RecordSegment>();

            var offset = format.ReadSegments(observer, stream, CancellationToken.None).Result;

            Assert.Equal(2, observer.Messages.Count);

            var segments = observer.Messages.Select(x => x.Value.Value).ToArray();

            Assert.True(segments.Any(x => x.Offset == 0 && x.Length == 342));
            Assert.True(segments.Any(x => x.Offset == 342 && x.Length == 347));
            Assert.Equal(stream.Length, offset);
        }
Exemplo n.º 20
0
        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}
                });
        }
Exemplo n.º 21
0
 public ReactiveSpecs()
 {
     scheduler = new TestScheduler();
     observer = scheduler.CreateObserver<int>();
     source = new Subject<int>();
     observedValues = observer.Messages
         .Where(x => x.Value.HasValue)
         .Select(x => x.Value.Value);
     observedErrors = observer.Messages
         .Where(x => x.Value.Kind == NotificationKind.OnError)
         .Select(x => x.Value.Exception);
 }
Exemplo n.º 22
0
        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 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 Should_return_all_bytes_in_same_order([Range(1,20)]int bufferSize)
            {
                var scheduler = new TestScheduler();
                var observer = scheduler.CreateObserver<byte>();
                using (_stream.ToObservable(bufferSize, scheduler).Subscribe(observer))
                {
                    scheduler.Start();

                    var actual = observer.Messages.Select(rn => rn.Value)
                        .Where(n => n.Kind == NotificationKind.OnNext)
                        .Select(n => n.Value)
                        .ToList();
                    CollectionAssert.AreEquivalent(_expected, actual);
                }
            }
Exemplo n.º 25
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)
                );
        }
Exemplo n.º 26
0
        public void Bla()
        {
            var stockTicks = new[]
            {
                new StockTick() {QuoteSymbol = "MSFT", Price = 53.49M},
                new StockTick() {QuoteSymbol = "INTC", Price = 32.68M},
                new StockTick() {QuoteSymbol = "ORCL", Price = 41.48M},
                new StockTick() {QuoteSymbol = "CSCO", Price = 28.33M},
            }.ToObservable().ToEvent();
            var testScheduler = new TestScheduler();
            var testableObserver = testScheduler.CreateObserver<DrasticChange>();
            var stockTicker = A.Fake<IStockTicker>();
            A.CallTo(()=>stockTicker.StockTick).
            var rxStockMonitor = new RxStockMonitor(stockTicker);

            rxStockMonitor.DrasticChanges.Subscribe(testableObserver);
        }
Exemplo n.º 27
0
        public void When_Subscribed_To_Then_Returns_Value_And_Does_Not_Complete()
        {
            // Arrange
            var scheduler = new TestScheduler();
            var sut = new Forever<int>(100);
            var observer = scheduler.CreateObserver<int>();
            var expected = new[]
            {
                OnNext(0, 100),
            };
            sut.Subscribe(observer);

            // Act
            scheduler.Start();

            // Assert
            KKAssert.AreEqualByValue(expected, observer.Messages);
        }
Exemplo n.º 28
0
        public void BufferWhileShouldReleaseBufferOnCompleted(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 producer ran to completion
            testScheduler.AdvanceBy(count + 1);
            
            // then
            observer.Messages.Count.Should().Be(2);
            observer.Messages[0].Value.Kind.Should().Be(NotificationKind.OnNext);
            observer.Messages[0].Value.Value.Count.Should().Be(count);

            observer.Messages[1].Value.Kind.Should().Be(NotificationKind.OnCompleted);
        }
Exemplo n.º 29
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));
        }
Exemplo n.º 30
0
        public void TwoStockTicksWithSmallChangeAndOneWithDrasticChange_OnlyOneDrasticChangeEmitted()
        {
            var testScheduler = new TestScheduler();
            var testableObserver = testScheduler.CreateObserver<DrasticChange>();
            var stockTicker = Substitute.For<IStockTicker>();
            var rxStockMonitor = new StockMonitor(stockTicker);

            testScheduler.Schedule(TimeSpan.FromTicks(1), () => { stockTicker.StockTick += Raise.Event<EventHandler<StockTick>>(stockTicker,new StockTick{Price=100,QuoteSymbol="MSFT"}); });
            testScheduler.Schedule(TimeSpan.FromTicks(2), () => { stockTicker.StockTick += Raise.Event<EventHandler<StockTick>>(stockTicker, new StockTick{Price=101,QuoteSymbol="MSFT"}); });
            testScheduler.Schedule(TimeSpan.FromTicks(3), () => { stockTicker.StockTick += Raise.Event<EventHandler<StockTick>>(stockTicker, new StockTick{Price=200,QuoteSymbol="MSFT"}); });

            rxStockMonitor.DrasticChanges.Subscribe(testableObserver);

            testScheduler.Start();

            testableObserver.Messages.AssertEqual(
                OnNext(3,(DrasticChange drasticChange)=>drasticChange.Symbol=="MSFT")
                );
        }
        public void ShouldScheduleWithConcurrency_WithContentModified()
        {
            var testScheduler  = new TestScheduler();
            var testObservable = testScheduler.CreateColdObservable(
                OnNext(Subscribed, Unit.Default),
                OnCompleted(Subscribed, Unit.Default)
                );
            var testObserver = testScheduler.CreateObserver <Unit>();

            using var s = new ProcessScheduler(new TestLoggerFactory(_testOutputHelper), true, 3, TimeSpan.FromSeconds(30), testScheduler);

            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Serial, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Serial, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));
            s.Add(RequestProcessType.Parallel, "bogus", DoStuff(testObservable, testObserver));

            testScheduler.Start();

            testObservable.Subscriptions.Count.Should().Be(11);
            testObserver.Messages
            .Where(z => z.Value.Kind != NotificationKind.OnCompleted).Should()
            .ContainInOrder(
                OnNext(Subscribed, Unit.Default),
                OnNext(Subscribed * 2, Unit.Default),
                OnNext(Subscribed * 3, Unit.Default),
                OnNext(Subscribed * 3, Unit.Default),
                OnNext(Subscribed * 3, Unit.Default)
                );
        }
Exemplo n.º 32
0
            public async Task DoesNotGroupProjectSegmentsWithPercentageGreaterThanOrEqualFivePercent()
            {
                ChartSegment[] segments =
                {
                    new ChartSegment("Project 1", "Client 1",  2,  2, 0, "#ffffff"),
                    new ChartSegment("Project 2", "Client 2",  2,  2, 0, "#ffffff"),
                    new ChartSegment("Project 3", "Client 3", 17, 17, 0, "#ffffff"),
                    new ChartSegment("Project 4", "Client 4", 23, 23, 0, "#ffffff"),
                    new ChartSegment("Project 5", "Client 5", 56, 56, 0, "#ffffff")
                };

                TimeService.CurrentDateTime.Returns(new DateTimeOffset(2018, 05, 15, 12, 00, 00, TimeSpan.Zero));
                Interactor.Execute().Returns(Observable.Return(new ProjectSummaryReport(segments, projectsNotSyncedCount)));
                var segmentsObservable        = TestScheduler.CreateObserver <IReadOnlyList <ChartSegment> >();
                var groupedSegmentsObservable = TestScheduler.CreateObserver <IReadOnlyList <ChartSegment> >();

                ViewModel.SegmentsObservable.Subscribe(segmentsObservable);
                ViewModel.GroupedSegmentsObservable.Subscribe(groupedSegmentsObservable);

                await Initialize();

                TestScheduler.Start();

                var actualSegments        = segmentsObservable.Values().Last();
                var actualGroupedSegments = groupedSegmentsObservable.Values().Last();

                actualSegments.Should().HaveCount(5);
                actualGroupedSegments.Should().HaveCount(4);
                actualGroupedSegments.Should().Contain(segment =>
                                                       segment.ProjectName == Resources.Other &&
                                                       segment.Percentage == segments[0].Percentage + segments[1].Percentage);
                actualGroupedSegments
                .Where(project => project.ProjectName != Resources.Other)
                .Select(segment => segment.Percentage)
                .ForEach(percentage => percentage.Should().BeGreaterOrEqualTo(5));
            }
Exemplo n.º 33
0
                public void EmitsFalseAfterAllTheCalendarsHaveBeenDeselected()
                {
                    var observer = Substitute.For <IObserver <bool> >();

                    ViewModel.Done.Enabled.Subscribe(observer);
                    var selectedableUserCalendars = Enumerable
                                                    .Range(0, 10)
                                                    .Select(id =>
                    {
                        var userCalendar = new UserCalendar(id.ToString(), id.ToString(), "Doenst matter");
                        return(new SelectableUserCalendarViewModel(userCalendar, false));
                    });

                    var selectAll = Observable
                                    .Concat(
                        selectedableUserCalendars
                        .Select(calendar => Observable.Defer(() => ViewModel.SelectCalendar.Execute(calendar)))
                        );

                    var auxObserver = TestScheduler.CreateObserver <Unit>();

                    Observable
                    .Concat(
                        selectAll,
                        selectAll
                        )
                    .Subscribe(auxObserver);
                    TestScheduler.Start();

                    Received.InOrder(() =>
                    {
                        observer.OnNext(false);
                        observer.OnNext(true);
                        observer.OnNext(false);
                    });
                }
Exemplo n.º 34
0
                public async void DoesNotShowTheRatingViewIfThereWasAnInteraction()
                {
                    var defaultRemoteConfiguration = new RatingViewConfiguration(5, RatingViewCriterion.Start);

                    RemoteConfigService
                    .GetRatingViewConfiguration()
                    .Returns(defaultRemoteConfiguration);

                    var now         = DateTimeOffset.Now;
                    var firstOpened = now - TimeSpan.FromDays(6);

                    TimeService.CurrentDateTime.Returns(now);
                    OnboardingStorage.GetFirstOpened().Returns(firstOpened);
                    OnboardingStorage.RatingViewOutcome().Returns(RatingViewOutcome.AppWasNotRated);

                    await ViewModel.Initialize();

                    var observer = TestScheduler.CreateObserver <bool>();

                    ViewModel.ShouldShowRatingView.Subscribe(observer);

                    TestScheduler.Start();
                    observer.LastEmittedValue().Should().BeFalse();
                }
Exemplo n.º 35
0
            public async Task ClosesTheViewModelAndReturnsSelectedCalendarIds()
            {
                var userCalendars = Enumerable
                                    .Range(0, 9)
                                    .Select(id => new UserCalendar(
                                                id.ToString(),
                                                $"Calendar #{id}",
                                                $"Source #{id % 3}",
                                                false));

                InteractorFactory
                .GetUserCalendars()
                .Execute()
                .Returns(Observable.Return(userCalendars));
                await ViewModel.Initialize();

                var selectedIds = new[] { "0", "2", "4", "7" };

                var selectCalendars = Observable.Concat(
                    userCalendars
                    .Where(calendar => selectedIds.Contains(calendar.Id))
                    .Select(calendar => new SelectableUserCalendarViewModel(calendar, false))
                    .Select(calendar => Observable.Defer(() => ViewModel.SelectCalendar.Execute(calendar)))
                    );

                var auxObserver = TestScheduler.CreateObserver <Unit>();

                Observable.Concat(
                    selectCalendars,
                    Observable.Defer(() => ViewModel.Done.Execute())
                    )
                .Subscribe(auxObserver);
                TestScheduler.Start();

                await NavigationService.Received().Close(ViewModel, Arg.Is <string[]>(ids => ids.SequenceEqual(selectedIds)));
            }
Exemplo n.º 36
0
            public void ThrowsIfThereAreNoRunningTimeEntries()
            {
                long duration    = (long)(Now - TimeEntry.Start).TotalSeconds;
                var  timeEntries = new List <IDatabaseTimeEntry>
                {
                    TimeEntry.With(duration),
                    TimeEntry.With(duration),
                    TimeEntry.With(duration)
                };

                Repository
                .GetAll(Arg.Any <Func <IDatabaseTimeEntry, bool> >())
                .Returns(callInfo =>
                         Observable
                         .Return(timeEntries)
                         .Select(x => x.Where(callInfo.Arg <Func <IDatabaseTimeEntry, bool> >())));

                var observer   = TestScheduler.CreateObserver <ITimeEntry>();
                var observable = TimeEntriesSource.Stop(Now);

                observable.Subscribe(observer);

                observer.Messages.Single().Value.Exception.Should().BeOfType <NoRunningTimeEntryException>();
            }
Exemplo n.º 37
0
                    public void SetsEmailAlreadyUsedErrorIfReceivedEmailIsAlreadyusedException()
                    {
                        var observer = TestScheduler.CreateObserver <string>();

                        ViewModel.ErrorMessage.Subscribe(observer);

                        var request = Substitute.For <IRequest>();

                        request.Endpoint.Returns(new Uri("https://any.url.com"));
                        prepareException(new EmailIsAlreadyUsedException(
                                             new BadRequestException(
                                                 request,
                                                 Substitute.For <IResponse>()
                                                 )
                                             ));

                        ViewModel.Signup.Execute();

                        TestScheduler.Start();
                        observer.Messages.AssertEqual(
                            ReactiveTest.OnNext(1, ""),
                            ReactiveTest.OnNext(2, Resources.EmailIsAlreadyUsedError)
                            );
                    }
Exemplo n.º 38
0
            public void DoesNotDisplayAnErrormessageWhenTheUserCancelsTheRequestOnTheGoogleService()
            {
                var hasErrorObserver = TestScheduler.CreateObserver <bool>();

                ViewModel.HasError.Subscribe(hasErrorObserver);
                var errorTextObserver = TestScheduler.CreateObserver <string>();

                ViewModel.ErrorMessage.Subscribe(errorTextObserver);

                LoginManager.SignUpWithGoogle().Returns(
                    Observable.Throw <ITogglDataSource>(new GoogleLoginException(true)));

                ViewModel.GoogleSignup();

                TestScheduler.Start();

                errorTextObserver.Messages.AssertEqual(
                    ReactiveTest.OnNext(1, "")
                    );

                hasErrorObserver.Messages.AssertEqual(
                    ReactiveTest.OnNext(2, false)
                    );
            }
Exemplo n.º 39
0
        public void Subscribe_StartsImmediately()
        {
            long expectedTicks       = 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, TimeSpan.FromHours(1), scheduler))
                using (sut.Subscribe(observer))
                {
                    scheduler.AdvanceTo(expectedTicks);
                }

            observer.Messages.AssertEqual(
                OnNext <int>(expectedTicks, x => x == 1),
                OnCompleted <int>(expectedTicks));
        }
            public async Task DoesNotIncludeProjectCreationRowWhenTheTextIsEmpty()
            {
                var workspaceId = 0;

                setupWorkspace(workspaceId, isEligibleForProjectCreation: true);
                var projectSuggestions    = getProjectSuggestions(10, workspaceId: workspaceId);
                var suggestionsObservable = Observable.Return(projectSuggestions);

                InteractorFactory
                .GetProjectsAutocompleteSuggestions(Arg.Any <IList <string> >())
                .Execute()
                .Returns(suggestionsObservable);
                var observer = TestScheduler.CreateObserver <IEnumerable <SectionModel <string, AutocompleteSuggestion> > >();

                ViewModel.Suggestions.Subscribe(observer);

                await ViewModel.Initialize();

                TestScheduler.Start();

                var latestSuggestions = observer.Messages.Last().Value.Value;

                latestSuggestions.Should().HaveCount(1);
            }
            public async Task GroupsProjectsByWorkspace()
            {
                var suggestions  = new List <ProjectSuggestion>();
                var workspaceIds = new[] { 0, 1, 10, 54 };

                suggestions.AddRange(getProjectSuggestions(3, workspaceId: workspaceIds[0]));
                suggestions.AddRange(getProjectSuggestions(4, workspaceId: workspaceIds[1]));
                suggestions.AddRange(getProjectSuggestions(1, workspaceId: workspaceIds[2]));
                suggestions.AddRange(getProjectSuggestions(10, workspaceId: workspaceIds[3]));
                var suggestionsObservable = Observable.Return(suggestions);

                InteractorFactory
                .GetProjectsAutocompleteSuggestions(Arg.Any <IList <string> >())
                .Execute()
                .Returns(suggestionsObservable);
                var observer = TestScheduler.CreateObserver <IEnumerable <SectionModel <string, AutocompleteSuggestion> > >();

                ViewModel.Suggestions.Subscribe(observer);

                await ViewModel.Initialize();

                TestScheduler.Start();

                var latestSuggestions = observer.Messages.Last().Value.Value.ToArray();

                latestSuggestions.Should().HaveCount(4);

                for (int i = 0; i < latestSuggestions.Length; i++)
                {
                    foreach (var suggestion in latestSuggestions[i].Items)
                    {
                        suggestion.WorkspaceName.Should().Be(latestSuggestions[i].Header);
                        suggestion.WorkspaceId.Should().Be(workspaceIds[i]);
                    }
                }
            }
        public async Task GetsAnEventWhenAChangeToTimeEntriesHappens()
        {
            var createSubject = new Subject <IThreadSafeTimeEntry>();
            var deleteSubject = new Subject <long>();

            DataSource.TimeEntries.Created.Returns(createSubject.AsObservable());
            DataSource.TimeEntries.Updated.Returns(Observable.Never <EntityUpdate <IThreadSafeTimeEntry> >());
            DataSource.TimeEntries.Deleted.Returns(deleteSubject.AsObservable());

            var testScheduler = new TestScheduler();
            var observer      = testScheduler.CreateObserver <Unit>();

            InteractorFactory.ObserveTimeEntriesChanges().Execute()
            .Subscribe(observer);

            var mockTimeEntry = new MockTimeEntry {
                Id = 42
            };

            createSubject.OnNext(mockTimeEntry);
            deleteSubject.OnNext(3);

            observer.Messages.Should().HaveCount(2);
        }
                public void EmitsFalseAfterAllTheCalendarsHaveBeenDeselected()
                {
                    var observer = Substitute.For <IObserver <bool> >();

                    ViewModel.Save.Enabled.Subscribe(observer);

                    var userCalendars = Enumerable
                                        .Range(0, 3)
                                        .Select(id => new UserCalendar(id.ToString(), id.ToString(), "Doesn't matter"));

                    var selectedableUserCalendars = userCalendars
                                                    .Select(userCalendar => new SelectableUserCalendarViewModel(userCalendar, false));

                    InteractorFactory
                    .GetUserCalendars()
                    .Execute()
                    .Returns(Observable.Return(userCalendars));


                    var auxObserver = TestScheduler.CreateObserver <Unit>();

                    ViewModel.SelectCalendar.ExecuteSequentally(
                        selectedableUserCalendars
                        .Concat(selectedableUserCalendars)
                        )
                    .Subscribe(auxObserver);

                    TestScheduler.Start();

                    Received.InOrder(() =>
                    {
                        observer.OnNext(false);
                        observer.OnNext(true);
                        observer.OnNext(false);
                    });
                }
Exemplo n.º 44
0
        public async Task ProcessCommand_ShouldNotifyCommandError(
            [Frozen] Mock <IAsyncCommandBus> innerCommandBus,
            NotifyCommandStateBus sut,
            IAsyncCommand command,
            [Frozen] TestScheduler scheduler,
            Exception exception)
        {
            //arrange
            var observer = scheduler.CreateObserver <Tuple <IAsyncCommand, Exception> >();

            innerCommandBus.Setup(bus => bus.ProcessCommand(It.IsAny <IAsyncCommand>()))
            .Returns(() =>
            {
                scheduler.AdvanceTo(300);
                throw exception;
            });
            sut.ObserveCommandError().Subscribe(observer);

            //act
            try
            {
                await sut.ProcessCommand(command);
            }
            catch (Exception ex)
            {
                if (ex != exception)
                {
                    throw;
                }
            }

            //assert
            var expected = OnNext(300, new Tuple <IAsyncCommand, Exception>(command, exception));

            observer.Messages.First().ShouldBeEquivalentTo(expected);
        }
Exemplo n.º 45
0
            public async Task UpdatesTheCountryButtonTitle()
            {
                var observer = TestScheduler.CreateObserver <string>();

                ViewModel.CountryButtonTitle.Subscribe(observer);

                var selectedCountry = await new GetAllCountriesInteractor()
                                      .Execute()
                                      .Select(countries => countries.Single(country => country.Id == 1));

                NavigationService
                .Navigate <SelectCountryViewModel, long?, long?>(Arg.Any <long?>())
                .Returns(selectedCountry.Id);
                await ViewModel.Initialize();

                ViewModel.PickCountry.Execute();

                TestScheduler.Start();
                observer.Messages.AssertEqual(
                    ReactiveTest.OnNext(1, Resources.SelectCountry),
                    ReactiveTest.OnNext(2, Location.CountryName),
                    ReactiveTest.OnNext(3, selectedCountry.Name)
                    );
            }
Exemplo n.º 46
0
            public void ReturnsAValueThatReflectsTheChangesToDurationForRunningTimeEntries(DateTimeOffset start, DateTimeOffset now)
            {
                if (start > now)
                {
                    return;
                }
                TimeService.CurrentDateTime.Returns(now);
                var startObserver = TestScheduler.CreateObserver <DateTimeOffset>();
                var viewModel     = CreateViewModel();

                viewModel.AttachView(View);
                viewModel.StartTime.Subscribe(startObserver);

                viewModel.Initialize(new EditDurationParameters(DurationParameter.WithStartAndDuration(start, null)));
                viewModel.ChangeDuration.Execute(TimeSpan.FromMinutes(10));

                viewModel.Save.Execute();

                TestScheduler.Start();
                var result = viewModel.Result.GetAwaiter().GetResult();

                result.Start.Should().Be(startObserver.LastEmittedValue());
                result.Duration.Should().BeNull();
            }
Exemplo n.º 47
0
            public async ThreadingTask EmitsObservableEventsForTheNewlyCreatedRunningTimeEntry()
            {
                var createdObserver = TestScheduler.CreateObserver <IThreadSafeTimeEntry>();
                var newTimeEntry    = new MockTimeEntry {
                    Id = -1, Duration = null
                };

                Repository.BatchUpdate(
                    Arg.Any <IEnumerable <(long, IDatabaseTimeEntry)> >(),
                    Arg.Any <Func <IDatabaseTimeEntry, IDatabaseTimeEntry, ConflictResolutionMode> >(),
                    Arg.Any <IRivalsResolver <IDatabaseTimeEntry> >())
                .Returns(Observable.Return(new IConflictResolutionResult <IDatabaseTimeEntry>[]
                {
                    new CreateResult <IDatabaseTimeEntry>(newTimeEntry)
                }));

                var timeEntriesSource = new TimeEntriesDataSource(Repository, TimeService, AnalyticsService);

                timeEntriesSource.Created.Subscribe(createdObserver);
                await timeEntriesSource.Create(newTimeEntry);

                createdObserver.Messages.Single().Value.Value.Id.Should().Be(newTimeEntry.Id);
                createdObserver.Messages.Single().Value.Value.Duration.Should().BeNull();
            }
Exemplo n.º 48
0
        public void DoesNotEmitNewValuesForMoreThanSevenDays(PositiveInt days)
        {
            if (days.Get <= 7)
            {
                return;
            }

            var legendObserver = TestScheduler.CreateObserver <DateTimeOffset[]>();
            var viewModel      = CreateViewModel();

            viewModel.HorizontalLegend.Subscribe(legendObserver);
            var groups = Enumerable.Range(0, days.Get)
                         .Select(_ => new TimeEntriesTotalsGroup {
                Billable = TimeSpan.Zero, Total = TimeSpan.Zero
            })
                         .ToArray <ITimeEntriesTotalsGroup>();

            Report.Groups.Returns(groups);

            ReportsSubject.OnNext(Report);

            TestScheduler.Start();
            legendObserver.SingleEmittedValue().Should().BeNull();
        }
    public void Trigger_100Percent_after_1000ms_of_mouse_position_within_fence()
    {
        //Assuming the fence is fixed from the first position, and isn't constantly reevaluated for each new position
        var testScheduler = new TestScheduler();
        var observer      = testScheduler.CreateObserver <double>();
        var coords        = testScheduler.CreateColdObservable(
            OnNext(020.Milliseconds(), new Point {
            X = 100, Y = 100
        }),
            OnNext(220.Milliseconds(), new Point {
            X = 100, Y = 100
        }),
            OnNext(420.Milliseconds(), new Point {
            X = 100, Y = 100
        }),
            OnNext(620.Milliseconds(), new Point {
            X = 100, Y = 100
        }),
            OnNext(820.Milliseconds(), new Point {
            X = 100, Y = 100
        }),
            OnNext(1020.Milliseconds(), new Point {
            X = 100, Y = 100
        })
            );

        Query(coords, testScheduler).Subscribe(observer);
        testScheduler.Start();
        observer.Messages.AssertEqual(
            OnNext(220.Milliseconds(), 0.2),
            OnNext(420.Milliseconds(), 0.4),
            OnNext(620.Milliseconds(), 0.6),
            OnNext(820.Milliseconds(), 0.8),
            OnNext(1020.Milliseconds(), 1.0)
            );
    }
Exemplo n.º 50
0
            public async Task EmitsAgainWhenCalendarPermissionsChangeAfterViewAppears()
            {
                PermissionsService.CalendarPermissionGranted.Returns(Observable.Return(false), Observable.Return(true));
                UserPreferences.EnabledCalendars.Returns(Observable.Return(new List <string>()
                {
                    "1"
                }));

                var observer  = TestScheduler.CreateObserver <bool>();
                var viewModel = CreateViewModel();

                await viewModel.Initialize();

                TestScheduler.Start();

                viewModel.IsCalendarSmartRemindersVisible.Subscribe(observer);

                viewModel.ViewAppeared();

                var messages = observer.Messages.Select(msg => msg.Value.Value);

                messages.First().Should().BeFalse();
                messages.Last().Should().BeTrue();
            }
Exemplo n.º 51
0
            public void IsSetToTheFirstEligibleForProjectCreationIfDefaultIsNotEligible()
            {
                var observer         = TestScheduler.CreateObserver <string>();
                var defaultWorkspace = Substitute.For <IThreadSafeWorkspace>();

                defaultWorkspace.Name.Returns(DefaultWorkspaceName);
                defaultWorkspace.Admin.Returns(false);
                defaultWorkspace.OnlyAdminsMayCreateProjects.Returns(true);
                var eligibleWorkspace = Substitute.For <IThreadSafeWorkspace>();

                eligibleWorkspace.Name.Returns("Eligible workspace for project creation");
                eligibleWorkspace.Admin.Returns(true);
                InteractorFactory.GetDefaultWorkspace().Execute()
                .Returns(Observable.Return(defaultWorkspace));
                InteractorFactory.GetAllWorkspaces().Execute()
                .Returns(Observable.Return(new[] { defaultWorkspace, eligibleWorkspace }));

                var viewModel = CreateViewModel();

                viewModel.WorkspaceName.Subscribe(observer);
                TestScheduler.Start();

                observer.LastEmittedValue().Should().Be(eligibleWorkspace.Name);
            }
        public void ShouldScheduleCompletedTask(RequestProcessType type)
        {
            var testScheduler  = new TestScheduler();
            var testObservable = testScheduler.CreateColdObservable(
                OnNext(Subscribed, Unit.Default),
                OnCompleted(Subscribed, Unit.Default)
                );
            var testObserver = testScheduler.CreateObserver <Unit>();

            using var s = new ProcessScheduler(new TestLoggerFactory(_testOutputHelper), false, null, TimeSpan.FromSeconds(30), testScheduler);


            s.Add(type, "bogus", DoStuff(testObservable, testObserver));

            testScheduler.AdvanceTo(Subscribed / 2);

            testObservable.Subscriptions.Count.Should().Be(1);

            testScheduler.AdvanceTo(Subscribed + 1);

            testObservable.Subscriptions.Count.Should().Be(1);
            testObserver.Messages.Should().Contain(z => z.Value.Kind == NotificationKind.OnNext);
            testObserver.Messages.Should().Contain(z => z.Value.Kind == NotificationKind.OnCompleted);
        }
Exemplo n.º 53
0
            public void EmitTheAppropriateIsSyncedValues(NonEmptyArray <SyncProgress> statuses)
            {
                var observer  = TestScheduler.CreateObserver <bool>();
                var viewModel = CreateViewModel();

                viewModel.IsSynced.Subscribe(observer);

                foreach (var state in statuses.Get)
                {
                    if (state == SyncProgress.Unknown)
                    {
                        continue;
                    }

                    observer.Messages.Clear();

                    ProgressSubject.OnNext(state);
                    TestScheduler.Start();
                    TestScheduler.Stop();

                    var isSynced = observer.SingleEmittedValue();
                    isSynced.Should().Be(state == SyncProgress.Synced);
                }
            }
    public async Task CachingTest()
    {
        var testScheduler = new TestScheduler();
        var cache         = new InMemoryBlobCache(testScheduler);
        var cacheTimeout  = TimeSpan.FromSeconds(10);
        var someApi       = new Mock <ISomeApi>();

        someApi.Setup(s => s.GetSomeStrings())
        .Returns(Task.FromResult("helloworld")).Verifiable();

        var apiWrapper = new SomeApiWrapper(someApi.Object, cache, cacheTimeout);
        var string1    = await apiWrapper.GetSomeStrings();

        someApi.Verify(s => s.GetSomeStrings(), Times.Once());
        StringAssert.AreEqualIgnoringCase("helloworld", string1);
        testScheduler.AdvanceToMs(5000);

        var observer = testScheduler.CreateObserver <string>();

        apiWrapper.GetSomeStrings().Subscribe(observer);
        testScheduler.AdvanceByMs(cacheTimeout.TotalMilliseconds);
        someApi.Verify(s => s.GetSomeStrings(), Times.Once());
        StringAssert.AreEqualIgnoringCase("helloworld", observer.Messages[0].Value.Value);
    }
            public async Task ReloadsSuggestionsWhenTimeEntriesUpdate()
            {
                var changesSubject = new Subject <Unit>();

                InteractorFactory.ObserveWorkspaceOrTimeEntriesChanges().Execute().Returns(changesSubject);

                var provider = suggestionProvider();

                SetProviders(SuggestionProviderContainer, provider);
                var observer = TestScheduler.CreateObserver <Suggestion[]>();

                await ViewModel.Initialize();

                ViewModel.Suggestions.Subscribe(observer);

                changesSubject.OnNext(Unit.Default);

                TestScheduler.Start();

                observer.Messages.Should().HaveCount(2);
                observer.Messages.First().Value.Value.Should().HaveCount(0);
                observer.LastEmittedValue().Should().HaveCount(0);
                await provider.Received(2).GetSuggestions();
            }
Exemplo n.º 56
0
            public void UsingAnyOfTheShortcutsDoesNotThrowAnyTimeOfTheYear(DateTimeOffset now)
            {
                var shortcutsObserver = TestScheduler.CreateObserver <List <ReportsCalendarBaseQuickSelectShortcut> >();

                TimeService.CurrentDateTime.Returns(now);
                // in this property test it is not possible to use the default ViewModel,
                // because we have to reset it in each iteration of the test
                var viewModel = CreateViewModel();

                viewModel.Prepare();
                viewModel.Initialize().Wait();
                viewModel.QuickSelectShortcutsObservable.Subscribe(shortcutsObserver);
                TestScheduler.Start();
                var shortcuts      = shortcutsObserver.Values().Last();
                var errorsObserver = TestScheduler.CreateObserver <Exception>();

                foreach (var shortcut in shortcuts)
                {
                    viewModel.SelectShortcut.Inputs.OnNext(shortcut);
                    TestScheduler.Start();
                }

                errorsObserver.Messages.Should().BeEmpty();
            }
            public async Task RecalculatesSuggestionsAfterUserSelectedCalendarsChange()
            {
                prepareSuggestionsForSuggestionsPresentedEvent();
                var subject = new Subject <List <string> >();

                UserPreferences.EnabledCalendars.Returns(subject);
                var observer = TestScheduler.CreateObserver <IImmutableList <Suggestion> >();

                await ViewModel.Initialize();

                ViewModel.Suggestions.Subscribe(observer);
                subject.OnNext(new List <string> {
                    ""
                });                                      // the app start event
                TestScheduler.Start();

                observer.Messages.Should().HaveCount(1);
                prepareSuggestionsForSuggestionsPresentedEvent(false);
                subject.OnNext(new List <string> {
                    ""
                });
                TestScheduler.Start();
                observer.Messages.Should().HaveCount(2);
            }
Exemplo n.º 58
0
            public async Task IsSortedBySelectedStatusThenByName()
            {
                var workspace      = createWorkspace(13, "Some workspace");
                var tagSuggestions = getTagSuggestions(4, workspace).ToArray();

                var shuffledTags   = new[] { tagSuggestions[3], tagSuggestions[1], tagSuggestions[2], tagSuggestions[0] };
                var selectedTagIds = new[] { tagSuggestions[0].TagId, tagSuggestions[2].TagId };

                InteractorFactory.GetTagsAutocompleteSuggestions(Arg.Any <IList <string> >())
                .Execute()
                .Returns(Observable.Return(shuffledTags));
                InteractorFactory.GetWorkspaceById(workspace.Id).Execute()
                .Returns(Observable.Return(workspace));

                await ViewModel.Initialize(new SelectTagsParameter(selectedTagIds, workspace.Id));

                var observer = TestScheduler.CreateObserver <IEnumerable <SelectableTagBaseViewModel> >();

                ViewModel.Tags.Subscribe(observer);
                TestScheduler.Start();

                var tags = observer.LastEmittedValue().ToArray();

                tags.Should().HaveCount(4);


                tags[0].Name.Should().Be("Tag0");
                tags[1].Name.Should().Be("Tag2");
                tags[2].Name.Should().Be("Tag1");
                tags[3].Name.Should().Be("Tag3");

                tags[0].Selected.Should().BeTrue();
                tags[1].Selected.Should().BeTrue();
                tags[2].Selected.Should().BeFalse();
                tags[3].Selected.Should().BeFalse();
            }
Exemplo n.º 59
0
            public void ReturnsFalseWhileExecuting()
            {
                var testScheduler = new TestScheduler();

                var action = new RxAction <int, string>(
                    i => Observable.Interval(TimeSpan.FromTicks(1), testScheduler)
                    .Take(i)
                    .Select(l => l.ToString())
                    );

                var observer = testScheduler.CreateObserver <bool>();

                action.Enabled.Subscribe(observer);

                testScheduler.Sleep(3);
                action.Execute(2);
                testScheduler.Start();

                observer.Messages.AssertEqual(
                    OnNext(0, true),
                    OnNext(3, false),
                    OnNext(5, true)
                    );
            }
        public void ObservePropertyExceptionFalse()
        {
            var testScheduler = new TestScheduler();
            var recorder      = testScheduler.CreateObserver <string>();
            var commonEx      = new Exception();

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

            m.ObserveProperty(x => x.Name, false)
            .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(1000, "bbb"),
                OnError <string>(1000, commonEx));
        }