public AsyncTestDriver(Action<Options, Output> action, Func<Options, bool> skipTest, uint maxWaitHandles)
 {
   this.action = action;
   this.actionDelegate = this.ActionAsIsolated;
   this.skipTest = skipTest;
   this.maxWaitHandles = maxWaitHandles;
 }
 private static void TestCasing(IReadOnlyList<string> array, Func<string, string> function)
 {
     for (var i = 0; i < array.Count; i++)
     {
         Assert.Equal(array[i], function(Camel[i]));
         Assert.Equal(array[i], function(Pascal[i]));
         Assert.Equal(array[i], function(Dashed[i]));
         Assert.Equal(array[i], function(Spaced[i]));
         Assert.Equal(array[i], function(Traps[i]));
     }
 }
        public static bool Until(Func<bool> operation, TimeSpan timeout = default(TimeSpan))
        {
            if (timeout == default(TimeSpan))
                timeout = TimeSpan.FromSeconds(15);

            var stopwatch = Stopwatch.StartNew();

            while (operation.Invoke() == false)
            {
                if (stopwatch.Elapsed >= timeout)
                    throw new TimeoutException("Timed out waiting for operation to complete....");

                Thread.Sleep(300);
            }

            return true;
        }
Exemple #4
0
        private IWebHost StartWebSocketServer(Func<HttpContext, Task> app)
        {
            Action<IApplicationBuilder> startup = builder =>
            {
                builder.Use(async (ct, next) =>
                {
                    try
                    {
                        // Kestrel does not return proper error responses:
                        // https://github.com/aspnet/KestrelHttpServer/issues/43
                        await next();
                    }
                    catch (Exception ex)
                    {
                        if (ct.Response.HasStarted)
                        {
                            throw;
                        }

                        ct.Response.StatusCode = 500;
                        ct.Response.Headers.Clear();
                        await ct.Response.WriteAsync(ex.ToString());
                    }
                });

                builder.UseWebSockets();
                builder.Run(c => app(c));
            };

            var configBuilder = new ConfigurationBuilder();
            configBuilder.AddInMemoryCollection();
            var config = configBuilder.Build();
            config["server.urls"] = "http://localhost:54321";

            var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .Configure(startup)
                .Build();

            host.Start();

            return host;
        }
        public void TestSetup()
        {
            isBadEntityAccessFromEntity = (badType, entityConatainerType) =>
                                              (isEntityType(badType) && isEntityType(entityConatainerType) && !badType.BaseType.GetGenericArguments().SequenceEqual(entityConatainerType.BaseType.GetGenericArguments())) ||
                                              badType.IsGenericType && badType.GetGenericArguments().Any(_ => isBadEntityAccessFromEntity(_, entityConatainerType));

            isBadEntityAccessFromAggregate = (badType, aggregateConatainerType) =>
                    (isEntityType(badType) && isAggregateRootType(aggregateConatainerType) && badType.BaseType.GetGenericArguments().Any(_ => _ != aggregateConatainerType)) ||
                                        badType.IsGenericType && badType.GetGenericArguments().Any(_ => isBadEntityAccessFromAggregate(_, aggregateConatainerType));

            /*
             * This one isn't needed because we don't care if entities access other aggregate roots. Thought it would a useful definition though.
             */
            isBadAggregateAccessFromEntity = (badType, entityConatainerType) =>
                (isAggregateRootType(badType) && isEntityType(entityConatainerType) && entityConatainerType.BaseType.GetGenericArguments().Any(_ => _ != badType)) ||
                (badType.IsGenericType && badType.GetGenericArguments().Any(_ => isBadAggregateAccessFromEntity(_, entityConatainerType)));

            badMemberType = (type, entityContainerType) =>
                                             isBadEntityAccessFromEntity(type, entityContainerType) ||
                                             isBadEntityAccessFromAggregate(type, entityContainerType);
        }
        private void TestEvents(Func<Context, Int32> saveChangesAction)
        {
            insertingFiredCount = 0;
            updatingFiredCount = 0;
            deletingFiredCount = 0;
            insertedFiredCount = 0;
            updatedFiredCount = 0;
            deletedFiredCount = 0;
            using (var context = new Context()) {
                var nickStrupat = new Person {
                                                 FirstName = "Nick",
                                                 LastName = "Strupat",
                                             };
                AddHandlers(nickStrupat);
                context.People.Add(nickStrupat);

                var johnSmith = new Person {
                                               FirstName = "John",
                                               LastName = "Smith"
                                           };
                AddHandlers(johnSmith);
                context.People.Add(johnSmith);
                AssertNoEventsHaveFired();

                saveChangesAction(context);
                AssertInsertEventsHaveFired();

                nickStrupat.FirstName = "Nicholas";
                saveChangesAction(context);
                AssertUpdateEventsHaveFired();

                context.People.Remove(nickStrupat);
                context.People.Remove(johnSmith);
                saveChangesAction(context);
                AssertAllEventsHaveFired();

                context.Database.Delete();
            }
        }
