示例#1
0
        public void GivenKeyAsString_WhenTypedGetItemIsCalled_ThenCorrectItemReturned()
        {
            //Assign
            const long id = 1L;

            const string propityValue = "NotDefaultValue";
            var fi = new FurnaceItemInformation<long> {Id = id, ContentTypeFullName = ContentType.FullName};
            var returnJson = new Stub
            {
                FurnaceItemInformation = fi,
                Test = propityValue
            }.BuildSerialisedString();

            var key = RedisBackedFurnaceItems.CreateItemKey(id, ContentType);

            Client.Hashes[key][SiteConfiguration.DefaultSiteCulture.Name].Returns(returnJson);

            ContentTypes.GetContentTypes().Returns(new[] {ContentType});

            //Act
            var result = Sut.GetItem(key);

            //Assert
            Assert.That(result.Id, Is.EqualTo(id));
            Assert.That(result["Test"], Is.EqualTo(propityValue));
            Assert.That(result.ContentType.Name, Is.EqualTo(ContentTypeName));
        }
 public void ShouldFireFromStronglyTypedLinqDerivedPropertyName()
 {
     var sample = new Stub();
     sample.ShouldFirePropertyChanged(
                         () => sample.Number++, 
                         LinqExtensions.GetPropertyName<Stub>(o => o.Number));
 }
        static void Main(string[] args)
        {
            var stub = new Stub();
            ;
            var tcp = new ViaTcp();
            var udp = new ViaUdp();
            var ec = new ViaEventCollector();
            var eco = new ViaEventCollectorWithExtendedOptions();

            eco.Configure();
            //ec.Configure();
            //udp.Configure();
            //tcp.Configure();

            Log.Information("Simulation running, press any key to exit.");

            stub.Run();

            var range = Enumerable.Range(0, 10000);

            foreach (var i in range)
            {
                Log.Information("Say hello to {0}", i);
            }

            Console.ReadLine();
        }
 public StubCalculationPeriod(XmlNode xmlNode)
 {
     XmlNodeList initialStubNodeList = xmlNode.SelectNodes("initialStub");
     if (initialStubNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in initialStubNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 initialStubIDRef = item.Attributes["id"].Name;
                 Stub ob = Stub();
                 IDManager.SetID(initialStubIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 initialStubIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 initialStub = new Stub(item);
             }
         }
     }
     
 
     XmlNodeList finalStubNodeList = xmlNode.SelectNodes("finalStub");
     if (finalStubNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in finalStubNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 finalStubIDRef = item.Attributes["id"].Name;
                 Stub ob = Stub();
                 IDManager.SetID(finalStubIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 finalStubIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 finalStub = new Stub(item);
             }
         }
     }
     
 
 }
 public StubCalculationPeriod(XmlNode xmlNode)
 {
     XmlNode initialStubNode = xmlNode.SelectSingleNode("initialStub");
     
     if (initialStubNode != null)
     {
         if (initialStubNode.Attributes["href"] != null || initialStubNode.Attributes["id"] != null) 
         {
             if (initialStubNode.Attributes["id"] != null) 
             {
                 initialStubIDRef_ = initialStubNode.Attributes["id"].Value;
                 Stub ob = new Stub(initialStubNode);
                 IDManager.SetID(initialStubIDRef_, ob);
             }
             else if (initialStubNode.Attributes["href"] != null)
             {
                 initialStubIDRef_ = initialStubNode.Attributes["href"].Value;
             }
             else
             {
                 initialStub_ = new Stub(initialStubNode);
             }
         }
         else
         {
             initialStub_ = new Stub(initialStubNode);
         }
     }
     
 
     XmlNode finalStubNode = xmlNode.SelectSingleNode("finalStub");
     
     if (finalStubNode != null)
     {
         if (finalStubNode.Attributes["href"] != null || finalStubNode.Attributes["id"] != null) 
         {
             if (finalStubNode.Attributes["id"] != null) 
             {
                 finalStubIDRef_ = finalStubNode.Attributes["id"].Value;
                 Stub ob = new Stub(finalStubNode);
                 IDManager.SetID(finalStubIDRef_, ob);
             }
             else if (finalStubNode.Attributes["href"] != null)
             {
                 finalStubIDRef_ = finalStubNode.Attributes["href"].Value;
             }
             else
             {
                 finalStub_ = new Stub(finalStubNode);
             }
         }
         else
         {
             finalStub_ = new Stub(finalStubNode);
         }
     }
     
 
 }
 public void ShouldFireFromMultipleStronglyTypedLinqDerivedPropertyName()
 {
     var sample = new Stub();
     sample.ShouldFirePropertyChanged(
                         sample.OnPropertyChangedViaLinkTest,
                                 LinqExtensions.GetPropertyName<Stub>(o => o.Text),
                                 LinqExtensions.GetPropertyName<Stub>(o => o.Number));
 }
        public void ShouldFirePropertyChangedEvent()
        {
            var model = new Stub();
            PropertyChangedEventArgs args = null;
            model.PropertyChanged += (sender, e) => args = e;

            model.Text = "New Value";
            args.PropertyName.ShouldBe(Stub.PropText);
        }
