示例#1
0
        /// <summary>
        /// Test ithe case when the post phase action throws an exception
        /// </summary>
        /// <returns>Tru if the test succeeded, false otherwise</returns>
        private static bool RunBarrierTest9_PostPhaseException()
        {
            TestHarness.TestLog("*RunBarrierTest9_PostPhaseException");
            Barrier barrier = new Barrier(1, (b) => b.SignalAndWait());

            if (!EnsurePostPhaseThrew(barrier))
            {
                return(false);
            }

            barrier = new Barrier(1, (b) => b.Dispose());
            if (!EnsurePostPhaseThrew(barrier))
            {
                return(false);
            }

            barrier = new Barrier(1, (b) => b.AddParticipant());
            if (!EnsurePostPhaseThrew(barrier))
            {
                return(false);
            }

            barrier = new Barrier(1, (b) => b.RemoveParticipant());
            if (!EnsurePostPhaseThrew(barrier))
            {
                return(false);
            }

            return(true);
        }
示例#2
0
        /// <summary>
        /// If the user delegate throws an OperationCanceledException, it should get aggregated.
        /// </summary>
        /// <returns></returns>
        internal static bool OperationCanceledExceptionsGetAggregated()
        {
            TestHarness.TestLog("* OperationCanceledExceptionsGetAggregated()");
            AggregateException caughtAggregateException = null;

            try
            {
                var enum1 = Enumerable.Range(1, 13);

                var query1 =
                    enum1
                    .AsParallel()
                    .Select <int, int>(i => { throw new OperationCanceledException(); });
                var output = query1.ToArray();
            }
            catch (AggregateException ae)
            {
                caughtAggregateException = ae;
            }

            bool success = true;

            success &= caughtAggregateException != null;
            success &= PlinqDelegateExceptionHelpers.AggregateExceptionContains(caughtAggregateException,
                                                                                typeof(OperationCanceledException));
            return(success);
        }
            // Helper method to verify the output of a GroupBy operator
            internal void MustGroupByEqual(IEnumerable <Pair <int, IEnumerable <int> > > e1, IEnumerable <Pair <int, IEnumerable <int> > > e2)
            {
                var es   = new IEnumerable <Pair <int, IEnumerable <int> > >[] { e1, e2 };
                var vals = new Dictionary <int, IEnumerable <int> > [2];

                for (int i = 0; i < 2; i++)
                {
                    vals[i] = new Dictionary <int, IEnumerable <int> >();
                    foreach (var group in es[i])
                    {
                        vals[i].Add(group.First, group.Second.OrderBy(x => x));
                    }
                }

                for (int i = 0; i < 2; i++)
                {
                    foreach (var key in vals[i].Keys)
                    {
                        if (!vals[1 - i].ContainsKey(key) || !vals[1 - i][key].SequenceEqual(vals[i][key]))
                        {
                            TestHarness.TestLog(" >> Failed. GroupBy results differ.");
                            m_passed = false;
                            return;
                        }
                    }
                }
            }
示例#4
0
        private static bool PartitioningTest(bool stripedPartitioning, int partitions, int minLen, int maxLen)
        {
            TestHarness.TestLog("PartitioningTest: {0}, {1}, {2}, {3}", stripedPartitioning, partitions, minLen, maxLen);

            for (int len = minLen; len < maxLen; len++)
            {
                int[]             arr = Enumerable.Range(0, len).ToArray();
                IEnumerable <int> query;

                if (stripedPartitioning)
                {
                    query = arr.AsParallel().AsOrdered().WithDegreeOfParallelism(partitions).Take(len).Select(i => i);
                }
                else
                {
                    query = arr.AsParallel().AsOrdered().WithDegreeOfParallelism(partitions).Select(i => i);
                }

                if (!arr.SequenceEqual(query))
                {
                    TestHarness.TestLog("  ** FAILED: incorrect output for array of length {0}", len);
                    return(false);
                }
            }

            TestHarness.TestLog("  ** Success");
            return(true);
        }
