예제 #1
0
        public void Should_consume_message_and_emit_payload()
        {
            var black = "#000000";

            string payload = $"{{ \"Color\": \"{black}\" }}";
            var    message = new MqttApplicationMessage {
                Payload = Encoding.UTF8.GetBytes(payload)
            };
            var eventArgs = new MqttApplicationMessageReceivedEventArgs("", message);
            var scheduler = new TestScheduler();

            MqttClientMock.SetupAllProperties();

            var subject = new MqttSource(Options, MqttClientMock.Object);

            scheduler.Schedule(TimeSpan.FromTicks(20), () =>
            {
                MqttClientMock.Object.ApplicationMessageReceivedHandler.HandleApplicationMessageReceivedAsync(eventArgs);
            });

            var actual = scheduler.Start(
                () => subject.Get(),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <object> >[] {
                OnNext(20, (object)payload)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #2
0
        public void Should_not_break_for_invalid_input(string testCase)
        {
            var input = testCase switch
            {
                "wrong type" => new object(),
                "exception on decode" => "#kennadecode"
            };

            var source = Observable.Return(input);

            var transformation = new ColorTransformation(new ColorTransformationOptions());

            var scheduler = new TestScheduler();


            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 0,
                disposed: 100
                );


            var expected = new Recorded <Notification <Ref <Color> > >[] {
                OnCompleted <Ref <Color> >(1)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
    }
예제 #3
0
        // Not very proud of this piece of code... if you find a smarter way of transforming
        // a IList<Recorded<Notification<T>>> to a IList<Recorded<Notification<object>>>
        // please share it and send a PR :)
        public static IList <Recorded <Notification <object> > > CastNotificationsFromTestableObservable(IEnumerable messages)
        {
            var result = new List <Recorded <Notification <object> > >();

            foreach (var message in messages)
            {
                var time            = GetProperty <long>(message, "Time");
                var rawNotification = GetProperty <object>(message, "Value");
                var kind            = GetProperty <NotificationKind>(rawNotification, "Kind");
                Notification <object> notification;
                switch (kind)
                {
                case NotificationKind.OnNext:
                    var value = GetProperty <object>(rawNotification, "Value");
                    notification = Notification.CreateOnNext(value);
                    break;

                case NotificationKind.OnError:
                    var exception = GetProperty <object>(rawNotification, "Exception");
                    notification = Notification.CreateOnError <object>((Exception)exception);
                    break;

                default:
                    notification = Notification.CreateOnCompleted <object>();
                    break;
                }
                var record = new Recorded <Notification <object> >(time, notification);
                result.Add(record);
            }

            return(result);
        }
예제 #4
0
        public void Should_not_break_for_invalid_input(string testCase)
        {
            var input = testCase switch {
                "no match" => "{\"POWER\": \"OFF\"}",
                "malformed json" => "{\"POWER\":",
                "wrong type" => new object(),
            };

            var source = Observable.Return(input);

            var options = new JsonPathTransformationOptions()
            {
                Expression = "$.data.livingRoom.color"
            };
            var transformation = new JsonPathTransformation <string>(options);

            var scheduler = new TestScheduler();


            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 0,
                disposed: 100
                );


            var expected = new Recorded <Notification <string> >[] {
                OnCompleted <string>(1)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #5
0
 public int GetHashCode(Recorded <INotification <T> > obj)
 {
     unchecked
     {
         return(obj.Time.GetHashCode() * Prime + _notificationComparer.GetHashCode(obj.Value));
     }
 }
예제 #6
0
        public static Recorded <Notification <char> > ConvertToChar <T>(
            this Recorded <Notification <T> > oldNotification,
            IReadOnlyDictionary <T, char> dict)
        {
            Notification <char> newNotification;

            switch (oldNotification.Value.Kind)
            {
            case NotificationKind.OnNext:
                T    oldValue = oldNotification.Value.Value;
                char newValue;
                if (!dict.TryGetValue(oldValue, out newValue))
                {
                    throw new KeyNotFoundException($"Convertion to char not found for notification {oldNotification}");
                }
                newNotification = Notification.CreateOnNext(newValue);
                break;

            case NotificationKind.OnError:
                newNotification = Notification.CreateOnError <char>(oldNotification.Value.Exception);
                break;

            case NotificationKind.OnCompleted:
                newNotification = Notification.CreateOnCompleted <char>();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(new Recorded <Notification <char> >(oldNotification.Time, newNotification));
        }
예제 #7
0
        public void Should_not_break_for_invalid_input()
        {
            var input  = "some string";
            var source = Observable.Return(input);
            var expressionExpectingColor = "value.B > value.R && value.B > value.G ? \"Bluish\" : \"Something else\"";

            var options = new ExpressionTransformationOptions()
            {
                Expression = expressionExpectingColor
            };

            var transformation = new ExpressionTransformation <string>(options);

            var scheduler = new TestScheduler();

            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <string> >[] {
                OnCompleted <string>(10)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #8
0
#pragma warning restore CA1000

        public bool Equals(Recorded <INotification <T> > x, Recorded <INotification <T> > y)
        {
            var ignoreTime  = x.Time < 0 || y.Time < 0;
            var isTimeEqual = ignoreTime || x.Time == y.Time;

            return(isTimeEqual && _notificationComparer.Equals(x.Value, y.Value));
        }
예제 #9
0
        public void Should_expose_input_value_in_context()
        {
            var input  = "Bruce";
            var source = Observable.Return(input);

            var options = new ExpressionTransformationOptions()
            {
                Expression = "\"Hello \" + value"
            };

            var transformation = new ExpressionTransformation <string>(options);

            var scheduler = new TestScheduler();

            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <string> >[] {
                OnNext(10, "Hello Bruce"),
                OnCompleted <string>(10)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #10
0
        public void Should_allow_usage_of_color_related_extensions_methods()
        {
            var input = new Dictionary <string, DeviceState>()
            {
                { "Copperhead", new DeviceState(new Color[] { Color.Red }) }
            };
            var source = Observable.Return(input);
            var expressionExpectingColor = "value[\"Copperhead\"].Colors.Cast().First().ToCommaSeparatedRgbString()";
            var expectation = "255,0,0";

            var options = new ExpressionTransformationOptions()
            {
                Expression = expressionExpectingColor
            };

            var transformation = new ExpressionTransformation <string>(options);

            var scheduler = new TestScheduler();

            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <string> >[] {
                OnNext(10, expectation),
                OnCompleted <string>(10)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #11
0
        public async void TextToSpeach(string text)
        {
            var voice             = SpeechSynthesizer.AllVoices.First(a => a.Language.Contains("en"));
            var speechSynthezizer = new SpeechSynthesizer();

            if (voice == null)
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("Please download en-US Language-Pack", "Language not found");
                    await messageDialog.ShowAsync();
                    Recorded?.Invoke("");
                });
            }
            else
            {
                speechSynthezizer.Voice = voice;
                var stream = await speechSynthezizer.SynthesizeTextToStreamAsync(text);

                Device.BeginInvokeOnMainThread(() =>
                {
                    MediaElement e = new MediaElement();
                    e.SetSource(stream, stream.ContentType);
                    e.Play();
                });
            }
        }
        public void RecordedConstructorTest()
        {
            string   initValue = "secret test string";
            Recorded target    = new Recorded(initValue);

            Assert.AreEqual(target.Value, initValue, "Object value should be identical after construction");
        }
            public void Verify()
            {
                var source = Observable.Return(Input);

                var scheduler      = new TestScheduler();
                var transformation = new MappingTransformation(Options);

                var actual = scheduler.Start(
                    () => transformation.GetOperator()(source),
                    created: 0,
                    subscribed: 10,
                    disposed: 100
                    );

                if (ShouldReturnEmpty)
                {
                    var expected = new Recorded <Notification <object> >[] {
                        OnCompleted <object>(10)
                    };
                    ReactiveAssert.AreElementsEqual(expected, actual.Messages);
                }
                else
                {
                    var expected = new Recorded <Notification <object> >[] {
                        OnNext(10, Output),
                        OnCompleted <object>(10)
                    };
                    ReactiveAssert.AreElementsEqual(expected, actual.Messages);
                }
            }
예제 #14
0
        public void Should_extract_deeply_nested_value()
        {
            var json   = "{\"data\":{\"livingRoom\":{\"color\": \"red\"}}}";
            var source = Observable.Return(json);

            var options = new JsonPathTransformationOptions()
            {
                Expression = "$.data.livingRoom.color"
            };
            var transformation = new JsonPathTransformation <string>(options);

            var scheduler = new TestScheduler();


            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <string> >[] {
                OnNext(10, "red"),
                OnCompleted <string>(10)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #15
0
        private void Assert(Recorded <Notification <T> > expected, Recorded <Notification <T> > actual, int index)
        {
            if (expected.Time != actual.Time)
            {
                throw CreateError(
                          $@"Times for elements at index {index} do not match.
Expected event at {expected.Time} but something happened at {actual.Time}",
                          expected.Time, actual.Time);
            }
            var exVal = expected.Value;
            var acVal = actual.Value;
            var time  = actual.Time;

            if (exVal.Kind != acVal.Kind)
            {
                throw CreateError(
                          $@"Types of elements at time {time} (index {index}) do not match.
Expected {exVal.Kind} but was {acVal.Kind}",
                          time);
            }
            if (exVal.Kind == NotificationKind.OnError && exVal.Exception.GetType() != acVal.Exception.GetType())
            {
                throw CreateError(
                          $@"Errors at time {time} (index {index}) do not match. 
Expected {exVal.Exception.GetType()} but was {acVal.Exception.GetType()}",
                          time);
            }
            if (exVal.Kind == NotificationKind.OnNext && !_comparer.Equals(exVal.Value, acVal.Value))
            {
                throw CreateError(
                          $@"Elements at time {time} (index {index}) do not match. 
Expected {exVal.Value} but was {acVal.Value}",
                          time);
            }
        }
예제 #16
0
        public void GivenAnObservableThatPublishesIntegersAtARateOf1EveryStartingAt(string name, int count, int periodCount, Duration period, Duration start)
        {
            var      scheduler    = _scenario.GetEx <TestScheduler>();
            Duration currentTime  = start;
            int      currentCount = count;
            int      index        = 0;
            var      messages     = new Recorded <Notification <int> > [count + 1];

            while (currentCount > 0)
            {
                int countToAdd = Math.Min(periodCount, currentCount);

                for (int i = 0; i < countToAdd; i++)
                {
                    messages[index] = OnNext(currentTime, index + 1);
                    index++;
                }

                currentTime   = currentTime + period;
                currentCount -= countToAdd;
            }

            messages[count] = OnCompleted <int>(currentTime - period);
            IObservable <int> obs = scheduler.CreateColdObservable(messages);

            //Array.ForEach(messages, m => Console.WriteLine(m));

            _scenario.Set(obs, name);
        }
예제 #17
0
        public void RecordSpeachToText()
        {
            Task.Factory.StartNew(async() =>
            {
                try
                {
                    var language = new Windows.Globalization.Language("en-US");

                    var speechRecognizer = new SpeechRecognizer(language);
                    await speechRecognizer.CompileConstraintsAsync();
                    var result = await speechRecognizer.RecognizeWithUIAsync();

                    Recorded?.Invoke(result.Text);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        var messageDialog = new Windows.UI.Popups.MessageDialog("Please download en-US Language-Pack", "Language not found");
                        await messageDialog.ShowAsync();
                        Recorded?.Invoke("");
                    });
                }
                catch
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        var messageDialog = new Windows.UI.Popups.MessageDialog("No permission to record", "Permission denied");
                        await messageDialog.ShowAsync();
                        Recorded?.Invoke("");
                    });
                }
            });
        }
예제 #18
0
        public void Should_transform_color_using_given_channel_layout()
        {
            var black         = "#FF0000";
            var expectedColor = new Ref <Color>(Color.FromArgb(255, 0, 255, 0));
            var source        = Observable.Return(black);

            var transformation = new ColorTransformation(new ColorTransformationOptions()
            {
                ChannelLayout = "GRB"
            });

            var scheduler = new TestScheduler();


            var actual = scheduler.Start(
                () => transformation.GetOperator()(source),
                created: 0,
                subscribed: 10,
                disposed: 100
                );

            var expected = new Recorded <Notification <Ref <Color> > >[] {
                OnNext(10, expectedColor),
                OnCompleted <Ref <Color> >(10)
            };

            ReactiveAssert.AreElementsEqual(expected, actual.Messages);
        }
예제 #19
0
                private void prepareException(TestScheduler scheduler)
                {
                    var message    = Notification.CreateOnError <string>(new Exception("Some api error"));
                    var recorded   = new Recorded <Notification <string> >(1, message);
                    var observable = scheduler.CreateColdObservable(recorded);

                    LoginManager.ResetPassword(Arg.Any <Email>()).Returns(observable);
                }
예제 #20
0
 private void EndRecognition(object sender, ElapsedEventArgs e)
 {
     node.RemoveTapOnBus(0);
     audioEngine.Stop();
     liveSpeechRequest.EndAudio();
     RecognitionTask.Cancel();
     recording = false;
     Recorded?.Invoke(lastSpokenString);
 }
예제 #21
0
                private void prepareException(
                    TestScheduler scheduler, Exception exception)
                {
                    var notification = Notification.CreateOnError <string>(exception);
                    var message      = new Recorded <Notification <string> >(1, notification);
                    var observable   = scheduler.CreateColdObservable(message);

                    LoginManager.ResetPassword(Arg.Any <Email>()).Returns(observable);
                }
예제 #22
0
 /// <summary>
 /// 将会用作主要的函数来记录操作。
 /// </summary>
 /// <param name="operations"></param>
 /// <param name="operationTime"></param>
 public void Record(OperationStack operations, DateTime operationTime)
 {
     if (operations != null)
     {
         Recording?.Invoke(operations, operationTime);
         UndoStack.Push(new Tuple <OperationStack, DateTime>(operations, operationTime));
         Recorded?.Invoke(operations, operationTime);
     }
 }
 public override void SetUp()
 {
     base.SetUp();
     _observer = new TestScheduler().CreateObserver <CollectionChangedData <SampleDto> >();
     _ageChanges.Subscribe(_observer);
     _expected = CreateJohn();
     _sut.Add(_expected);
     _message = _observer.Messages.Single();
     _data    = _message.Value.Value;
 }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = 27;
                    _sut.Add(_expected);

                    _observer = new TestScheduler().CreateObserver <CollectionChangedData <int> >();
                    _changes.Subscribe(_observer);
                    _sut.RemoveAt(0);
                    _message = _observer.Messages.Single();
                    _data    = _message.Value.Value;
                }
예제 #25
0
 /// <summary>
 /// 添加一个操作
 /// </summary>
 /// <param name="operation">要添加的操作</param>
 public void Record(Operation operation)
 {
     if (operation != null && IsRecording)
     {
         var stack = new OperationStack(operation.PropertyName.ToString());
         stack.Push(operation);
         var recordTime = DateTime.Now;
         Recording?.Invoke(stack, recordTime);
         UndoStack.Push(new Tuple <OperationStack, DateTime>(stack, recordTime));
         RedoStack.Clear();
         Recorded?.Invoke(stack, recordTime);
     }
 }
예제 #26
0
        public void HugeBatch()
        {
            const int BatchSize = 1024;
            var       engine1   = CreateQueryEngine("reactor:/engine1");
            var       reactive1 = engine1.GetReactiveService();

            var engine2   = CreateQueryEngine("reactor:/engine2");
            var reactive2 = engine2.GetReactiveService();

            var batch = new Recorded <Notification <int> > [BatchSize];

            for (int i = 0; i < BatchSize; i++)
            {
                batch[i] = ReactiveTest.OnNext(100, i);
            }

            var source = GetTestableQbservable(reactive1, "source", batch.ToArray());

            Assert.IsNotNull(source);

            var engine1ObservableUri = new Uri("reactor:/engine1/middle");

            reactive1.DefineObservable(engine1ObservableUri, source.Where(x => true), null);
            var engine1Observable = reactive1.GetObservable <int>(engine1ObservableUri);

            var engine2ObservableUri = new Uri("reactor:/engine2/middle");

            reactive2.DefineObservable(engine2ObservableUri, engine1Observable.Where(x => true), null);
            var engine2Observable = reactive2.GetObservable <int>(engine1ObservableUri);

            var result = GetTestableQbserver <int>(reactive2, "result");

            Scheduler.ScheduleAbsolute(10, () => engine2Observable.Subscribe(result, new Uri("reactor:/subscription"), null));
            Scheduler.Start();

            var sub = GetTestableSubscribable <int>("source");

            sub.Subscriptions.AssertEqual(
                ReactiveTest.Subscribe(10));

            var output = new Recorded <Notification <int> > [BatchSize];

            for (int i = 0; i < BatchSize; i++)
            {
                output[i] = ReactiveTest.OnNext(10 + 100, i);
            }
            var res = GetTestableObserver <int>("result");

            res.Messages.AssertEqual(output);
        }
예제 #27
0
        public int Compare(Recorded <Notification <T> > x, Recorded <Notification <T> > y)
        {
            var compare = x.Time.CompareTo(y.Time);

            if (compare != 0)
            {
                return(compare);
            }

            compare = x.Value.Kind.CompareTo(y.Value.Kind);
            if (compare != 0)
            {
                return(compare);
            }

            switch (x.Value.Kind)
            {
            case NotificationKind.OnNext:
                compare = _valueComparer.Compare(x.Value.Value, y.Value.Value);
                break;

            case NotificationKind.OnError:
                switch (ReferenceEquals(x.Value.Exception, null), ReferenceEquals(y.Value.Exception, null))
                {
                case (true, true):
                    compare = 0;
                    break;

                case (false, true):
                    compare = 1;
                    break;

                case (true, false):
                    compare = -1;
                    break;

                case (false, false):
                    if (_errorComparer != null)
                    {
                        compare = _errorComparer.Compare(x.Value.Exception !, y.Value.Exception !);
                    }
                    else
                    {
                        compare = x.Value?.Exception?.GetType() == y.Value?.Exception?.GetType() ? 0 : -1;
                    }
                    break;
                }

                break;
            }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = CreateJohn();
                    _sut.Add(_expected);

                    _observer     = new TestScheduler().CreateObserver <CollectionChangedData <SampleDto> >();
                    _subscription = _changes.Subscribe(_observer);
                    Assume.That(_sut[0].Age != _expectedAge);

                    _sut[0].Reset();

                    _message = _observer.Messages.Single();
                    _data    = _message.Value.Value;
                }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = new[] { 27, 12, 79 };
                    foreach (var i in _expected)
                    {
                        _sut.Add(i);
                    }

                    _observer = new TestScheduler().CreateObserver <CollectionChangedData <int> >();
                    _changes.Subscribe(_observer);
                    _sut.Clear();
                    _message = _observer.Messages.Single();
                    _data    = _message.Value.Value;
                }
예제 #30
0
        private void StartSpeechRecognizer()
        {
            if (!recording)
            {
                speechRecognizer = new SFSpeechRecognizer();
                node             = audioEngine.InputNode;
                var recordingFormat = node.GetBusOutputFormat(0);
                liveSpeechRequest = new SFSpeechAudioBufferRecognitionRequest();

                node.InstallTapOnBus(0, 1024, recordingFormat,
                                     (AVAudioPcmBuffer buffer, AVAudioTime when) =>
                {
                    liveSpeechRequest.Append(buffer);
                });
                recording = true;

                audioEngine.Prepare();
                audioEngine.StartAndReturnError(out NSError error);
                if (error != null)
                {
                    return;
                }

                Timer timer = new Timer(2000);
                timer.Start();
                timer.Elapsed  += EndRecognition;
                RecognitionTask = speechRecognizer.GetRecognitionTask(liveSpeechRequest,
                                                                      (SFSpeechRecognitionResult result, NSError err) =>
                {
                    if (err != null)
                    {
                        Recorded?.Invoke("");
                        return;
                    }
                    else
                    {
                        lastSpokenString = result.BestTranscription.FormattedString;
                        timer.Stop();
                        timer.Interval = 2000;
                        timer.Start();
                    }
                });
            }
            else
            {
                Recorded?.Invoke("");
            }
        }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = 27;
                    _sut.Add(_expected);

                    _observer = new TestScheduler().CreateObserver<CollectionChangedData<int>>();
                    _changes.Subscribe(_observer);
                    _sut.RemoveAt(0);
                    _message = _observer.Messages.Single();
                    _data = _message.Value.Value;
                }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = new[] { 27, 12, 79 };
                    foreach (var i in _expected)
                    {
                        _sut.Add(i);
                    }

                    _observer = new TestScheduler().CreateObserver<CollectionChangedData<int>>();
                    _changes.Subscribe(_observer);
                    _sut.Clear();
                    _message = _observer.Messages.Single();
                    _data = _message.Value.Value;
                }
                public override void SetUp()
                {
                    base.SetUp();
                    _expectedOld = CreateJohn();
                    _expectedNew = CreateJack();
                    _sut.Add(_expectedOld);

                    _observer = new TestScheduler().CreateObserver<CollectionChangedData<SampleDto>>();
                    _ageChanges.Subscribe(_observer);
                    _sut[0] = _expectedNew;
                    _message = _observer.Messages.Single();
                    _data = _message.Value.Value;
                }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = new[] { CreateJohn(), CreateJack(), new SampleDto() { Name = "Jill", Age = 19, FriendsCount = 30 } };
                    foreach (var i in _expected)
                    {
                        _sut.Add(i);
                    }

                    _observer = new TestScheduler().CreateObserver<CollectionChangedData<SampleDto>>();
                    _ageChanges.Subscribe(_observer);
                    _sut.Clear();
                    _message = _observer.Messages.Single();
                    _data = _message.Value.Value;
                }
                public override void SetUp()
                {
                    base.SetUp();
                    _expected = CreateJohn();
                    _sut.Add(_expected);

                    _observer = new TestScheduler().CreateObserver<CollectionChangedData<SampleDto>>();
                    _subscription = _ageChanges.Subscribe(_observer);
                    Assume.That(_sut[0].Age != _expectedAge);
                    _sut[0].Age = _expectedAge;
                    _message = _observer.Messages.Single();
                    _data = _message.Value.Value;
                }