Ejemplo n.º 1
0
        private void RunLoggerPerfTest(string testName, int n, int logCode, TimeSpan target, Logger logger)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            for (int i = 0; i < n; i++)
            {
                logger.Warn(logCode, "msg " + i);
            }
            var    elapsed = stopwatch.Elapsed;
            string msg     = testName + " : Elapsed time = " + elapsed;

            // Wait until the BulkMessageInterval time interval expires before wring the final log message - should cause bulk message flush
            while (stopwatch.Elapsed <= LogManager.BulkMessageInterval)
            {
                Thread.Sleep(10);
            }

            output.WriteLine(msg);
            logger.Info(logCode, msg);
            Assert.IsTrue(elapsed < target.Multiply(timingFactor), "{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target);
        }
Ejemplo n.º 2
0
        public void PermutationOrder()
        {
            Random rng = new Random(37498327);

            for (int i = 0; i < 16; i++)
            {
                int         n = rng.Next(1, 16);
                Permutation p = Permutation.GetRandomPermutation(n, rng);

                int order = (int)p.Order;
                Assert.IsTrue(order > 0);

                Permutation q = p;
                for (int j = 1; j < order; j++)
                {
                    q *= p;
                }
                Assert.IsTrue(q.IsIdentity);

                Console.WriteLine("{0} {1} {2}", p.ToString("M"), p.ToString("C"), order);
            }
        }
Ejemplo n.º 3
0
        public void DistributionMomentTranslations()
        {
            int n = 4;

            foreach (ContinuousDistribution distribution in distributions)
            {
                if (Double.IsNaN(distribution.Mean))
                {
                    continue;
                }
                Console.Write(distribution.GetType().Name);

                // Convert central moments to raw moments
                double[] centralInputs = new double[n];
                for (int k = 0; k < n; k++)
                {
                    centralInputs[k] = distribution.CentralMoment(k);
                }
                double[] rawOutputs = MomentMath.CentralToRaw(distribution.Mean, centralInputs);
                Assert.IsTrue(rawOutputs.Length == n);
                for (int k = 0; k < n; k++)
                {
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(rawOutputs[k], distribution.RawMoment(k)));
                }

                // Convert cumulants to central moments
                double[] cumulantInputs = new double[n];
                for (int k = 0; k < n; k++)
                {
                    cumulantInputs[k] = distribution.Cumulant(k);
                }
                double[] centralOutputs = MomentMath.CumulantToCentral(cumulantInputs);
                Assert.IsTrue(centralOutputs.Length == n);
                for (int k = 0; k < n; k++)
                {
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(centralOutputs[k], distribution.CentralMoment(k)));
                }
            }
        }
Ejemplo n.º 4
0
        public void SerializationOrder_VerifyThatExternalIsHigherPriorityThanAttributeDefined()
        {
            FakeSerializer1.SupportedTypes = FakeSerializer2.SupportedTypes = new[] { typeof(FakeTypeToSerialize) };
            var serializationItem = new FakeTypeToSerialize {
                SomeValue = 1
            };

            SerializationManager.RoundTripSerializationForTesting(serializationItem);

            Assert.IsTrue(
                FakeSerializer1.SerializeCalled,
                "IExternalSerializer.Serialize should have been called on FakeSerializer1");
            Assert.IsTrue(
                FakeSerializer1.DeserializeCalled,
                "IExternalSerializer.Deserialize should have been called on FakeSerializer1");
            Assert.IsFalse(
                FakeTypeToSerialize.SerializeWasCalled,
                "Serialize on the type should NOT have been called");
            Assert.IsFalse(
                FakeTypeToSerialize.DeserializeWasCalled,
                "Deserialize on the type should NOT have been called");
        }
