public static void SubscribeASync(CimSession cimSession, string cimNamespace)
        {
            try
            {
                string query = QueryInstanceCore();

                //Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Press <Enter> to abort the subscription");
                //Console.ResetColor();

                IObservable<CimSubscriptionResult> queryInstances = cimSession.SubscribeAsync(cimNamespace, "WQL", query, GetOperationOptions());
                TestObserver<CimSubscriptionResult> observer = new TestObserver<CimSubscriptionResult>();
                IDisposable disposeAble = queryInstances.Subscribe(observer);

                Console.ReadLine();

                disposeAble.Dispose();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch( Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    GrainClient.Initialize();
                    break;
                }
                catch (Exception)
                {
                    Task.Delay(500).Wait();
                }
            }
            Console.WriteLine("Waiting");
            Task.Delay(5000).Wait();
            Console.WriteLine("Starting");

            var streamProvider = GrainClient.GetStreamProvider("DSProvider");
            var stream = streamProvider.GetStream<Price>(new Guid("00000000-0000-0000-0000-000000000000"), "Global");

            var testObserver = new TestObserver();
            stream.SubscribeAsync(testObserver).Wait();

            Console.ReadLine();
        }
Exemplo n.º 3
0
        public void CanUseTestObserver()
        {
            const string MailBoxName = "box";
            const string ErrorText = "error";
            using (var mailBox = new ProcessMailBox(MailBoxName, TimeSpan.FromMilliseconds(-1)))
            {
                using (var observer = new TestObserver(MailBoxName))
                {
                    var list = new List<object>();

                    var taskObserve = Task.Factory.StartNew(
                        () =>
                            {
                                observer.OnNext(PerTestResultGenerator.CreatePerfResult());
                                observer.OnError(new Exception(ErrorText));
                                observer.OnCompleted();
                            });

                    var taskMailBox = Task.Factory.StartNew(
                        () =>
                            {
                                list.Add(mailBox.Content);
                                list.Add(mailBox.Content);
                                list.Add(mailBox.Content);
                            });

                    Task.WaitAll(new[] { taskObserve, taskMailBox }, TimeSpan.FromSeconds(20)).Should().BeTrue();
                    list.Count.Should().Be(3);
                    list[0].Should().Be(PerTestResultGenerator.CreatePerfResult());
                    list[1].Should().Be(new ExperimentError(new Exception(ErrorText)));
                    list[2].Should().Be(new ExperimentCompleted());
                }
            }
        }
Exemplo n.º 4
0
        public void Observer_Dispose()
        {
            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                var cs = new MaybeSubject <int>();

                var to = new TestObserver <int>();

                var cdl = new CountdownEvent(1);

                Task.Factory.StartNew(() =>
                {
                    while (!cs.HasObserver())
                    {
                        ;
                    }
                    to.Dispose();
                    cdl.Signal();
                });

                cs.BlockingSubscribe(to);

                cdl.Wait();

                Assert.False(cs.HasObserver());
            }
        }
Exemplo n.º 5
0
        public void OnNext_OnCompleted_Race()
        {
            var ex = new InvalidOperationException();

            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                wip   = 0;
                error = null;

                var to = new TestObserver <int>();

                TestHelper.Race(() =>
                {
                    HalfSerializer.OnNext(to, 1, ref wip, ref error);
                },
                                () =>
                {
                    HalfSerializer.OnCompleted(to, ref wip, ref error);
                });

                to.AssertNoError()
                .AssertCompleted();

                Assert.True(to.ItemCount <= 1);
            }
        }
