Beispiel #1
0
    public Hangman(string word)
    {
        HashSet <char> emptySetOfChars = new HashSet <char>();
        var            stateSubject    = new BehaviorSubject <HangmanState>(new HangmanState(MaskedWord(word, emptySetOfChars), emptySetOfChars.ToImmutableHashSet(), MaxGuessCount));

        StateObservable = stateSubject;

        GuessObserver = Observer.Create <char>(x =>
        {
            HashSet <char> guessedChars = new HashSet <char>(stateSubject.Value.GuessedChars);
            bool isHit = !guessedChars.Contains(x) && word.Contains(x);
            guessedChars.Add(x);
            string maskedWord = MaskedWord(word, guessedChars);
            if (maskedWord == word)
            {
                stateSubject.OnCompleted();
            }
            else if (stateSubject.Value.RemainingGuesses < 1)
            {
                stateSubject.OnError(new TooManyGuessesException());
            }
            else
            {
                stateSubject.OnNext(new HangmanState(maskedWord, guessedChars.ToImmutableHashSet(),
                                                     isHit ? stateSubject.Value.RemainingGuesses : stateSubject.Value.RemainingGuesses - 1));
            }
        });
    }
Beispiel #2
0
        public void OnOuterError()
        {
            var lbs1 = new ListBehaviorSubject <int>();

            lbs1.OnAdd(1);
            lbs1.OnAdd(2);

            var source = new BehaviorSubject <IObservableList <int> >(lbs1);

            var list = new List <int>();

            var       completed = false;
            Exception error     = null;

            var sub = source
                      .Switch()
                      .Subscribe(
                Observer.Create <ListChange <int> >(
                    change => change.Apply(list),
                    e => error      = e,
                    () => completed = true));

            var ex = new Exception("AAAAAA");

            source.OnError(ex);

            Assert.AreEqual(ex, error);
            Assert.IsFalse(completed);

            sub.Dispose();
        }
Beispiel #3
0
        public void TestOnError()
        {
            var expectedOnNext = new List <int> {
                7, 1, 10, 100
            };
            var onNext               = new List <int>();
            var exceptions           = new List <Exception>();
            var onCompletedCallCount = 0;
            var subject              = new BehaviorSubject <int>(7);

            subject.Subscribe(x => onNext.Add(x), x => exceptions.Add(x), () => onCompletedCallCount++);

            subject.OnNext(1);
            subject.OnNext(10);
            subject.OnNext(100);
            Assert.That(onNext, Is.EqualTo(expectedOnNext));
            Assert.That(exceptions, Has.Count.EqualTo(0));
            Assert.That(onCompletedCallCount, Is.EqualTo(0));

            subject.OnError(new Exception());
            Assert.That(exceptions, Has.Count.EqualTo(1));

            subject.OnNext(1);
            subject.OnNext(10);
            subject.OnNext(200);
            Assert.That(onNext, Is.EqualTo(expectedOnNext));
            Assert.That(onCompletedCallCount, Is.EqualTo(0));
        }
Beispiel #4
0
    private void OnNextGuess(char guess)
    {
        if (_state.Value.RemainingGuesses == 0)
        {
            _state.OnError(new TooManyGuessesException());
            return;
        }

        var currentState = _state.Value;
        var remaining    = currentState.GuessedChars.Contains(guess) || !_word.Contains(guess)
            ? currentState.RemainingGuesses - 1
            : currentState.RemainingGuesses;

        var guessed = currentState.GuessedChars.Add(guess);
        var masked  = MaskWord(guessed);

        if (masked == _word)
        {
            _state.OnCompleted();
        }
        else
        {
            _state.OnNext(new HangmanState(masked, guessed, remaining));
        }
    }
Beispiel #5
0
        public override void OnError(Exception error)
        {
            if (_isDisposed)
            {
                throw error;
            }

            _subject.OnError(error);
        }
Beispiel #6
0
        public void Value_ThrowsAfterOnError()
        {
            var s = new BehaviorSubject <int>(42);

            Assert.AreEqual(42, s.Value);

            s.OnError(new InvalidOperationException());

            Assert.Fail("Should not be able to read Value: {0}", s.Value);
        }