Exemple #7
0
 public FakeDbProvider(Func<DbConnection> factory, string providerId) : base(factory, providerId)
 {
     
 }
		private static async Task<IEnumerable<SMTP.EMail>> GetEmails(
			Server sut, 
			Func<Server, IEnumerable<SMTP.EMail>> getEmailsFunc, 
			params Func<Task>[] sendEmails)
		{
			using (var countdown = new CountdownEvent(sendEmails.Count()))
			using (sut.EmailReceived.Subscribe(actual =>
				{					
					countdown.Signal();
				}))
			{
				foreach (var t in sendEmails)
					await t();
				countdown.Wait ();
				return getEmailsFunc(sut);
			}
		}
 static KeyValuePair<Expression, Func<double, double>> Test(Expression K, Func<double, double> V)
 {
     return new KeyValuePair<Expression, Func<double, double>>(K, V);
 }
        static bool RunTest(Expression fx, Func<double, double> Result)
        {
            Variable vx = Variable.New("x");

            try
            {
                Func<double, double> compiled = ExprFunction.New(fx, vx).Compile<Func<double, double>>();

                int N = 1000;
                for (int i = 0; i < N; ++i)
                {
                    double x = (((double)i / N) * 2 - 1) * Math.PI;

                    if (Math.Abs((double)fx.Evaluate(vx, x) - Result(x)) > 1e-6)
                    {
                        Console.WriteLine("{0} -> {1} != {2}", fx, fx.Evaluate(vx, x), Result(x));
                        return false;
                    }

                    if (Math.Abs(compiled(x) - Result(x)) > 1e-6)
                    {
                        Console.WriteLine("Miscompile: {0} -> {1} != {2}", fx, compiled(x), Result(x));
                        return false;
                    }
                }
                return true;
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
                return false;
            }
        }
 public Func(Func<int> f)
 {
     m_func = f;
 }
 public AsyncTestDriver(Action<Options, Output> action, Func<Options, bool> skipTest)
   : this(action, skipTest, MaxWaitHandles_Default)
 { }
 private void AssertCompile(Func<Func<string, Expression>, Expression, Expression> createExpression, LogAndResult<object> expected)
 {
     var res = WithLog(createExpression).Compile()();
     Assert.AreEqual(expected, res);
 }
Exemple #14
0
        public double RunTest(Circuit.Circuit C, Simulation S, Func<double, double> Vin, int Samples, string Name)
        {
            double t0 = (double)S.Time;
            double T = S.TimeStep;

            int N = 353;
            double[] input = new double[N];

            List<List<double>> output = S.Output.Select(i => new List<double>(Samples)).ToList();
            List<double[]> buffers = S.Output.Select(i => new double[N]).ToList();

            double time = 0.0;
            int samples = 0;
            double t = 0;
            for (; samples < Samples; samples += N)
            {
                for (int n = 0; n < N; ++n, t += T)
                    input[n] = Vin(t);

                long a = Timer.Counter;
                S.Run(input, buffers);
                time += Timer.Delta(a);

                for (int i = 0; i < S.Output.Count(); ++i)
                    output[i].AddRange(buffers[i]);
            }
            simulateTime += time;

            int t1 = Math.Min(samples, 4000);

            Log.WriteLine("Performance {0}", Quantity.ToString(samples / time, Units.Hz));

            Plot p = new Plot()
            {
                Title = Name,
                Width = 800,
                Height = 400,
                x0 = t0,
                x1 = T * t1,
                xLabel = "Time (s)",
                yLabel = "Voltage (V)",
            };

            p.Series.AddRange(output.Select((i, j) => new Scatter(
                i.Take(t1)
                .Select((k, n) => new KeyValuePair<double, double>(n * T, k)).ToArray()) { Name = S.Output.ElementAt(j).ToString() }));
            return samples / time;
        }