Exemplo n.º 6
0
        public static void CreateInstanceASync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            try
            {
                CimInstance createInstance = CreateInstanceCore(cimSession, cimNamespace, cimClassName);
                if (createInstance == null)
                {
                    Console.WriteLine("CreateInstance operation not performed");
                    return;
                }

                CimAsyncResult<CimInstance> enumeratedInstances = cimSession.CreateInstanceAsync(cimNamespace, createInstance, GetOperationOptions());
                TestObserver<CimInstance> observer = new TestObserver<CimInstance>();
                IDisposable disposeable = enumeratedInstances.Subscribe(observer);
                observer.WaitForCompletion();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void Basic_Observer_Dispose()
        {
            var to  = new TestObserver <int>();
            var cdl = new CountdownEvent(2);
            var us  = new MonocastSubject <int>();

            Task.Factory.StartNew(() =>
            {
                while (to.ItemCount != 5)
                {
                    ;
                }
                to.Dispose();
                cdl.Signal();
            });

            Task.Factory.StartNew(() =>
            {
                us.Emit(1, 2, 3, 4, 5);
                cdl.Signal();
            });

            us.BlockingSubscribe(to);

            to.AssertValuesOnly(1, 2, 3, 4, 5);

            Assert.True(cdl.Wait(3000));

            Assert.False(us.HasObserver());
        }
Exemplo n.º 8
0
        public void Q4()
        {
            var observer = new TestObserver <int>();
            var subject1 = new Subject <int>();
            var subject2 = new Subject <int>();

            // Q. subject1, subject2を組み合わせ、きた順に値を流すobservableをつくれ
            var observable = (UniRx.IObservable <int>)null; // FIXME

            observable.Subscribe(observer);

            subject1.OnNext(1);
            subject2.OnNext(10);
            subject1.OnNext(2);
            subject2.OnNext(20);
            subject1.OnCompleted();
            subject2.OnNext(30);

            Assert.AreEqual(5, observer.CountNext);
            Assert.AreEqual(1, observer.NextList[0]);
            Assert.AreEqual(10, observer.NextList[1]);
            Assert.AreEqual(2, observer.NextList[2]);
            Assert.AreEqual(20, observer.NextList[3]);
            Assert.AreEqual(30, observer.NextList[4]);
        }
Exemplo n.º 9
0
        protected TestObserver <ConnectionState> GetObserver(ClientHolder holder)
        {
            var observer = new TestObserver <ConnectionState>();

            holder.OnConnectionStateChanged.Subscribe(observer);
            return(observer);
        }
Exemplo n.º 10
0
    // Static void method with same signature as "Main" is always
    // file base name:
    //
    /// <summary>
    /// VTK test Main method
    /// </summary>
    public static void vtkCommandTest(string[] args)
    {
        // Create an object to send an event:
        //
        Kitware.VTK.vtkObject sender = new Kitware.VTK.vtkObject();

        // Create an event observer:
        //
        TestObserver observer = new TestObserver();

        // Connect them:
        //
        uint observerModifiedEventTag = sender.AddObserver(
            (uint)Kitware.VTK.vtkCommand.EventIds.ModifiedEvent, observer, 0.69f);

        // Trigger the event:
        //
        sender.Modified();

        // Toggle Debug, trigger event again, then turn off Debug before objects are destroyed...
        //
        sender.SetDebug((byte)((0 == sender.GetDebug()) ? 1 : 0));
        sender.Modified();
        sender.DebugOff();

        // Disconnect them:
        //
        sender.RemoveObserver(observerModifiedEventTag);
    }
Exemplo n.º 11
0
        public void Sut_AllMethods_WhenErrorOccurs_ShouldCallOnNext(
            Func <ReportingActor, INamed, object> executeAction,
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters
            Func <INamed, Expression <Func <IActor, object> > > dummy,
#pragma warning restore xUnit1026 // Theory methods should use all of their parameters
            CommandType commandType)
        {
            //arrange
            var fixture  = CreateFixture();
            var observer = new TestObserver <ActionNotification>();

            fixture.Inject((IObserver <ActionNotification>)observer);
            var date             = fixture.Freeze <DateTimeOffset>();
            var measureDuration  = fixture.Freeze <Mock <IMeasureDuration> >();
            var sut              = fixture.Create <ReportingActor>();
            var action           = fixture.Create <MockToString>();
            var exception        = fixture.Create <Exception>();
            var expectedDuration = fixture.Create <TimeSpan>();

            measureDuration.Setup(m => m.Measure(It.IsAny <Func <object> >())).Returns((expectedDuration, null, exception));
            //act
            try
            {
                executeAction(sut, action);
            }
            catch { }
            //assert
            var expected = new[] {
                new ActionNotification(action, 1, new BeforeActionNotificationContent(date, commandType)),
                new ActionNotification(action, 1, new ExecutionErrorNotificationContent(exception, expectedDuration))
            };

            observer.Values.Should().BeEquivalentTo(expected, o => o.RespectingRuntimeTypes().ComparingByMembers <ActionNotification>());
        }
Exemplo n.º 12
0
        public void Sut_AllMethods_WhenErrorOccurs_ShouldCallOnNext(
            Func <ReportingActor, INamed, object> executeAction,
            Func <INamed, Expression <Func <IActor, object> > > dummy)
        {
            //arrange
            var fixture  = CreateFixture();
            var observer = new TestObserver <ActionNotification>();

            fixture.Inject((IObserver <ActionNotification>)observer);
            var measureDuration = fixture.Freeze <Mock <IMeasureDuration> >();
            var sut             = fixture.Create <ReportingActor>();
            var action          = fixture.Create <MockToString>();
            var exception       = fixture.Create <Exception>();

            measureDuration.Setup(m => m.Measure(It.IsAny <Func <object> >())).Throws(exception);
            //act
            try
            {
                executeAction(sut, action);
            }
            catch { }
            //assert
            var expected = new[] {
                new ActionNotification(action, 1, new BeforeActionNotificationContent()),
                new ActionNotification(action, 1, new ExecutionErrorNotificationContent(exception))
            };

            observer.Values.ShouldAllBeEquivalentTo(expected, o => o.RespectingRuntimeTypes());
        }
Exemplo n.º 13
0
        public void OnNext_OnError_Race()
        {
            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                var to = new TestObserver <int>();

                var s = ReactiveExtensions.ToSerialized(to);

                var ex = new InvalidOperationException();

                Action emit = () => {
                    for (int j = 0; j < 500; j++)
                    {
                        s.OnNext(j);
                    }
                };

                Action complete = () =>
                {
                    for (int j = 0; j < 250; j++)
                    {
                        s.OnNext(j);
                    }

                    s.OnError(ex);
                };

                TestHelper.Race(emit, complete);

                Assert.True(to.ItemCount >= 250);

                to.AssertError(typeof(InvalidOperationException))
                .AssertNotCompleted();
            }
        }