示例#5
0
        private static bool SimplePartitionMergeWhereScanTest1(int dataSize, int partitions, bool pipeline)
        {
            TestHarness.TestLog("SimplePartitionMergeWhereScanTest1: {0}, {1}, {2}", dataSize, partitions, pipeline);

            int[] data = new int[dataSize];
            for (int i = 0; i < dataSize; i++)
            {
                data[i] = i;
            }

            WhereQueryOperator <int> whereOp = new WhereQueryOperator <int>(
                data, delegate(int x) { return((x % 2) == 0); }); // select only even elements

            IEnumerator <int> stream = whereOp.GetEnumerator();

            int count = 0;

            while (stream.MoveNext())
            {
                // @TODO: verify all the elements we expected are present.
                count++;
            }

            bool passed = count == (dataSize / 2);

            TestHarness.TestLog("  > count == dataSize/2? i.e. {0} == {1}? {2}", count, dataSize / 2, passed);
            return(passed);
        }
示例#6
0
        /// <summary>
        /// Bug545118:
        ///   This bug occurred because aggregations like Sum or Average would incorrectly
        ///   wrap OperationCanceledException with AggregateException.
        /// </summary>
        private static bool BugFix545118_AggregatesShouldntWrapOCE()
        {
            TestHarness.TestLog("* PlinqCancellationTests.BugFix545118_AggregatesShouldntWrapOCE()");

            var cs = new CancellationTokenSource();

            cs.Cancel();

            // Expect OperationCanceledException rather than AggregateException or something else
            try
            {
                Enumerable.Range(0, 1000).AsParallel().WithCancellation(cs.Token).Sum(x => x);
            }
            catch (OperationCanceledException)
            {
                return(true);
            }
            catch (Exception e)
            {
                TestHarness.TestLog("  > Failed: got {0}, expected OperationCanceledException", e.GetType().ToString());
                return(false);
            }

            TestHarness.TestLog("  > Failed: no exception occured, expected OperationCanceledException");
            return(false);
        }
