Esempio n. 1
0
        static void Main(string[] args)
        {
            // Optional: increases verbosity level to see the P# runtime log.
            var configuration = Configuration.Create().WithVerbosityEnabled(2);

            // Creates a new P# runtime instance, and passes an optional configuration.
            var runtime = PSharpRuntime.Create(configuration);

            // Creates and installs a custom logger.
            ILogger myLogger = new MyLogger();

            runtime.SetLogger(myLogger);

            // Executes the P# program.
            Program.Execute(runtime);

            // Disposes the logger and removes it from the runtime.
            myLogger.Dispose();
            runtime.RemoveLogger();

            // The P# runtime executes asynchronously, so we wait
            // to not terminate the process.
            Console.WriteLine("Press Enter to terminate...");
            Console.ReadLine();
        }
        public void Context_should_return_same_Machine_if_it_is_in_local_and_single_application()
        {
            // Arrange
            var ctx      = default(DistributedStorageContext);
            var expected = default(int);
            var actual   = default(int);

            // Act
            {
                var configuration = Configuration.Create();
                var runtime       = PSharpRuntime.Create(configuration);
                var runtimeHost   = HostInfo.NewRuntimeHost(runtime);

                ctx        = runtimeHost.New <DistributedStorageContext>();
                ctx.Server = runtimeHost.New(MachineInterface.Sender <IServerSender>().Bundler <IServerBundler>().Receiver <ServerReceiverWithoutBug>());
                expected   = RuntimeHelpers.GetHashCode(ctx.Server);
            }

            {
                actual = RuntimeHelpers.GetHashCode(ctx.Server);
            }


            // Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 3
0
        public void TestNoMemoryLeakAfterHalt()
        {
            var runtime = PSharpRuntime.Create();

            Program.Execute(runtime);
            runtime.Wait();
        }
Esempio n. 4
0
        public void TestProcessedOrDropped()
        {
            var config = Configuration.Create();

            config.EnableMonitorsInProduction = true;

            var runtime = PSharpRuntime.Create(config);
            var tcs     = new TaskCompletionSource <bool>();

            runtime.RegisterMonitor(typeof(Monitor3));
            runtime.InvokeMonitor(typeof(Monitor3), new E(tcs));

            runtime.OnFailure += delegate
            {
                Assert.True(false);
                tcs.SetResult(false);
            };

            runtime.OnEventDropped += delegate(Event e, MachineId target)
            {
                runtime.InvokeMonitor(typeof(Monitor3), new EventDropped());
            };

            var m = runtime.CreateMachine(typeof(M3c));

            runtime.CreateMachine(typeof(M3a), new E(m));
            runtime.CreateMachine(typeof(M3b), new E(m));
            tcs.Task.Wait(5000);
        }
        static string StartClients(string sctx, SynchronizedLogger logger, out DomainCommunicationProvider clientsNetworkProvider)
        {
            var configuration = Configuration.Create().WithMonitorsInProductionEnabled().WithVerbosityEnabled(2);
            var runtime       = PSharpRuntime.Create(configuration);
            var runtimeHost   = HostInfo.NewRuntimeHost(runtime);

            clientsNetworkProvider = new DomainCommunicationProvider(runtimeHost, "clients");
            runtimeHost.SetNetworkProvider(clientsNetworkProvider);
            runtimeHost.SetLogger(logger);

            var messages = new MessageCollection();

            messages.CollectionChanged += (sender, e) => logger.WriteLine(e.NewItems[0].ToString());
            var ctx = sctx.FromJson <DistributedStorageContext>();

            var synchronizable = Synchronizable.Empty();

            foreach (var storageNode in ctx.StorageNodes)
            {
                var waitIfHandledReplReq = logger.MachineActionHandledWait((machineId, _, actionName) => Equals(machineId, storageNode.Id) && actionName == "HandleReplReq");
                synchronizable = synchronizable.Then(waitIfHandledReplReq.Delay(10));
            }
            logger.ApplySynchronization(synchronizable);

            NewClients(runtimeHost, ctx, messages);
            logger.WaitForWriting(6000);
            return(ctx.ToJson());
        }
        public void Machine_can_be_created_faster_than_the_first_time()
        {
            AppDomain.CurrentDomain.RunAtIsolatedDomain(() =>
            {
                // Arrange
                var configuration = Configuration.Create();
                var runtime       = PSharpRuntime.Create(configuration);
                var runtimeHost   = HostInfo.NewRuntimeHost(runtime);


                // Act
                var sw1 = Stopwatch.StartNew();
                runtimeHost.New(MachineInterface.Sender <IServerSender>().Bundler <IServerBundler>().Receiver <ServerReceiverWithoutBug>());
                var elapsed1 = sw1.ElapsedTicks;

                var sw10 = Stopwatch.StartNew();
                for (var i = 0; i < 10; i++)
                {
                    runtimeHost.New(MachineInterface.Sender <IServerSender>().Bundler <IServerBundler>().Receiver <ServerReceiverWithoutBug>());
                }
                var elapsed10 = sw10.ElapsedTicks;


                // Assert
                Assert.Less(elapsed10, elapsed1 / 10);
            });
        }
        public void Monitor_should_not_notify_safety_bug_if_it_is_not_existing()
        {
            // Arrange
            var configuration = Configuration.Create().WithMonitorsInProductionEnabled();
            var runtime       = PSharpRuntime.Create(configuration);
            var runtimeHost   = HostInfo.NewRuntimeHost(runtime);
            var safetyMonitor = runtimeHost.New(MonitorInterface.Sender <ISafetyMonitorSender>().Bundler <ISafetyMonitorBundler>().Receiver <SafetyMonitorReceiver>());


            // Act
            var messages = new MessageCollection();

            safetyMonitor.Configure(new ConfigureSafetyMonitor(messages));

            var storageNodeId   = runtime.NewMachine(typeof(StorageNode));
            var storageNodeMock = new Mock <IStorageNodeSender>();

            storageNodeMock.SetupGet(_ => _.Id).Returns(storageNodeId);
            safetyMonitor.Handshake(new HandshakeSafetyMonitor(new[] { storageNodeMock.Object }));

            safetyMonitor.LogUpdated(new LogUpdated(storageNodeMock.Object, 42));


            // Assert
            Assert.DoesNotThrow(() => safetyMonitor.Ack(new Ack()));
        }
Esempio n. 8
0
        public void TestUnhandledExceptionEventHandler()
        {
            var  tcsFail            = new TaskCompletionSource <bool>();
            int  count              = 0;
            bool sawFilterException = false;

            PSharpRuntime runtime = PSharpRuntime.Create();

            runtime.OnFailure += delegate(Exception exception)
            {
                // This test throws an exception that we should receive a filter call for
                if (exception is MachineActionExceptionFilterException)
                {
                    sawFilterException = true;
                    return;
                }
                count++;
                tcsFail.SetException(exception);
            };

            var tcs = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(N), new Configure(tcs));
            tcs.Task.Wait();
            Task.Delay(10).Wait(); // give it some time

            AggregateException ex = Assert.Throws <AggregateException>(() => tcsFail.Task.Wait());

            Assert.IsType <AssertionFailureException>(ex.InnerException);
            Assert.IsType <InvalidOperationException>(ex.InnerException.InnerException);
            Assert.Equal(1, count);
            Assert.True(sawFilterException);
        }