Beispiel #7
0
        public void Should_Invoke_OnError_On_Activator_Error()
        {
            var activator = new BehaviorSubject <bool>(false);
            var source    = new TestSubject();
            var target    = new ActivatedSubject(activator, source, string.Empty);

            activator.OnError(new Exception());

            Assert.NotNull(source.Error);
        }
Beispiel #8
0
        public void Should_Complete_When_Source_Observable_Errors()
        {
            var source    = new BehaviorSubject <object>(1);
            var target    = new ExpressionObserver(source, "Foo");
            var completed = false;

            target.Subscribe(_ => { }, () => completed = true);
            source.OnError(new Exception());

            Assert.True(completed);
        }
        public void Should_Complete_When_Source_Observable_Errors()
        {
            var source = new BehaviorSubject<object>(1);
            var target = new ExpressionObserver(source, "Foo");
            var completed = false;

            target.Subscribe(_ => { }, () => completed = true);
            source.OnError(new Exception());

            Assert.True(completed);
        }
Beispiel #10
0
        public void Should_Error_When_Activator_Errors()
        {
            var activator = new BehaviorSubject <bool>(false);
            var target    = new ActivatedValue(activator, 1, string.Empty);
            var error     = new Exception();
            var completed = false;

            target.Subscribe(_ => { }, x => completed = true);
            activator.OnError(error);

            Assert.True(completed);
        }
Beispiel #11
0
        public void replays_error_sequence()
        {
            BehaviorSubject <int> subject = new BehaviorSubject <int>(0);

            StatsObserver <int> stats = new StatsObserver <int>();

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsTrue(stats.ErrorCalled);
        }
Beispiel #12
0
        public void Should_Error_When_Source_Errors()
        {
            var activator = new BehaviorSubject <bool>(false);
            var source    = new BehaviorSubject <object>(1);
            var target    = new ActivatedObservable(activator, source, string.Empty);
            var error     = new Exception();
            var completed = false;

            target.Subscribe(_ => { }, x => completed = true);
            source.OnError(error);

            Assert.True(completed);
        }
        public ReactiveAsyncAgent(
            TState initialState,
            Func <TState, TMessage, CancellationToken, Task <TState> > messageHandler,
            Func <Exception, CancellationToken, Task <bool> > errorHandler)
        {
            if (initialState == null)
            {
                throw new ArgumentNullException(nameof(initialState));
            }

            if (messageHandler == null)
            {
                throw new ArgumentNullException(nameof(messageHandler));
            }

            if (errorHandler == null)
            {
                throw new ArgumentNullException(nameof(errorHandler));
            }

            _stateSubject = new BehaviorSubject <TState>(initialState);
            _asyncAgent   = new AsyncAgent <TState, TMessage>(
                initialState: initialState,
                messageHandler: async(state, msg, ct) =>
            {
                TState newState = state;

                newState = await messageHandler(state, msg, ct);

                if (!ct.IsCancellationRequested)
                {
                    _stateSubject.OnNext(newState);
                }

                return(newState);
            },
                errorHandler: async(ex, ct) =>
            {
                bool shouldContinue = false;
                shouldContinue      = await errorHandler(ex, ct);

                if (!shouldContinue && !ct.IsCancellationRequested)
                {
                    _stateSubject.OnError(ex);
                }

                return(shouldContinue);
            });

            State = _stateSubject.AsObservable();
        }
        public void Should_Invoke_OnError_On_Activator_Error()
        {
            var activator   = new BehaviorSubject <bool>(false);
            var source      = new TestSubject();
            var target      = new ActivatedSubject(activator, source, string.Empty);
            var targetError = default(Exception);
            var error       = new Exception();

            target.Subscribe(_ => { }, e => targetError = e);
            activator.OnError(error);

            Assert.Same(error, source.Error);
            Assert.Same(error, targetError);
        }