示例#7
0
        // throwing a fake OCE(ct) when the ct isn't canceled should produce an AggregateException.
        private static bool Bugfix640886_SetOperationsThrowAggregateOnCancelOrDispose_2()
        {
            bool passed = true;

            TestHarness.TestLog("* PlinqCancellationTests.Bugfix640886_SetOperationsThrowAggregateOnCancelOrDispose_2()");

            try
            {
                CancellationTokenSource cs = new CancellationTokenSource();
                var plinq = Enumerable.Range(0, 50)
                            .AsParallel().WithCancellation(cs.Token)
                            .WithDegreeOfParallelism(1)
#if PFX_LEGACY_3_5
                            .Union(Enumerable.Range(0, 10).AsParallel().Select <int, int>(x => { throw new OperationCanceledException(); }));
#else
                            .Union(Enumerable.Range(0, 10).AsParallel().Select <int, int>(x => { throw new OperationCanceledException(cs.Token); }));
#endif


                var walker = plinq.GetEnumerator();
                while (walker.MoveNext())
                {
                    Thread.Sleep(1);
                }
                walker.MoveNext();
                passed &= TestHarnessAssert.Fail("AggregateException was expected, but no exception occured.");
            }
示例#8
0
        internal static bool RunTest(string workDir, string exeFileName, string arg, StreamWriter sw)
        {
            if (!File.Exists(exeFileName))
            {
                TestHarness.TestLog("Error: " + exeFileName + " not found! Make sure you have built all required tests");
                return(false);
            }
            int exitcode;

            using (Process p = new Process())
            {
                p.StartInfo.RedirectStandardError  = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.WorkingDirectory       = workDir;
                p.StartInfo.FileName  = exeFileName;
                p.StartInfo.Arguments = arg;
                p.Start();
                ProcessOutput(p.StandardOutput, sw, true);
                p.WaitForExit();
                exitcode = p.ExitCode;
                p.Close();
            }
            if (exitcode != 0)
            {
                TestHarness.TestLog("Error: test process failed with exit code {0}", exitcode);
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#9
0
        // Tries some simple timeout cases.
        private static bool RunCountdownEventTest1_SimpleTimeout(int ms)
        {
            TestHarness.TestLog("* RunCountdownEventTest1_SimpleTimeout(ms={0})", ms);

            // Wait on the event.
            CountdownEvent ev = new CountdownEvent(999);

            if (ev.Wait(ms))
            {
                TestHarness.TestLog("  > error: wait returned true, yet it was supposed to timeout");
                return(false);
            }

            if (ev.IsSet)
            {
                TestHarness.TestLog("  > error: event says it was set...  shouldn't be");
                return(false);
            }

            if (ev.WaitHandle.WaitOne(ms, false))
            {
                TestHarness.TestLog("  > error: WaitHandle.Wait returned true, yet it was supposed to timeout");
                return(false);
            }

            return(true);
        }
示例#10
0
        /// <summary>Tests for the Ctor.</summary>
        /// <returns>True if the tests succeeds, false otherwise.</returns>
        private static bool RunThreadLocalTest1_Ctor()
        {
            TestHarness.TestLog("* RunThreadLocalTest1_Ctor()");
            try
            {
                new ThreadLocal <object>();
            }
            catch
            {
                TestHarness.TestLog(" > test failed - un expected exception has been thrown.");
                return(false);
            }

            try
            {
                new ThreadLocal <object>(() => new object());
            }
            catch
            {
                TestHarness.TestLog(" > test failed - un expected exception has been thrown.");
                return(false);
            }

            return(true);
        }
示例#11
0
        internal static bool RunBoundedSingleChannelTests_Parallel()
        {
            bool passed = true;

            int iters    = 1;
            int dataMult = 1;

            if ((TestHarness.RunFlags & TestType.Stress) != TestType.None)
            {
                TestHarness.TestLog("*** Running parallel tests in stress mode ***");
                iters    = 100;
                dataMult = 4;
            }

            for (int k = 0; k < iters; k++)
            {
                TestHarness.TestLog("*** ITERATION: {0} of {1} ***", k, iters);

                passed &= ProducerConsumer_InParallel <int>(delegate(int i) { return(i); }, 1024 * 8 * dataMult, 4, 1024, 128);
                passed &= ProducerConsumer_InParallel <object>(delegate(int i) { return(new object()); }, 1024 * 8 * dataMult, 4, 1024, 128);
                passed &= ProducerConsumer_InParallel <int>(delegate(int i) { return(i); }, 1024 * 8 * dataMult, 4, 2, 128);
                passed &= ProducerConsumer_InParallel <object>(delegate(int i) { return(new object()); }, 1024 * 8 * dataMult, 4, 2, 128);
                passed &= ProducerConsumer_InParallel <int>(delegate(int i) { return(i); }, 1024 * 16 * dataMult, 8, 2048, 128);
                passed &= ProducerConsumer_InParallel <object>(delegate(int i) { return(new object()); }, 1024 * 16 * dataMult, 8, 2048, 128);
                passed &= ProducerConsumer_InParallel <int>(delegate(int i) { return(i); }, 1024 * 16 * dataMult, 8, 2048, 128);
                passed &= ProducerConsumer_InParallel <object>(delegate(int i) { return(new object()); }, 1024 * 16 * dataMult, 8, 2048, 128);
            }

            return(passed);
        }
示例#12
0
        /// <summary>
        /// Test SemaphoreSlim AvailableWaitHandle property
        /// </summary>
        /// <param name="initial">The initial semaphore count</param>
        /// <param name="maximum">The maximum semaphore count</param>
        /// <param name="action">SemaphoreSlim action to be called before WaitHandle</param>
        /// <param name="state">The expected wait handle state</param>
        /// <returns>True if the test succeeded, false otherwise</returns>
        private static bool RunSemaphoreSlimTest7_AvailableWaitHandle
            (int initial, int maximum, SemaphoreSlimActions?action, bool state)
        {
            TestHarness.TestLog("AvailableWaitHandle(" + initial + "," + maximum + "," + action + ")");
            SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);

            try
            {
                CallSemaphoreAction(semaphore, action, null);
                if (semaphore.AvailableWaitHandle == null)
                {
                    TestHarness.TestLog("AvailableWaitHandle failed, handle is null.");
                    return(false);
                }
                if (semaphore.AvailableWaitHandle.WaitOne(0, false) != state)
                {
                    TestHarness.TestLog("AvailableWaitHandle failed, expected " + state + " actual " + !state);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                TestHarness.TestLog("AvailableWaitHandle failed, the code threw exception " + ex);
                return(false);
            }

            TestHarness.TestLog("AvailableWaitHandle succeeded.");
            return(true);
        }
示例#13
0
        /// <summary>
        /// Test SemaphoreSlim Dispose
        /// </summary>
        /// <param name="initial">The initial semaphore count</param>
        /// <param name="maximum">The maximum semaphore count</param>
        /// <param name="action">SemaphoreSlim action to be called after Dispose</param>
        /// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
        /// null for valid cases</param>
        /// <returns>True if the test succeeded, false otherwise</returns>
        private static bool RunSemaphoreSlimTest4_Dispose
            (int initial, int maximum, SemaphoreSlimActions?action, Type exceptionType)
        {
            TestHarness.TestLog("Dispose(" + initial + "," + maximum + "," + action + ")");
            Exception     exception = null;
            SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);

            try
            {
                semaphore.Dispose();
                CallSemaphoreAction(semaphore, action, null);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            // The code threw excption and it is not expected because the excyptionType param is null
            if (exceptionType == null && exception != null)
            {
                TestHarness.TestLog("Dispose failed, the code threw an exception, and it is not supposed to.");
                return(false);
            }

            // Compare both exception types in case of the code threw exception
            if (exception != null && !Type.Equals(exception.GetType(), exceptionType))
            {
                TestHarness.TestLog("Dispose failed, Excption types do not match");
                return(false);
            }
            TestHarness.TestLog("Dispose succeeded");
            return(true);
        }
示例#14
0
        /// <summary>
        /// Testing Barrier constructor
        /// </summary>
        /// <param name="initialCount">The intial barrier count</param>
        /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param>
        /// <returns>Tru if the test succeeded, false otherwise</returns>
        private static bool RunBarrierTest1_ctor(int initialCount, Type exceptionType)
        {
            TestHarness.TestLog("Barrier(" + initialCount + ")");
            Exception exception = null;

            try
            {
                Barrier b = new Barrier(initialCount);
                if (b.ParticipantCount != initialCount)
                {
                    TestHarness.TestLog("Constructor failed, ParticipantCount doesn't match the initialCount.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null && exceptionType == null)
            {
                TestHarness.TestLog("Constructor failed, unexpected exception has been thrown.");
                return(false);
            }
            if (exception != null && !Type.Equals(exceptionType, exception.GetType()))
            {
                TestHarness.TestLog("Constructor failed, exceptions types do not match.");
                return(false);
            }
            TestHarness.TestLog("Constructor succeeded");
            return(true);
        }
示例#15
0
        private static bool MultiplesWithCancellationIsIllegal()
        {
            bool passed = true;

            TestHarness.TestLog("* PlinqCancellationTests.MultiplesWithCancellationIsIllegal()");

            InvalidOperationException caughtException = null;

            try
            {
                CancellationTokenSource cs = new CancellationTokenSource();
                CancellationToken       ct = cs.Token;
                var query = Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(2).WithDegreeOfParallelism(2);
                query.ToArray();
            }
            catch (InvalidOperationException ex)
            {
                caughtException = ex;
                //Console.WriteLine("IOE caught. message = " + ex.Message);
            }

            passed &= TestHarnessAssert.IsNotNull(caughtException, "An exception should be thrown.");

            return(passed);
        }
示例#16
0
        // Validates init, set, reset state transitions.
        private static bool RunManualResetEventSlimTest0_StateTrans(bool init)
        {
            TestHarness.TestLog("* RunManualResetEventSlimTest0_StateTrans(init={0})", init);

            ManualResetEventSlim ev = new ManualResetEventSlim(init);

            if (ev.IsSet != init)
            {
                TestHarness.TestLog("  > expected IsSet=={0}, but it's {1}", init, ev.IsSet);
                return(false);
            }

            for (int i = 0; i < 50; i++)
            {
                ev.Set();
                if (!ev.IsSet)
                {
                    TestHarness.TestLog("  > expected IsSet, but it's false");
                    return(false);
                }

                ev.Reset();
                if (ev.IsSet)
                {
                    TestHarness.TestLog("  > expected !IsSet, but it's true");
                    return(false);
                }
            }

            return(true);
        }
示例#17
0
        /// <summary>
        ///
        /// Bug535510:
        ///   This bug occured because the QuerySettings structure was not being deep-cloned during
        ///   query-opening.  As a result, the concurrent inner-enumerators (for the RHS operators)
        ///   that occur in SelectMany were sharing CancellationState that they should not have.
        ///   The result was that enumerators could falsely believe they had been canceled when
        ///   another inner-enumerator was disposed.
        ///
        ///   Note: the failure was intermittent.  this test would fail about 1 in 2 times on mikelid1 (4-core).
        /// </summary>
        /// <returns></returns>
        private static bool BugFix535510_CloningQuerySettingsForSelectMany()
        {
            bool passed = true;

            TestHarness.TestLog("* PlinqCancellationTests.BugFix535510_CloningQuerySettingsForSelectMany()");

            var       plinq_src       = ParallelEnumerable.Range(0, 1999).AsParallel();
            Exception caughtException = null;

            try
            {
                var inner  = ParallelEnumerable.Range(0, 20).AsParallel().Select(_item => _item);
                var output = plinq_src
                             .SelectMany(
                    _x => inner,
                    (_x, _y) => _x
                    )
                             .ToArray();
            }
            catch (Exception ex)
            {
                caughtException = ex;
            }

            passed &= TestHarnessAssert.IsNull(caughtException, "No exception should occur.");
            return(passed);
        }
示例#18
0
        // Tests timeout on an event that is never set.
        private static bool RunManualResetEventSlimTest2_TimeoutWait()
        {
            TestHarness.TestLog("* RunManualResetEventSlimTest2_TimeoutWait()");

            ManualResetEventSlim ev = new ManualResetEventSlim(false);

            if (ev.Wait(0))
            {
                TestHarness.TestLog("  > ev.Wait(0) returned true -- event isn't set  ({0})", ev.IsSet);
                return(false);
            }

            if (ev.Wait(100))
            {
                TestHarness.TestLog("  > ev.Wait(100) returned true -- event isn't set  ({0})", ev.IsSet);
                return(false);
            }

            if (ev.Wait(TimeSpan.FromMilliseconds(100)))
            {
                TestHarness.TestLog("  > ev.Wait(0) returned true -- event isn't set  ({0})", ev.IsSet);
                return(false);
            }

            ev.Dispose();

            return(true);
        }
示例#19
0
        // Plinq supresses OCE(externalCT) occuring in worker threads and then throws a single OCE(ct)
        // if a manual OCE(ct) is thrown but ct is not canceled, Plinq should not suppress it, else things
        // get confusing...
        // ONLY an OCE(ct) for ct.IsCancellationRequested=true is co-operative cancellation
        private static bool Bugfix632544_OnlySuppressOCEifCTCanceled()
        {
            bool passed = true;

#if !PFX_LEGACY_3_5
            TestHarness.TestLog("* PlinqCancellationTests.Bugfix632544_OnlySuppressOCEifCTCanceled()");

            AggregateException      caughtException = null;
            CancellationTokenSource cts             = new CancellationTokenSource();
            CancellationToken       externalToken   = cts.Token;
            try
            {
                Enumerable.Range(1, 10).AsParallel()
                .WithCancellation(externalToken)
                .Select(
                    x =>
                {
                    if (x % 2 == 0)
                    {
                        throw new OperationCanceledException(externalToken);
                    }
                    return(x);
                }
                    )
                .ToArray();
            }
            catch (AggregateException ae)
            {
                caughtException = ae;
            }

            passed &= TestHarnessAssert.IsNotNull(caughtException, "We expect this OCE(ct) to merely be aggregated.");
#endif
            return(passed);
        }
示例#20
0
        private static bool RunFixedMaxHeapRemoveTest(int heapSize)
        {
            TestHarness.TestLog("* RunFixedMaxHeapRemoveTest(heapSize={0})", heapSize);

            FixedMaxHeap <int> heap = new FixedMaxHeap <int>(heapSize);

            for (int j = 0; j < heapSize; j++)
            {
                heap.Insert(j);
            }

            int i = 0;

            while (heap.Count > 0)
            {
                if (heap.Count != heapSize - i)
                {
                    TestHarness.TestLog("> Wrong heap size. Expected={0}  Got={1}", heapSize - i, heap.Count);
                    return(false);
                }

                int got    = heap.MaxValue;
                int expect = heapSize - i - 1;
                if (got != expect)
                {
                    TestHarness.TestLog("> Failed. Expected={0}  Got={1}", expect, got);
                    return(false);
                }

                heap.RemoveMax();
                i++;
            }

            return(true);
        }
示例#21
0
        public static bool PreCanceledToken_SimpleEnumerator()
        {
            bool passed = true;

            TestHarness.TestLog("* PlinqCancellationTests.PreCanceledToken_SimpleEnumerator()");

            OperationCanceledException caughtException = null;
            var cs = new CancellationTokenSource();

            cs.Cancel();

            int[] srcEnumerable = Enumerable.Range(0, 1000).ToArray();
            ThrowOnFirstEnumerable <int> throwOnFirstEnumerable = new ThrowOnFirstEnumerable <int>(srcEnumerable);

            try
            {
                var query = throwOnFirstEnumerable
                            .AsParallel()
                            .WithCancellation(cs.Token);

                foreach (var item in query)
                {
                }
            }
            catch (OperationCanceledException ex)
            {
                caughtException = ex;
            }

            passed &= TestHarnessAssert.IsNotNull(caughtException, "an OCE should be throw during query opening");
            passed &= TestHarnessAssert.AreEqual(cs.Token, OCEHelper.ExtractCT(caughtException), "The OCE should reference the cancellation token.");

            return(passed);
        }
示例#22
0
        private static bool RunFixedMaxHeapRemoveTest2(int heapSize)
        {
            TestHarness.TestLog("* RunFixedMaxHeapRemoveTest2(heapSize={0})", heapSize);

            try
            {
                FixedMaxHeap <int> heap = new FixedMaxHeap <int>(heapSize);
                for (int j = 0; j < heapSize; j++)
                {
                    heap.Insert(j);
                }

                // Will removing an element create a spot for another element?
                heap.RemoveMax();
                heap.Insert(10);
            }
            catch (Exception e)
            {
                TestHarness.TestLog("> Failed: exception {0}", e.GetType());
                return(false);
            }

            // So long as we didn't get an exception, the test passed.
            return(true);
        }
示例#23
0
        /// <summary>
        /// Checks whether an ordered pipelining merge pipelines the results
        /// instead of running in a stop-and-go fashion.
        /// </summary>
        private static bool OrderedPipeliningTest2(bool buffered)
        {
            TestHarness.TestLog("OrderedPipeliningTest2: buffered={0}", buffered);
            ParallelMergeOptions merge = buffered ? ParallelMergeOptions.AutoBuffered : ParallelMergeOptions.NotBuffered;

            IEnumerable <int> src = Enumerable.Range(0, int.MaxValue)
                                    .Select(x => { if (x == 1000000)
                                                   {
                                                       throw new Exception();
                                                   }
                                                   return(x); });


            try
            {
                int expect = 0;
                int got    = Enumerable.First(src.AsParallel().AsOrdered().WithMergeOptions(merge).Select(x => x));
                if (got != expect)
                {
                    TestHarness.TestLog("> FAILED: Expected {0}, got {1}.", expect, got);
                    return(false);
                }
            }
            catch (Exception e)
            {
                TestHarness.TestLog("> FAILED: Caught an exception: {0}.", e.GetType());
            }

            return(true);
        }
示例#24
0
        private static bool RunFixedMaxHeapReplaceTest(int heapSize)
        {
            TestHarness.TestLog("* RunFixedMaxHeapReplaceTest(heapSize={0})", heapSize);

            // Create a heap, replace the max value with newValue, and then verify that
            // the heap contains the correct values.
            for (int newValue = 0; newValue < heapSize; newValue++)
            {
                FixedMaxHeap <int> heap = new FixedMaxHeap <int>(heapSize);
                for (int i = 0; i < heapSize; i++)
                {
                    heap.Insert(i);
                }
                heap.ReplaceMax(newValue);

                List <int> sortedHeap = new List <int>();
                while (heap.Count > 0)
                {
                    sortedHeap.Add(heap.MaxValue);
                    heap.RemoveMax();
                }

                IEnumerable <int> expect = Enumerable.Range(0, heapSize - 1)
                                           .Concat(Enumerable.Repeat(newValue, 1))
                                           .OrderByDescending(x => x).ToArray();

                if (!sortedHeap.SequenceEqual(expect))
                {
                    TestHarness.TestLog("> Failed. Wrong sequence.");
                    return(false);
                }
            }

            return(true);
        }
示例#25
0
        private static bool CheckWhereSelectComposition(int dataSize)
        {
            TestHarness.TestLog("CheckWhereSelectComposition: {0}", dataSize);

            int[] data = new int[dataSize];
            for (int i = 0; i < dataSize; i++)
            {
                data[i] = i;
            }

            WhereQueryOperator <int> whereOp = new WhereQueryOperator <int>(
                data, delegate(int x) { return((x % 2) == 0); }); // select only even elements
            SelectQueryOperator <int, int> selectOp = new SelectQueryOperator <int, int>(
                whereOp, delegate(int x) { return(x * 2); });     // just double the elements

            bool passed = true;

            // Verify composition of the tree:
            //     SELECT <-- WHERE <-- SCAN <-- {data}

            SelectQueryOperator <int, int> sel = selectOp as SelectQueryOperator <int, int>;

            passed &= sel != null;
            TestHarness.TestLog("  > {0}: SELECT is non-null", passed);

            WhereQueryOperator <int> where = sel.Child as WhereQueryOperator <int>;
            passed &= where != null;
            TestHarness.TestLog("  > {0}: WHERE is non-null", passed);

            ScanQueryOperator <int> scan = where.Child as ScanQueryOperator <int>;

            passed &= scan != null;
            TestHarness.TestLog("  > {0}: SCAN is non-null", passed);

            // Now verify the output is what we expect.

            int expectSum = 0;

            for (int i = 0; i < dataSize; i++)
            {
                if ((i % 2) == 0)
                {
                    expectSum += (i * 2);
                }
            }

            int realSum         = 0;
            IEnumerator <int> e = selectOp.GetEnumerator();

            while (e.MoveNext())
            {
                realSum += e.Current;
            }

            passed = (realSum == expectSum);

            TestHarness.TestLog("  > {0}: actual sum {1} == expected sum {2}?", passed, realSum, expectSum);

            return(passed);
        }
示例#26
0
        /// <summary>Tests for the ToString.</summary>
        /// <returns>True if the tests succeeds, false otherwise.</returns>
        private static bool RunLazyTest5_ToString()
        {
            TestHarness.TestLog("* RunLazyTest5_ToString()");
            Lazy <object> lazy = new Lazy <object>(() => (object)1);

            if (lazy.ToString() == 1.ToString())
            {
                TestHarness.TestLog(" > test failed - Unexpected return value from ToString(); Actual={0}, Expected={1}.", lazy.ToString(), 1.ToString());
                return(false);
            }
            if (lazy.IsValueCreated)
            {
                TestHarness.TestLog(" > test failed - ToString shouldn't force allocation");
                return(false);
            }

            object tmp = lazy.Value;

            if (lazy.ToString() != 1.ToString())
            {
                TestHarness.TestLog(" > test failed - Unexpected return value from ToString(); Actual={0}, Expected={1}.", lazy.ToString(), 1.ToString());
                return(false);
            }

            return(true);
        }
示例#27
0
        /// <summary>
        /// The plinq chunk partitioner calls takes an IEnumerator over the source, and disposes the enumerator when it is
        /// finished.
        /// If an exception occurs, the calling enumerator disposes the enumerator... but then other callers generate ODEs.
        /// These ODEs either should not occur (prefered), or should not get into the aggregate exception.
        ///
        /// Also applies to the standard stand-alone chunk partitioner.
        /// Does not apply to other partitioners unless an exception in one consumer would cause flow-on exception in others.
        /// </summary>
        /// <returns></returns>
        private static bool Bug599487_PlinqChunkPartitioner_DontEnumerateAfterException()
        {
            TestHarness.TestLog("* Bug599487_PlinqChunkPartitioner_DontEnumerateAfterException()");
            bool success = true;

            try
            {
                Enumerable.Range(1, 10)
                .AsParallel()
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .Select(x => { if (x == 4)
                               {
                                   throw new ApplicationException("manual exception");
                               }
                               return(x); })
                .Zip(Enumerable.Range(1, 10).AsParallel(), (a, b) => a + b)
                .AsParallel()
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .ToArray();
            }
            catch (AggregateException e)
            {
                if (!e.Flatten().InnerExceptions.All(ex => ex.GetType() == typeof(ApplicationException)))
                {
                    success = false;
                    TestHarness.TestLog("  FAIL. only a single ApplicationException should appear in the aggregate:");
                    foreach (var exception in e.Flatten().InnerExceptions)
                    {
                        TestHarness.TestLog("     exception = " + exception);
                    }
                }
            }

            return(success);
        }
示例#28
0
        /// <summary>Tests for the Ctor.</summary>
        /// <returns>True if the tests succeeds, false otherwise.</returns>
        private static bool RunLazyTest1_Ctor()
        {
            TestHarness.TestLog("* RunLazyTest1_Ctor()");
            try
            {
                new Lazy <object>();
            }
            catch
            {
                TestHarness.TestLog(" > test failed - un expected exception has been thrown.");
                return(false);
            }

            try
            {
                new Lazy <object>(null);
                TestHarness.TestLog(" > test failed - expected exception ArgumentOutOfRangeException");
                return(false);
            }
            catch (ArgumentNullException)
            {
            }

            return(true);
        }
示例#29
0
        public static bool EnsureOperationCanceledExceptionThrown(UntypedAction action, CancellationToken expectedCancellationTokenInException, string message)
        {
            OperationCanceledException exception = null;

            try
            {
                action();
            }
            catch (OperationCanceledException ex)
            {
                exception = ex;
            }

            if (exception == null)
            {
                TestHarness.TestLog("  > " + "OperationCanceledException was not thrown.  " + message);
                return(false);
            }

#if !PFX_LEGACY_3_5
            if (exception.CancellationToken != expectedCancellationTokenInException)
            {
                TestHarness.TestLog("  > " + "CancellationToken does not match.  " + message);
                return(false);
            }
#endif
            return(true);
        }
示例#30
0
        /// <summary>
        /// Test RemoveParticipants
        /// </summary>
        /// <param name="initialCount">The initial barrier participants count</param>
        /// <param name="participantsToRemove">The aprticipants that will be added</param>
        /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param>
        /// <returns>Tru if the test succeeded, false otherwise</returns>
        private static bool RunBarrierTest5_RemoveParticipants(int initialCount, int participantsToRemove, Type exceptionType)
        {
            TestHarness.TestLog("RemoveParticipants(" + initialCount + "," + participantsToRemove + ")");
            Barrier   b         = new Barrier(initialCount);
            Exception exception = null;

            try
            {
                b.RemoveParticipants(participantsToRemove);
                if (b.ParticipantCount != initialCount - participantsToRemove)
                {
                    TestHarness.TestLog("RemoveParticipants failed, total participant was not decreased");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null && exceptionType == null)
            {
                TestHarness.TestLog("RemoveParticipants failed, unexpected exception has been thrown.");
                return(false);
            }
            if (exception != null && !Type.Equals(exceptionType, exception.GetType()))
            {
                TestHarness.TestLog("RemoveParticipants failed, exceptions types do not match.");
                return(false);
            }
            TestHarness.TestLog("RemoveParticipants succeeded");
            return(true);
        }