Esempio n. 9
0
        public void TestAssertFailureEventHandler()
        {
            var tcsFail = new TaskCompletionSource <bool>();
            int count   = 0;

            PSharpRuntime runtime = PSharpRuntime.Create();

            runtime.OnFailure += delegate(Exception exception)
            {
                if (!(exception is MachineActionExceptionFilterException))
                {
                    count++;
                    tcsFail.SetException(exception);
                }
            };

            var tcs = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(M), new Configure(tcs));
            tcs.Task.Wait();
            Task.Delay(10).Wait(); // give it some time

            AggregateException ex = Assert.Throws <AggregateException>(() => tcsFail.Task.Wait());

            Assert.IsType <AssertionFailureException>(ex.InnerException);
            Assert.Equal(1, count);
        }
        public void TestCreateWithId5()
        {
            var r      = PSharpRuntime.Create();
            var failed = false;
            var tcs    = new TaskCompletionSource <bool>();

            r.OnFailure += delegate
            {
                failed = true;
                tcs.SetResult(false);
            };

            try
            {
                var m1 = r.CreateMachineIdFromName(typeof(M2), "M2");
                r.CreateMachine(m1, typeof(M2));
                r.CreateMachine(m1, typeof(M2));
            }
            catch (Exception)
            {
                failed = true;
                tcs.SetResult(false);
            }

            tcs.Task.Wait();
            Assert.True(failed);
        }