示例#8
0
 public void GivenJapaneseAsTheCultureSetUp()
 {
     CultureInfo = CultureInfo.GetCultureInfo("ja-JP");
     var fi = new FurnaceItemInformation<long>();
     CultureStub = new Stub
     {
         FurnaceItemInformation = fi,
         Test = "bonjour"
     };
 }
        public void TestSetup()
        {
            if (observer != null) observer.Dispose();
            eventCount = 0;

            element = new TextBlock();
            observer = new DataContextPropertyObserver<Stub>(element);

            viewModel = new Stub();
            observer.RegisterHandler(m => m.Text, m => eventCount++);
        }
        public void Initialize(DisposeWithViewModelTestControl control)
        {
            control.Width = 500;
            control.Height = 500;

            viewModel = new Stub();
            control.placeholder.DataContext = viewModel;

            viewModel.Disposed += delegate { Debug.WriteLine("View-Model Disposed"); };
            control.placeholder.Disposed += delegate { Debug.WriteLine("Placeholder Disposed"); };
        }
示例#11
0
        public void LocalisationTestsSetUp()
        {
            Id = 99L;
            Key = RedisBackedFurnaceItems.CreateItemKey(Id, typeof(Stub));
            var fi = new FurnaceItemInformation<long>();
            DefultCultureStub = new Stub
            {

                Test = "Hello"
            };
            Client.Hashes[Key][SiteConfiguration.DefaultSiteCulture.Name].Returns(DefultCultureStub.BuildSerialisedString());
        }
示例#12
0
        static void Main(string[] args)
        {
            var stub = new Stub();

            var http = new ViaHttp();
            var tcp = new ViaTcp();
            var udp = new ViaHttp();

            http.Configure();
            udp.Configure();
            tcp.Configure();

            Log.Information("Simulation running, press any key to exit.");

            stub.Run();

            Console.ReadLine();
        }
        public void ShouldFirePropertyChangedOnUiThread()
        {
            var uiThread = Thread.CurrentThread;
            Thread backgroundThread = null;

            var model = new Stub();
            model.PropertyChanged += delegate
                                         {
                                             // The event notification should arrive on the UI Thread.
                                             model.Text.ShouldBe("New Value");
                                             Thread.CurrentThread.ShouldBe(uiThread);
                                             EnqueueTestComplete();
                                         };

            ThreadStart backgroundAction = delegate
                                     {
                                         // Cause a property change to occur on the background thread.
                                         Thread.CurrentThread.ShouldBe(backgroundThread);
                                         model.Text = "New Value";
                                     };
            backgroundThread = new Thread(backgroundAction){Name = "Background"};
            uiThread.ShouldNotBe(backgroundThread);
            backgroundThread.Start();
        }
示例#14
0
 public static TypedBehaviorPreparable <IndirectionAction <System.Collections.Generic.List <T>, T> > AddT()
 {
     return(Stub <OfPList <T> > .Setup <IndirectionAction <System.Collections.Generic.List <T>, T> >(_ => _.AddT()));
 }
示例#15
0
 public override String AStringify(Stub Stub)
 {
     return(null);
 }
示例#16
0
 public BasicRequestHandler() : this(new FrontController(),
                                     Stub.with <StubRequestFactory>())
 {
 }
示例#17
0
 public override void Decompile(StringBuilder Buf, Stub OwnerStub, ref int Index)
 {
     Buf.Append(String.Format("R1[{0}]\t= {1}", OwnerStub.DecompileInstruction_B(this), OwnerStub.DecompileInstruction_C(this)));
 }
示例#18
0
文件: Asks.cs 项目: Fehrox/Tachyon
 public Asks(Stub stub, ISerializer serializer)
 {
     _serializer = serializer;
 }
示例#19
0
 public static TypedBehaviorPreparable <IndirectionFunc <System.Globalization.JapaneseLunisolarCalendar, System.Int32, System.Int32, System.Int32> > GetGregorianYearInt32Int32()
 {
     return(Stub <OfPJapaneseLunisolarCalendar> .Setup <IndirectionFunc <System.Globalization.JapaneseLunisolarCalendar, System.Int32, System.Int32, System.Int32> >(_ => _.GetGregorianYearInt32Int32()));
 }
示例#20
0
        public void WhenTypedGetItemIsCalled_ThenTheReturnedItem_IsCorrect()
        {
            //Assign
            const long id = 1L;

            const string propityValue = "NotDefault Value";
            var fi = new FurnaceItemInformation<long>();
            var returnJon = new Stub
            {
                FurnaceItemInformation = fi,
                Test = propityValue
            }.BuildSerialisedString();

            var key = RedisBackedFurnaceItems.CreateItemKey(id, typeof(Stub));

            Client.Hashes[key][Arg.Any<string>()].Returns(returnJon);

            //Act
            var result = Sut.GetItem<Stub>(id);

            //Assert
            Assert.That(result.Test, Is.EqualTo(propityValue));
        }