Exemplo n.º 14
0
        public void DiagnosticSourceStartStop()
        {
            using (DiagnosticListener listener = new DiagnosticListener("Testing"))
            {
                DiagnosticSource source = listener;
                var observer            = new TestObserver();

                using (listener.Subscribe(observer))
                {
                    var arguments = new { args = "arguments" };

                    var activity = new Activity("activity");

                    source.StartActivity(activity, arguments);
                    Assert.Equal(activity.OperationName + ".Start", observer.EventName);
                    Assert.Equal(arguments, observer.EventObject);

                    observer.Reset();

                    source.StopActivity(activity, arguments);
                    Assert.Equal(activity.OperationName + ".Stop", observer.EventName);
                    Assert.Equal(arguments, observer.EventObject);
                }
            }
        }
        public void Observe_should_reflect_updates_correctly()
        {
            var observer         = new TestObserver <Dictionary <string, int> >();
            var expectedSettings = new List <Dictionary <string, int> >();

            using (var temporaryFile = new TemporaryFile())
            {
                source = CreateJsonFileSource(temporaryFile.FileName);

                using (provider.Observe <Dictionary <string, int> >(source).Subscribe(observer))
                {
                    Action assertion = () => observer.Values.Should().BeEquivalentTo(expectedSettings, options => options.WithStrictOrdering());

                    expectedSettings.Add(new Dictionary <string, int>());
                    assertion.ShouldPassIn(500.Milliseconds());

                    File.WriteAllText(temporaryFile.FileName, "{ 'a': 1 }");
                    expectedSettings.Add(new Dictionary <string, int> {
                        ["a"] = 1
                    });
                    assertion.ShouldPassIn(500.Milliseconds());

                    File.WriteAllText(temporaryFile.FileName, "error");
                    assertion.ShouldNotFailIn(500.Milliseconds());

                    File.WriteAllText(temporaryFile.FileName, "{ 'a': 2 }");
                    expectedSettings.Add(new Dictionary <string, int> {
                        ["a"] = 2
                    });
                    assertion.ShouldPassIn(500.Milliseconds());
                }
            }
        }
        public void SendErrorsToCallback_should_work_correctly([Values] bool hasError)
        {
            var errorCallback = Substitute.For <Action <Exception> >();
            var subject       = new Subject <(object, Exception)>();

            var testObserver = new TestObserver <object>();

            using (subject.SendErrorsToCallback(errorCallback).Subscribe(testObserver))
            {
                var settings = new object();
                var error    = hasError ? new Exception() : null;

                subject.OnNext((settings, error));


                if (hasError)
                {
                    errorCallback.Received(1).Invoke(error);
                    testObserver.Values.Should().BeEmpty();
                }
                else
                {
                    errorCallback.DidNotReceiveWithAnyArgs().Invoke(null);
                    testObserver.Values.Should().Equal(settings);
                }
            }
        }
Exemplo n.º 17
0
        public void Execute_WithThenActionWithError_ShouldCallOnNext(
            [Frozen(Matching.ImplementedInterfaces)] TestObserver <ActionNotification> observer,
            [Frozen] DateTimeOffset date,
            [Frozen] IMeasureDuration measureDuration,
            ReportingActor sut,
            ThenAction <object, string> thenAction,
            Exception error,
            TimeSpan expectedDuration
            )
        {
            //arrange
            Mock.Get(measureDuration).Setup(m => m.Measure(It.IsAny <Func <string> >()))
            .Returns((expectedDuration, null, error));
            //act
            try
            {
                sut.Execute(thenAction);
            }
            catch (Exception)
            {
            }
            //assert
            var expected = new[] {
                new ActionNotification(thenAction, 1, new BeforeThenNotificationContent(date, thenAction.Question)),
                new ActionNotification(thenAction, 1, new AfterThenNotificationContent(expectedDuration, ThenOutcome.Error, error))
            };

            observer.Values.Should().BeEquivalentTo(expected, o => o.RespectingRuntimeTypes().ComparingByMembers <ActionNotification>());
        }
Exemplo n.º 18
0
        public void Q7()
        {
            var observer = new TestObserver <int[]>();
            var subject1 = new Subject <int>();
            var subject2 = new Subject <int>();
            var subject3 = new Subject <int>();

            // Q. subject1, subject2, subject3 がすべてcompleteしたら、それぞれの最後の値を流すobservableは?
            var observable = (UniRx.IObservable <int[]>)null; // FIXME

            observable.Subscribe(observer);

            subject1.OnNext(1);
            subject2.OnNext(2);
            subject3.OnNext(3);
            subject3.OnNext(4);

            Assert.AreEqual(0, observer.CountNext);

            subject1.OnCompleted();
            subject2.OnCompleted();
            subject3.OnCompleted();

            Assert.AreEqual(1, observer.CountNext);
            Assert.AreEqual(new[] { 1, 2, 4 }, observer.NextList[0]);
        }
        public void Dulicate_message_is_detected()
        {
            var streamer = EnvelopeStreamer.CreateDefault(typeof(Message));

            var builder = new CqrsEngineBuilder(streamer);

            var cfg = new MemoryStorageConfig();

            var sender = cfg.CreateSimpleSender(streamer, "in");

            builder.Handle(cfg.CreateInbox("in"), envelope => Console.WriteLine("Got message"));

            var env = new EnvelopeBuilder("fixed ID").Build();

            using (var token = new CancellationTokenSource())
                using (var build = builder.Build())
                    using (TestObserver.When <EnvelopeDuplicateDiscarded>(discarded => token.Cancel()))
                    {
                        sender.SendBatch(new object[] { new Message() }, IdGeneration.HashContent);
                        sender.SendBatch(new object[] { new Message() }, IdGeneration.HashContent);
                        build.Start(token.Token);

                        if (Debugger.IsAttached)
                        {
                            token.Token.WaitHandle.WaitOne();
                        }
                        else
                        {
                            token.Token.WaitHandle.WaitOne(10000);
                        }

                        Assert.IsTrue(token.IsCancellationRequested);
                    }
        }