Ejemplo n.º 5
0
        public void StudentFromNormal()
        {
            // make sure Student t is consistent with its definition

            // we are going to take a sample that we expect to be t-distributed
            Sample tSample = new Sample();

            // begin with an underlying normal distribution
            ContinuousDistribution xDistribution = new NormalDistribution();

            // compute a bunch of t statistics from the distribution
            Random rng = new Random(314159);

            for (int i = 0; i < 10000; i++)
            {
                double p = xDistribution.GetRandomValue(rng);
                double q = 0.0;
                for (int j = 0; j < 5; j++)
                {
                    double x = xDistribution.GetRandomValue(rng);
                    q += x * x;
                }
                q = q / 5;

                double t = p / Math.Sqrt(q);
                tSample.Add(t);
            }

            ContinuousDistribution tDistribution = new StudentDistribution(5);
            TestResult             tResult       = tSample.KolmogorovSmirnovTest(tDistribution);

            Assert.IsTrue(tResult.Probability > 0.05);

            // Distribution should be demonstrably non-normal
            ContinuousDistribution zDistribution = new NormalDistribution(tDistribution.Mean, tDistribution.StandardDeviation);
            TestResult             zResult       = tSample.KolmogorovSmirnovTest(zDistribution);

            Assert.IsTrue(zResult.Probability < 0.05);
        }
Ejemplo n.º 6
0
        private void ValidateBalance(List <int> buckets, List <int> resources, Dictionary <int, List <int> > balancerResults, int idealBalance)
        {
            var resultBuckets   = new List <int>();
            var resultResources = new List <int>();

            foreach (KeyValuePair <int, List <int> > kvp in balancerResults)
            {
                Assert.IsFalse(resultBuckets.Contains(kvp.Key), "Duplicate bucket found.");
                Assert.IsTrue(buckets.Contains(kvp.Key), "Unknown bucket found.");
                resultBuckets.Add(kvp.Key);
                kvp.Value.ForEach(resource =>
                {
                    Assert.IsFalse(resultResources.Contains(resource), "Duplicate resource found.");
                    Assert.IsTrue(resources.Contains(resource), "Unknown resource found.");
                    resultResources.Add(resource);
                });
                Assert.IsTrue(idealBalance <= kvp.Value.Count, "Balance not ideal");
                Assert.IsTrue(idealBalance + 1 >= kvp.Value.Count, "Balance not ideal");
            }
            Assert.AreEqual(buckets.Count, resultBuckets.Count, "bucket counts do not match");
            Assert.AreEqual(resources.Count, resultResources.Count, "resource counts do not match");
        }
Ejemplo n.º 7
0
        public void MultivariateManipulations()
        {
            MultivariateSample S = new MultivariateSample(3);

            Assert.IsTrue(S.Dimension == 3);

            Assert.IsTrue(S.Count == 0);

            S.Add(1.1, 1.2, 1.3);
            S.Add(2.1, 2.2, 2.3);

            Assert.IsTrue(S.Count == 2);

            // check that an entry is there, remove it, check that it is not there
            Assert.IsTrue(S.Contains(1.1, 1.2, 1.3));
            Assert.IsTrue(S.Remove(1.1, 1.2, 1.3));
            Assert.IsFalse(S.Contains(1.1, 1.2, 1.3));

            // clear it and check that the count went to zero
            S.Clear();
            Assert.IsTrue(S.Count == 0);
        }
Ejemplo n.º 8
0
        public void TransformedBetaMoments()
        {
            // For x ~ B(a,b), kth cumulant of \ln\left(\frac{x}{1-x}\right) = \psi^{(k-1)}(a) \pm \psi^{(k-1)}(b)

            BetaDistribution D = new BetaDistribution(2.0, 3.0);

            double m = D.ExpectationValue(x => Math.Log(x / (1.0 - x)));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(m, AdvancedMath.Psi(D.Alpha) - AdvancedMath.Psi(D.Beta)));

            double c2 = D.ExpectationValue(x => MoreMath.Pow(Math.Log(x / (1.0 - x)) - m, 2));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(c2, AdvancedMath.Psi(1, D.Alpha) + AdvancedMath.Psi(1, D.Beta)));

            double c3 = D.ExpectationValue(x => MoreMath.Pow(Math.Log(x / (1.0 - x)) - m, 3));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(c3, AdvancedMath.Psi(2, D.Alpha) - AdvancedMath.Psi(2, D.Beta)));

            double c4 = D.ExpectationValue(x => MoreMath.Pow(Math.Log(x / (1.0 - x)) - m, 4));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(c4 - 3.0 * c2 * c2, AdvancedMath.Psi(3, D.Alpha) + AdvancedMath.Psi(3, D.Beta)));
        }