Exemple #15
0
        public double Run(Circuit.Circuit C, Func<double, double> Vin, Expression Input, IEnumerable<Expression> Plots)
        {
            long a = Timer.Counter;

            Analysis analysis = C.Analyze();
            TransientSolution TS = TransientSolution.Solve(analysis, (Real)1 / (SampleRate * Oversample), Log);

            analysisTime += Timer.Delta(a);

            Simulation S = new Simulation(TS)
            {
                Oversample = Oversample,
                Iterations = Iterations,
                Log = Log,
                Input = new[] { Input },
                Output = Plots,
            };

            Log.WriteLine("");
            if (Samples > 0)
                return RunTest(
                    C, S,
                    Vin,
                    Samples,
                    C.Name);
            else
                return 0.0;
        }
Exemple #16
0
 public double Run(string FileName, Func<double, double> Vin, Expression Input, IEnumerable<Expression> Plots)
 {
     Circuit.Circuit C = Schematic.Load(FileName, Log).Build();
     C.Name = System.IO.Path.GetFileNameWithoutExtension(FileName);
     return Run(C, Vin, Input, Plots);
 }
Exemple #17
0
 public double Run(string FileName, Func<double, double> Vin)
 {
     Circuit.Circuit C = Schematic.Load(FileName, Log).Build();
     C.Name = System.IO.Path.GetFileNameWithoutExtension(FileName);
     return Run(
         C,
         Vin,
         C.Components.OfType<Input>().Select(i => Expression.Parse(i.Name + "[t]")).DefaultIfEmpty("V[t]").SingleOrDefault(),
         C.Nodes.Select(i => i.V));
 }
Exemple #18
0
        public void Run(IEnumerable<string> Tests, Func<double, double> Vin)
        {
            List<string> errors = new List<string>();
            List<string> performance = new List<string>();

            // This test generates the signal for the LiveSPICE 'logo'.
            //Run("Subcircuit Trivial.schx", Vin, "V1[t]", new Expression[] { "_v15[t]", "_v11[t]" });
            //return;

            foreach (string File in Tests)
            {
                string Name = System.IO.Path.GetFileNameWithoutExtension(File);
                try
                {
                    double perf = Run(File, Vin);
                    performance.Add(Name + ":\t" + Quantity.ToString(perf, Units.Hz) + " (" + (perf / (double)SampleRate).ToString("G3") + "x real time)");
                }
                catch (Exception ex)
                {
                    errors.Add(Name + ":\t" + ex.Message);
                    Log.WriteLine(ex.Message);
                }
            }

            Log.WriteLine("Analyze/Simulate {0}/{1}", analysisTime, simulateTime);

            Log.WriteLine("{0} succeeded:", performance.Count);
            foreach (string i in performance)
                Log.WriteLine(i);

            Log.WriteLine("{0} failed:", errors.Count);
            foreach (string i in errors)
                Log.WriteLine(i);
        }
		protected void Check(Formula actual, Func<bool> expected)
		{
			Check(actual, new StateFormula(expected));
		}
Exemple #20
0
        private int CountPixelsHorizontal(LockBitmap locked, Func<Color, bool> colorFunc, IEnumerable<int> range, int y)
        {
            int count = 0;

            foreach (var x in range)
            {
                var pixel = locked.GetPixel(x, y);
                if (colorFunc(pixel))
                {
                    count++;
                }
                else
                {
                    break;
                }
            }

            return count;
        }