示例#21
0
 /// <summary>
 /// Protected constructor that does not instantiate the property hash table.
 /// </summary>
 /// <param name="param">Pass <see cref="Stub.Param" />.</param>
 private DeliveryMsg(Stub param)
     : base(param)
 {
 }
示例#22
0
        public static int DecompileExpressionStatement(String ExprLogic, BaseInstruction Cur, StringBuilder Buf, Stub OwnerStub, int Index)
        {
            bool   AVal        = Cur.A != 0;
            String IfStatement = "";

            BaseInstruction BI = OwnerStub.Instructions[Index + 1];

            if (BI.GetFullName().Contains("_JMP"))
            {
                if (AVal)
                {
                    IfStatement = String.Format("if ({0} {2} {1})", OwnerStub.DecompileInstruction_B(Cur), OwnerStub.DecompileInstruction_C(Cur), ExprLogic);
                }
                else
                {
                    IfStatement = String.Format("if (not({0} {2} {1}))", OwnerStub.DecompileInstruction_B(Cur), OwnerStub.DecompileInstruction_C(Cur), ExprLogic);
                }
                IfStatement += String.Format(" goto {0}", Index + BI.B + 1 + 1);
                Index++;
            }
            else
            {
                if (AVal)
                {
                    IfStatement = String.Format("if (not({0} {2} {1}))", OwnerStub.DecompileInstruction_B(Cur), OwnerStub.DecompileInstruction_C(Cur), ExprLogic);
                }
                else
                {
                    IfStatement = String.Format("if ({0} {2} {1})", OwnerStub.DecompileInstruction_B(Cur), OwnerStub.DecompileInstruction_C(Cur), ExprLogic);
                }
                IfStatement += String.Format(" goto {0}", Index + 2);
            }

            Buf.Append(IfStatement);
            return(Index);
        }
 private void AddItem()
 {
     var item = new Stub();
     items.Add(item);
 }
示例#24
0
 public override void Decompile(StringBuilder Buf, Stub OwnerStub, ref int Index)
 {
     Index = IfExpHelper.DecompileExpressionStatement("==", this, Buf, OwnerStub, Index);
 }