Ejemplo n.º 9
0
        public void StopOrleans_OrleansNotRunning_NotRunningMessage()
        {
            // Shut down any instances of OrleansHost.
            string processName = "OrleansHost";

            StopProcesses(processName);

            // Test script when Orleans Host is not running.
            Collection <PSObject> results = RunPowerShellCommand(".\\StopOrleans.ps1");

            // Check to see if Orleans Host is running.
            Process[] orleansHostTestProcess = Process.GetProcessesByName("OrleansHost");

            CheckResultsForErrors(results);

            Assert.IsTrue(orleansHostTestProcess.Count() < 1, "OrleansHost is still running.");

            // Check to see if the expected message or an error was returned.
            KeyValuePair <string, string> notStartedSearchPair = new KeyValuePair <string, string>("\tOrleansHost is not running on deployment machine(s)", "The script did not report that the OrleansHost was not started.");

            CheckResultsForStrings(results, true, notStartedSearchPair);
        }
Ejemplo n.º 10
0
        public void AddDossier_WithSavingMedecinAppelantFirst_ReturnTrue_Test()
        {
            var usersBll           = new UsersBLL();
            var firstUserId        = usersBll.GetUsersList().FirstOrDefault();
            var medecinAppelantDto = MedecinAppelantTestHelper.GetFakeMedecinAppelantDto();
            var medecinAppelantBll = new MedecinAppelantBLL();
            var addOrUpdateMedecinAppelantResult = medecinAppelantBll.AddOrUpdateMedecinAppelant(medecinAppelantDto);

            Assert.IsTrue(addOrUpdateMedecinAppelantResult.Success);
            var medecinAppelantDtoSaved = addOrUpdateMedecinAppelantResult.Result;

            var newDossierDto = new DossierDto
            {
                IdUser             = firstUserId.Id,
                IdMedecinAppelant  = medecinAppelantDtoSaved.Id,
                MedecinAppelantDto = medecinAppelantDto
            };
            var dossierBll = new DossiersBLL();
            var addOrUpdateDossierResult = dossierBll.AddOrUpdateDossier(newDossierDto);

            Assert.IsTrue(addOrUpdateDossierResult.Success);
        }
Ejemplo n.º 11
0
        public async Task BadActivate_GetValue()
        {
            try
            {
                int id = random.Next();
                IBadActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain <IBadActivateDeactivateTestGrain>(id);

                long key = await grain.GetKey();

                Assert.Fail("Expected ThrowSomething call to fail as unable to Activate grain, but returned " + key);
            }
            catch (Exception exc)
            {
                Console.WriteLine("Received exception: " + exc);
                Exception e = exc.GetBaseException();
                Console.WriteLine("Nested exception type: " + e.GetType().FullName);
                Console.WriteLine("Nested exception message: " + e.Message);
                Assert.IsInstanceOfType(e, typeof(Exception), "Did not get expected exception type returned: " + e);
                Assert.IsNotInstanceOfType(e, typeof(InvalidOperationException), "Did not get expected exception type returned: " + e);
                Assert.IsTrue(e.Message.Contains("Application-OnActivateAsync"), "Did not get expected exception message returned: " + e.Message);
            }
        }
        public void DiscreteDistributionProbabilityAxioms()
        {
            foreach (DiscreteDistribution distribution in distributions)
            {
                // some of these values will be outside the support, but that's fine, our results should still be consistent with probability axioms
                foreach (int k in TestUtilities.GenerateUniformIntegerValues(-10, +100, 8))
                {
                    Console.WriteLine("{0} {1}", distribution.GetType().Name, k);

                    double DP = distribution.ProbabilityMass(k);
                    Assert.IsTrue(DP >= 0.0); Assert.IsTrue(DP <= 1.0);

                    double P = distribution.LeftInclusiveProbability(k);
                    double Q = distribution.RightExclusiveProbability(k);
                    Console.WriteLine("{0} {1} {2}", P, Q, P + Q);

                    Assert.IsTrue(P >= 0.0); Assert.IsTrue(P <= 1.0);
                    Assert.IsTrue(Q >= 0.0); Assert.IsTrue(Q <= 1.0);
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(P + Q, 1.0));
                }
            }
        }
