public void Setup_a_type_using_implicit_conversion()
        {
            SingleDependencyClass sut = new Spec<SingleDependencyClass>();

            sut.ShouldNotBeNull()
                .ShouldBeOfType<SingleDependencyClass>();
        }
Example #2
1
 public async Task AsyncMethodFindsRightTestClass()
 {
     var spec = new Spec("");
     await spec.ExecuteAsync();
     PAssert.IsTrue(() => spec.CallingMethod.DeclaringType == typeof(ReflectionTests));
     PAssert.IsTrue(() => spec.CallingMethod.Name == "AsyncMethodFindsRightTestClass");
 }
        public void Setup_a_type_with_zero_dependencies()
        {
            ZeroDependencyClass sut = new Spec<ZeroDependencyClass>();

            sut.ShouldNotBeNull()
                .ShouldBeOfType<ZeroDependencyClass>();
        }
Example #4
1
 public void NormalMethodFindsRightTestClass()
 {
     var spec = new Spec("");
     spec.ExecuteAsync().Wait();
     PAssert.IsTrue(() => spec.CallingMethod.DeclaringType == typeof(ReflectionTests));
     PAssert.IsTrue(() => spec.CallingMethod.Name == "NormalMethodFindsRightTestClass");
 }
        public void Setup_a_type_using_builder_method()
        {
            var sut = new Spec<SingleDependencyClass>().Build();

            sut.ShouldNotBeNull()
                .ShouldBeOfType<SingleDependencyClass>();
        }
        public void Dependency_has_protected_constructor()
        {
            var spec = new Spec<DependencyWithProtectedConstructor>();
            var sut = spec.Build();

            //Should fall back to default mocked instance
            sut.Echo("foo").ShouldBeNull();
        }
 public void Deep_level_dependency_mock()
 {
     var sut = new Spec<DeepDependencyClass>();
     sut.The<IFirstDependency>()
         .Setup(fd => fd.StringValue).Returns("Gorilla");
     sut.The<ISecondDependency>()
         .Setup(sd => sd.Calculate()).Returns(5150);
     var instance = sut.Build();
     instance.NumericValue.ShouldEqual(5150);
     instance.StringValue.ShouldEqual("Gorilla");
 }
 public void Multi_dependency_subject_with_mocks()
 {
     var sut = new Spec<MultiDependencyClass>();
     sut.The<IFirstDependency>()
         .Setup(fd => fd.StringValue).Returns("Gorilla");
     sut.The<ISecondDependency>()
         .Setup(sd => sd.Calculate()).Returns(5150);
     var instance = sut.Build();
     instance.TheNumber.ShouldEqual(5150);
     instance.TheValue.ShouldEqual("Gorilla");
 }
        public void Specify_mock_for_dependency_has_protected_constructor()
        {
            var spec = new Spec<DependencyWithProtectedConstructor>();
            spec.The<IProtectedConstructor>()
                .Setup(c => c.Echo("foo"))
                .Returns("NotFoo");
            var sut = spec.Build();

            //Should fall back to specific mocked instance
            sut.Echo("foo").ShouldEqual("NotFoo");
        }
        public void PostConditionBeforeInvariant()
        {
            ITestRunReport stub = MockRepository.GenerateMock<ITestRunReport>();
            CounterAssert assert = new CounterAssert();
            Spec spec =
                new Spec(
                    () => assert.Count(2))
                    .IfAfter(() => assert.CountAsCondition(1));

            spec.Verify(null, stub);
        }
        public void Setup_mocked_operations_on_a_type_with_more_than_one_interface_dependency()
        {
            var spec = new Spec<MultiDependencyClass>();

            spec.The<IFirstDependency>().SetupGet(fd => fd.StringValue).Returns("TheValue");
            spec.The<ISecondDependency>().Setup(sd => sd.Calculate()).Returns(42);

            var sut = spec.Build();

            sut.ShouldNotBeNull()
                .ShouldBeOfType<MultiDependencyClass>()
                .TheValue.ShouldEqual("TheValue");
            sut.TheNumber.ShouldEqual(42);
        }