示例#25
0
文件: Bond.cs 项目: stepinto163/Qdp
        public Bond(
            string id,
            Date startDate,
            Date maturityDate,
            double notional,
            CurrencyCode currency,
            ICoupon coupon,
            ICalendar calendar,
            Frequency paymentFreq,
            Stub stub,
            IDayCount accrualDayCount,
            IDayCount paymentDayCount,
            BusinessDayConvention accrualBizDayRule,
            BusinessDayConvention paymentBizDayRule,
            DayGap settlementGap,
            TradingMarket bondTradingMarket,
            bool stickToEom               = false,
            IRedemption redemption        = null,
            Date firstPaymentDate         = null,
            bool isZeroCouponBond         = false,
            double issuePrice             = double.NaN,
            double issueRate              = double.NaN,
            AmortizationType amortionType = AmortizationType.None,
            Dictionary <Date, double> amortizationInDates     = null,
            Dictionary <int, double> amortizationInIndex      = null,
            bool renormalizeAfterAmoritzation                 = false,
            Dictionary <int, double> stepWiseCompensationRate = null,
            Dictionary <string, double> optionToCall          = null,
            Dictionary <string, double> optionToPut           = null,
            Dictionary <string, double> optionToAssPut        = null,
            double settlementCoupon = double.NaN,
            bool roundCleanPrice    = false
            )
        {
            Id        = id;
            StartDate = startDate;
            UnderlyingMaturityDate = maturityDate;
            Notional                 = notional;
            Currency                 = currency;
            Coupon                   = coupon;
            Calendar                 = calendar;
            PaymentFreq              = paymentFreq;
            Stub                     = stub;
            AccrualDayCount          = accrualDayCount;
            PaymentDayCount          = paymentDayCount;
            AccrualBizDayRule        = accrualBizDayRule;
            PaymentBizDayRule        = paymentBizDayRule;
            SettlmentGap             = settlementGap;
            _settlementCoupon        = settlementCoupon;
            BondTradeingMarket       = bondTradingMarket;
            FirstPaymentDate         = firstPaymentDate;
            IsZeroCouponBond         = isZeroCouponBond;
            IssuePrice               = issuePrice;
            IssueRate                = issueRate;
            StickToEom               = stickToEom;
            StepWiseCompensationRate = stepWiseCompensationRate;
            RoundCleanPrice          = roundCleanPrice;

            OptionToCall   = optionToCall;
            OptionToPut    = optionToPut;
            OptionToAssPut = optionToAssPut;

            Tenor = string.Format("{0},{1}", (int)(UnderlyingMaturityDate - StartDate), "D");

            IrregularPayment = false;
            if (Coupon is CustomizedCoupon)
            {
            }
            else
            {
                List <Date> tmpDate;
                if (FirstPaymentDate == null)
                {
                    var schedule = new Schedule(StartDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar,
                                                AccrualBizDayRule);
                    tmpDate       = schedule.ToList();
                    _isRegualDate = schedule.IsRegular;
                }
                else
                {
                    var schedule    = new Schedule(FirstPaymentDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, AccrualBizDayRule);
                    var regAccruals = schedule.ToList();
                    tmpDate = new List <Date> {
                        StartDate
                    };
                    tmpDate.AddRange(regAccruals);
                    IrregularPayment = false;
                    _isRegualDate    = new List <bool> {
                        IrregularPayment
                    };
                    _isRegualDate.AddRange(schedule.IsRegular);
                }

                if (tmpDate.Count > 2)
                {
                    if (PaymentBizDayRule.Adjust(calendar, tmpDate[tmpDate.Count - 2]).Equals(tmpDate.Last()))
                    {
                        tmpDate.RemoveAt(tmpDate.Count - 2);
                        _isRegualDate.RemoveAt(_isRegualDate.Count - 2);
                    }
                }

                Accruals = new Schedule(tmpDate);

                if (FirstPaymentDate == null)
                {
                    PaymentSchedule =
                        new Schedule(
                            new Schedule(StartDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, PaymentBizDayRule).Skip(1));
                }
                else
                {
                    PaymentSchedule =
                        new Schedule(
                            new Schedule(FirstPaymentDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, PaymentBizDayRule));
                }
            }

            if (Accruals.Count() != PaymentSchedule.Count() + 1)
            {
                throw new PricingLibraryException("Bond's number of accrual periods do not match number of payments");
            }

            AmortizationType             = amortionType;
            AmortizationInDates          = amortizationInDates;
            AmortizationInIndex          = amortizationInIndex;
            RenormalizeAfterAmoritzation = renormalizeAfterAmoritzation;
            IAmortization amortization;

            if (AmortizationInDates != null)
            {
                amortization = new Amortization(amortizationInDates, RenormalizeAfterAmoritzation);
            }
            else if (AmortizationInIndex != null)
            {
                amortization = new Amortization(ToAmortizationSchedule(PaymentSchedule.ToArray(), AmortizationInIndex), RenormalizeAfterAmoritzation);
            }
            else
            {
                //EqualPrincipal or EqualPrincipalAndInterest will be calculated later
                amortization = new Amortization();
            }
            Amoritzation        = amortization;
            _mortgageCalculator = new MortgageCalculator(new Psa(0.0), new Sda(0.0));

            Redemption = redemption ?? new Redemption(1.0, RedemptionType.None);
            //Redemption = redemption ?? new Redemption(1.0, PriceQuoteType.Clean);

            if (PaymentFreq == Frequency.None)
            {
                IrregularPayment = true;
            }
            else
            {
                for (var i = 0; i < Accruals.Count() - 1; ++i)
                {
                    if (PaymentFreq.GetTerm().Next(Accruals.ToArray()[i]) != Accruals.ToArray()[i + 1])
                    {
                        IrregularPayment = false;
                        break;
                    }
                }
            }

            _compensationRate = Accruals.Skip(1).Select(x => 0.0).ToArray();

            if (stepWiseCompensationRate != null)
            {
                var compensationCoupons = new List <double>();
                var arr = StepWiseCompensationRate.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).ToArray();
                for (var i = 0; i < Accruals.Count() - 1; ++i)
                {
                    compensationCoupons.Add(i > 0 ? compensationCoupons[i - 1] : 0.0);
                    var updateCoupon       = arr.FirstOrDefault(x => x.Item1 == (i + 1));
                    var compensationCoupon = updateCoupon != null ? updateCoupon.Item2 : 0.0;
                    compensationCoupons[i] += compensationCoupon;
                }
                _compensationRate = compensationCoupons.ToArray();
            }
        }
 static bool StubIsRemoved(Stub stub)
 {
     return(!stub.wrapper.body.IsAdded);
 }
示例#27
0
 public static TypeBehaviorSetting ExcludeGeneric()
 {
     return(Stub <OfPJapaneseLunisolarCalendar> .ExcludeGeneric(new TypeBehaviorSetting()));
 }
示例#28
0
 public static TypedBehaviorPreparable <IndirectionFunc <System.DateTime> > NowGet()
 {
     return(Stub <OfPDateTime> .Setup <IndirectionFunc <System.DateTime> >(_ => _.NowGet()));
 }
        public void MapToProperty_GetItemByIdDifferentLanguage_ReturnsItem()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(Utilities.CreateStandardResolver());
            var mapper = new SitecoreItemMapper();
            var language = LanguageManager.GetLanguage("af-ZA");
            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));

            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();
            var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreItemMapper/Source", language);
            var target = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreItemMapper/Target", language);
            var service = Substitute.For<ISitecoreService>();
            var expected = new StubMapped();

            config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
            config.Id = "{EC4351CE-C5F1-4F01-B354-3D26DC7A66CD}";

            service.CreateType(
                typeof(StubMapped),
                Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                false,
                false).Returns(expected);

            var mappingContext = new SitecoreDataMappingContext(obj, source, service);

            //Act
            var result = mapper.MapToProperty(mappingContext);

            //Assert
            Assert.AreEqual(expected, result);
        }