Exemplo n.º 20
0
        public void ValuedSubjectTest()
        {
            var tenseSubject  = new TenseSubject <int>();
            var tenseObserver = new TestObserver <Tuple <int, Tense> >();
            var testObserver  = new TestObserver <int>();

            tenseSubject.Subscribe(tenseObserver);
            tenseSubject.WhenDo().Subscribe(testObserver);
            tenseSubject.WhenWill().Subscribe(testObserver);
            tenseSubject.WhenDid().Subscribe(testObserver);

            tenseSubject.Do(4);

            Assert.AreEqual(4, tenseObserver.OnNextLastValue.Item1);
            Assert.AreEqual(Tense.Do, tenseObserver.OnNextLastValue.Item2);
            Assert.AreEqual(1, testObserver.OnNextCount);
            Assert.AreEqual(4, testObserver.OnNextLastValue);

            tenseSubject.Will(5);

            Assert.AreEqual(5, tenseObserver.OnNextLastValue.Item1);
            Assert.AreEqual(Tense.Will, tenseObserver.OnNextLastValue.Item2);
            Assert.AreEqual(2, testObserver.OnNextCount);
            Assert.AreEqual(5, testObserver.OnNextLastValue);

            tenseSubject.Did(6);

            Assert.AreEqual(6, tenseObserver.OnNextLastValue.Item1);
            Assert.AreEqual(Tense.Did, tenseObserver.OnNextLastValue.Item2);
            Assert.AreEqual(3, testObserver.OnNextCount);
            Assert.AreEqual(6, testObserver.OnNextLastValue);
        }