Ejemplo n.º 13
0
        public void LogOn_Post_ReturnsRedirectOnSuccess_WithoutReturnUrl()
        {
            // Arrange
            AccountController controller = GetAccountController();
            LogOnModel        model      = new LogOnModel()
            {
                Email      = "goodEmail",
                Password   = "******",
                RememberMe = false
            };

            // Act
            ActionResult result = controller.LogOn(model, null);

            // Assert
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;

            Assert.AreEqual("Home", redirectResult.RouteValues["controller"]);
            Assert.AreEqual("Index", redirectResult.RouteValues["action"]);
            Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignIn_WasCalled);
        }
Ejemplo n.º 14
0
        public async Task GeneratorDerivedGrain2ControlFlow()
        {
            var grainName = typeof(GeneratorTestDerivedGrain2).FullName;
            IGeneratorTestDerivedGrain2 grain = GrainClient.GrainFactory.GetGrain <IGeneratorTestDerivedGrain2>(GetRandomGrainId(), grainName);

            bool boolPromise = await grain.StringIsNullOrEmpty();

            Assert.IsTrue(boolPromise);

            await grain.StringSet("Begin");

            boolPromise = await grain.StringIsNullOrEmpty();

            Assert.IsFalse(boolPromise);

            MemberVariables members = await grain.GetMemberVariables();

            Assert.AreEqual("Begin", members.stringVar);

            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[]          bytes           = encoding.GetBytes("ByteBegin");
            string          str             = "StringBegin";
            MemberVariables memberVariables = new MemberVariables(bytes, str, ReturnCode.Fail);

            await grain.SetMemberVariables(memberVariables);

            members = await grain.GetMemberVariables();

            ASCIIEncoding enc = new ASCIIEncoding();

            Assert.AreEqual("ByteBegin", enc.GetString(members.byteArray));
            Assert.AreEqual("StringBegin", members.stringVar);
            Assert.AreEqual(ReturnCode.Fail, members.code);

            string strPromise = await grain.StringConcat("Begin", "Cont", "End");

            Assert.AreEqual("BeginContEnd", strPromise);
        }
        public void Sched_AC_RequestContext_StartNew_ContinueWith()
        {
            UnitTestSchedulingContext rootContext = new UnitTestSchedulingContext();
            OrleansTaskScheduler scheduler = TestInternalHelper.InitializeSchedulerForTesting(rootContext);

            const string key = "A";
            int val = TestConstants.random.Next();
            RequestContext.Set(key, val);

            output.WriteLine("Initial - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                SynchronizationContext.Current, TaskScheduler.Current);

            Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get Initial");

            Task t0 = Task.Factory.StartNew(() =>
            {
                output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                    SynchronizationContext.Current, TaskScheduler.Current);

                Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #0");

                Task t1 = Task.Factory.StartNew(() =>
                {
                    output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                        SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #1");
                });
                Task t2 = t1.ContinueWith((_) =>
                {
                    output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
                        SynchronizationContext.Current, TaskScheduler.Current);
                    Assert.AreEqual(val, RequestContext.Get(key), "RequestContext.Get #2");
                });
                t2.Wait(TimeSpan.FromSeconds(5));
            });
            t0.Wait(TimeSpan.FromSeconds(10));
            Assert.IsTrue(t0.IsCompleted, "Task #0 FAULTED=" + t0.Exception);
        }
Ejemplo n.º 16
0
        public void TwoSampleKolmogorovNullDistributionTest()
        {
            Random rng = new Random(4);
            ContinuousDistribution population = new ExponentialDistribution();

            int[] sizes = new int[] { 23, 30, 175 };

            foreach (int na in sizes)
            {
                foreach (int nb in sizes)
                {
                    Sample d = new Sample();
                    ContinuousDistribution nullDistribution = null;
                    for (int i = 0; i < 128; i++)
                    {
                        List <double> a = TestUtilities.CreateDataSample(rng, population, na).ToList();
                        List <double> b = TestUtilities.CreateDataSample(rng, population, nb).ToList();

                        TestResult r = Univariate.KolmogorovSmirnovTest(a, b);
                        d.Add(r.Statistic.Value);
                        nullDistribution = r.Statistic.Distribution;
                    }

                    // Only do full KS test if the number of bins is larger than the sample size, otherwise we are going to fail
                    // because the KS test detects the granularity of the distribution.
                    TestResult mr = d.KolmogorovSmirnovTest(nullDistribution);
                    if (AdvancedIntegerMath.LCM(na, nb) > d.Count)
                    {
                        Assert.IsTrue(mr.Probability > 0.01);
                    }
                    // But always test that mean and standard deviation are as expected
                    Assert.IsTrue(d.PopulationMean.ConfidenceInterval(0.99).ClosedContains(nullDistribution.Mean));
                    Assert.IsTrue(d.PopulationStandardDeviation.ConfidenceInterval(0.99).ClosedContains(nullDistribution.StandardDeviation));
                    // This test is actually a bit sensitive, probably because the discrete-ness of the underlying distribution
                    // and the inaccuracy of the asymptotic approximation for intermediate sample size make strict comparisons iffy.
                }
            }
        }