示例#30
0
 /// <summary>
 /// Protected constructor that does not instantiate the property hash table.
 /// </summary>
 /// <param name="param">Pass <see cref="Stub.Param" />.</param>
 private DeliveryAck(Stub param)
     : base(param)
 {
 }
        public void MapToProperty_GetItemByPath_ReturnsItem()
        {
            //Assign
            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Source"),
                new Sitecore.FakeDb.DbItem("Target")
            })
            {
                var config = new SitecoreNodeConfiguration();
                var mapper = new SitecoreNodeMapper();
                var language = LanguageManager.GetLanguage("en");

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var obj = new Stub();
                var source = database.Database.GetItem("/sitecore/content/Source", language);
                var target = database.Database.GetItem("/sitecore/content/Target", language);
                var service = Substitute.For<ISitecoreService>();
                var expected = new StubMapped();

                config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
                config.Path = "/sitecore/content/Target";

                service.CreateType(
                    typeof(StubMapped),
                    Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                    false,
                    false, null).Returns(expected);
                service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
                var mappingContext = new SitecoreDataMappingContext(obj, source, service);

                //Act
                var result = mapper.MapToProperty(mappingContext);

                //Assert
                Assert.AreEqual(expected, result);
            }

        }
示例#32
0
 public override void Decompile(StringBuilder Buf, Stub OwnerStub, ref int Index)
 {
 }
示例#33
0
 /// <summary>
 /// Used by unit tests to load the option fields from the query passed.
 /// </summary>
 /// <param name="queryMsg">The source message.</param>
 /// <param name="stub">Pass a <see cref="Stub"/> value.</param>
 /// <remarks>
 /// The derived class must store its values as <see cref="PropertyMsg" /> fields
 /// using <b>"Option."</b> as the key prefix for each value's property name.
 /// </remarks>
 internal void LoadFrom(GeoQueryMsg queryMsg, Stub stub)
 {
     LoadFrom(queryMsg);
 }
        public void Validate_When_Pact_Is_Not_Valid()
        {
            var exception = Assert.Throws <InvalidDataException>(() => Stub.Create(9000).FromJson("<Invalid Json"));

            exception.Message.Should().Be("The pact file is not a valid JSON document.");
        }
示例#35
0
文件: Index.cs 项目: stepinto163/Qdp
        public double GetFixingRate(IYieldCurve fixingCurve,
                                    ICalendar resetCalendar,
                                    IDayCount dayCount,
                                    Date accStartDate,
                                    Date accEndDate,
                                    ITerm resetTerm,
                                    ITerm fixingTenor,
                                    DayGap fixingToResetGap,
                                    Stub resetStub,
                                    BusinessDayConvention resetBda,
                                    double couponSpread,
                                    double capRate,
                                    double floorRate,
                                    out CfCalculationDetail[] resetDetails,
                                    IDictionary <Date, double> historicalRate = null,
                                    FloatingCouponCalcType frnCalc            = FloatingCouponCalcType.SimpleFrn,
                                    double stepWiseCompensationCoupon         = 0.0,
                                    double multiplier = 1.0)
        {
            var details     = new List <CfCalculationDetail>();
            var resetPriods = resetTerm == null
                                ? new List <Date> {
                accStartDate, accEndDate
            }
                                : new Schedule(accStartDate, accEndDate, resetTerm, resetStub, resetCalendar, resetBda).ToList();


            for (var i = 0; i < resetPriods.Count - 1; ++i)
            {
                var resetStartDate = resetPriods[i];
                var resetEndDate   = resetPriods[i + 1];
                if (resetEndDate > accEndDate)
                {
                    resetEndDate = accEndDate;
                }
                var fixingStartDate = fixingToResetGap.Get(resetCalendar, resetStartDate);

                var forwardCompound = frnCalc == FloatingCouponCalcType.ZzFrn ? Compound.Continuous : IndexType.ForwardCompound();
                details.Add(new CfCalculationDetail(
                                resetStartDate,
                                resetEndDate,
                                fixingStartDate,
                                multiplier * GetResetRate(fixingCurve, fixingStartDate, resetCalendar, fixingTenor, AverageDays, historicalRate, forwardCompound, IndexType.DayCount()) + stepWiseCompensationCoupon,
                                dayCount.CalcDayCountFraction(resetStartDate, resetEndDate, accStartDate, accEndDate),
                                resetStartDate < (fixingCurve == null ? fixingStartDate : fixingCurve.ReferenceDate)));
            }

            resetDetails = details.ToArray();
            var    totalDcf = resetDetails.Sum(x => x.FixingDcf);
            double couponRate;

            switch (CouponCompound)
            {
            case CouponCompound.Compounded:
                couponRate =
                    (resetDetails.Select(x =>
                {
                    var coupon = FilterRate(x.FixingRate + couponSpread, capRate, floorRate);
                    return(1.0 + coupon * x.FixingDcf);
                })
                     .Aggregate(1.0, (current, v) => current * v) - 1.0) / totalDcf;
                return(couponRate);

            case CouponCompound.Simple:
                couponRate =
                    resetDetails.Select(x =>
                {
                    var coupon = FilterRate(x.FixingRate + couponSpread, capRate, floorRate);
                    return(coupon * x.FixingDcf);
                }).Sum() / totalDcf;
                return(couponRate);

            default:
                throw new PricingLibraryException("Unknow type of coupon compund type" + CouponCompound);
            }
        }