Exemplo n.º 21
0
        public async Task Server_ClientWebRepository_CommunicationValid()
        {
            using Server server = new Server(TEST_PORT, new DataRepository(), null);
            using AutoResetEvent
                  clientConnEvent    = new AutoResetEvent(false),
                  clientDisconnEvent = new AutoResetEvent(false);
            server.ServerWebSocketConnection.OnError           += (o, a) => Assert.Fail($"Server error! {a.Exception}");
            server.ServerWebSocketConnection.OnClientConnected += (o, a) => clientConnEvent.Set();
            server.ServerWebSocketConnection.OnClose           += (o, a) => clientDisconnEvent.Set();
            Task serverTask = Task.Run(server.RunServer);

            using (WebRepository client = new WebRepository())
            {
                Assert.IsTrue(await client.OpenRepository(ClientUtil.CreateLocalConnectionString(TEST_PORT)));
                Assert.IsTrue(clientConnEvent.WaitOne(TEST_TIMEOUT));
                Assert.AreEqual((await server.DataRepository.GetAllClients()).Count, (await client.GetAllClients()).Count);
                Assert.AreEqual((await server.DataRepository.GetAllProducts()).Count, (await client.GetAllProducts()).Count);
                Assert.AreEqual((await server.DataRepository.GetAllOrders()).Count, (await client.GetAllOrders()).Count);
                TestObserver testObserver = new TestObserver();
                using (IDisposable _ = server.DataRepository.Subscribe((IObserver <DataChanged <IClient> >)testObserver),
                       __ = server.DataRepository.Subscribe((IObserver <DataChanged <IProduct> >)testObserver))
                {
                    await client.RemoveClient((await client.GetAllClients()).First());

                    await client.RemoveProduct((await client.GetAllProducts()).First());
                }
                Assert.AreEqual(0, testObserver.ClientErrors.Count);
                Assert.AreEqual(0, testObserver.ProductErrors.Count);
                Assert.AreEqual(1, testObserver.ClientNext.Count);
                Assert.AreEqual(1, testObserver.ProductNext.Count);
                Assert.AreEqual(DataChangedAction.Remove, testObserver.ClientNext.Dequeue().Action);
                Assert.AreEqual(DataChangedAction.Remove, testObserver.ProductNext.Dequeue().Action);
            }
            Assert.IsTrue(clientDisconnEvent.WaitOne(TEST_TIMEOUT));
        }
        public void Fail_Multi_Error_Info()
        {
            var to = new TestObserver <int>();

            to.OnSubscribe(DisposableHelper.EMPTY);
            to.WithTag("Tag");

            try
            {
                to.AwaitDone(TimeSpan.FromMilliseconds(100));

                to.OnError(new NullReferenceException());

                to.OnError(new InvalidOperationException());

                to.AssertEmpty();

                Assert.Fail();
            }
            catch (Exception ex)
            {
                if (!ex.Message.StartsWith("Multiple errors"))
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 23
0
        public void SubjectTest()
        {
            var tenseSubject  = new TenseSubject();
            var tenseObserver = new TestObserver <Tense>();
            var testObserver  = new TestObserver <Unit>();

            tenseSubject.Subscribe(tenseObserver);
            tenseSubject.WhenDo().Subscribe(testObserver);
            tenseSubject.WhenWill().Subscribe(testObserver);
            tenseSubject.WhenDid().Subscribe(testObserver);

            tenseSubject.Do();

            Assert.AreEqual(Tense.Do, tenseObserver.OnNextLastValue);
            Assert.AreEqual(1, testObserver.OnNextCount);

            tenseSubject.Will();

            Assert.AreEqual(Tense.Will, tenseObserver.OnNextLastValue);
            Assert.AreEqual(2, testObserver.OnNextCount);

            tenseSubject.Did();

            Assert.AreEqual(Tense.Did, tenseObserver.OnNextLastValue);
            Assert.AreEqual(3, testObserver.OnNextCount);
        }
        public void Fail_Full_Info()
        {
            var to = new TestObserver <int>();

            to.OnSubscribe(DisposableHelper.EMPTY);
            to.WithTag("Tag");

            try
            {
                to.AwaitDone(TimeSpan.FromMilliseconds(100));

                to.OnCompleted();

                to.AssertEmpty();

                Assert.Fail();
            }
            catch (Exception ex)
            {
                if (!ex.Message.StartsWith("Unexpected"))
                {
                    throw ex;
                }
            }
        }
        public void Enumerable_Item_Longer()
        {
            var to = new TestObserver <List <int> >();

            to.OnNext(new List <int>()
            {
                1
            });

            try
            {
                to.AssertValuesOnly(new List <int>()
                {
                    1, 2
                });
                Assert.Fail();
            }
            catch (Exception ex)
            {
                if (!ex.Message.StartsWith("Item @ 0, more items expected"))
                {
                    throw ex;
                }
            }
        }
        public void Wrong_Enumerable()
        {
            var to = new TestObserver <List <int> >();

            to.OnNext(new List <int>()
            {
                1
            });

            try
            {
                to.AssertValuesOnly(new List <int>()
                {
                    2
                });
                Assert.Fail();
            }
            catch (Exception ex)
            {
                if (!ex.Message.StartsWith("Item @ 0/0 differ."))
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 27
0
        public void ObservableTest()
        {
            var property = new SubjectProperty <int>();
            var observer = new TestObserver <int>();

            property.Subscribe(observer);

            Assert.AreEqual(0, observer.OnNextCount);
            property.Value = 10;

            Assert.AreEqual(1, observer.OnNextCount);
            Assert.AreEqual(10, observer.OnNextLastValue);

            property.Value = 20;
            Assert.AreEqual(2, observer.OnNextCount);
            Assert.AreEqual(20, observer.OnNextLastValue);

            var observer2 = new TestObserver <int>();

            property.Subscribe(observer2);
            Assert.AreEqual(0, observer2.OnNextCount);

            property.Value = 30;
            Assert.AreEqual(1, observer2.OnNextCount);
            Assert.AreEqual(30, observer2.OnNextLastValue);
            Assert.AreEqual(3, observer.OnNextCount);
            Assert.AreEqual(30, observer.OnNextLastValue);
        }
Exemplo n.º 28
0
    // Static void method with same signature as "Main" is always
    // file base name:
    //
    /// <summary>
    /// VTK test Main method
    /// </summary>
    public static void vtkCommandTest(string[] args)
    {
        // Create an object to send an event:
        //
        Kitware.VTK.vtkObject sender = new Kitware.VTK.vtkObject();

        // Create an event observer:
        //
        TestObserver observer = new TestObserver();

        // Connect them:
        //
        uint observerModifiedEventTag = sender.AddObserver(
          (uint) Kitware.VTK.vtkCommand.EventIds.ModifiedEvent, observer, 0.69f);

        // Trigger the event:
        //
        sender.Modified();

        // Toggle Debug, trigger event again, then turn off Debug before objects are destroyed...
        //
        sender.SetDebug((byte)((0 == sender.GetDebug()) ? 1 : 0));
        sender.Modified();
        sender.DebugOff();

        // Disconnect them:
        //
        sender.RemoveObserver(observerModifiedEventTag);
    }
Exemplo n.º 29
0
        public void Action_Dispose()
        {
            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                var cs = new CompletableSubject();

                var to = new TestObserver <object>();

                var cdl = new CountdownEvent(1);

                Task.Factory.StartNew(() =>
                {
                    while (!cs.HasObserver())
                    {
                        ;
                    }
                    to.Dispose();
                    cdl.Signal();
                });

                cs.BlockingSubscribe(to.OnCompleted, to.OnError, to.OnSubscribe);

                cdl.Wait();

                Assert.False(cs.HasObserver());
            }
        }
Exemplo n.º 30
0
        public void Poll_GeneratesExpectedEvents()
        {
            var source   = new CLRRuntimeSource();
            var listener = source.Source as DiagnosticListener;

            var options  = new MetricsEndpointOptions();
            var stats    = new OpenCensusStats();
            var tags     = new OpenCensusTags();
            var observer = new TestObserver(options, stats, tags, null);

            listener.Subscribe(observer);

            source.Poll();

            Assert.Equal(2, observer.Events.Count);
            Assert.Equal(2, observer.Args.Count);

            Assert.Equal(CLRRuntimeSource.HEAP_EVENT, observer.Events[0]);
            Assert.Equal(CLRRuntimeSource.THREADS_EVENT, observer.Events[1]);

            var heapMetrics = (CLRRuntimeSource.HeapMetrics)observer.Args[0];

            Assert.NotEqual(0, heapMetrics.TotalMemory);
            Assert.NotNull(heapMetrics.CollectionCounts);
            Assert.NotEqual(0, heapMetrics.CollectionCounts.Count);

            var threadMetrics = (CLRRuntimeSource.ThreadMetrics)observer.Args[1];

            Assert.NotEqual(0, threadMetrics.AvailableThreadCompletionPort);
            Assert.NotEqual(0, threadMetrics.AvailableThreadPoolWorkers);
            Assert.NotEqual(0, threadMetrics.MaxThreadCompletionPort);
            Assert.NotEqual(0, threadMetrics.MaxThreadPoolWorkers);
        }
        public void Race_While()
        {
            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                var us = new MonocastSubject <int>();

                var to = new TestObserver <int>();

                TestHelper.Race(() =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        us.OnNext(j);
                    }
                    us.OnCompleted();
                },
                                () =>
                {
                    us.BlockingSubscribeWhile(v =>
                    {
                        to.OnNext(v);
                        return(true);
                    }, to.OnError, to.OnCompleted);
                });

                to.AssertValueCount(1000)
                .AssertNoError()
                .AssertCompleted();
            }
        }