Exemple #21
0
        private void TestBrains(Func<RobotAI> botFactory, string dir)
        {
            var now = DateTime.Now;
            var typeBot = botFactory();
            string botName = typeBot.GetType().Name;
            using (var writer = new StreamWriter(Path.Combine(TestsDir, botName + "_" + now.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt")))
            {
                long sum = 0;
                WriteLineAndShow(writer, botName + " " + now.ToString("yyyy-MM-dd HH:mm:ss"));
                WriteLineAndShow(writer);
                WriteLineAndShow(writer, "\t  score: [W|N|A] <SCORE> (W - win, N - nothing, A - Abort)");
                WriteLineAndShow(writer);

                WriteLineAndShow(writer,
                    "map".PadRight(FilenamePadding)
                    + "ms".PadRight(ValuePadding)
                    + "ch?".PadRight(ValuePadding)
                    + "curScore".PadRight(ValuePadding)
                    + "prevScores    ...   moves");
                foreach (var file in Directory.GetFiles(dir, "*.map.txt"))
                {
                    string mapName = Path.GetFileNameWithoutExtension(file) ?? "NA";
                    var lines = File.ReadAllLines(file);
                    var bot = botFactory();
                    var map = new Map(lines);

                    var robotMove = RobotMove.Wait;

                    var timer = Stopwatch.StartNew();
                    var botWrapper = new BotWithBestMomentsMemory(bot);
                    while(robotMove != RobotMove.Abort && map.State == CheckResult.Nothing)
                    {
                        robotMove = (timer.Elapsed.TotalSeconds < 150) ? botWrapper.NextMove(map) : RobotMove.Abort;

                        map = map.Move(robotMove);
                        botWrapper.UpdateBestSolution(map);
                    }
                    string[] history = LoadHistory(dir, mapName, botName);
                    string result = botWrapper.BestMovesEndState.ToString()[0] + " " + botWrapper.BestScore.ToString();
                    bool resultChanged = result != history.FirstOrDefault();
                    WriteLineAndShow(writer,
                        mapName.PadRight(FilenamePadding)
                        + timer.ElapsedMilliseconds.ToString().PadRight(ValuePadding)
                        + (resultChanged ? "*" : "").PadRight(ValuePadding)
                        + result.PadRight(ValuePadding)
                        + String.Join(" ", history.Take(10)) + "  "
                        + botWrapper.GetBestMoves());
                    if (resultChanged)
                        history = new[] {result}.Concat(history).ToArray();
                    File.WriteAllLines(GetHistoryFilename(dir, mapName, botName), history);
                    sum += botWrapper.BestScore;
                }
                WriteLineAndShow(writer, sum.ToString());
            }
        }
Exemple #22
0
        private Line FindVerticalBorder(LockBitmap locked, IEnumerable<int> range, int y, Func<double, int> v, Func<Color, bool> borderFunc, bool isLeft = true)
        {
            foreach (var x in range)
            {
                var pixel = locked.GetPixel(x, y);
                if (borderFunc(pixel))
                {
                    var upStart = Math.Max(y - v(6), 0);
                    var upRange = Enumerable.Range(upStart, y - upStart).Reverse();
                    var downRange = Enumerable.Range(y + 1, locked.Height - y - 1);

                    var rng = isLeft ? Enumerable.Range(x + 1, 5) : Enumerable.Range(x - 5, 5).Reverse();
                    var up = CountPixelsVertical(locked, borderFunc, upRange, x, rng);
                    var down = CountPixelsVertical(locked, borderFunc, downRange, x);

                    return new Line(new Point(x, y - up), new Point(x, y + down));
                }
            }

            return null;
        }
 public LoopBackHandler(Func<HttpRequestMessage, HttpResponseMessage> f)
 {
     _f = f;
 }
        public void ConditionalAccess_ManOrBoy2()
        {
            var p = Expression.Parameter(typeof(S?));

            var x = Expression.Constant(0);

            var P = p.Type.GetGenericArguments()[0].GetProperty("P");
            var I = p.Type.GetGenericArguments()[0].GetProperty("Item");
            var M = p.Type.GetGenericArguments()[0].GetMethod("M");

            var cP = (Func<Expression, Expression>)(e => CSharpExpression.ConditionalProperty(e, P));
            var cI = (Func<Expression, Expression>)(e => CSharpExpression.ConditionalIndex(e, I, new[] { x }));
            var cM = (Func<Expression, Expression>)(e => CSharpExpression.ConditionalCall(e, M, new[] { x }));

            var cases = new Func<Expression, Expression>[][]
            {
                new[] { cP },
                new[] { cP, cI },
                new[] { cP, cI, cM },
                new[] { cM },
                new[] { cM, cP },
                new[] { cM, cP, cI },
                new[] { cI },
                new[] { cI, cM },
                new[] { cI, cM, cP },
            };

            foreach (var cs in cases)
            {
                var e = cs.Aggregate((Expression)p, (a, b) => b(a));

                var f = Expression.Lambda<Func<S?, S?>>(e, p).Compile();

                Assert.IsNull(f(null));

                for (var i = 0; i < cs.Length; i++)
                {
                    Assert.IsNull(f(new S(i)));
                }

                Assert.IsNotNull(f(new S(cs.Length)));
            }
        }
 private void TestOrder(Func<Context, Int32> saveChangesAction) {
     var list = new List<Int32>();
     using (var context = new Context()) {
         var janeDoe = new Person {
             FirstName = "Jane",
             LastName = "Doe",
         };
         janeDoe.Triggers().Inserted += e => list.Add(0);
         ((EntityWithInsertTracking)janeDoe).Triggers().Inserted += e => list.Add(1);
         ((EntityWithTracking)janeDoe).Triggers().Inserted += e => list.Add(2);
         context.People.Add(janeDoe);
         saveChangesAction(context);
     }
     Assert.IsTrue(list.SequenceEqual(new [] {0, 1, 2}));
 }
        private void TestCommon(Func<ITestObject> generator)
        {
            stream.Seek(0, SeekOrigin.Begin);
            var obj = generator();
            input.Write(obj);
            stream.Seek(0, SeekOrigin.Begin);
            var obj2 = output.Read();

            TestResult(obj, (ITestObject)obj2);
        }
Exemple #27
0
        private int CountPixelsVertical(LockBitmap locked, Func<Color, bool> colorFunc, IEnumerable<int> range, int x, IEnumerable<int> additionalRange = null)
        {
            int count = 0;

            foreach (var y in range)
            {
                var pixel = locked.GetPixel(x, y);
                if (colorFunc(pixel))
                {
                    count++;

                    if (additionalRange != null && additionalRange.All(ax => colorFunc(locked.GetPixel(ax, y))))
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }

            return count;
        }
        private void TestEvents(Func<Context, Int32> saveChangesAction) {
            insertingFiredCount = 0;
            updatingFiredCount = 0;
            deletingFiredCount = 0;
			insertFailedFiredCount = 0;
			updateFailedFiredCount = 0;
			deleteFailedFiredCount = 0;
            insertedFiredCount = 0;
            updatedFiredCount = 0;
			deletedFiredCount = 0;
			updateFailedThingValue = null;
            using (var context = new Context()) {
                var nickStrupat = new Person {
                                                 FirstName = "Nick",
                                                 LastName = "Strupat",
                                             };
                AddHandlers(nickStrupat);
				nickStrupat.Triggers().Deleting += e => {
					e.Entity.IsMarkedDeleted = true;
					e.Cancel();
				};
                context.People.Add(nickStrupat);

	            var johnSmith = new Person {
                                               FirstName = "John",
                                               LastName = "Smith"
                                           };
                AddHandlers(johnSmith);
                context.People.Add(johnSmith);
                AssertNoEventsHaveFired();

                saveChangesAction(context);
				Assert.IsTrue(nickStrupat.Number == 42);
                AssertInsertEventsHaveFired();
				Assert.IsTrue(context.Things.First().Value == "Insert trigger fired for Nick");

                nickStrupat.FirstName = "Nicholas";
                saveChangesAction(context);
				AssertUpdateEventsHaveFired();

				nickStrupat.LastName = null;
				try {
					context.SaveChanges();
				}
				catch (DbEntityValidationException ex) {
					nickStrupat.LastName = "Strupat";
				}
				catch (Exception ex) {
					Assert.Fail(ex.GetType().Name + " exception caught");
				}
				context.SaveChanges();
				Assert.AreEqual(updateFailedFiredCount, 1);
				Assert.IsTrue(context.Things.OrderByDescending(x => x.Id).First().Value == updateFailedThingValue);

                context.People.Remove(nickStrupat);
                context.People.Remove(johnSmith);
                saveChangesAction(context);
				AssertAllEventsHaveFired();

                context.Database.Delete();
            }
        }
Exemple #29
0
        private List<Line> GetTooltipBlackLines(LockBitmap locked, Rectangle searchArea, int projectedTooltipWidth, Func<double, int> v, Graphics g)
        {
            var lines = new List<Line>();

            Func<Color, bool> blackFunc = c => c.R < 10 && c.G < 10 && c.B < 10;
            var blackLinesThreshold = (int)Math.Floor(0.6 / 100 * locked.Height); // 0,6% of Height

            // It doesn't make sense to start search at the beginning of searchArea as it always covers the upper-left corner,
            // so we can skip this first vertical scanline to save some time (wouldn't find black lines there anyway).
            // In most cases tooltip will be found in first iteration as long as it was on the left side of the mouse cursor,
            // otherwise it should take no more than 2 iterations of the outer loop
            for (int x = searchArea.Left + projectedTooltipWidth * 3 / 4; x < searchArea.Right; x += projectedTooltipWidth * 3 / 4)
            {
                int? firstLineX = null;

                g.DrawLine(Pens.Red, x, searchArea.Top, x, searchArea.Bottom);

                for (int y = searchArea.Top; y < searchArea.Bottom; y++)
                {
                    var pixel = locked.GetPixel(x, y);

                    if (blackFunc(pixel))
                    {
                        var leftRange = Enumerable.Range(searchArea.Left, x - searchArea.Left).Reverse(); // search until the searchArea.Left as it covers the upper-left corner
                        var rightRange = Enumerable.Range(x + 1, (int)(projectedTooltipWidth * 1.2));

                        int left = CountPixelsHorizontal(locked, blackFunc, leftRange, y); // count black pixels to the left from current pos
                        int right = CountPixelsHorizontal(locked, blackFunc, rightRange, y); // count black pixels to the right from current pos

                        var line_width = left + right + 1;

                        if (line_width > v(39))
                        {
                            // make bigger steps when longer lines are found, they waste a lot of pixels and give no results (step is almost like tooltip border width)
                            y += v(0.5);
                            continue;
                        }
                        if (line_width > v(37) && line_width < v(39)) // potential tooltip width, can't calculate it to the pixel's accuracy
                        {
                            if (!firstLineX.HasValue && lines.Count > 0 && lines.Last().P1.X != x - left) // group only lines with the same x-pos
                            {
                                lines.Clear();
                            }

                            if (!firstLineX.HasValue || lines[0].P1.X == x - left)
                            {
                                lines.Add(new Line(new Point(x - left, y), new Point(x + right, y)));
                                g.DrawLine(Pens.Lime, lines.Last().P1, lines.Last().P2);
                            }

                            if (!firstLineX.HasValue && lines.Count > blackLinesThreshold) // just found the beginning of the tooltip
                            {
                                firstLineX = lines[0].P1.X;

                                // already found a potential tooltip, so need to adjust X a bit, so that it's more efficiently used (as less pixels checked as possible)
                                // leaving it as it is would cause the algorithm to find a lot of black areas inside the tooltip (and a lot of pixels read for no reason),
                                // but if we move X just next to the left border then the other inner border of the tooltip will stop search very soon for each line, reducing the number of checked pixels massively
                                // Note: it's safe to modify a loop iterator as the code won't iterate more over the outer loop anyway (see below: if (firstLineX.HasValue))
                                x = firstLineX.Value;

                                searchArea.Height = locked.Height - searchArea.Top; // extend searchArea to the bottom (almost.. see comment below)
                            }
                        }
                    }
                    else if (firstLineX.HasValue) // no need to search until the very bottom of the screenshot, last "black" pixel is for sure last "black" line in the tooltip
                    {
                        break;
                    }
                }

                if (firstLineX.HasValue)
                {
                    return lines;
                }
            }

            return null;
        }
 public AsyncTestDriver(ITestOutputHelper testOutputHelper, Action<ITestOutputHelper, Options, Output> action, Func<Options, bool> skipTest)
   : this(testOutputHelper, action, skipTest, MaxWaitHandles_Default)
 { }