示例#36
0
 public override void Decompile(StringBuilder Buf, Stub OwnerStub, ref int Index)
 {
     Index = TestHelper.DecompileTest(false, this, Buf, OwnerStub, Index);
 }
示例#37
0
        public async Task <TeamStubCreatedEvent> HandleAsync(CreateTeamStubCommand command,
                                                             CancellationToken cancellationToken)
        {
            var team = _authenticatedUserAccessor.AuthenticatedUser.Teams.SingleOrDefault(t => t.Id == command.TeamId);

            if (team == null)
            {
                throw new UserNotAddedToTeamException
                      (
                          _authenticatedUserAccessor.AuthenticatedUser.Id,
                          command.TeamId
                      );
            }

            if (!team.Role.Permissions.Contains(Permission.ManageStubs))
            {
                throw new MemberCannotManageStubsException
                      (
                          _authenticatedUserAccessor.AuthenticatedUser.Id,
                          team.Id
                      );
            }

            var stub = new Stub
            {
                Id      = ObjectId.GenerateNewId(),
                TeamId  = team.Id,
                Name    = command.Name,
                Request = new Request
                {
                    HttpMethod            = command.Request.HttpMethod,
                    Path                  = command.Request.Path,
                    QueryStringParameters = command.Request.QueryStringParameters
                                            ?.Select(qsp => new QueryStringParameter {
                        Key = qsp.Key, Value = qsp.Value
                    }).ToList(),
                    BodyTokens = command.Request.BodyTokens
                                 ?.Select(bt => new BodyToken {
                        Path = bt.Path, Type = bt.Type, Value = bt.Value
                    }).ToList(),
                    Headers = command.Request.Headers?.Select(h => new Header {
                        Key = h.Key, Value = h.Value
                    }).ToList()
                },
                Response = new Response
                {
                    HttpStatusCode = command.Response.HttpStatusCode,
                    Body           = command.Response.Body,
                    Headers        = command.Request.Headers?.Select(h => new Header {
                        Key = h.Key, Value = h.Value
                    }).ToList()
                },
                Tags = command.Tags
            };

            await _stubsCollection.InsertOneAsync(stub, cancellationToken : cancellationToken);

            return(new TeamStubCreatedEvent
                   (
                       stub.Id,
                       stub.TeamId,
                       stub.Name,
                       new Events.Shared.Version1.Request
                       (
                           stub.Request.HttpMethod,
                           stub.Request.Path,
                           stub.Request.QueryStringParameters
                           ?.Select(qsp => new Events.Shared.Version1.QueryStringParameter(qsp.Key, qsp.Value)).ToList(),
                           stub.Request.BodyTokens
                           ?.Select(bt => new Events.Shared.Version1.BodyToken(bt.Path, bt.Type, bt.Value)).ToList(),
                           stub.Request.Headers?.Select(h => new Events.Shared.Version1.Header(h.Key, h.Value)).ToList()
                       ),
                       new Events.Shared.Version1.Response
                       (
                           stub.Response.HttpStatusCode,
                           stub.Response.Body,
                           stub.Request.Headers?.Select(h => new Events.Shared.Version1.Header(h.Key, h.Value)).ToList()
                       ),
                       stub.Tags
                   ));
        }
示例#38
0
 /// <summary>
 /// Protected constructor that does not instantiate the property hash table.
 /// </summary>
 /// <param name="param">Pass <see cref="Stub.Param" />.</param>
 private SessionKeepAliveMsg(Stub param)
     : base(param)
 {
     this._Flags = MsgFlag.Priority;
 }
 public void Initialize()
 {
     stub = new Stub();
 }
示例#40
0
		public void YeniBirIASIcine_YeniBirFTEklendiginde_YeniFaaliyetEkleCagirilmaliVeTrueDonmeli()
		{
			Stub.On(_surum).Method("FaaliyetTanimIceriyor").WithAnyArguments().Will(Return.Value(false));
			Expect.Once.On(_surum).Method("YeniFaaliyetTanimEkle").With(_faaliyetTanim).Will(Return.Value(true));
			_yonetici.YeniFaaliyetTanimEkle(_faaliyetTanim);
		}