Exemplo n.º 32
0
        public void A4()
        {
            var testObserver1 = new TestObserver <int>();
            var testObserver2 = new TestObserver <int>();

            // A.
            var observableAndObserver = new AsyncSubject <int>();

            // SUBSCRIBE
            ((IObserver <int>)observableAndObserver).OnNext(1);
            observableAndObserver.Subscribe(testObserver1);

            ((IObserver <int>)observableAndObserver).OnNext(2);
            ((IObserver <int>)observableAndObserver).OnCompleted();
            observableAndObserver.Subscribe(testObserver2);

            // CHECK
            Assert.AreEqual(1, testObserver1.CountNext);
            Assert.AreEqual(2, testObserver1.NextList[0]);
            Assert.AreEqual(1, testObserver1.CountComplete);

            Assert.AreEqual(1, testObserver1.CountNext);
            Assert.AreEqual(2, testObserver1.NextList[0]);
            Assert.AreEqual(1, testObserver1.CountComplete);
        }
Exemplo n.º 33
0
        public void A2()
        {
            var testObserver1 = new TestObserver <int>();
            var testObserver2 = new TestObserver <int>();

            // A.
            var observableAndObserver = new BehaviorSubject <int>(1);

            var disposable1 = observableAndObserver.Subscribe(testObserver1);

            ((IObserver <int>)observableAndObserver).OnNext(2);
            disposable1.Dispose();

            var disposable2 = observableAndObserver.Subscribe(testObserver2);

            ((IObserver <int>)observableAndObserver).OnNext(3);
            disposable2.Dispose();

            // CHECK
            Assert.AreEqual(2, testObserver1.CountNext);
            Assert.AreEqual(1, testObserver1.NextList[0]);
            Assert.AreEqual(2, testObserver1.NextList[1]);

            Assert.AreEqual(2, testObserver2.CountNext);
            Assert.AreEqual(2, testObserver2.NextList[0]);
            Assert.AreEqual(3, testObserver2.NextList[1]);
        }
        public void Race()
        {
            for (int i = 0; i < TestHelper.RACE_LOOPS; i++)
            {
                var us = new MonocastSubject <int>();

                var to = new TestObserver <int>();

                TestHelper.Race(() =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        us.OnNext(j);
                    }
                    us.OnCompleted();
                },
                                () =>
                {
                    foreach (var v in us.BlockingEnumerable())
                    {
                        to.OnNext(v);
                    }
                    to.OnCompleted();
                });

                to.AssertValueCount(1000)
                .AssertNoError()
                .AssertCompleted();
            }
        }
Exemplo n.º 35
0
        public void An_ObservableSink_subscriber_must_be_disposable()
        {
            var probe = new TestObserver <int>(this);
            var tuple = Source.Queue <int>(1, OverflowStrategy.DropHead)
                        .ToMaterialized(Sink.AsObservable <int>(), Keep.Both)
                        .Run(Materializer);
            var queue      = tuple.Item1;
            var observable = tuple.Item2;

            var d1 = observable.Subscribe(probe);

            var t = queue.OfferAsync(1);

            t.Wait(TimeSpan.FromSeconds(1)).ShouldBeTrue();
            t.Result.ShouldBe(QueueOfferResult.Enqueued.Instance);

            probe.ExpectEvent(1);

            t = queue.OfferAsync(2);
            t.Wait(TimeSpan.FromSeconds(1)).ShouldBeTrue();
            t.Result.ShouldBe(QueueOfferResult.Enqueued.Instance);

            probe.ExpectEvent(2);

            d1.Dispose();

            t = queue.OfferAsync(3);
            t.Wait(TimeSpan.FromSeconds(1)).ShouldBeTrue();

            probe.ExpectCompleted();
            probe.ExpectNoMsg();
        }
Exemplo n.º 36
0
        private static void TestRead()
        {
            //var testObserver = GrainClient.GrainFactory.GetGrain<ITestObserver>(0);
            var testObserver = new TestObserver();

            testObserver = new TestObserver();
            testObserver.Subscribe(true).Wait();
        }