Example #12
1
 public void AddingADelegateStepThrowsAnException()
 {
     var spec = new Spec("");
     try
     {
         //can't use Assert.Throws here as that would introduce an extra lambda
         spec.And(() => Foo("x"));
     }
     catch (ArgumentException e)
     {
         return; //pass
     }
     throw new Exception("Expected method to throw exception");
 }
        public IList<ESiteMessage> GetSiteMessages(int top, int userId, bool isRead = false)
        {
            Spec<ESiteMessage> sp = new Spec<ESiteMessage>();
            sp.And(p => p.IsRead == isRead);
            var userIds = _rep.GetList<EUser>(0, p => p.ParentUserId == userId, p => new Columns(p.Id))
                .Select(p => p.Id)
                .ToList();
            userIds.Add(userId);

            sp.And(p => p.ReceiveUserId.In(string.Join(",", userIds)));

            return _rep.GetList<ESiteMessage>(top, sp, p => new Columns(p.Id.Desc()));

        }
        public void Setup_a_mocked_operation_on_a_type_with_an_interface_dependency()
        {
            var spec = new Spec<SingleDependencyClass>();

            spec.The<IFirstDependency>()
                .SetupGet(d => d.StringValue)
                .Returns("TheValue");

            var sut = spec.Build();

            sut.ShouldNotBeNull()
                .ShouldBeOfType<SingleDependencyClass>()
                .TheValue
                .ShouldNotBeNull()
                .ShouldEqual("TheValue");
        }
        public void Setup_multiple_mocked_operations_on_a_single_interface_dependency()
        {
            var spec = new Spec<AnotherClass>();

            spec.The<IDependency>()
                .Setup(x => x.FirstOperation())
                .Returns("Foo");

            spec.The<IDependency>()
                .Setup(x => x.SecondOperation())
                .Returns("Bar");

            var sut = spec.Build();

            sut.Write().ShouldEqual("FooBarFoo");
        }
        public void VerifyDoesNotCallPreConditon()
        {
            ITestRunReport stub = MockRepository.GenerateMock<ITestRunReport>();
            CounterAssert assert = new CounterAssert();
            Spec spec =
                new Spec(
                    () => assert.Count(1))
                    .If(
                    () =>
                        {
                            Assert.Fail();
                            return true;
                        });

            spec.Verify(null, stub);
        }
        public IPageList<ESiteMessage> SearchSiteMessages(int? userId, bool? isRead, string searchKeyword, string searchType, DateTime? startTime, DateTime? endTime, string orderName, string orderType, int pageIndex, int pageSize)
        {
            Spec<ESiteMessage> sp = new Spec<ESiteMessage>();
            if (searchKeyword.HasValue())
            {
                if (!searchType.HasValue())
                {
                    sp.And(p => p.Title.Like(searchKeyword)).Or(p => p.Content.Like(searchKeyword));
                }
                else
                {
                    sp.And(p => p.Column(searchType).Like(searchKeyword));
                }
            }

            if (isRead.HasValue)
            {
                sp.And(p => p.IsRead == isRead);
            }

            if (userId.HasValue)
            {
                var userIds = _rep.GetList<EUser>(0, p => p.ParentUserId == userId, p => new Columns(p.Id))
                    .Select(p => p.Id)
                    .ToList();
                userIds.Add(userId.Value);

                sp.And(p => p.ReceiveUserId.In(string.Join(",", userIds)));
            }

            if (startTime.HasValue) sp.And(p => p.CreateTime >= startTime);
            if (endTime.HasValue) sp.And(p => p.CreateTime <= endTime);

            var cp = new CSpec<ESiteMessage>();

            if (orderType.HasValue())
            {
                cp.And(orderName, orderType);
            }

            return _rep.GetPageList<ESiteMessage>(pageIndex, pageSize, sp, cp);
        }
        public IPageList<EMileageReportDay> SearchMileageReportDays(int deviceId, DateTime st, DateTime et, string orderName, string orderType, int pageIndex, int pageSize)
        {

            if (et > DateTime.Now)
            {
                et = DateTime.Now;
            }

            //生成查询时间段
            var day = (et - st).TotalDays;
            var dts = new List<DateTime>();
            for (var i = 0; i <= day; i++)
            {
                dts.Add(st.AddDays(i).GetDayStartTime());
            }

            var sp = new Spec<EMileageReportDay>();
            sp.And(p => p.DeviceId == deviceId && p.ReportDay >= st.GetDayStartTime() && p.ReportDay <= et.GetDayStartTime());

            //获取已经生成的数据
            var haveddks =
                _rep.GetList<EMileageReportDay>(0, sp,
                    p => new Columns(p.ReportDay)).Select(p => p.ReportDay.GetDayStartTime()).ToList();

            foreach (var ddk in dts)
            {
                if (!haveddks.Contains(ddk))
                {
                    //发现当前日期的数据没有生成 那么开始生成
                    CreateMileageReportDayByReportDay(deviceId, ddk);
                }
            }

            var cp = new CSpec<EMileageReportDay>();

            if (orderType.HasValue())
            {
                cp.And(orderName, orderType);
            }
            return _rep.GetPageList<EMileageReportDay>(pageIndex, pageSize, sp, cp);
        }