Esempio n. 11
0
        protected async Task RunAsync(Func <IMachineRuntime, Task> test, Configuration configuration = null)
        {
            configuration = configuration ?? GetConfiguration();

            ILogger logger;

            if (configuration.IsVerbose)
            {
                logger = new TestOutputLogger(this.TestOutput, true);
            }
            else
            {
                logger = new NulLogger();
            }

            try
            {
                var runtime = PSharpRuntime.Create(configuration);
                runtime.SetLogger(logger);
                await test(runtime);
            }
            catch (Exception ex)
            {
                Assert.False(true, ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                logger.Dispose();
            }
        }
Esempio n. 12
0
        public static void Main(String[] args)
        {
            var runtime = PSharpRuntime.Create();

            Program.Execute(runtime);
            Console.ReadLine();
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var runtime = PSharpRuntime.Create();

            Test.Execute(runtime);
            Console.ReadLine();
        }
        public void TestNoMemoryLeakInEventSending()
        {
            var runtime = PSharpRuntime.Create();

            Program.Execute(runtime);
            runtime.Wait();
        }
Esempio n. 15
0
        public void Monitor_should_notify_safety_bug_if_it_is_existing()
        {
            // Arrange
            var configuration = Configuration.Create().WithMonitorsInProductionEnabled();
            var runtime       = PSharpRuntime.Create(configuration);
            var runtimeHost   = HostInfo.NewRuntimeHost(runtime);
            var safetyMonitor = runtimeHost.New(MonitorInterface.Sender <ISafetyMonitorSender>().Bundler <ISafetyMonitorBundler>().Receiver <SafetyMonitorReceiver>());


            // Act
            var messages = new MessageCollection();

            safetyMonitor.Configure(new ConfigureSafetyMonitor(messages));

            var storageNodeId   = runtime.NewMachine(typeof(StorageNode));
            var storageNodeMock = new Mock <IStorageNodeSender>();

            storageNodeMock.SetupGet(_ => _.Id).Returns(storageNodeId);
            safetyMonitor.Handshake(new HandshakeSafetyMonitor(new[] { storageNodeMock.Object }));


            // Assert
            var expectedExType = typeof(PSharpRuntime).Assembly.GetTypes().First(_ => _.FullName == "Microsoft.PSharp.AssertionFailureException");

            Assert.Throws(expectedExType, () => safetyMonitor.Ack(new Ack()));
        }
Esempio n. 16
0
        public void Context_should_return_same_Machine_if_it_is_in_remote_and_single_application()
        {
            // Arrange
            var expected  = default(int);
            var actual    = default(int);
            var parameter = default(string);

            // Act
            {
                var configuration = Configuration.Create();
                var runtime       = PSharpRuntime.Create(configuration);
                var runtimeHost   = HostInfo.NewRuntimeHost(runtime);

                var ctx = runtimeHost.New <DistributedStorageContext>();
                ctx.Server = runtimeHost.New(MachineInterface.Sender <IServerSender>().Bundler <IServerBundler>().Receiver <ServerReceiverWithoutBug>());
                expected   = RuntimeHelpers.GetHashCode(ctx.Server);
                parameter  = ctx.ToJson();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            {
                var ctx = parameter.FromJson <DistributedStorageContext>();
                actual = RuntimeHelpers.GetHashCode(ctx.Server);
            }


            // Assert
            Assert.AreEqual(expected, actual);
        }
Esempio n. 17
0
        public void TestNullCustomLoggerFail()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();

            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => runtime.SetLogger(null));

            Assert.Equal("Cannot install a null logger.", ex.Message);
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            var configuration = Configuration.Create().WithVerbosityEnabled(1);
            var runtime       = PSharpRuntime.Create(configuration);

            Execute(runtime);
            Console.ReadLine();
        }