Beispiel #15
0
        public async Task Start()
        {
            try
            {
                _stateSignal.OnNext(TestState.Running);
                _output.OnNext("========================================\\");
                _output.OnNext(Name);
                if (FilePath.HasValue)
                {
                    _output.OnNext(FilePath.Value.ToString());
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();
                await _toDo(_output);

                sw.Stop();
                _output.OnNext("Passed");
                _output.OnNext($"{sw.ElapsedMilliseconds / 1000d}s");
                _output.OnNext("========================================/");
                _stateSignal.OnNext(TestState.Complete);
                if (_parallel)
                {
                    await Task.WhenAll(_children.Select(c => Task.Run(c.Start)));
                }
                else
                {
                    await Task.WhenAll(_children.Select(c => c.Start()));
                }
                _disposables.Dispose();
            }
            catch (Exception ex)
            {
                _stateSignal.OnError(ex);
                while (ex != null)
                {
                    _output.OnNext(ex.ToString());
                    ex = ex.InnerException;
                }
                _output.OnNext("Failed");
                _output.OnNext("========================================/");
                _stateSignal.OnNext(TestState.Error);
            }
            finally
            {
                _output.OnCompleted();
                _stateSignal.OnCompleted();
            }
        }
Beispiel #16
0
        public void replays_no_values_when_errored()
        {
            BehaviorSubject <int> subject = new BehaviorSubject <int>(0);

            StatsObserver <int> stats = new StatsObserver <int>();

            subject.OnNext(1);
            subject.OnNext(2);
            subject.OnNext(3);
            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.ErrorCalled);
        }
Beispiel #17
0
        public void HasObservers_OnError()
        {
            var s = new BehaviorSubject <int>(42);

            Assert.IsFalse(s.HasObservers);

            var d = s.Subscribe(_ => { }, ex => { });

            Assert.IsTrue(s.HasObservers);

            s.OnNext(42);
            Assert.IsTrue(s.HasObservers);

            s.OnError(new Exception());
            Assert.IsFalse(s.HasObservers);
        }
Beispiel #18
0
        public void errors_are_sent_through_scheduler()
        {
            ManualScheduler scheduler = new ManualScheduler();

            BehaviorSubject <int> subject = new BehaviorSubject <int>(0, scheduler);

            StatsObserver <int> stats = new StatsObserver <int>();

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsFalse(stats.ErrorCalled);

            scheduler.RunNext();
            Assert.IsTrue(stats.ErrorCalled);
        }
        public void errors_are_sent_through_scheduler()
        {
            ManualScheduler scheduler = new ManualScheduler();

            BehaviorSubject<int> subject = new BehaviorSubject<int>(0, scheduler);

            StatsObserver<int> stats = new StatsObserver<int>();

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsFalse(stats.ErrorCalled);

            scheduler.RunNext();
            Assert.IsTrue(stats.ErrorCalled);
        }