示例#41
0
 public static TypedBehaviorPreparable <IndirectionFunc <T[], System.Predicate <T>, System.Boolean> > ExistsOfTTArrayPredicateOfT <T>()
 {
     return(Stub <OfPArray> .Setup <IndirectionFunc <T[], System.Predicate <T>, System.Boolean> >(_ => _.ExistsOfTTArrayPredicateOfT <T>()));
 }
        public void MapToProperty_GetItemByIdDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(Utilities.CreateStandardResolver());
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("af-ZA");
            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));

            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();
            var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Source", language);
            var target = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/TargetOneLanguage", language);
            var service = Substitute.For<ISitecoreService>();
            var expected = new StubMapped();

            config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
            config.Id = "{03CDE6B5-B2A2-40D6-A944-53D66DDD2CA4}";

            service.CreateType(
                typeof(StubMapped),
                Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                false,
                false, null).Returns(expected);

            var mappingContext = new SitecoreDataMappingContext(obj, source, service);

            //Act
            var result = mapper.MapToProperty(mappingContext);

            //Assert
            Assert.IsNull(result);
        }
示例#43
0
 public void GivenJapaneseAsTheCultureSetUp()
 {
     CultureInfo = CultureInfo.GetCultureInfo("fr-FR");
     var fi = new FurnaceItemInformation<long>();
     CultureStub = new Stub
     {
         FurnaceItemInformation = fi,
         Test = "こんにいちわ"
     };
 }
 public void ShouldFirePropertyChangedEvent()
 {
     var sample = new Stub();
     sample.ShouldFirePropertyChanged(() => sample.Text = "value", Stub.PropText);
 }
 public void ShouldHaveSyncContext()
 {
     var model = new Stub();
     model.SyncContext.ShouldNotBe(null);
 }
 public void Change_ViewModel(DisposeWithViewModelTestControl control)
 {
     viewModel= new Stub();
     control.placeholder.DataContext = viewModel;
 }
示例#47
0
        public void WhenGetItemIsCalled_ThenTheReturnedItem_IsCorrect()
        {
            //Assign
            const long id = 1L;
            ContentType.AddPropity("Test", "string");
            var item = Sut.CreateItem(ContentType);
            item.Id = id;

            const string propityValue = "NotDefaultValue";
            var fi = new FurnaceItemInformation<long>() {Id = id};
            var returnJson = new Stub
            {
                FurnaceItemInformation = fi,
                Test = propityValue
            }.BuildSerialisedString();

            var key = RedisBackedFurnaceItems.CreateItemKey(id, ContentType);

            Client.Hashes[key][SiteConfiguration.DefaultSiteCulture.Name].Returns(returnJson);

            //Act
            var result = Sut.GetItem(id, ContentType);

            //Assert
            Assert.That(result.Id, Is.EqualTo(id));
            Assert.That(result["Test"], Is.EqualTo(propityValue));
            Assert.That(result.ContentType.Name == ContentTypeName);
        }
        public void MapToProperty_GetItemByIdDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("af-ZA");
            context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));


            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Source"),
                new Sitecore.FakeDb.DbItem("Target")
            })
            {
                var source = database.Database.GetItem("/sitecore/content/Source", language);
                var target = database.Database.GetItem("/sitecore/content/Target", language);
                var service = Substitute.For<ISitecoreService>();
                var expected = new StubMapped();

                config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
                config.Id = target.ID.Guid.ToString();

                service.CreateType(
                    typeof(StubMapped),
                    Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                    false,
                    false, null).Returns(expected);

                service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(false);

                var mappingContext = new SitecoreDataMappingContext(obj, source, service);

                //Act
                var result = mapper.MapToProperty(mappingContext);

                //Assert
                Assert.IsNull(result);
            }
        }
示例#49
0
 public object CreateStub()
 {
     return(Stub.Delegate <T>());
 }
示例#50
0
 /// <summary>
 /// Used by unit tests to save the option fields to the query message passed.
 /// </summary>
 /// <param name="queryMsg">The target message.</param>
 /// <param name="stub">Pass a <see cref="Stub"/> value.</param>
 /// <remarks>
 /// The derived class must store its values as <see cref="PropertyMsg" /> fields
 /// using <b>"Option."</b> as the key prefix for each value's property name.
 /// </remarks>
 internal void SaveTo(GeoQueryMsg queryMsg, Stub stub)
 {
     SaveTo(queryMsg);
 }
 public void ShouldNotHaveEqualPropertiesWhereExplicitPropertiesAreDeclared()
 {
     Should.Throw<AssertionException>(() =>
                     {
                         var stub1 = new Stub { Text = "Foo1", Child = new ConstructorStub() };
                         var stub2 = new Stub { Text = "Foo", Child = new ConstructorStub() };
                         stub1.ShouldHaveEqualProperties(stub2, m => m.Text, m => m.Text);
                     });
 }