Esempio n. 19
0
        public void TestAssertFailureNoEventHandler()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();
            var           tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(M), new Configure(tcs));
            tcs.Task.Wait();
        }
        public void TestCreateWithId9()
        {
            var r  = PSharpRuntime.Create();
            var m1 = r.CreateMachineIdFromName(typeof(M4), "M4");
            var m2 = r.CreateMachineIdFromName(typeof(M4), "M4");

            Assert.True(m1.Equals(m2));
        }
Esempio n. 21
0
        public async Task TestAssertFailureNoEventHandler()
        {
            var runtime = PSharpRuntime.Create();
            var tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(M), new Configure(tcs));
            await tcs.Task;
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var runtime = PSharpRuntime.Create();

            TestAdd.Execute(runtime);

            Console.WriteLine("Unit test is running.\nPress Enter to terminate...");
            Console.ReadLine();
        }
Esempio n. 23
0
        public void TestNoMemoryLeakAfterHalt()
        {
            var tcs     = new TaskCompletionSource <bool>();
            var runtime = PSharpRuntime.Create();

            runtime.CreateMachine(typeof(M), new Configure(tcs));
            tcs.Task.Wait();
            runtime.Stop();
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            var configuration = Configuration.Create().WithVerbosityEnabled(2);
            var runtime       = PSharpRuntime.Create(configuration);

            Program.Execute(runtime);
            Console.WriteLine("Press Enter to terminate...");
            Console.ReadLine();
        }
Esempio n. 25
0
        public async Task BasicSingleTimerOperationTest()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();
            var           tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(T1), new Configure(tcs, false));
            var result = await tcs.Task;

            Assert.True(result);
        }
Esempio n. 26
0
        public async Task InboxFlushOperationTest()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();
            var           tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(FlushingClient), new Configure(tcs, true));
            var result = await tcs.Task;

            Assert.True(result);
        }
Esempio n. 27
0
        public async Task IllegalTimerStoppageTest()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();
            var           tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(T2), new Configure(tcs, true));
            var result = await tcs.Task;

            Assert.True(result);
        }
Esempio n. 28
0
        public async Task IllegalPeriodSpecificationTest()
        {
            PSharpRuntime runtime = PSharpRuntime.Create();
            var           tcs     = new TaskCompletionSource <bool>();

            runtime.CreateMachine(typeof(T4), new ConfigureWithPeriod(tcs, -1));
            var result = await tcs.Task;

            Assert.True(result);
        }
Esempio n. 29
0
File: Test.cs Progetto: p-org/PSharp
        static void Main(string[] args)
        {
            var runtime = PSharpRuntime.Create();

            // Create a machine.
            var mid = runtime.CreateMachine(typeof(M1));

            // Do some work.
            runtime.SendEvent(mid, new M1.Inc());
            runtime.SendEvent(mid, new M1.Inc());
            runtime.SendEvent(mid, new M1.Inc());

            // Grab the result from the machine.
            GetDataAndPrint(runtime, mid).Wait();
        }
Esempio n. 30
0
        public static void Main(string[] args)
        {
            // Optional: increases verbosity level to see the P# runtime log.
            var configuration = Configuration.Create().WithVerbosityEnabled(2);

            // Creates a new P# runtime instance, and passes an optional configuration.
            var runtime = PSharpRuntime.Create(configuration);

            // Executes the P# program.
            DefaultImpl.Execute(runtime);

            // The P# runtime executes asynchronously, so we wait
            // to not terminate the process.
            Console.WriteLine("Press Enter to terminate...");
        }