Exemplo n.º 37
0
        protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            _observer = GetObserver<A>();

            configurator.Observer(_observer);

            configurator.Observer(Observer.Create<ConsumeContext<A>>(m => Console.WriteLine(m.Message.Name)));
        }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            // Retry till connected
            while (true)
            {
                try
                {
                    GrainClient.Initialize();
                    break;
                }
                catch (Exception)
                {
                    Task.Delay(500).Wait();
                }
            }
            // Delay
            Console.WriteLine("Waiting");
            Task.Delay(2000).Wait();
            Console.WriteLine("Starting");

            // Test: repeat till problem occurs

            var list = new List<TestObserver>();


            while (true)
            {
                var testObserver = new TestObserver();
                list.Add(testObserver);
                testObserver.Subscribe().Wait();
                var received = false;
                // wait for client to receive message
                for (int i = 0; i < 1000; i++)
                {
                    if (testObserver.ReceivedMessage)
                    {
                        received = true;
                        break;
                    }
                    Task.Delay(5).Wait();
                }
                //testObserver.Unsubscribe().Wait();
                if (!received)
                {
                    Console.WriteLine("Client did not receive the message.");
                    break;
                }

                Task.Delay(1500).Wait();
            }

            Console.ReadLine();
        }
Exemplo n.º 39
0
        public void CanObserveTestRunner()
        {
            var setUpCounter = 0;
            var testCounter = 0;
            var tearDownCounter = 0;
            const int Start = 0;
            const int Step = 7;
            const int End = 135;
            const string MailBoxName = "box";

            using (var mailBox = new ProcessMailBox(MailBoxName, TimeSpan.FromMilliseconds(-1)))
            {
                using (var observer = new TestObserver(MailBoxName))
                {
                    var list = new List<PerfTestResult>();
                    var runner = new TestRunner(i => setUpCounter++, () => testCounter++, () => tearDownCounter++, i => i / 2d, Start, Step, End);

                    var taskObserve = Task.Factory.StartNew(
                        () =>
                        {
                            runner.Subscribe(observer);
                        });

                    var taskMailBox = Task.Factory.StartNew(
                        () =>
                        {
                            for (int i = Start; i < End; i += Step)
                            {
                                list.Add((PerfTestResult)mailBox.Content);
                            }
                        });

                    Task.WaitAll(new[] { taskObserve, taskMailBox }, TimeSpan.FromSeconds(20)).Should().BeTrue();

                    var count = (int)Math.Ceiling((End - Start + 1) / (double)Step);
                    setUpCounter.Should().Be(count);
                    testCounter.Should().Be(count);
                    tearDownCounter.Should().Be(count);

                    var index = 0;
                    for (var i = Start; i < End; i += Step)
                    {
                        list[index++].Descriptor.Should().Be(i / 2d);
                    }
                }
            }
        }
Exemplo n.º 40
0
        public void Activator_And_Should_Follow_Single_Input()
        {
            var inputs = new[] { new TestSubject<bool>(false) };
            var target = new StyleActivator(inputs, ActivatorMode.And);
            var result = new TestObserver<bool>();

            target.Subscribe(result);
            Assert.False(result.GetValue());
            inputs[0].OnNext(true);
            Assert.True(result.GetValue());
            inputs[0].OnNext(false);
            Assert.False(result.GetValue());
            inputs[0].OnNext(true);
            Assert.True(result.GetValue());

            Assert.Equal(1, inputs[0].SubscriberCount);
        }
Exemplo n.º 41
0
        public void Activator_And_Should_Not_Unsubscribe_All_When_Input_Completes_On_True()
        {
            var inputs = new[]
            {
                new TestSubject<bool>(false),
                new TestSubject<bool>(false),
                new TestSubject<bool>(true),
            };
            var target = new StyleActivator(inputs, ActivatorMode.And);
            var result = new TestObserver<bool>();

            target.Subscribe(result);
            Assert.False(result.GetValue());
            inputs[0].OnNext(true);
            inputs[0].OnCompleted();

            Assert.Equal(1, inputs[0].SubscriberCount);
            Assert.Equal(1, inputs[1].SubscriberCount);
            Assert.Equal(1, inputs[2].SubscriberCount);
        }
Exemplo n.º 42
0
        public static void Start(StartParameters startParameters)
        {
            using (var testObserver = new TestObserver(startParameters.ChannelName))
            {
                var suite = AssemblyLoader.CreateInstance<PerfTestSuite>(
                    startParameters.SuiteAssembly, startParameters.SuiteType);

                var subject = AssemblyLoader.CreateInstanceFullyQualifiedName(
                    startParameters.SubjectAssembly, startParameters.SubjectType);

                var start = startParameters.Start;
                var step = startParameters.Step;
                var end = startParameters.End;

                if (suite != null && subject != null)
                {
                    var test = suite.Tests.First(x => x.TestMethodName == startParameters.TestMethod && x.TestedType == subject.GetType());

                    PerfTestResultFactory.Instance.Init(test.TestId);

                    var runner = new TestRunner(
                        delegate(int idx) { suite.SetUp(idx, subject); },
                        delegate { test.Test(subject); },
                        delegate { suite.TearDown(subject); },
                        delegate(int idx) { return suite.GetRunDescriptor(idx); },
                        string.IsNullOrEmpty(start) ? 0 : int.Parse(start),
                        string.IsNullOrEmpty(step) ? 1 : int.Parse(step),
                        string.IsNullOrEmpty(end) ? suite.DefaultTestCount : int.Parse(end),
                        startParameters.IgnoreFirstRunDueToJITting,
                        startParameters.TriggerGCBeforeEachTest);

                    runner.Subscribe(testObserver);
                    testObserver.OnCompleted();
                }
                else
                {
                    testObserver.OnError(new Exception());
                }
            }
        }