Ejemplo n.º 17
0
        public void KuiperNullDistributionTest()
        {
            // The distribution is irrelevent; pick one at random
            ContinuousDistribution sampleDistribution = new NormalDistribution();

            // Loop over various sample sizes
            foreach (int n in TestUtilities.GenerateIntegerValues(2, 128, 8))
            {
                // Create a sample to hold the KS statistics
                Sample testStatistics = new Sample();
                // and a variable to hold the claimed null distribution, which should be the same for each test
                ContinuousDistribution nullDistribution = null;

                // Create a bunch of samples, each with n+1 data points
                // We pick n+1 instead of n just to have different sample size values than in the KS test case
                for (int i = 0; i < 256; i++)
                {
                    // Just use n+i as a seed in order to get different points each time
                    Sample sample = TestUtilities.CreateSample(sampleDistribution, n + 1, 512 * n + i + 2);

                    // Do a Kuiper test of the sample against the distribution each time
                    TestResult r1 = sample.KuiperTest(sampleDistribution);

                    // Record the test statistic value and the claimed null distribution
                    testStatistics.Add(r1.Statistic.Value);
                    nullDistribution = r1.Statistic.Distribution;
                }

                // Do a KS test of our sample of Kuiper statistics against the claimed null distribution
                // We could use a Kuiper test here instead, which would be way cool and meta, but we picked KS instead for variety
                TestResult r2 = testStatistics.KolmogorovSmirnovTest(nullDistribution);
                Assert.IsTrue(r2.Probability > 0.01);

                // Test moment matches, too
                Assert.IsTrue(testStatistics.PopulationMean.ConfidenceInterval(0.99).ClosedContains(nullDistribution.Mean));
                Assert.IsTrue(testStatistics.PopulationVariance.ConfidenceInterval(0.99).ClosedContains(nullDistribution.Variance));
            }
        }
Ejemplo n.º 18
0
        public void OrleansHostParseDeploymentGroupArgFormats()
        {
            var expectedDeploymentId = Guid.NewGuid().ToString("N");
            WindowsServerHost prog   = new WindowsServerHost();

            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString("D");
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString("B");
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString("P");
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString("X");
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString("");
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);

            prog = new WindowsServerHost();
            expectedDeploymentId = Guid.NewGuid().ToString();
            Assert.IsTrue(prog.ParseArguments(new string[] { "DeploymentId=" + expectedDeploymentId }));
            Assert.AreEqual(expectedDeploymentId, prog.SiloHost.DeploymentId);
        }
Ejemplo n.º 19
0
        public void OdeOrbitFigureEight()
        {
            Func <double, IReadOnlyList <double>, IReadOnlyList <double> > rhs = (double t, IReadOnlyList <double> q) => {
                double x01 = q[0] - q[2];
                double y01 = q[1] - q[3];

                double x02 = q[0] - q[4];
                double y02 = q[1] - q[5];

                double x12 = q[2] - q[4];
                double y12 = q[3] - q[5];

                double r01 = MoreMath.Pow(MoreMath.Hypot(x01, y01), 3);
                double r02 = MoreMath.Pow(MoreMath.Hypot(x02, y02), 3);
                double r12 = MoreMath.Pow(MoreMath.Hypot(x12, y12), 3);

                return(new double[] {
                    -x01 / r01 - x02 / r02,
                    -y01 / r01 - y02 / r02,
                    +x01 / r01 - x12 / r12,
                    +y01 / r01 - y12 / r12,
                    +x02 / r02 + x12 / r12,
                    +y02 / r02 + y12 / r12
                });
            };

            double[] q1 = new double[] { 0.97000435669734, -0.24308753153583 };
            double[] p3 = new double[] { -0.93240737144104, -0.86473146092102 };

            ColumnVector q0 = new ColumnVector(q1[0], q1[1], -q1[0], -q1[1], 0.0, 0.0);
            ColumnVector p0 = new ColumnVector(-p3[0] / 2.0, -p3[1] / 2.0, -p3[0] / 2.0, -p3[1] / 2.0, p3[0], p3[1]);

            double T = 6.32591398292621;

            MultiOdeResult result = MultiFunctionMath.IntegrateConservativeOde(rhs, 0.0, q0, p0, T);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(q0, result.Y, 1.0E-10));
        }