示例#52
0
 public static TypeBehaviorSetting ExcludeGeneric()
 {
     return(Stub <OfPArray> .ExcludeGeneric(new TypeBehaviorSetting()));
 }
示例#53
0
		public void BirFTIcerenBirIASIcine_AyniIsimliBirFTDahaEklendiginde_HicBirSeyCagirilmamaliVeFalseDonmeli()
		{
			Stub.On(_surum).Method("FaaliyetTanimIceriyor").WithAnyArguments().Will(Return.Value(true));
			Expect.Never.On(_surum);
			_yonetici.YeniFaaliyetTanimEkle(_faaliyetTanim);
		}
        public void MapToProperty_GetItemByPathDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("af-ZA");

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Source")
                {
                    new Sitecore.FakeDb.DbField("Title")
                    {
                        {language.Name, language.Name}
                    }
                },
                new Sitecore.FakeDb.DbItem("TargetOneLanguage")
                {
                   
                },
            })
            {
                mapper.Setup(new DataMapperResolverArgs(null, config));

                var obj = new Stub();
                var source = database.Database.GetItem("/sitecore/content/Source", language);
                var target = database.Database.GetItem(
                    "/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/TargetOneLanguage", language);
                var service = Substitute.For<ISitecoreService>();
                var expected = new StubMapped();

                config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
                config.Path = "/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target";

                service.CreateType(
                    typeof(StubMapped),
                    Arg.Is<Item>(x => 
                        x.Paths.FullPath == target.Paths.FullPath 
                        && x.Language == language
                        && x.Versions.Count == 0),
                    false,
                    false, null).Returns(expected);

                var mappingContext = new SitecoreDataMappingContext(obj, source, service);

                //Act
                var result = mapper.MapToProperty(mappingContext);

                //Assert
                Assert.IsNull(result);
            }
        }
        public void MapToProperty_GetItemByPathInferType_ReturnsItem()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(Utilities.CreateStandardResolver());
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("en");
            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));

            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();
            var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Source", language);
            var target = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target", language);
            var service = Substitute.For<ISitecoreService>();
            var itemVersionHandler = Substitute.For<IItemVersionHandler>();
            itemVersionHandler.VersionCountEnabledAndHasVersions(Arg.Any<Item>()).Returns(true);
            service.ItemVersionHandler.Returns(itemVersionHandler);

            var expected = new StubMapped();

            config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
            config.Path = "/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target";
            config.InferType = true;

            service.CreateType(
                typeof(StubMapped),
                Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                false,
                true, null).Returns(expected);

            var mappingContext = new SitecoreDataMappingContext(obj, source, service);

            //Act
            var result = mapper.MapToProperty(mappingContext);

            //Assert
            Assert.AreEqual(expected, result);

        }
示例#56
0
		public void IkiFTIcerenBirIASIcine_YeniBirFTIEklendiginde_FTYeniIliskiEkleCagirilmaliVeTrueDonmeli()
		{
			Expect.Once.On(_faaliyetTanim).Method("IliskiEkle").With(_faaliyetTanim2).Will(Return.Value(true));
			Stub.On(_surum).Method("FaaliyetTanimIceriyor").WithAnyArguments().Will(Return.Value(true));
			Assert.That(_yonetici.YeniFaaliyetTanimIliskisiEkle(_faaliyetTanim, _faaliyetTanim2), Is.True);
		}
 public void ShouldFireMultipleProperties()
 {
     var sample = new Stub();
     sample.ShouldFirePropertyChanged(() => sample.OnPropertyChangedTest("one", "two"), "one", "two");
 }
示例#58
0
		public void YeniBirIASIcinde_YeniBirFTIEklendiginde_HicBirSeyCagirilmamaliVeFalseDonmeli()
		{
			Expect.Never.On(_faaliyetTanim);
			Stub.On(_surum).Method("FaaliyetTanimIceriyor").WithAnyArguments().Will(Return.Value(false));
			Assert.That(_yonetici.YeniFaaliyetTanimIliskisiEkle(_faaliyetTanim, _faaliyetTanim2), Is.False);
		}
示例#59
0
 public object CreateStub()
 {
     return(Stub.Interface <T>());
 }
        public void ShouldNotHaveEqualProperties()
        {
            Should.Throw<AssertionException>(() =>
                            {
                                var stub1 = new Stub { Text = "Foo", Child = new ConstructorStub() };
                                var stub2 = new Stub { Text = "Foo", Child = new ConstructorStub() };
                                stub1.ShouldHaveEqualProperties(stub2);
                            });

            Should.Throw<AssertionException>(() =>
                            {
                                var stub1 = new Stub { Text = "Foo" };
                                var stub2 = new Stub { Text = "Bar" };
                                stub1.ShouldHaveEqualProperties(stub2);
                            });
        }