Example #19
1
        /// <summary>
        /// ËÑË÷
        /// </summary>
        /// <returns></returns>
        public IPageList<EGuestbook> SearchGuestbooks(int? userId, string searchKeyword, string searchType, string orderName, string orderType, int pageIndex, int pageSize)
        {
            Spec<EGuestbook> sp = new Spec<EGuestbook>();
            if (searchKeyword.HasValue())
            {
                if (!searchType.HasValue())
                {
                    sp.And(p => p.NickName.Like(searchKeyword))
                        //.Or(p => p.Phone.Like(searchKeyword))
                        //.Or(p => p.Email.Like(searchKeyword))
                        //.Or(p => p.Fax.Like(searchKeyword))
                        //.Or(p => p.Mobile.Like(searchKeyword))
                        //.Or(p => p.Phone.Like(searchKeyword))
                        //.Or(p => p.ReplyContent.Like(searchKeyword))
                        //.Or(p => p.ReplyUserName.Like(searchKeyword))
                        .Or(p => p.Content.Like(searchKeyword));
                }
                else
                {
                    sp.And(p => p.Column(searchType).Like(searchKeyword));
                }
            }

            if (userId.HasValue)
            {
                sp.And(p => p.UserId == userId);
            }

            var cp = new CSpec<EGuestbook>();

            if (orderType.HasValue())
            {
                cp.And(orderName, orderType);
            }

            return _rep.GetPageList<EGuestbook>(pageIndex, pageSize, sp, cp);
        }
        public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
        {
            using (var memoryBuffer = new MemoryStream(1024))
            using (var streamWriter = new StreamWriter(memoryBuffer, utf8Encoding))
            {
                WriteQuery(new JsonWriter(streamWriter), query);
                streamWriter.Flush();

                var data = memoryBuffer.ToArray();
                memoryBuffer.Seek(0, SeekOrigin.Begin);

                if (logger.InformationEnabled())
                {
                    string dataStr = Encoding.UTF8.GetString(data);
                    logger.Information("JSON query: {0}", dataStr);
                }

                var tokenHeader = BitConverter.GetBytes(query.token);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(tokenHeader, 0, tokenHeader.Length);
                memoryBuffer.Write(tokenHeader, 0, tokenHeader.Length);

                var lengthHeader = BitConverter.GetBytes(data.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(lengthHeader, 0, lengthHeader.Length);
                memoryBuffer.Write(lengthHeader, 0, lengthHeader.Length);

                memoryBuffer.Write(data, 0, data.Length);

                logger.Debug("Writing packet, {0} bytes", data.Length);
                data = memoryBuffer.ToArray();
                await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
        }
Example #21
0
        protected Fixture()
        {
            testMethods = new Dictionary<Spec, FactInfo>();
            var specs = GetType()
                .GetMethods()
                .Where(mi => mi.HasAttribute<SpecAttribute>());

            foreach (var mi in specs)
            {
                var action = (Action)Delegate.CreateDelegate(typeof (Action), this, mi);
                var spec = new Spec(action) { Name = GetType().Name + "." + mi.Name};
                testMethods[spec] = new FactInfo { Name = spec.Name };
            }

            specs = GetType()
                .GetMethods()
                .Where(mi => mi.ReturnType == typeof(Spec));

            foreach (var mi in specs)
            {
                var action = (Func<Spec>)Delegate.CreateDelegate(typeof(Func<Spec>), this, mi);
                var spec = action();
                spec.Name = GetType().Name + "." + mi.Name;
                testMethods[spec] = new FactInfo { Name = spec.Name };
            }
        }
 public void Setup_a_class_with_an_implemented_interface_dependency()
 {
     // SingleDependencyClass has a constructor with an interface
     // dependency which has an implementation
     var instance = new Spec<SingleDependencyClass>().Build();
     instance.TheValue.ShouldEqual("Monkey");
 }
Example #23
0
 public AddToBehavior(string name, Type type, Spec spec, Rule rule)
 {
     Name = name;
     Type = type;
     Spec = spec;
     Rule = rule;
 }
Example #24
0
        public Runner(Spec spec)
        {
            this.spec = spec;

            preExistingExample = spec.Example;
            preExistingSetUpAction = spec.SetUpAction;
            preExistingTearDownAction = spec.TearDownAction;
        }
 internal Parameter(Symbol symbol, Spec spec, IExpression initCode)
 {
     if (symbol.isDynamic)
         throw new Exception("Dynamic variables cannot be parameters to functions or let");
     if (symbol is Keyword)
         throw new Exception("Keywords cannot be parameters to functions or let");
     this.symbol = symbol;
     this.spec = spec;
     this.initCode = initCode;
 }
        public override async Task WriteQueryToStream(Stream stream, ILogger logger, Spec.Query query, CancellationToken cancellationToken)
        {
            using (var memoryBuffer = new MemoryStream(1024))
            {
                Serializer.Serialize(memoryBuffer, query);

                var data = memoryBuffer.ToArray();
                var lengthHeader = BitConverter.GetBytes(data.Length);
                if (!BitConverter.IsLittleEndian)
                    Array.Reverse(lengthHeader, 0, lengthHeader.Length);

                logger.Debug("Writing packet, {0} bytes", data.Length);
                await stream.WriteAsync(lengthHeader, 0, lengthHeader.Length, cancellationToken);
                await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            }
        }
 private static void WriteQuery(JsonWriter writer, Spec.Query query)
 {
     writer.BeginArray();
     writer.WriteNumber((int)query.type);
     if (query.type == Spec.Query.QueryType.START)
     {
         WriteTerm(writer, query.query);
         writer.BeginObject();
         foreach (var opt in query.global_optargs)
         {
             writer.WriteMember(opt.key);
             WriteTerm(writer, opt.val);
         }
         writer.EndObject();
     }
     writer.EndArray();
 }
        public static void PrintOutcomes(Spec spec)
        {
            Console.WriteLine("> SpecLight results:");
            Console.WriteLine();
            if (spec.SpecTags.Any())
            {
                Console.WriteLine(String.Join(", ", spec.SpecTags.Select(x => "@" + x)));
            }
            Console.WriteLine(spec.Description);
            Console.WriteLine();
            
            var specData = spec.DataDictionary.FormatExtraData();
            if (!string.IsNullOrWhiteSpace(specData))
            {
                Console.WriteLine(specData);
                Console.WriteLine();
            }

            if (!spec.Outcomes.Any())
            {
                return;
            }

            var maxMessageWidth = spec.Outcomes.Max(x => x.Step.Description.Length + x.Step.FormattedType.Length) + 3;
            foreach (var o in spec.Outcomes)
            {
                var step = o.Step;
                var message = String.Format("{0} {1}:", step.FormattedType, step.Description);
                var s = o.Status.ToString();
                if (o.Empty)
                {
                    s += Empty;
                }
                var cells = new[]
                {
                    message.PadRight(maxMessageWidth), 
                    s.PadRight(MaxStepOutcomeNameLength + 1), 
                    string.Join(", ", step.Tags.Select(x => "@" + x)),
                    step.DataDictionary.FormatExtraData()
                };
                Console.WriteLine(string.Join("\t", cells.Where(x => x != null)));
            }
        }
        public void GroupBy()
        {
            Spec.ForAny <int[]>(xs =>
            {
#if MONO_BUILD
                var x = xs.AsParallelQueryExpr().GroupBy(num => num.ToString()).Select(g => g.Count()).Sum().Run();
#else
                var x = (from num in xs.AsParallelQueryExpr()
                         group num by num.ToString() into g
                         select g.Count()).Sum()
                        .Run();
#endif

                var y = (from num in xs.AsParallel()
                         group num by num.ToString() into g
                         select g.Count()).Sum();

                return(x == y);
            }).QuickCheckThrowOnFailure();
        }
Example #30
0
        public void Pipelined()
        {
            using (var context = new GpuContext())
            {
                Spec.ForAny <int[]>(xs =>
                {
                    using (var _xs = context.CreateGpuArray(xs))
                    {
                        var x = context.Run(_xs.AsGpuQueryExpr()
                                            .Select(n => (float)n * 2)
                                            .Select(n => n + 1).ToArray());
                        var y = xs
                                .Select(n => (float)n * 2)
                                .Select(n => n + 1).ToArray();

                        return(x.SequenceEqual(y));
                    }
                }).QuickCheckThrowOnFailure();
            }
        }
Example #31
0
        public void Where()
        {
            using (var context = new GpuContext())
            {
                Spec.ForAny <int[]>(xs =>
                {
                    using (var _xs = context.CreateGpuArray(xs))
                    {
                        var x = context.Run((from n in _xs.AsGpuQueryExpr()
                                             where n % 2 == 0
                                             select n + 1).ToArray());
                        var y = (from n in xs
                                 where n % 2 == 0
                                 select n + 1).ToArray();

                        return(x.SequenceEqual(y));
                    }
                }).QuickCheckThrowOnFailure();
            }
        }
Example #32
0
        public void TestEmptyParsing()
        {
            Message signal = new EmptyMessage(MessageType.RST);

            signal.Type  = MessageType.NON;
            signal.ID    = 15;
            signal.Token = new byte[] { 33, 3, 5, 0, 39, 40 };

            byte[] bytes = Spec.NewMessageEncoder().Encode(signal);

            IMessageDecoder decoder = Spec.NewMessageDecoder(bytes);

            Assert.IsTrue(decoder.IsEmpty);

            Message result = decoder.Decode();

            Assert.AreEqual(signal.ID, result.ID);
            Assert.IsTrue(signal.Token.SequenceEqual(result.Token));
            Assert.IsTrue(signal.GetOptions().SequenceEqual(result.GetOptions()));
        }
Example #33
0
        private static ValidationResult <UserMessage> Map(UserMessageXml userMessage)
        {
            ValidationResult <UserMessage> CreateModel(UserMessageXml validated)
            {
                var transactionsResult = NonEmptyEnumerable <int> .Create(validated.Transactions);

                var propertiesResult =
                    validated.Properties.Traverse(MessageProperty.Create)
                    .SelectMany(ids => ids.AsUnique(p => p.Name));

                return(ValidationResult.Combine(
                           transactionsResult,
                           propertiesResult,
                           (ts, ps) => new UserMessage(ts, ps)));
            }

            return(Spec.Of <UserMessageXml>()
                   .NotNull("cannot create user message from 'null' input")
                   .CreateModel(userMessage, CreateModel));
        }
Example #34
0
 private BuffData(Spec spec, IReadOnlyDictionary <Spec, IReadOnlyList <Buff> > buffsBySpec, IReadOnlyDictionary <long, FinalActorBuffs> uptimes)
 {
     foreach (Buff buff in buffsBySpec[spec])
     {
         var boonVals = new List <object>();
         Data.Add(boonVals);
         if (uptimes.TryGetValue(buff.ID, out FinalActorBuffs uptime))
         {
             boonVals.Add(uptime.Uptime);
             if (buff.Type == Buff.BuffType.Intensity && uptime.Presence > 0)
             {
                 boonVals.Add(uptime.Presence);
             }
         }
         else
         {
             boonVals.Add(0);
         }
     }
 }
        public void ThenBy()
        {
            Spec.ForAny <DateTime[]>(ds =>
            {
                var x = ds.AsParallelQueryExpr()
                        .OrderBy(d => d.Year)
                        .ThenBy(d => d.Month)
                        .ThenBy(d => d.Day)
                        .ThenBy(d => d)
                        .Run();

                var y = ds.AsParallel().AsOrdered()
                        .OrderBy(d => d.Year)
                        .ThenBy(d => d.Month)
                        .ThenBy(d => d.Day)
                        .ThenBy(d => d);

                return(x.SequenceEqual(y));
            }).QuickCheckThrowOnFailure();
        }
Example #36
0
        private ProgramNode[] LearnAll(Spec spec, Feature <double> scorer, DomainLearningLogic witnessFunctions)
        {
            //See if there is a ranking function.
            ProgramSet consistentPrograms = LearnProgramSet(spec, witnessFunctions);

            if (scorer != null)
            {
                //If there is a ranking function then find the best program.
                ProgramNode bestProgram = consistentPrograms.TopK(scorer).FirstOrDefault();
                if (bestProgram == null)
                {
                    Utils.Utils.WriteColored(ConsoleColor.Red, "No program :(");
                    return(null);
                }
                var score = bestProgram.GetFeatureValue(scorer);
                Utils.Utils.WriteColored(ConsoleColor.Cyan, $"[score = {score:F3}] {bestProgram}");
                return(new ProgramNode[] { bestProgram });
            }
            return(consistentPrograms.AllElements.ToArray());
        }
Example #37
0
        private static void LoadAndTestSubstrings()
        {
            var grammar = LoadGrammar("ProseSample.Substrings.grammar",
                                      CompilerReference.FromAssemblyFiles(typeof(StringRegion).GetTypeInfo().Assembly,
                                                                          typeof(Substrings.Semantics).GetTypeInfo().Assembly,
                                                                          typeof(Record).GetTypeInfo().Assembly));

            if (grammar == null)
            {
                return;
            }

            StringRegion prose = new StringRegion("Microsoft Program Synthesis using Examples SDK", Token.Tokens);
            StringRegion sdk   = prose.Slice(prose.End - 3, prose.End);
            Spec         spec  = ShouldConvert.Given(grammar).To(prose, sdk);

            Learn(grammar, spec, new Substrings.RankingScore(grammar), new Substrings.WitnessFunctions(grammar));

            TestFlashFillBenchmark(grammar, "emails");
        }
Example #38
0
        public void Pipelined()
        {
            Spec.ForAny <int[]>(xs =>
            {
                var x = xs.AsQueryExpr()
                        .Where(n => n % 2 == 0)
                        .Select(n => n * 2)
                        .Select(n => n.ToString())
                        .Select(n => n + "!")
                        .Run();

                var y = xs
                        .Where(n => n % 2 == 0)
                        .Select(n => n * 2)
                        .Select(n => n.ToString())
                        .Select(n => n + "!");

                return(Enumerable.SequenceEqual(x, y));
            }).QuickCheckThrowOnFailure();
        }
Example #39
0
        public void SelectManyPipeline()
        {
            Spec.ForAny <int[]>(xs =>
            {
                var x = xs.AsQueryExpr()
                        .Where(num => num % 2 == 0)
                        .SelectMany(num => xs.Select(_num => num * _num))
                        .Select(i => i + 1)
                        .Sum()
                        .Run();

                var y = xs
                        .Where(num => num % 2 == 0)
                        .SelectMany(num => xs.Select(_num => num * _num))
                        .Select(i => i + 1)
                        .Sum();

                return(x == y);
            }).QuickCheckThrowOnFailure();
        }
Example #40
0
 public int SaveSpec(Spec spec)
 {
     return(Flash.Scalar <int>
            (
                Collection.Locate <IDbConnection>("quality"),
                "quality.spec_save",
                new
     {
         Id = spec.Id,
         name = spec.Name,
         customer = spec.Customer,
         location = spec.Location,
         title = spec.Title,
         control = spec.Control,
         revision = spec.Revision,
         amendment = spec.Amendment,
         fileunder = spec.FileUnder,
         supercededby = spec.SupercededBy,
         typematerial = spec.TypeMaterial,
         typeprocess = spec.TypeProcess,
         typeother = spec.TypeOther,
         allplants = spec.AllPlants,
         anaheim = spec.Anaheim,
         canton = spec.Canton,
         heavypress = spec.HeavyPress,
         noexceptions = spec.NoExceptions,
         waiversrequired = spec.WaiversRequired,
         limitedscope = spec.LimitedScope,
         notacceptable = spec.NotAcceptable,
         onfile = spec.OnFile,
         notreviewed = spec.NotReviewed,
         metreviewnotrequired = spec.MetReviewNotRequired,
         metrevieweveryorder = spec.MetReviewEveryOrder,
         metreviewrequiredwhen = spec.MetReviewRequiredWhen,
         metalurgicalreviewwhen = spec.MetalurgicalReviewWhen,
         reviewedby = spec.ReviewedBy,
         reviewedat = spec.ReviewedAt,
         supercedereviewdate = spec.SupercedeReviewDate
     }
            ));
 }
Example #41
0
        public void should_set_endpoint_headers_on_handlers_and_actions()
        {
            var endpoint = Spec.GetEndpoint <HeaderDescriptions.HeadersGetHandler>();

            endpoint.Request.Headers.Count.ShouldEqual(2);

            var header = endpoint.Request.Headers[0];

            header.Name.ShouldEqual("accept");
            header.Comments.ShouldEqual("This is an endpoint description.");
            header.Optional.ShouldBeTrue();
            header.Required.ShouldBeFalse();
            header.IsAccept.ShouldBeTrue();
            header.IsContentType.ShouldBeFalse();

            header = endpoint.Request.Headers[1];
            header.Name.ShouldEqual("api-key");
            header.Comments.ShouldEqual("This is a handler description.");
            header.Optional.ShouldBeFalse();
            header.Required.ShouldBeTrue();
            header.IsAccept.ShouldBeFalse();
            header.IsContentType.ShouldBeFalse();

            endpoint.Response.Headers.Count.ShouldEqual(2);

            header = endpoint.Response.Headers[0];
            header.Name.ShouldEqual("content-length");
            header.Comments.ShouldBeNull();
            header.Optional.ShouldBeFalse();
            header.Required.ShouldBeFalse();
            header.IsAccept.ShouldBeFalse();
            header.IsContentType.ShouldBeFalse();

            header = endpoint.Response.Headers[1];
            header.Name.ShouldEqual("content-type");
            header.Comments.ShouldBeNull();
            header.Optional.ShouldBeFalse();
            header.Required.ShouldBeFalse();
            header.IsAccept.ShouldBeFalse();
            header.IsContentType.ShouldBeTrue();
        }
        public void Pipelined()
        {
            Spec.ForAny <int[]>(xs =>
            {
                var x = xs.AsParallelQueryExpr()
                        .Where(n => n % 2 == 0)
                        .Select(n => n * 2)
                        .Select(n => n * n)
                        .Sum()
                        .Run();

                var y = xs
                        .AsParallel()
                        .Where(n => n % 2 == 0)
                        .Select(n => n * 2)
                        .Select(n => n * n)
                        .Sum();

                return(x == y);
            }).QuickCheckThrowOnFailure();
        }
Example #43
0
 private void ReadState()
 {
     if (File.Exists(stateFilePath))
     {
         using (var fs = File.Open(stateFilePath, FileMode.Open, FileAccess.Read))
         {
             using (var tr = new StreamReader(fs))
             {
                 using (var jr = new JsonTextReader(tr))
                 {
                     var serializer = new JsonSerializer();
                     this.spec = serializer.Deserialize <Spec>(jr);
                 }
             }
         }
     }
     else
     {
         this.spec = new Spec();
     }
 }
Example #44
0
        public void Count()
        {
            using (var context = new GpuContext(platformWildCard))
            {
                Spec.ForAny <int[]>(xs =>
                {
                    using (var _xs = context.CreateGpuArray(xs))
                    {
                        var x = context.Run((from n in _xs.AsGpuQueryExpr()
                                             where n % 2 == 0
                                             select n + 1).Count());

                        var y = (from n in xs
                                 where n % 2 == 0
                                 select n + 1).Count();

                        return(x == y);
                    }
                }).QuickCheckThrowOnFailure();
            }
        }
Example #45
0
        public void PreCompileAction()
        {
            Spec.ForAny <int>(i =>
            {
                if (i < 1)
                {
                    return(true);
                }

                var xs = new List <int>();
                Expression <Func <int, IQueryExpr> > lam = m => QueryExpr.Range(1, m).ForEach(n => xs.Add(n));
                Action <int> t = Extensions.Compile <int>(lam);

                t(i);

                var ys = new List <int>();
                Enumerable.Range(1, i).ToList().ForEach(n => ys.Add(n));

                return(Enumerable.SequenceEqual(xs, ys));
            }).QuickCheckThrowOnFailure();
        }
Example #46
0
        }                                  //0x10


        //#define BEID_FIELD_TAG_ID_PhotoHash				0x11
        //#define BEID_FIELD_TAG_ID_Duplicata				0x12
        //#define BEID_FIELD_TAG_ID_SpecialOrganization	0x13
        //#define BEID_FIELD_TAG_ID_MemberOfFamily		0x14
        //#define BEID_FIELD_TAG_ID_DateAndCountryOfProtection	0x15
        //#define BEID_FIELD_TAG_ID_WorkPermitType		0x16
        //#define BEID_FIELD_TAG_ID_Vat1					0x17
        //#define BEID_FIELD_TAG_ID_Vat2					0x18
        //#define BEID_FIELD_TAG_ID_RegionalFileNumber	0x19
        //#define BEID_FIELD_TAG_ID_BasicKeyHash			0x1A


        public Identity(byte[] file)
        {
            IDictionary <byte, byte[]> d = file.Parse();

            CardNr                      = d[0x01].ToStr();
            ChipNr                      = d[0x02];
            ValidityBeginDate           = d[0x03].ToDate();
            ValidityEndDate             = d[0x04].ToDate();
            IssuingMunicipality         = d[0x05].ToStr();
            NationalNr                  = d[0x06].ToStr();
            Surname                     = d[0x07].ToStr();
            FirstNames                  = d[0x08].ToStr();
            FirstLetterOfThirdGivenName = d[0x09].ToStr();
            Nationality                 = d[0x0A].ToStr();
            LocationOfBirth             = d[0x0B].ToStr();
            DateOfBirth                 = d[0x0C].ToBirthDate();
            Gender                      = d[0x0D].ToGender();
            Nobility                    = d[0x0E].ToStr();
            DocumentType                = d[0x0F].ToDocType();
            SpecialStatus               = d[0x10].ToSpec();
        }
Example #47
0
        public Spec getSpec(int accountid)
        {
            Spec spec = null;

            Debug.WriteLine("gdfgfd" + spec + "gfd");
            if (repo.GetSpec(accountid) != null)
            {
                spec = repo.GetSpec(accountid);
            }

            if (spec != null)
            {
                Debug.WriteLine("Entered");
            }
            else
            {
                Debug.WriteLine("NotEntered");
            }

            return(spec);
        }
Example #48
0
        public void AppleOrOrangeJuice()
        {
            // Arrange
            Drink         blackberryJuice = Drink.BlackberryJuice();
            Drink         appleJuice      = Drink.AppleJuice();
            Drink         orangeJuice     = Drink.OrangeJuice();
            ASpec <Drink> juiceSpec       = new Spec <Drink>(d => d.With.Any(w => w.ToLower().Contains("juice")));
            ASpec <Drink> appleSpec       = new Spec <Drink>(d => d.With.Any(w => w.ToLower().Contains("apple")));
            ASpec <Drink> orangeSpec      = new Spec <Drink>(d => d.With.Any(w => w.ToLower().Contains("orange")));

            // Act
            var appleOrOrangeJuice = juiceSpec & (appleSpec | orangeSpec);

            // Assert
            appleOrOrangeJuice.IsSatisfiedBy(appleJuice).Should().BeTrue();
            appleOrOrangeJuice.IsSatisfiedBy(orangeJuice).Should().BeTrue();
            appleOrOrangeJuice.IsSatisfiedBy(blackberryJuice).Should().BeFalse();
            // And
            new[] { appleJuice, orangeJuice }.Are(appleOrOrangeJuice).Should().BeTrue();
            blackberryJuice.Is(appleOrOrangeJuice).Should().BeFalse();
        }
Example #49
0
        public void TestGenerateOutputOnEmptySpec()
        {
            // arrange
            var spec =
                new Spec
            {
                Targets = new Dictionary <string, TargetInfo>
                {
                    { Constants.CSharpTarget, new TargetInfo {
                          Path = "some_path", Namespace = "Blogged"
                      } }
                }
            };
            var generator = new CSharpGenerator();

            // act
            var outputs = generator.GenerateOutputs(spec);

            // assert
            Assert.Equal(0, outputs.Count());
        }
Example #50
0
        private Tuple <INakedObjectAdapter, TypeOfDefaultValue> GetDefaultValueAndType(INakedObjectAdapter nakedObjectAdapter)
        {
            if (parentAction.IsContributedMethod && nakedObjectAdapter != null)
            {
                IActionParameterSpec[] matchingParms = parentAction.Parameters.Where(p => nakedObjectAdapter.Spec.IsOfType(p.Spec)).ToArray();

                if (matchingParms.Any() && matchingParms.First() == this)
                {
                    return(new Tuple <INakedObjectAdapter, TypeOfDefaultValue>(nakedObjectAdapter, TypeOfDefaultValue.Explicit));
                }
            }

            Tuple <object, TypeOfDefaultValue> defaultValue = null;

            // Check Facet on parm, then facet on type finally fall back on type;

            var defaultsFacet = GetFacet <IActionDefaultsFacet>();

            if (defaultsFacet != null && !defaultsFacet.IsNoOp)
            {
                defaultValue = defaultsFacet.GetDefault(parentAction.RealTarget(nakedObjectAdapter));
            }

            if (defaultValue == null)
            {
                var defaultFacet = Spec.GetFacet <IDefaultedFacet>();
                if (defaultFacet != null && !defaultFacet.IsNoOp)
                {
                    defaultValue = new Tuple <object, TypeOfDefaultValue>(defaultFacet.Default, TypeOfDefaultValue.Implicit);
                }
            }

            if (defaultValue == null)
            {
                object rawValue = nakedObjectAdapter == null ? null : nakedObjectAdapter.Object.GetType().IsValueType ? (object)0 : null;
                defaultValue = new Tuple <object, TypeOfDefaultValue>(rawValue, TypeOfDefaultValue.Implicit);
            }

            return(new Tuple <INakedObjectAdapter, TypeOfDefaultValue>(manager.CreateAdapter(defaultValue.Item1, null, null), defaultValue.Item2));
        }
Example #51
0
        private bool isAssignable(Spec s, Spec slot)
        {
            C.Nn(s, slot);

            switch (slot)
            {
            case NotSetSpec _:
            case AnySpec _:
                return(true);

            case VoidSpec _:
                return(s is VoidSpec);

            case IntSpec _:
                return(s is IntSpec);

            case CharSpec _:
                return(s is CharSpec);

            case BoolSpec _:
                return(s is BoolSpec);

            case TextSpec _:
                return(s is TextSpec);

            case ArrSpec slotArr:
                return(s is ArrSpec sArr && areSame(sArr.ItemSpec, slotArr.ItemSpec));

            case FnSpec slotFn:
                return(s is FnSpec sFn &&
                       areAssignable(slotFn.ParameterSpec, sFn.ParameterSpec) &&
                       (slotFn.ReturnSpec is VoidSpec || isAssignable(sFn.ReturnSpec, slotFn.ReturnSpec)));

            case ObjSpec slotObj:
                return(s is ObjSpec sObj && isObjAssignable(sObj, slotObj));

            default:
                return(false);
            }
        }
 public Property InterleavePropertyFluent(IList <int> xsParam, IList <int> ysParam)
 {
     return(Spec
            .For(Any.Value(xsParam), Any.Value(ysParam), (xs, ys) =>
     {
         var res = Interleaving.Interleave(xs, ys);
         return xs.Count + ys.Count == res.Count();
     }).Label("length")
            .And((xs, ys) =>
     {
         var res = Interleaving.Interleave(xs, ys);
         var idxs = Enumerable.Range(0, Math.Min(xs.Count, ys.Count)).ToList();
         return xs.SequenceEqual(idxs.Select(idx => res[2 * idx]).Concat(res.Skip(2 * ys.Count)));
     }, "zip xs")
            .And((xs, ys) =>
     {
         var res = Interleaving.Interleave(xs, ys);
         var idxs = Enumerable.Range(0, Math.Min(xs.Count, ys.Count)).ToList();
         return ys.SequenceEqual(idxs.Select(idx => res[2 * idx + 1]).Concat(res.Skip(2 * xs.Count)));
     }, "zip ys")
            .Build());
 }
 public void InterleaveTestFluent()
 {
     Spec
     .For(Any.OfType <IList <int> >(), Any.OfType <IList <int> >(), (xs, ys) =>
     {
         var res = Interleaving.Interleave(xs, ys);
         return(xs.Count + ys.Count == res.Count());
     }).Label("length")
     .And((xs, ys) =>
     {
         var res  = Interleaving.Interleave(xs, ys);
         var idxs = Enumerable.Range(0, Math.Min(xs.Count, ys.Count)).ToList();
         return(xs.SequenceEqual(idxs.Select(idx => res[2 * idx]).Concat(res.Skip(2 * ys.Count))));
     }, "zip xs")
     .And((xs, ys) =>
     {
         var res  = Interleaving.Interleave(xs, ys);
         var idxs = Enumerable.Range(0, Math.Min(xs.Count, ys.Count)).ToList();
         return(ys.SequenceEqual(idxs.Select(idx => res[2 * idx + 1]).Concat(res.Skip(2 * xs.Count))));
     }, "zip ys")
     .Check(Configuration);
 }
Example #54
0
        public void TestRequestParsing()
        {
            Request request = new Request(Method.POST, false);

            request.ID    = 7;
            request.Token = new Byte[] { 11, 82, 165, 77, 3 };
            request.AddIfMatch(new Byte[] { 34, 239 })
            .AddIfMatch(new Byte[] { 88, 12, 254, 157, 5 });
            request.ContentType = 40;
            request.Accept      = 40;

            Byte[]          bytes   = Spec.NewMessageEncoder().Encode(request);
            IMessageDecoder decoder = Spec.NewMessageDecoder(bytes);

            Assert.IsTrue(decoder.IsRequest);

            Request result = decoder.DecodeRequest();

            Assert.AreEqual(request.ID, result.ID);
            Assert.IsTrue(request.Token.SequenceEqual(result.Token));
            Assert.IsTrue(request.GetOptions().SequenceEqual(result.GetOptions()));
        }
Example #55
0
        void Write(Spec spec, StreamWriter writer)
        {
            writer.WriteLine("#include<iostream>");
            writer.WriteLine("#include<vulkan/vulkan.h>");
            writer.WriteLine("#include<fstream>");
            writer.WriteLine();
            writer.WriteLine("int main() {");
            writer.WriteLine("    std::ofstream file;");
            writer.WriteLine("    file.open(\"offsets.txt\");");

            foreach (var s in spec.Structs)
            {
                if (s.Handle)
                {
                    continue;
                }
                if (spec.ExtensionTypes.Contains(s.Name))
                {
                    if (!spec.IncludedTypes.Contains(s.Name))
                    {
                        continue;
                    }
                }
                if (s.Name == "VkRect3D")
                {
                    continue;                       //defined in xml, but not in header
                }
                writer.WriteLine("    file << \"{0}\" << std::endl;", s.Name);
                writer.WriteLine("    file << sizeof({0}) << std::endl;", s.Name);
                foreach (var f in s.Fields)
                {
                    writer.WriteLine("        file << \"    {0}: \" << offsetof({1}, {0}) << std::endl;", f.Name, s.Name);
                }
                writer.WriteLine("    file << std::endl;");
                writer.WriteLine();
            }

            writer.WriteLine("}");
        }
        private static void testLearning(Grammar grammar)
        {
            var inputList = new[] { "Hello", "World!!!!!!", "Eureka!!", "oh!!" };

            var outputLists = new String[][] {
                new [] { "oh!!", "Hello", "Eureka!!", "World!!!!!!" },
                new [] { "Eureka!!", "oh!!", "Hello", "World!!!!!!" },
                new [] { "Hello", "oh!!", "World!!!!!!", "Eureka!!" },
                new [] { "Eureka!!", "oh!!", "World!!!!!!", "Hello" },
                new [] { "Hello", "oh!!", "Eureka!!", "World!!!!!!" },
                new [] { "Hello", "Eureka!!", "oh!!", "World!!!!!!" },
            };

            foreach (var outputList in outputLists)
            {
                Spec spec = ShouldConvert.Given(grammar).To(inputList, outputList);

                Learn(grammar, spec,
                      new SortKeySynthesis.Learning.RankingScore(grammar),
                      new SortKeySynthesis.Learning.Learners(grammar));
            }
        }
Example #57
0
        static void Main(string[] args)
        {
            string output = "output";

            if (!Directory.Exists(output))
            {
                Directory.CreateDirectory(output);
            }

            Spec spec;

            using (var reader = File.Open("vk.xml", FileMode.Open)) {
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                spec = new Spec(doc, 1, 0, null);
            }

            CppSpec   cppSpec = new CppSpec(spec);
            Generator g       = new Generator(cppSpec);

            g.WriteEnums(output);
        }
Example #58
0
        public void SelectManyComprehensionNestedTestTypeEraser()
        {
            Spec.ForAny <int>(max =>
            {
                if (max < 0)
                {
                    return(true);
                }

                var x = (from a in QueryExpr.Range(1, max + 1)
                         from b in Enumerable.Range(a, max + 1 - a)
                         where a * a + b * b == b
                         select Tuple.Create(a, b)).ToArray().Run();

                var y = (from a in Enumerable.Range(1, max + 1)
                         from b in Enumerable.Range(a, max + 1 - a)
                         where a * a + b * b == b
                         select Tuple.Create(a, b)).ToArray();

                return(Enumerable.SequenceEqual(x, y));
            }).QuickCheckThrowOnFailure();
        }
Example #59
0
        public static ProgramNode Learn(Grammar grammar, Spec spec)
        {
            var engine = new SynthesisEngine(grammar, new SynthesisEngine.Config
            {
                UseThreads = false,
                LogListener = new LogListener(),
            });
            ProgramSet consistentPrograms = engine.LearnGrammar(spec);
            engine.Configuration.LogListener.SaveLogToXML("learning.log.xml");

            //foreach (ProgramNode p in consistentPrograms.RealizedPrograms) {
            //    Console.WriteLine(p);
            //}

            ProgramNode bestProgram = consistentPrograms.TopK("Score").FirstOrDefault();
            if (bestProgram == null)
            {
                WriteColored(ConsoleColor.Red, "No program :(");
                return null;
            }
            var score = bestProgram["Score"];
            WriteColored(ConsoleColor.Cyan, $"[score = {score:F3}] {bestProgram}");
            return bestProgram;
        }
Example #60
0
 /// <summary>
 /// 获取当前定位数据
 /// </summary>
 /// <param name="coordinates"></param>
 /// <returns></returns>
 public VDeviceCurrentDataDetail GetVDeviceCurrentDataDetail(int? userId, int? deviceGroupId, EnumMapCoordinates coordinates)
 {
     var sp = new Spec<EDevice, EDeviceCurrentData>();
     if (userId.HasValue)
     {
         sp.And(p => p.UserId == userId);
     }
     if (deviceGroupId.HasValue)
     {
         var deviceGroup = _rep.Get<EDeviceGroup>(p => p.Id == deviceGroupId);
         if (deviceGroup.IsRoot)
         {
             //如果当前查询的是根分类 那么把没有分类的车辆一并查询了
             sp.And(p => p.DeviceGroupId == deviceGroupId || (p.UserId == deviceGroup.UserId && p.DeviceGroupId == 0));
         }
         else
         {
             sp.And(p => p.DeviceGroupId == deviceGroupId);
         }
     }
     var list = _rep.Query<EDevice, EDeviceCurrentData, VDeviceCurrentData>()
         .LeftJoin<EDeviceCurrentData>((d, c) => d.Id == c.DeviceId)
         .Where(sp)
         .Select((d, c) => new Columns(d.Id.As("DeviceId"), d.DeviceName, c)).ToList();
     return GetVDeviceCurrentDataDetailWrap(list, coordinates);
 }