Ejemplo n.º 20
0
        public async Task ActivationSched_ContinueWith_1_Test()
        {
            TaskScheduler scheduler = masterScheduler.GetWorkItemGroup(context).TaskRunner;

            var result = new TaskCompletionSource <bool>();
            int n      = 0;

            Task wrapper = new Task(() =>
            {
                // ReSharper disable AccessToModifiedClosure
                Task task1 = Task.Factory.StartNew(() => { output.WriteLine("===> 1a"); Thread.Sleep(1000); n = n + 3; output.WriteLine("===> 1b"); });
                Task task2 = task1.ContinueWith(task => { n = n * 5; output.WriteLine("===> 2"); });
                Task task3 = task2.ContinueWith(task => { n = n / 5; output.WriteLine("===> 3"); });
                Task task4 = task3.ContinueWith(task => { n = n - 2; output.WriteLine("===> 4"); result.SetResult(true); });
                // ReSharper restore AccessToModifiedClosure
                task4.ContinueWith(task =>
                {
                    output.WriteLine("Done Faulted={0}", task.IsFaulted);
                    Assert.IsFalse(task.IsFaulted, "Faulted with Exception=" + task.Exception);
                });
            });

            wrapper.Start(scheduler);

            var timeoutLimit = TimeSpan.FromSeconds(2);

            try
            {
                await result.Task.WithTimeout(timeoutLimit);
            }
            catch (TimeoutException)
            {
                Assert.Fail("Result did not arrive before timeout " + timeoutLimit);
            }

            Assert.IsTrue(n != 0, "Work items did not get executed");
            Assert.AreEqual(1, n, "Work items executed out of order");
        }
Ejemplo n.º 21
0
        public void GoThroughAllPagesAsAdmin()
        {
            try
            {
                this.GoToAdminHomePage();

                WebDriverWait wait = new WebDriverWait(this.Driver, ConfigHelper.GetTimeout());

                this.Driver.TryFind(By.Id(Strings.Id.ToolkitManagementLink)).ClickWrapper(this.Driver);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id(@Strings.Id.ToolkitManagementForm)));

                this.Driver.TryFind(By.Id(Strings.Id.PortalAdminDashboardLink)).ClickWrapper(this.Driver);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id(@Strings.Id.PortalSummary)));

                this.Driver.TryFind(By.Id(Strings.Id.PortalUsersLink)).ClickWrapper(this.Driver);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id(@Strings.Id.PortalUsersTable)));

                this.Driver.TryFind(By.Id(Strings.Id.DeveloperDashboardLink)).ClickWrapper(this.Driver);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id(@Strings.Id.DeveloperDashboard)));

                //this.Driver.TryFind(By.Id(Strings.Id.TeamManagementLink)).ClickWrapper(this.Driver);
                //wait.Until(ExpectedConditions.ElementIsVisible(By.Id(Strings.Id.TeamMembersList)));

                this.Driver.TryFind(By.Id(Strings.Id.RegisterApplicationLink)).ClickWrapper(this.Driver);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id(@Strings.Id.RegisterApplicationForm)));

                this.ValidateAppPages(Apps.Names.AutomaticTestsClient, wait);

                //api should be last
                this.Driver.TryFind(By.Id(Strings.Id.ApiDocsLink)).ClickWrapper(this.Driver);
                var apiInfo = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("api_info")));
                Assert.IsTrue(apiInfo.Text.Contains("Telimena API"), "apiInfo.Text.Contains('Telimena API')");
            }
            catch (Exception ex)
            {
                this.HandleError(ex, MethodBase.GetCurrentMethod().Name);
            }
        }
        public void VerifySubjectIsPassedToEmailServiceSend()
        {
            //Arrange
            var customer = new Customer();
            var customerList = new List <Customer> {
                customer
            }.AsQueryable();

            customerServiceMock.Setup(m => m.FindAll()).Returns(customerList);


            string subject = string.Empty;

            emailServiceMock.Setup(
                m => m.Send(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Callback <string, string, string>((s1, s2, s3) => subject = s2);

            //Act
            sendJobOffersService.SendJobOffers();

            //Assert
            Assert.IsTrue(subject.Equals("Ofertas de Trabajo"));
        }
Ejemplo n.º 23
0
        public void EchoGrain_EchoError()
        {
            grain = GrainClient.GrainFactory.GetGrain <IEchoTaskGrain>(Guid.NewGuid());

            Task <string> promise = grain.EchoErrorAsync(expectedEchoError);
            bool          ok      = promise.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    Assert.Fail("EchoError should not have completed successfully");
                }

                Exception exc = t.Exception;
                while (exc is AggregateException)
                {
                    exc = exc.InnerException;
                }
                string received = exc.Message;
                Assert.AreEqual(expectedEchoError, received);
            }).Wait(timeout);

            Assert.IsTrue(ok, "Finished OK");
        }