Exemplo n.º 43
0
        public void Activator_And_Should_AND_Multiple_Inputs()
        {
            var inputs = new[]
            {
                new TestSubject<bool>(false),
                new TestSubject<bool>(false),
                new TestSubject<bool>(true),
            };
            var target = StyleActivator.And(inputs);
            var result = new TestObserver<bool>();

            target.Subscribe(result);
            Assert.False(result.GetValue());
            inputs[0].OnNext(true);
            inputs[1].OnNext(true);
            Assert.True(result.GetValue());
            inputs[0].OnNext(false);
            Assert.False(result.GetValue());

            Assert.Equal(1, inputs[0].SubscriberCount);
            Assert.Equal(1, inputs[1].SubscriberCount);
            Assert.Equal(1, inputs[2].SubscriberCount);
        }
Exemplo n.º 44
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    GrainClient.Initialize();
                    break;
                }
                catch (Exception)
                {
                    Task.Delay(500).Wait();
                }
            }

            Console.WriteLine("Waiting");
            Task.Delay(2000).Wait();
            Console.WriteLine("Starting");
            //var testObserver = GrainClient.GrainFactory.GetGrain<ITestObserver>(0);
            var testObserver = new TestObserver();
            testObserver.Subscribe().Wait();

            Console.ReadLine();
        }
        public async Task Test_Observer_Succeed()
        {
            var userLogin = _actorBoundChannel.CreateRef<UserLoginRef>();
            var observer = new TestObserver();

            var user = await userLogin.Login(
                "test", "test", _actorBoundChannel.CreateObserver<IUserObserver>(observer));
            await user.Say("Hello");

            Assert.Equal(new[] { "Hello" }, observer.Messages);
        }
        public static void GetInstanceASync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            // Check Arguments
            if (cimNamespace == null)
            {
                throw new ArgumentNullException("cimNamespace");
            }

            if (cimClassName == null)
            {
                throw new ArgumentNullException("cimClassName");
            }

            try
            {
                CimInstance inputInstance = GetInstanceCore(cimSession, cimNamespace, cimClassName);
                IObservable<CimInstance> enumeratedInstances = cimSession.GetInstanceAsync(cimNamespace, inputInstance, GetOperationOptions());
                TestObserver<CimInstance> observer = new TestObserver<CimInstance>();
                IDisposable disposeable = enumeratedInstances.Subscribe(observer);
                observer.WaitForCompletion();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch( Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }
 public static void QueryInstanceASync(CimSession cimSession, string cimNamespace)
 {
     try
     {
         string query = QueryInstanceCore();
         IObservable<CimInstance> queryInstances = cimSession.QueryInstancesAsync(cimNamespace, "WQL", query, GetOperationOptions());
         TestObserver<CimInstance> observer = new TestObserver<CimInstance>();
         IDisposable disposeable = queryInstances.Subscribe(observer);
         observer.WaitForCompletion();
     }
     catch (CimException ex)
     {
         PrintCimException(ex);
     }
     catch( Exception ex)
     {
         Console.WriteLine(ex.Message);
     }            
 }
        public static void EnumerateAssociatedInstanceASync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            try
            {
                string resultClassName;
                string associationClassName;
                CimInstance associatedInputInstance = EnumerateAssociatedInstanceCore(
                    cimSession, 
                    cimNamespace, 
                    cimClassName,
                    out associationClassName, 
                    out resultClassName);
                if (associatedInputInstance == null)
                {
                    Console.WriteLine("EnumerateAssociatedInstanceSync operation not performed");
                    return;
                }

                IObservable<CimInstance> enumeratedInstances = cimSession.EnumerateAssociatedInstancesAsync(
                    cimNamespace, 
                    associatedInputInstance,
                    associationClassName, 
                    resultClassName, 
                    null, 
                    null,
                    GetOperationOptions());
                TestObserver<CimInstance> observer = new TestObserver<CimInstance>();
                IDisposable disposeable = enumeratedInstances.Subscribe(observer);
                observer.WaitForCompletion();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch( Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }
        public static void InvokeMethodASync(CimSession cimSession, string cimNamespace, string cimClassName)
        {
            try
            {
                string methodName;
                CimInstance inputInstance;
                CimMethodParametersCollection methodParameters = InvokeMethodCore(cimSession, cimNamespace, cimClassName, out methodName, out inputInstance);
                if (methodParameters == null)
                {
                    Console.WriteLine("Operation InvokeMethod not performed");
                    return;
                }

                CimAsyncMultipleResults<CimMethodResultBase> invokeParams;
                CimOperationOptions options = GetOperationOptions();
                options.EnableMethodResultStreaming = true;
                if (inputInstance == null)
                {
                    invokeParams = cimSession.InvokeMethodAsync(cimNamespace, cimClassName, methodName, methodParameters, options);
                }
                else
                {
                    invokeParams = cimSession.InvokeMethodAsync(cimNamespace, inputInstance, methodName, methodParameters, options);
                }

                TestObserver<CimMethodResultBase> observer = new TestObserver<CimMethodResultBase>();
                IDisposable disposeable = invokeParams.Subscribe(observer);
                observer.WaitForCompletion();
            }
            catch (CimException ex)
            {
                PrintCimException(ex);
            }
            catch( Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
        }