Beispiel #20
0
        public void Value_ThrowsAfterOnError()
        {
            var s = new BehaviorSubject <int>(42);

            Assert.Equal(42, s.Value);

            s.OnError(new InvalidOperationException());

            ReactiveAssert.Throws <InvalidOperationException>(() =>
            {
                var ignored = s.Value;
            });

            ReactiveAssert.Throws <InvalidOperationException>(() =>
            {
                s.TryGetValue(out var x);
            });
        }
        public async Task Observable_Current_propagates_exception()
        {
            var subject         = new BehaviorSubject <int>(1);
            var asyncEnumerable = subject.Current();

            await using (var asyncEnumerator = asyncEnumerable.GetAsyncEnumerator())
            {
                subject.OnNext(1);
                subject.OnNext(2);
                subject.OnNext(3);

                subject.OnError(new DivideByZeroException());

                asyncEnumerator
                .Awaiting(_ => _.MoveNextAsync().AsTask())
                .Should()
                .ThrowExactly <DivideByZeroException>();
            }
        }
    public Hangman(string word)
    {
        var emptySet = new HashSet <char>();
        var subject  = new BehaviorSubject <HangmanState>(new HangmanState(
                                                              Mask(word, emptySet),
                                                              emptySet.ToImmutableHashSet(),
                                                              MaxGuesses
                                                              ));

        this.StateObservable = subject;

        this.GuessObserver = Observer.Create <char>(ch =>
        {
            var guessedChars     = new HashSet <char>(subject.Value.GuessedChars);
            var remainingGuesses = subject.Value.RemainingGuesses;
            if (!word.Contains(ch) || guessedChars.Contains(ch))
            {
                remainingGuesses--;
            }
            guessedChars.Add(ch);
            var masked = Mask(word, guessedChars);
            if (masked == word)
            {
                subject.OnCompleted();
            }
            else if (remainingGuesses < 0)                     // Game over
            {
                subject.OnError(new TooManyGuessesException());
            }
            else
            {
                subject.OnNext(new HangmanState(
                                   masked,
                                   guessedChars.ToImmutableHashSet(),
                                   remainingGuesses
                                   ));
            }
        }
                                                    );
    }
        public async Task Observable_Current_propagates_exception()
        {
            var subject = new BehaviorSubject<int>(1);
            var asyncEnumerable = subject.Current();

            using (var asyncEnumerator = asyncEnumerable.GetEnumerator())
            {
                subject.OnNext(1);
                subject.OnNext(2);
                subject.OnNext(3);

                subject.OnError(new InvalidOperationException());

                asyncEnumerator
                    .Awaiting(_ => _.MoveNext(CancellationToken.None))
                    .ShouldThrowExactly<AggregateException>()
                    .Where(ex => ex.GetBaseException() is InvalidOperationException);
            }
        }
        public void replays_no_values_when_errored()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

            StatsObserver<int> stats = new StatsObserver<int>();

            subject.OnNext(1);
            subject.OnNext(2);
            subject.OnNext(3);
            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.AreEqual(0, stats.NextCount);
            Assert.IsTrue(stats.ErrorCalled);
        }
Beispiel #25
0
        public void BehaviorSubject()
        {
            // OnCompletedPattern
            {
                var subject = new BehaviorSubject<int>(3333);

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                onNext.IsCollection(3333);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);

                onNext.IsCollection(3333, 1, 10, 100, 1000);

                // re subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.IsCollection(1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(1);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new BehaviorSubject<int>(3333);

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.IsCollection(3333, 1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(5);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }
        public void HasObservers_OnError()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.IsFalse(s.HasObservers);

            var d = s.Subscribe(_ => { }, ex => { });
            Assert.IsTrue(s.HasObservers);

            s.OnNext(42);
            Assert.IsTrue(s.HasObservers);

            s.OnError(new Exception());
            Assert.IsFalse(s.HasObservers);
        }
        public void Value_ThrowsAfterOnError()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.AreEqual(42, s.Value);

            s.OnError(new InvalidOperationException());
            
            Assert.Fail("Should not be able to read Value: {0}", s.Value);
        }
Beispiel #28
0
 void IObserver <T> .OnError(Exception error)
 => subject.OnError(error);
Beispiel #29
0
        public void Value_ThrowsAfterOnError()
        {
            var s = new BehaviorSubject<int>(42);
            Assert.AreEqual(42, s.Value);

            s.OnError(new InvalidOperationException());

            ReactiveAssert.Throws<InvalidOperationException>(() =>
            {
                var ignored = s.Value;
            });

            ReactiveAssert.Throws<InvalidOperationException>(() =>
            {
                var x = default(int);
                s.TryGetValue(out x);
            });
        }
        public void replays_error_sequence()
        {
            BehaviorSubject<int> subject = new BehaviorSubject<int>(0);

            StatsObserver<int> stats = new StatsObserver<int>();

            subject.OnError(new Exception());

            subject.Subscribe(stats);

            Assert.IsTrue(stats.ErrorCalled);
        }
Beispiel #31
0
        public void BehaviorSubject()
        {
            // OnCompletedPattern
            {
                var subject = new BehaviorSubject <int>(3333);

                var onNext               = new List <int>();
                var exception            = new List <Exception>();
                int onCompletedCallCount = 0;
                var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                onNext.Is(3333);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);

                onNext.Is(3333, 1, 10, 100, 1000);

                // re subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(1);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new BehaviorSubject <int>(3333);

                var onNext               = new List <int>();
                var exception            = new List <Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(3333, 1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(5);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }
Beispiel #32
0
 public void OnError(Exception error)
 {
     _subject.OnError(error);
 }