Ejemplo n.º 24
0
        public async Task LocallyPlacedGrainShouldCreateActivationsOnLocalSilo()
        {
            await this.HostedCluster.WaitForLivenessToStabilizeAsync();

            logger.Info("********************** Starting the test LocallyPlacedGrainShouldCreateActivationsOnLocalSilo ******************************");
            TestSilosStarted(2);

            const int sampleSize = 5;
            var       placement  = new StatelessWorkerPlacement(sampleSize);
            var       proxy      = GrainClient.GrainFactory.GetGrain <IRandomPlacementTestGrain>(Guid.NewGuid());
            await proxy.StartLocalGrains(new List <Guid> {
                Guid.Empty
            });

            var expected = await proxy.GetEndpoint();

            // locally placed grains are multi-activation and stateless. this means that we have to sample the value of
            // the result, rather than simply ask for it once in order to get a consensus of the result.
            var actual = await proxy.SampleLocalGrainEndpoint(Guid.Empty, sampleSize);

            Assert.IsTrue(actual.All(expected.Equals),
                          "A grain instantiated with the local placement strategy should create activations on the local silo.");
        }
Ejemplo n.º 25
0
        public async Task RandomlyPlacedGrainShouldPlaceActivationsRandomly()
        {
            await this.HostedCluster.WaitForLivenessToStabilizeAsync();

            logger.Info("********************** Starting the test RandomlyPlacedGrainShouldPlaceActivationsRandomly ******************************");
            TestSilosStarted(2);

            logger.Info("********************** TestSilosStarted passed OK. ******************************");

            var placement = RandomPlacement.Singleton;
            var grains    =
                Enumerable.Range(0, 20).
                Select(
                    n =>
                    GrainClient.GrainFactory.GetGrain <IRandomPlacementTestGrain>(Guid.NewGuid()));
            var places        = grains.Select(g => g.GetRuntimeInstanceId().Result);
            var placesAsArray = places as string[] ?? places.ToArray();
            // consider: it seems like we should check that we get close to a 50/50 split for placement.
            var groups = placesAsArray.GroupBy(s => s);

            Assert.IsTrue(groups.Count() > 1,
                          "Grains should be on different silos, but they are on " + Utils.EnumerableToString(placesAsArray.ToArray())); // will randomly fail one in a million times if RNG is good :-)
        }
Ejemplo n.º 26
0
        public void ActivationSched_SimpleFifoTest()
        {
            // This is not a great test because there's a 50/50 shot that it will work even if the scheduling
            // is completely and thoroughly broken and both closures are executed "simultaneously"
            TaskScheduler scheduler = masterScheduler.GetWorkItemGroup(context).TaskRunner;

            int n = 0;
            // ReSharper disable AccessToModifiedClosure
            Task task1 = new Task(() => { Thread.Sleep(1000); n = n + 5; });
            Task task2 = new Task(() => { n = n * 3; });

            // ReSharper restore AccessToModifiedClosure

            task1.Start(scheduler);
            task2.Start(scheduler);

            // Pause to let things run
            Thread.Sleep(1500);

            // N should be 15, because the two tasks should execute in order
            Assert.IsTrue(n != 0, "Work items did not get executed");
            Assert.AreEqual(15, n, "Work items executed out of order");
        }
Ejemplo n.º 27
0
        public async Task ObserverTest_SubscribeUnsubscribe()
        {
            TestInitialize();
            var result = new AsyncResultHandle();

            ISimpleObserverableGrain grain = GetGrain();

            observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result);
            ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference <ISimpleGrainObserver>(observer1);

            await grain.Subscribe(reference);

            await grain.SetA(5);

            Assert.IsTrue(await result.WaitForContinue(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetA");
            await grain.Unsubscribe(reference);

            await grain.SetB(3);

            Assert.IsFalse(await result.WaitForFinished(timeout), "Should timeout waiting {0} for {1}", timeout, "SetB");

            await GrainFactory.DeleteObjectReference <ISimpleGrainObserver>(reference);
        }
Ejemplo n.º 28
0
        public async Task Test_AppUsageTable()
        {
            string   viewName = nameof(this.Test_AppUsageTable);
            FileInfo app      = this.LaunchTestsAppNewInstanceAndGetResult(out _, out TelemetryItem first, Actions.ReportViewUsage, Apps.Keys.AutomaticTestsClient, Apps.PackageNames.AutomaticTestsClientAppV1, nameof(this.Test_AppUsageTable)
                                                                           , viewName: viewName);

            Task.Delay(1000).GetAwaiter().GetResult();
            DateTime previous = await this.GetLatestUsageFromTable().ConfigureAwait(false);

            Task.Delay(1500).GetAwaiter().GetResult();

            var second = this.LaunchTestsAppAndGetResult <TelemetryItem>(app, Actions.ReportViewUsage, Apps.Keys.AutomaticTestsClient, viewName: viewName);

            DateTime current = await this.GetLatestUsageFromTable().ConfigureAwait(false);

            if (current == previous)
            {
                await Task.Delay(2000);
            }
            current = await this.GetLatestUsageFromTable().ConfigureAwait(false);

            Assert.IsTrue(current > previous, $"current {current} is not larger than previous {previous}");
        }
Ejemplo n.º 29
0
        public void CollectionEditItemTest()
        {
            var col = new EmployeeCollection();

            for (var i = 1; i <= 5; i++)
            {
                var emp = CreateEmployee();
                emp.StartTrackingChanges();
                col.Attach(emp);
            }


            col.StartTrackingChanges();
            var p = col.Items.First();

            p.FirstName = "ChangedName";

            Debug.WriteLine($"Emp No. => {p.EmployeeNumber}");
            Assert.IsTrue(col.IsDirty, "Collection Must Be Dirty");
            Assert.IsTrue(p.IsDirty, "Item Must be dirty");

            Assert.AreEqual(EntityObjectState.Modified, p.StateStatus, "StateStatus NOT Same");
        }
Ejemplo n.º 30
0
        public void IsNoneTest()
        {
            Assert.IsTrue(TextUtils.IsNone(null));
            Assert.IsTrue(TextUtils.IsNone(""));
            Assert.IsTrue(TextUtils.IsNone("   "));
            Assert.IsTrue(TextUtils.IsNone("none"));
            Assert.IsTrue(TextUtils.IsNone("nOnE"));
            Assert.IsTrue(TextUtils.IsNone(" n O n E "));
            Assert.IsTrue(TextUtils.IsNone("None"));
            Assert.IsTrue(TextUtils.IsNone("NONE"));
            Assert.IsTrue(TextUtils.IsNone(" N ONE   "));
            Assert.IsTrue(TextUtils.IsNone(TextUtils.None));
            Assert.IsFalse(TextUtils.IsNone(" N e SSu nO "));
            Assert.IsFalse(TextUtils.IsNone("Nessuno"));
            Assert.IsFalse(TextUtils.IsNone("nessuno"));
            Assert.IsFalse(TextUtils.IsNone("NotNone"));

            TextUtils.None = "Nessuno";

            Assert.IsTrue(TextUtils.IsNone(" N e SSu nO "));
            Assert.IsTrue(TextUtils.IsNone(TextUtils.None));
            Assert.IsFalse(TextUtils.IsNone("NotNone"));
        }