method2testcases
stringlengths 118
3.08k
|
---|
### Question:
DividendsPerShare { public static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares) { return dividends.divide(numberOfShares); } private DividendsPerShare(); static MonetaryAmount calculate(MonetaryAmount dividends, double numberOfShares); }### Answer:
@Test public void testCalculate() { assertEquals(Money.of(25, "GBP"), DividendsPerShare.calculate(DIVIDENDS, NUMBER_OF_SHARES)); } |
### Question:
PriceToEarningsRatio { public static BigDecimal calculate(MonetaryAmount pricePerShare, MonetaryAmount earningsPerShare) { BigDecimal pricePerShareValue = BigDecimal.valueOf(pricePerShare.getNumber().doubleValueExact()); BigDecimal earningsPerShareValue = BigDecimal.valueOf(earningsPerShare.getNumber().doubleValueExact()); return pricePerShareValue.divide(earningsPerShareValue, MathContext.DECIMAL64); } private PriceToEarningsRatio(); static BigDecimal calculate(MonetaryAmount pricePerShare, MonetaryAmount earningsPerShare); }### Answer:
@Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.25), PriceToEarningsRatio.calculate(PRICE_PER_SHARE, EARNINGS_PER_SHARE)); } |
### Question:
StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testCalculateForConstantGrowth() { assertEquals(Money.of(1700, "GBP"), StockPresentValue.calculateForConstantGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN, GROWTH_RATE)); } |
### Question:
StockPresentValue implements MonetaryOperator { public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testCalculateForZeroGrowth() { assertEquals(Money.of(680, "GBP"), StockPresentValue.calculateForZeroGrowth(ESTIMATED_DIVIDENDS, REQUIRED_RATE_OF_RETURN)); } |
### Question:
StockPresentValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate); Rate getRequiredRateOfReturn(); Rate getGrowthRate(); static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate); static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn); @Override MonetaryAmount apply(MonetaryAmount estimatedDividends); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testApply() { assertEquals(Money.of(1700, "GBP"), ESTIMATED_DIVIDENDS.with(StockPresentValue.of(REQUIRED_RATE_OF_RETURN, GROWTH_RATE))); } |
### Question:
TaxEquivalentYield { public static BigDecimal calculate(Rate taxFreeYield, Rate taxRate) { return taxFreeYield.get().divide(BigDecimal.ONE.subtract(taxRate.get()), MathContext.DECIMAL64); } private TaxEquivalentYield(); static BigDecimal calculate(Rate taxFreeYield, Rate taxRate); }### Answer:
@Test public void testCalculate() { assertEquals(0.0597, TaxEquivalentYield.calculate(TAX_FREE_YIELD, TAX_RATE).doubleValue(), 0.0001); } |
### Question:
HoldingPeriodReturn { public static BigDecimal calculate(List<Rate> returns) { BigDecimal product = BigDecimal.ONE; for (Rate rateOfReturn : returns) { if (rateOfReturn == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } product = product.multiply(rateOfReturn.get().add(BigDecimal.ONE)); } return product.subtract(BigDecimal.ONE); } private HoldingPeriodReturn(); static BigDecimal calculate(List<Rate> returns); static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods); }### Answer:
@Test public void testCalculate() { assertEquals(0.1319, HoldingPeriodReturn.calculate(RATES_OF_RETURN).doubleValue(), 0.00001); }
@Test(expected = IllegalArgumentException.class) public void testCalculateWithNullReturnsThrowsException() { HoldingPeriodReturn.calculate(Arrays.asList(Rate.of(0.1), Rate.of(0.1), null, Rate.of(0.5))); } |
### Question:
HoldingPeriodReturn { public static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods) { if (periodicRate == null) { throw new IllegalArgumentException("The list of returns cannot contain null elements"); } if (numberOfPeriods <= 0) { throw new IllegalArgumentException("The number of periods should be positive"); } BigDecimal product = BigDecimal.ONE; final BigDecimal multiplicand = periodicRate.get().add(BigDecimal.ONE); for (int i = 0; i < numberOfPeriods; i++) { product = product.multiply(multiplicand); } return product.subtract(BigDecimal.ONE); } private HoldingPeriodReturn(); static BigDecimal calculate(List<Rate> returns); static BigDecimal calculateForSameReturn(Rate periodicRate, int numberOfPeriods); }### Answer:
@Test public void testCalculateForSameReturn() { assertEquals(0.728, HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, NUMBER_OF_PERIODS).doubleValue(), 0.0001); }
@Test(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNullRateThrowsException() { HoldingPeriodReturn.calculateForSameReturn(null, NUMBER_OF_PERIODS); }
@Test(expected = IllegalArgumentException.class) public void testCalculateForSameReturnWithNegativeNumberOfPeriodsThrowsException() { HoldingPeriodReturn.calculateForSameReturn(PERIODIC_RATE, -1); } |
### Question:
ZeroCouponBondYield { public static double calculate(MonetaryAmount faceAmount, MonetaryAmount presentAmount, int numberOfPeriods) { final BigDecimal faceValue = BigDecimal.valueOf(faceAmount.getNumber().doubleValueExact()); final BigDecimal presentValue = BigDecimal.valueOf(presentAmount.getNumber().doubleValueExact()); final double fraction = faceValue.divide(presentValue, MathContext.DECIMAL64).doubleValue(); return Math.pow(fraction, 1 / (double) numberOfPeriods) - 1; } private ZeroCouponBondYield(); static double calculate(MonetaryAmount faceAmount, MonetaryAmount presentAmount, int numberOfPeriods); }### Answer:
@Test public void testCalculate() { assertEquals(0.2974, ZeroCouponBondYield.calculate(FACE_AMOUNT, PRESENT_AMOUNT, NUMBER_OF_PERIODS), 0.0001); } |
### Question:
BondEquivalentYield { public static BigDecimal calculate(MonetaryAmount faceValue, MonetaryAmount priceAmount, int numberOfDaysToMaturity) { BigDecimal face = BigDecimal.valueOf(faceValue.getNumber().doubleValueExact()); BigDecimal price = BigDecimal.valueOf(priceAmount.getNumber().doubleValueExact()); BigDecimal returnOnInvestment = (face.subtract(price)).divide(price, MathContext.DECIMAL64); BigDecimal maturity = BigDecimal.valueOf(365).divide(BigDecimal.valueOf(numberOfDaysToMaturity), MathContext.DECIMAL64); return returnOnInvestment.multiply(maturity); } private BondEquivalentYield(); static BigDecimal calculate(MonetaryAmount faceValue, MonetaryAmount priceAmount, int numberOfDaysToMaturity); }### Answer:
@Test public void testCalculate() { assertEquals(0.40556, BondEquivalentYield.calculate(FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_DAYS_TO_MATURITY).doubleValue(), 0.00001); } |
### Question:
TotalStockReturn { public static BigDecimal calculate(MonetaryAmount initialPrice, MonetaryAmount endingPrice, MonetaryAmount dividends) { BigDecimal initialPriceValue = BigDecimal.valueOf(initialPrice.getNumber().doubleValueExact()); BigDecimal endingPriceValue = BigDecimal.valueOf(endingPrice.getNumber().doubleValueExact()); BigDecimal dividendsValue = BigDecimal.valueOf(dividends.getNumber().doubleValueExact()); return (endingPriceValue.subtract(initialPriceValue).add(dividendsValue)).divide(initialPriceValue, MathContext.DECIMAL64); } private TotalStockReturn(); static BigDecimal calculate(MonetaryAmount initialPrice, MonetaryAmount endingPrice, MonetaryAmount dividends); }### Answer:
@Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.04), TotalStockReturn.calculate(INITIAL_PRICE, ENDING_PRICE, DIVIDENDS)); } |
### Question:
EquityMultiplier { public static BigDecimal calculate(MonetaryAmount totalAssets, MonetaryAmount equity) { BigDecimal totalAssetValue = BigDecimal.valueOf(totalAssets.getNumber().doubleValueExact()); BigDecimal equityValue = BigDecimal.valueOf(equity.getNumber().doubleValueExact()); return totalAssetValue.divide(equityValue, MathContext.DECIMAL64); } private EquityMultiplier(); static BigDecimal calculate(MonetaryAmount totalAssets, MonetaryAmount equity); }### Answer:
@Test public void testCalculate() { assertEquals(0.5, EquityMultiplier.calculate(TOTAL_ASSETS, EQUITY).doubleValue()); } |
### Question:
CapitalAssetPricingModelFormula { public static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn) { return calculate(riskFreeRate, beta, marketReturn, BigDecimal.ZERO); } private CapitalAssetPricingModelFormula(); static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn); static Rate calculate(Rate riskFreeRate, BigDecimal beta, Rate marketReturn, BigDecimal epsilon); }### Answer:
@Test public void testCalculateWithRegression() { assertEquals(Rate.of(0.301), CapitalAssetPricingModelFormula.calculate(RISKFREE_RATE, BETA, MARKET_RETURN, EPSILON)); }
@Test public void testCalculate() { assertEquals(Rate.of(0.3), CapitalAssetPricingModelFormula.calculate(RISKFREE_RATE, BETA, MARKET_RETURN)); } |
### Question:
PreferredStock implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate) { return dividend.divide(discountRate.get()); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate); @Override MonetaryAmount apply(MonetaryAmount dividend); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testCalculate() { assertEquals(Money.of(400, "GBP"), PreferredStock.calculate(DIVIDEND, DISCOUNT_RATE)); } |
### Question:
PreferredStock implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount dividend) { return calculate(dividend, discountRate); } private PreferredStock(Rate discountRate); Rate getDiscountRate(); static PreferredStock of(Rate discountRate); static MonetaryAmount calculate(MonetaryAmount dividend, Rate discountRate); @Override MonetaryAmount apply(MonetaryAmount dividend); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testApply() { assertEquals(Money.of(400, "GBP"), DIVIDEND.with(PreferredStock.of(DISCOUNT_RATE))); } |
### Question:
ZeroCouponBondValue implements MonetaryOperator { public static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity) { return face.divide(BigDecimal.ONE.add(rate.get()).pow(numberOfYearsToMaturity)); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); Rate getRate(); int getNumberOfYearsToMaturity(); static ZeroCouponBondValue of(Rate rate, int numberOfYearsToMaturity); static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity); @Override MonetaryAmount apply(MonetaryAmount face); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testCalculate() { assertEquals(Money.of(100, "GBP"), ZeroCouponBondValue.calculate(FACE, RATE, NUMBER_OF_YEARS_TO_MATURITY)); } |
### Question:
ZeroCouponBondValue implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount face) { return calculate(face, rate, numberOfYearsToMaturity); } private ZeroCouponBondValue(Rate rate, int numberOfYearsToMaturity); Rate getRate(); int getNumberOfYearsToMaturity(); static ZeroCouponBondValue of(Rate rate, int numberOfYearsToMaturity); static MonetaryAmount calculate(MonetaryAmount face, Rate rate, int numberOfYearsToMaturity); @Override MonetaryAmount apply(MonetaryAmount face); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testApply() { assertEquals(Money.of(100, "GBP"), FACE.with(ZeroCouponBondValue.of(RATE, NUMBER_OF_YEARS_TO_MATURITY))); } |
### Question:
YieldToMaturity { public static BigDecimal calculate(MonetaryAmount couponPaymentAmount, MonetaryAmount faceAmount, MonetaryAmount priceAmount, int numberOfYearsToMaturity) { final BigDecimal coupon = BigDecimal.valueOf(couponPaymentAmount.getNumber().doubleValueExact()); final BigDecimal face = BigDecimal.valueOf(faceAmount.getNumber().doubleValueExact()); final BigDecimal price = BigDecimal.valueOf(priceAmount.getNumber().doubleValueExact()); final BigDecimal averagedDifference = face.subtract(price).divide(BigDecimal.valueOf(numberOfYearsToMaturity), MathContext.DECIMAL64); final BigDecimal averagePrice = face.add(price).divide(BigDecimal.valueOf(2), MathContext.DECIMAL64); return coupon.add(averagedDifference).divide(averagePrice, MathContext.DECIMAL64); } private YieldToMaturity(); static BigDecimal calculate(MonetaryAmount couponPaymentAmount, MonetaryAmount faceAmount, MonetaryAmount priceAmount, int numberOfYearsToMaturity); }### Answer:
@Test public void testCalculate() { assertEquals(BigDecimal.valueOf(0.1125), YieldToMaturity.calculate(COUPON_PAYMENT_AMOUNT, FACE_AMOUNT, PRICE_AMOUNT, NUMBER_OF_YEARS_TO_MATURITY)); } |
### Question:
EstimatedEarnings { public static MonetaryAmount calculate(MonetaryAmount forecastedSales, MonetaryAmount forecastedExpenses) { return forecastedSales.subtract(forecastedExpenses); } private EstimatedEarnings(); static MonetaryAmount calculate(MonetaryAmount forecastedSales, MonetaryAmount forecastedExpenses); static MonetaryAmount calculate(MonetaryAmount projectedSales, BigDecimal projectedNetProfitMargin); }### Answer:
@Test public void testCalculate() { assertEquals(Money.of(200, "GBP"), EstimatedEarnings.calculate(FORECASTED_SALES, FORECASTED_EXPENSES)); }
@Test public void testCalculateWithProfitMarginFormula() { assertEquals(Money.of(2, "GBP"), EstimatedEarnings.calculate(PROJECTED_SALES, PROJECTED_NET_PROFIT_MARGIN)); } |
### Question:
ContinuousCompoundInterest extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private ContinuousCompoundInterest(RateAndPeriods rateAndPeriods); static ContinuousCompoundInterest of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { ContinuousCompoundInterest ci = ContinuousCompoundInterest.of( RateAndPeriods.of(0.1,2) ); assertEquals(ci.apply(Money.of(1000,"CHF")) .getNumber().doubleValue(), Money.of(221.401536766165,"CHF").getNumber().doubleValue(), 0.00d); } |
### Question:
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(100, "CHF"); assertEquals(val.apply(m), m.with(val)); } |
### Question:
PresentValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueOfAnnuityDue{" + "\n " + rateAndPeriods + '}'; } private PresentValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static PresentValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void toStringTest() throws Exception { PresentValueOfAnnuityDue val = PresentValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals("PresentValueOfAnnuityDue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); } |
### Question:
CompoundInterest extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private CompoundInterest(RateAndPeriods rateAndPeriods, int timesCompounded); int getTimesCompounded(); static CompoundInterest of(RateAndPeriods rateAndPeriods, int timesCompounded); static CompoundInterest of(RateAndPeriods rateAndperiods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods, int timesCompounded); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { CompoundInterest ci = CompoundInterest.of( RateAndPeriods.of(0.05,2) ); assertEquals(ci.apply(Money.of(1,"CHF")),Money.of(0.1025,"CHF")); } |
### Question:
PresentValueOfPerpetuity implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rate); } private PresentValueOfPerpetuity(Rate rate); Rate getRate(); static PresentValueOfPerpetuity of(Rate rate); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testApply(){ PresentValueOfPerpetuity op = PresentValueOfPerpetuity.of(Rate.of(0.05)); assertEquals(Money.of(2000, "CHF"), Money.of(100, "CHF").with(op)); assertEquals(Money.of(2000, "CHF"), op.apply(Money.of(100, "CHF"))); assertEquals(Money.of(-2000, "CHF"), Money.of(-100, "CHF").with(op)); op = PresentValueOfPerpetuity.of(Rate.of(-0.05)); assertEquals(Money.of(-2000, "CHF"), op.apply(Money.of(100, "CHF"))); } |
### Question:
PresentValueOfPerpetuity implements MonetaryOperator { @Override public String toString() { return "PresentValueOfPerpetuity{" + "rate=" + rate + '}'; } private PresentValueOfPerpetuity(Rate rate); Rate getRate(); static PresentValueOfPerpetuity of(Rate rate); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testToString(){ PresentValueOfPerpetuity op = PresentValueOfPerpetuity.of(Rate.of(0.056778)); assertEquals("PresentValueOfPerpetuity{rate=Rate[0.056778]}", op.toString()); } |
### Question:
AnnualPercentageYield implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rate, periods); } private AnnualPercentageYield(Rate rate, int periods); int getPeriods(); Rate getRate(); static AnnualPercentageYield of(Rate rate, int periods); static Rate calculate(Rate rate, int periods); static MonetaryAmount calculate(MonetaryAmount amount, Rate rate, int periods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { AnnualPercentageYield ci = AnnualPercentageYield.of( Rate.of(0.05),2 ); assertEquals(ci.apply(Money.of(1,"CHF")),Money.of(0.050625,"CHF")); } |
### Question:
FutureValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private FutureValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); } |
### Question:
FutureValueOfAnnuityDue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "FutureValueOfAnnuityDue{" + "\n " + rateAndPeriods + '}'; } private FutureValueOfAnnuityDue(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuityDue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void toStringTest() throws Exception { FutureValueOfAnnuityDue val = FutureValueOfAnnuityDue.of( RateAndPeriods.of(0.05, 10) ); assertEquals("FutureValueOfAnnuityDue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); } |
### Question:
FutureValueFactor { public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods); BigDecimal base = CalculationContext.one().add(rateAndPeriods.getRate().get()); return base.pow(rateAndPeriods.getPeriods(), CalculationContext.mathContext()); } private FutureValueFactor(); static BigDecimal calculate(RateAndPeriods rateAndPeriods); }### Answer:
@Test public void calculate_PositiveRates() throws Exception { assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(0.05,0)).doubleValue(), 0.0d); assertEquals(1.0500, FutureValueFactor.calculate(RateAndPeriods.of(0.05,1)).doubleValue(), 0.0d); assertEquals(1.628894626777441, FutureValueFactor.calculate(RateAndPeriods.of(0.05,10)).doubleValue(), 0.0d); }
@Test public void calculate_NegativeRates() throws Exception { assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,0)).doubleValue(), 0.0d); assertEquals(0.9500, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,1)).doubleValue(), 0.0d); assertEquals(0.5987369392383789, FutureValueFactor.calculate(RateAndPeriods.of(-0.05,10)).doubleValue(), 0.0d); }
@Test public void calculate_Invalid(){ assertEquals(1.0, FutureValueFactor.calculate(RateAndPeriods.of(0,0)).doubleValue(), 0.0d); } |
### Question:
DoublingTimeWithContCompounding { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTimeWithCompounding with a rate=zero"); } return BigDecimal.valueOf(Math.log(2.0d)).divide(rate.get(), CalculationContext.mathContext()); } private DoublingTimeWithContCompounding(); static BigDecimal calculate(Rate rate); }### Answer:
@Test public void calculate() throws Exception { assertEquals(8.30116383904126, DoublingTimeWithContCompounding.calculate(Rate.of(0.0835)).doubleValue(), 0.0d); assertEquals(1.386294361119891, DoublingTimeWithContCompounding.calculate(Rate.of(0.5)).doubleValue(), 0.0d); assertEquals(0.6931471805599453, DoublingTimeWithContCompounding.calculate(Rate.of(1)).doubleValue(), 0.0d); assertEquals(15.4032706791099, DoublingTimeWithContCompounding.calculate(Rate.of(0.045)).doubleValue(), 0.0d); }
@Test(expected = MonetaryException.class) public void calculate_Invalid(){ DoublingTimeWithContCompounding.calculate(Rate.of(0)); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { public static Rate of(BigDecimal rate) { return new Rate(rate, null); } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void of_BD() throws Exception { Rate r = Rate.of(BigDecimal.valueOf(0.0567)); assertNotNull(r); }
@Test public void of_Num() throws Exception { Rate r = Rate.of(0.0567f); assertNotNull(r); }
@Test(expected=NullPointerException.class) public void of_Null() throws Exception { Rate.of((Number)null); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((rate == null) ? 0 : rate.hashCode()); result = prime * result + ((info == null) ? 0 : info.hashCode()); return result; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void testHashCode() throws Exception { Rate r1 = Rate.of(0.0567f); Rate r2 = Rate.of(0.0567d); assertTrue(r1.hashCode()==r2.hashCode()); r2 = Rate.of(0.0568d); assertFalse(r1.hashCode()==r2.hashCode()); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rate other = (Rate) obj; if (rate == null) { if (other.rate != null) return false; } else if (!rate.equals(other.rate)) return false; if (info == null) { if (other.info != null) return false; } else if (!info.equals(other.info)) return false; return true; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void testEquals() throws Exception { Rate r1 = Rate.of(0.0567f); Rate r2 = Rate.of(0.0567d); assertEquals(r1, r2); r2 = Rate.of(0.0568d); assertNotSame(r1, r2); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public BigDecimal get() { return this.rate; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void get() throws Exception { Rate r1 = Rate.of(0.0567f); assertEquals(BigDecimal.valueOf(0.0567d), r1.get()); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public String toString() { if(info!=null){ return "Rate[rate=" + rate + ",info="+info+"]"; } return "Rate[" + rate + "]"; } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void testToString() throws Exception { Rate r1 = Rate.of(0.0567f); assertEquals("Rate[0.0567]", r1.toString()); } |
### Question:
Rate implements MonetaryOperator, Supplier<BigDecimal> { @Override public MonetaryAmount apply(MonetaryAmount amount) { return amount.multiply(rate); } private Rate(BigDecimal rate, String info); static Rate zero(String info); static Rate of(BigDecimal rate); static Rate of(BigDecimal rate, String info); static Rate of(Number rate); static Rate of(Number rate, String info); @Override int hashCode(); @Override boolean equals(Object obj); @Override BigDecimal get(); String getInfo(); @Override String toString(); @Override MonetaryAmount apply(MonetaryAmount amount); static final Rate ZERO; }### Answer:
@Test public void apply() throws Exception { Rate r1 = Rate.of(0.05); assertEquals(Money.of(5, "CHF"), r1.apply(Money.of(100, "CHF"))); assertEquals(Money.of(5, "CHF"), Money.of(100, "CHF").with(r1)); } |
### Question:
FutureValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private FutureValueOfAnnuity(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { FutureValueOfAnnuity val = FutureValueOfAnnuity.of( RateAndPeriods.of(0.08, 10) ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); } |
### Question:
FutureValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "FutureValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } private FutureValueOfAnnuity(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void toStringTest() throws Exception { FutureValueOfAnnuity val = FutureValueOfAnnuity.of( RateAndPeriods.of(0.05, 10) ); assertEquals("FutureValueOfAnnuity{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=10}}", val.toString()); } |
### Question:
FutureValue extends AbstractRateAndPeriodBasedOperator { public static FutureValue of(RateAndPeriods rateAndPeriods) { return new FutureValue(rateAndPeriods); } private FutureValue(RateAndPeriods rateAndPeriods); static FutureValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testOfAndApply() throws Exception { Money money = Money.of(100, "CHF"); MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN) .build()); assertEquals(Money.of(BigDecimal.valueOf(105.00), "CHF"), money.with(FutureValue .of(RateAndPeriods.of(0.05, 1))).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(110.25), "CHF"), money.with(FutureValue.of(RateAndPeriods.of(0.05, 2))).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(210.49), "CHF"), money.with(FutureValue.of(RateAndPeriods.of(0.07, 11))).with(rounding)); } |
### Question:
FutureValue extends AbstractRateAndPeriodBasedOperator { public static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods) { BigDecimal f = (CalculationContext.one().add(rateAndPeriods.getRate().get())).pow(rateAndPeriods.getPeriods()); return amount.multiply(f); } private FutureValue(RateAndPeriods rateAndPeriods); static FutureValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testCalculate() throws Exception { Money money = Money.of(100, "CHF"); MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN) .build()); assertEquals(Money.of(BigDecimal.valueOf(105.00), "CHF"), FutureValue.calculate(money, RateAndPeriods.of(0.05, 1)).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(110.25), "CHF"), FutureValue.calculate(money, RateAndPeriods.of(0.05, 2)).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(210.49), "CHF"), FutureValue.calculate(money, RateAndPeriods.of(0.07, 11)).with(rounding)); } |
### Question:
FutureValue extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "FutureValue{" + "\n " + rateAndPeriods + '}'; } private FutureValue(RateAndPeriods rateAndPeriods); static FutureValue of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { assertEquals("FutureValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=1}}", FutureValue.of(RateAndPeriods.of(0.05, 1)).toString()); assertEquals("FutureValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=2}}", FutureValue.of(RateAndPeriods.of(0.05, 2)).toString()); assertEquals("FutureValue{\n" + " RateAndPeriods{\n" + " rate=Rate[0.07]\n" + " periods=11}}", FutureValue.of(RateAndPeriods.of(0.07, 11)).toString()); } |
### Question:
AverageCollectionPeriod implements MonetaryQuery<BigDecimal> { public static BigDecimal calculate(Number receivablesTurnover) { return new BigDecimal(365, CalculationContext.mathContext()) .divide(new BigDecimal(receivablesTurnover.toString()), CalculationContext.mathContext()); } BigDecimal getAvgAccountsReceivable(); static BigDecimal calculate(Number receivablesTurnover); static BigDecimal receivablesTurnover(MonetaryAmount revenue, Number avgAccountsReceivable); static BigDecimal calculate(MonetaryAmount revenue, Number avgAccountsReceivable); @Override BigDecimal queryFrom(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void calculate_POSITIVE() throws Exception { assertEquals(99.23871669385536, AverageCollectionPeriod.calculate(BigDecimal.valueOf(3.678)).doubleValue(), 0.0000001d); }
@Test public void calculate_NEGATIVE() throws Exception { assertEquals(-99.23871669385536, AverageCollectionPeriod.calculate(BigDecimal.valueOf(-3.678)).doubleValue(), 0.0000001d); }
@Test public void calculate_Explicit() throws Exception { assertEquals(BigDecimal.valueOf(1042.006525285481), AverageCollectionPeriod.calculate(Money.of(3.678, "CHF"), BigDecimal.valueOf(10.5))); } |
### Question:
AverageCollectionPeriod implements MonetaryQuery<BigDecimal> { public static BigDecimal receivablesTurnover(MonetaryAmount revenue, Number avgAccountsReceivable){ return new BigDecimal(avgAccountsReceivable.toString()).divide( revenue.getNumber().numberValue(BigDecimal.class), MathContext.DECIMAL64); } BigDecimal getAvgAccountsReceivable(); static BigDecimal calculate(Number receivablesTurnover); static BigDecimal receivablesTurnover(MonetaryAmount revenue, Number avgAccountsReceivable); static BigDecimal calculate(MonetaryAmount revenue, Number avgAccountsReceivable); @Override BigDecimal queryFrom(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void receivableTurnover() throws Exception { assertEquals(BigDecimal.valueOf(2.854812398042414), AverageCollectionPeriod.receivablesTurnover( Money.of(3.678, "CHF"), BigDecimal.valueOf(10.5))); } |
### Question:
RuleOf72 { public static BigDecimal calculate(Rate input) { return BD72.divide(input.get().multiply(BigDecimal.valueOf(100)), CalculationContext.mathContext()); } private RuleOf72(); static BigDecimal calculate(Rate input); }### Answer:
@Test public void calculate_POSITIVE() throws Exception { assertEquals(BigDecimal.valueOf(9.411764705882353), RuleOf72.calculate(Rate.of(0.0765))); }
@Test public void calculate_NEGATIVE() throws Exception { assertEquals(BigDecimal.valueOf(-9.411764705882353), RuleOf72.calculate(Rate.of(-0.0765))); } |
### Question:
DoublingTimeSimple { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTimeSimple with a rate=zero"); } return CalculationContext.one(). divide(rate.get(), CalculationContext.mathContext()); } private DoublingTimeSimple(); static BigDecimal calculate(Rate rate); }### Answer:
@Test public void calculate() throws Exception { assertEquals(11.72332942555686, DoublingTimeSimple.calculate(Rate.of(0.0853)).doubleValue(), 0.0d); assertEquals(2.0, DoublingTimeSimple.calculate(Rate.of(0.5)).doubleValue(), 0.0d); assertEquals(1.0, DoublingTimeSimple.calculate(Rate.of(1)).doubleValue(), 0.0d); assertEquals(22.22222222222222, DoublingTimeSimple.calculate(Rate.of(0.045)).doubleValue(), 0.0d); }
@Test(expected = MonetaryException.class) public void calculate_Invalid(){ DoublingTimeSimple.calculate(Rate.of(0)); } |
### Question:
PresentValueContinuousCompounding extends AbstractRateAndPeriodBasedOperator { public static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods) { Objects.requireNonNull(amount, "Amount required"); Objects.requireNonNull(rateAndPeriods, "Rate required"); Rate rate = rateAndPeriods.getRate(); int periods = rateAndPeriods.getPeriods(); BigDecimal fact = CalculationContext.one().divide( new BigDecimal(Math.pow(Math.E, rate .get().doubleValue() * periods), CalculationContext.mathContext()), CalculationContext.mathContext()); return amount.multiply(fact); } private PresentValueContinuousCompounding(RateAndPeriods rateAndPeriods); static PresentValueContinuousCompounding of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testCalculate() throws Exception { Money money = Money.of(100, "CHF"); MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN) .build()); assertEquals(Money.of(BigDecimal.valueOf(95.12), "CHF"), PresentValueContinuousCompounding.calculate(money, RateAndPeriods.of(0.05, 1)).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(90.48), "CHF"), PresentValueContinuousCompounding.calculate(money, RateAndPeriods.of(0.05, 2)).with(rounding)); assertEquals(Money.of(BigDecimal.valueOf(46.3), "CHF"), PresentValueContinuousCompounding.calculate(money, RateAndPeriods.of(0.07, 11)).with(rounding)); } |
### Question:
PresentValueContinuousCompounding extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueContinuousCompounding{" + "\n " + rateAndPeriods + '}'; } private PresentValueContinuousCompounding(RateAndPeriods rateAndPeriods); static PresentValueContinuousCompounding of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { assertEquals("PresentValueContinuousCompounding{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=1}}", PresentValueContinuousCompounding.of(RateAndPeriods.of(0.05, 1)).toString()); assertEquals("PresentValueContinuousCompounding{\n" + " RateAndPeriods{\n" + " rate=Rate[0.05]\n" + " periods=2}}", PresentValueContinuousCompounding.of(RateAndPeriods.of(0.05, 2)).toString()); assertEquals("PresentValueContinuousCompounding{\n" + " RateAndPeriods{\n" + " rate=Rate[0.07]\n" + " periods=11}}", PresentValueContinuousCompounding.of(RateAndPeriods.of(0.07, 11)).toString()); } |
### Question:
WeightedAverage { public static WeightedValue ofWeightedValue(BigDecimal value, BigDecimal weight){ return new WeightedValue(value, weight); } private WeightedAverage(Collection<WeightedValue> values); static WeightedValue ofWeightedValue(BigDecimal value, BigDecimal weight); static Builder newBuilder(); Collection<WeightedValue> getValues(); BigDecimal calculateWeightedAverage(); static BigDecimal calculateWeightedAverage(Collection<WeightedValue> values); }### Answer:
@Test public void ofWeightedValue() throws Exception { WeightedAverage.WeightedValue val = WeightedAverage.ofWeightedValue( new BigDecimal(100.45), new BigDecimal(243) ); assertEquals(val.getValue(), new BigDecimal(100.45)); assertEquals(val.getWeight(), new BigDecimal(243)); } |
### Question:
WeightedAverage { public Collection<WeightedValue> getValues() { return Collections.unmodifiableCollection(values); } private WeightedAverage(Collection<WeightedValue> values); static WeightedValue ofWeightedValue(BigDecimal value, BigDecimal weight); static Builder newBuilder(); Collection<WeightedValue> getValues(); BigDecimal calculateWeightedAverage(); static BigDecimal calculateWeightedAverage(Collection<WeightedValue> values); }### Answer:
@Test public void getValues() throws Exception { } |
### Question:
SimpleInterest extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private SimpleInterest(RateAndPeriods rateAndPeriods); static SimpleInterest of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(MonetaryAmount amount, RateAndPeriods rateAndPeriods); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); }### Answer:
@Test public void apply() throws Exception { SimpleInterest ci = SimpleInterest.of( RateAndPeriods.of(0.05,7) ); assertEquals(ci.apply(Money.of(100,"CHF")),Money.of(35,"CHF")); } |
### Question:
BasisPoint implements MonetaryOperator { public static BasisPoint of(Number number) { return new BasisPoint(number); } private BasisPoint(final Number decimal); static BasisPoint of(Number number); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amount, Number basisPoints); }### Answer:
@Test public void testOf() { BasisPoint perc = BasisPoint.of(BigDecimal.ONE); assertNotNull(perc); } |
### Question:
BasisPoint implements MonetaryOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return amount.multiply(basisPointValue); } private BasisPoint(final Number decimal); static BasisPoint of(Number number); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amount, Number basisPoints); }### Answer:
@Test public void testApply() { Money m = Money.of(BigDecimal.valueOf(2.35d), "CHF"); assertEquals(Money.of(BigDecimal.valueOf(0.00235d), "CHF"), BasisPoint.of(BigDecimal.TEN).apply(m)); } |
### Question:
BasisPoint implements MonetaryOperator { @Override public String toString() { return NumberFormat.getInstance() .format( basisPointValue.multiply(ONE_TENTHOUSAND, CalculationContext.mathContext())) + "\u2031"; } private BasisPoint(final Number decimal); static BasisPoint of(Number number); @Override MonetaryAmount apply(MonetaryAmount amount); @Override String toString(); static MonetaryAmount calculate(MonetaryAmount amount, Number basisPoints); }### Answer:
@Test public void testToString() { assertEquals("15\u2031", BasisPoint.of(BigDecimal.valueOf(15)) .toString()); } |
### Question:
DoublingTime { public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); } private DoublingTime(); static BigDecimal calculate(Rate rate); }### Answer:
@Test public void calculate() throws Exception { assertEquals(8.467838642560691, DoublingTime.calculate(Rate.of(0.0853)).doubleValue(), 0.0d); assertEquals(1.709511291351455, DoublingTime.calculate(Rate.of(0.5)).doubleValue(), 0.0d); assertEquals(1.0, DoublingTime.calculate(Rate.of(1)).doubleValue(), 0.0d); assertEquals(15.74730183648559, DoublingTime.calculate(Rate.of(0.045)).doubleValue(), 0.0d); }
@Test(expected = MonetaryException.class) public void calculate_Invalid(){ DoublingTime.calculate(Rate.of(0)); } |
### Question:
RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } private RangeSorter(List<Range> ranges); }### Answer:
@Test public void should_sort_ranges() throws Exception { Range first = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 3)); Range second = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 5)); Range third = range(from(2017, Calendar.AUGUST, 1), from(2017, Calendar.AUGUST, 7)); Range fourth = range(from(2017, Calendar.AUGUST, 10), from(2017, Calendar.AUGUST, 27)); List<Range> result = RangeSorter.sort(asList(second, first, third, fourth)); List<Range> expected = asList(first, second, third, fourth); assertEquals(expected, result); } |
### Question:
CalendarWeekDayFormatter implements WeekDayFormatter { @Override public CharSequence format(int dayOfWeek) { calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek); return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } CalendarWeekDayFormatter(Calendar calendar); CalendarWeekDayFormatter(); @Override CharSequence format(int dayOfWeek); }### Answer:
@Test public void testFormattedDayOfWeek_Sunday() throws Exception { assertThat(formatter.format(Calendar.SUNDAY).toString(), is("Sun")); }
@Test public void testFormattedDayOfWeek_Monday() throws Exception { assertThat(formatter.format(Calendar.MONDAY).toString(), is("Mon")); }
@Test public void testFormattedDayOfWeek_Tuesday() throws Exception { assertThat(formatter.format(Calendar.TUESDAY).toString(), is("Tue")); }
@Test public void testFormattedDayOfWeek_Wednesday() throws Exception { assertThat(formatter.format(Calendar.WEDNESDAY).toString(), is("Wed")); }
@Test public void testFormattedDayOfWeek_Thursday() throws Exception { assertThat(formatter.format(Calendar.THURSDAY).toString(), is("Thu")); }
@Test public void testFormattedDayOfWeek_Friday() throws Exception { assertThat(formatter.format(Calendar.FRIDAY).toString(), is("Fri")); }
@Test public void shouldReturnCorrectFormattedEnglishTextOfSaturday() throws Exception { assertThat(formatter.format(Calendar.SATURDAY).toString(), is("Sat")); } |
### Question:
RealtimeMessagingMonitor extends Monitor { @Override public void stop() { super.stop(); if (!rtMessagingDisposable.isDisposed()) { rtMessagingDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingDisposable"); } if (!rtMessagingSessionDisposable.isDisposed()) { rtMessagingSessionDisposable.dispose(); logger.d(TAG, "stop: disposed rtMessagingSessionDisposable"); } } RealtimeMessagingMonitor(@NonNull Observable<RealtimeMessagingActivity> rtDataObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); RealtimeMessagingMonitor(@NonNull UtilComponent utilComponent,
@NonNull Observable<RealtimeMessagingActivity> rtMessagingObservable,
@NonNull Observable<RealtimeMessagingSession> rtMessagingSessionObservable); static UtilComponent createDaggerComponent(); @Override void stop(); }### Answer:
@Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<RealtimeMessagingActivity> rtMessagingPublishSubject = PublishSubject.create(); PublishSubject<RealtimeMessagingSession> realtimeMessagingSessionObservable = PublishSubject.create(); RealtimeMessagingMonitor monitor = new RealtimeMessagingMonitor(testUtilComponent, rtMessagingPublishSubject, realtimeMessagingSessionObservable) { @Override protected void saveToDataStore(RealtimeMessagingActivity activity) { } }; Assert.assertNotNull(monitor.rtMessagingDisposable); Assert.assertFalse(monitor.rtMessagingDisposable.isDisposed()); monitor.stop(); Assert.assertTrue(monitor.rtMessagingDisposable.isDisposed()); } |
### Question:
NetworkMonitor extends Monitor { @Override public void stop() { super.stop(); if (!networkActivityDisposable.isDisposed()) { networkActivityDisposable.dispose(); logger.d(TAG, "stop: disposed networkActivityDisposable"); } } NetworkMonitor(@NonNull Observable<NetworkActivity> networkActivityObservable); NetworkMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<NetworkActivity> networkActivityObservable); static UtilComponent createDaggerComponent(); @Override void stop(); }### Answer:
@Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<NetworkActivity> networkActivityPublishSubject = PublishSubject.create(); NetworkMonitor monitor = new NetworkMonitor(testUtilComponent, networkActivityPublishSubject) { @Override protected void saveToDataStore(NetworkActivity activity) { } }; Assert.assertNotNull(monitor.networkActivityDisposable); Assert.assertFalse(monitor.networkActivityDisposable.isDisposed()); monitor.stop(); Assert.assertTrue(monitor.networkActivityDisposable.isDisposed()); } |
### Question:
OnOffMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean turnedOff() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a GPS session"); endTime = startTime; } logger.d(Logger.TAG, label + " Session completed, duration (seconds): " + ((endTime - startTime) / 1000)); OnOffSessionData sessionData = new OnOffSessionData(metricName, startTime, endTime); eventPublishSubject.onNext(new FalxMonitorEvent(sessionData.getName(), sessionData.getArgumentMap())); startTime = 0; return true; } OnOffMonitor(@NonNull UtilComponent utilComponent, @NonNull Observable<Boolean> stateObservable, String metricName, String label); @Override void stop(); }### Answer:
@Test public void sessionTestErrorCase() throws Exception { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); OnOffMonitor monitor = new OnOffMonitor(testUtilComponent, stateObservable(), EVENT_GPS_ON, MONITOR_LABEL_GPS); TestObserver<FalxMonitorEvent> testObserver = monitor.getEventObservable().test(); TestClock testClock = (TestClock) monitor.clock; final long firstSessionStartTime = 100L; long currentTime = firstSessionStartTime; testClock.setCurrentTimeMillis(currentTime); Assert.assertEquals(testClock.currentTimeMillis(), currentTime); monitor.turnedOff(); FalxMonitorEvent event = testObserver.values().get(0); Assert.assertEquals(EVENT_GPS_ON, event.getName()); Assert.assertEquals(0, (long)(event.getArguments().get(FalxConstants.PROP_DURATION) * DateUtils.SECOND_IN_MILLIS)); } |
### Question:
ArticleMapper extends Mapper<Article,ArticleEntity> { @Override public Article map(ArticleEntity fake) { Article article=new Article(); article.setId(fake.getId()); article.setAuthor(fake.getAuthor()); article.setBackdropUrl(fake.getBackdropUrl()); article.setPosterUrl(fake.getPosterUrl()); article.setTitle(fake.getTitle()); article.setPublishedDate(fake.getPublishedDate()); article.setBody(fake.getBody()); article.setPosterRatio(fake.getPosterRatio()); return article; } @Inject ArticleMapper(); @Override Article map(ArticleEntity fake); }### Answer:
@Test public void mapsFakeEntityToReal(){ ArticleEntity entity= FakeProvider.provideArticleEntity(); Article article=mapper.map(entity); assertThatAreEqual(article,entity); }
@Test public void mapsFakeEntityListToRealList(){ List<ArticleEntity> entities=FakeProvider.provideArticleEntityList(); List<Article> articles=mapper.map(entities); assertThat(articles,notNullValue()); assertThat(articles.size(),is(entities.size())); for(int index=0;index<articles.size();index++){ assertThatAreEqual(articles.get(index),entities.get(index)); } } |
### Question:
ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@NonNull IArticlesConfig iArticlesConfig); @Override void start(); @Override void stop(); @Override void refresh(); @Override void onConfigChanged(ViewConfig config); @Override void attachView(@NonNull View view); }### Answer:
@Test public void showsEmptyMessageOnStartMethod(){ when(repository.get()).thenReturn(Observable.just(null)); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showEmptyMessage(); }
@Test public void showsErrorMessageOnStartMethod(){ when(repository.get()).thenReturn(Observable.error(new Exception())); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showErrorMessage(); }
@Test public void showsDataToViewOnStartMethod(){ when(repository.get()).thenReturn(Observable.just(FakeProvider.provideArticleList())); presenter.start(); verify(view).setLoadingIndicator(eq(true)); verify(view).setLoadingIndicator(eq(false)); verify(view).showList(anyList()); } |
### Question:
CacheStore { public T get(int key){ return inMemoryCache.get(key); } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); }### Answer:
@Test public void returnsNullIfThereIsNoValueInCache(){ assertThat(cacheStore.get(FakeProvider.FAKE_ID),nullValue()); } |
### Question:
CacheStore { public boolean isInCache(int key){ return inMemoryCache.get(key,null)!=null; } CacheStore(int size); void put(int key, T item); boolean isInCache(int key); T get(int key); }### Answer:
@Test public void checksIfItemIsInCache(){ putIn(); assertTrue(cacheStore.isInCache(FakeProvider.FAKE_ID)); } |
### Question:
ArticlePresenter implements ArticleContract.Presenter { @Override public void loadArticle(int id) { repository.get(id) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .subscribe(this::processArticle,this::catchError); } @Inject ArticlePresenter(IRepository<Article> repository,
BaseSchedulerProvider schedulerProvider); @Override void attachView(@NonNull View view); @Override void loadArticle(int id); }### Answer:
@Test public void showsDataToViewOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.just(FakeProvider.provideArticle())); presenter.loadArticle(1); verify(view).showArticle(any(Article.class)); }
@Test public void showsEmptyMessageOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.just(null)); presenter.loadArticle(1); verify(view).showEmptyMessage(); }
@Test public void showsErrorMessageOnStartMethod(){ when(repository.get(1)).thenReturn(Observable.error(new Exception())); presenter.loadArticle(1); verify(view).showErrorMessage(); } |
### Question:
Strings { public static String format(final String format, final Object... args) { String retVal = format; for (final Object current : args) { retVal = retVal.replaceFirst("[%][s]", current.toString()); } return retVal; } static String format(final String format, final Object... args); }### Answer:
@Test public void format() throws Exception { this.assertFormat("Some test here %s.", 54); this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA"); this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA", "DONT SHOW"); Assert.assertEquals("Formatting is not working", "Some test here 54 %s.", Strings.format("Some test here %s %s.", 54)); } |
### Question:
PromptWrapper { public void close() throws IOException { this.prompt.close(); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); }### Answer:
@Test public void testClose() throws Exception { final IPrompter prompt = mock(IPrompter.class); Mockito.doThrow(IOException.class).when(prompt).close(); FieldUtils.writeField(wrapper, "prompt", prompt, true); try { wrapper.close(); fail("Should throw IOException"); } catch (IOException ex) { } Mockito.verify(prompt); prompt.close(); } |
### Question:
XmlUtils { public static String prettyPrintElementNoNamespace(Element node) { removeAllNamespaces(node); try { final StringWriter out = new StringWriter(); final OutputFormat format = OutputFormat.createPrettyPrint(); format.setSuppressDeclaration(true); format.setIndent(" "); format.setPadText(false); final XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.flush(); return StringUtils.stripStart(out.toString(), null); } catch (IOException e) { throw new RuntimeException("IOException while generating " + "textual representation: " + e.getMessage()); } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); }### Answer:
@Test public void testPrettyPrintElementNoNamespace() throws Exception { final String[] lines = TextUtils.splitLines(XmlUtils.prettyPrintElementNoNamespace(propertiesNode)); assertEquals(5, lines.length); assertEquals("<properties>", lines[0]); assertEquals(" <maven.compiler.source>1.8</maven.compiler.source>", lines[1]); assertEquals(" <maven.compiler.target>1.8</maven.compiler.target>", lines[2]); assertEquals(" <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>", lines[3]); assertEquals("</properties>", lines[4]); } |
### Question:
XmlUtils { public static String getChildValue(Element element, String attribute) { final Element child = element.element(attribute); return child == null ? null : child.getText(); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); }### Answer:
@Test public void testGetChildValue() { assertEquals("1.8\n", XmlUtils.getChildValue(propertiesNode, "maven.compiler.target")); } |
### Question:
XmlUtils { public static void addDomWithKeyValue(Element node, String key, Object value) { final DOMElement newNode = new DOMElement(key); if (value != null) { newNode.setText(value.toString()); } node.add(newNode); } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); }### Answer:
@Test public void testAddDomWithKeyValue() { XmlUtils.addDomWithKeyValue(propertiesNode, "foo", "bar"); final String[] lines = TextUtils.splitLines(XmlUtils.prettyPrintElementNoNamespace(propertiesNode)); assertEquals(6, lines.length); assertEquals(" <foo>bar</foo>", lines[4]); } |
### Question:
XmlUtils { public static void trimTextBeforeEnd(Element parent, Node target) { final List<Node> children = parent.content(); final int index = children.indexOf(target); int pos = index - 1; while (pos >= 0 && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos--); textNode.setText(StringUtils.stripEnd(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } final int size = children.size(); pos = index + 1; while (pos < size && children.get(pos).getNodeType() == Node.TEXT_NODE) { final Node textNode = children.get(pos++); textNode.setText(StringUtils.stripStart(textNode.getText(), null)); if (StringUtils.isNotBlank(textNode.getText())) { break; } } } private XmlUtils(); static String getChildValue(Element element, String attribute); static String prettyPrintElementNoNamespace(Element node); static void trimTextBeforeEnd(Element parent, Node target); static void addDomWithValueList(Element element, String attribute, String subAttribute, List<String> values); static void addDomWithKeyValue(Element node, String key, Object value); static void removeAllNamespaces(Element ele); }### Answer:
@Test public void testTrimTextBeforeEnd() { XmlUtils.removeAllNamespaces(propertiesNode); XmlUtils.addDomWithKeyValue(propertiesNode, "foo", "bar"); final Namespace ns = propertiesNode.getNamespace(); final Element fooNode = propertiesNode.element(new QName("foo", ns)); propertiesNode.addText(" "); final String xmlBefore = propertiesNode.asXML(); XmlUtils.trimTextBeforeEnd(propertiesNode, fooNode); final String xmlAfter = propertiesNode.asXML(); assertTrue(xmlBefore.contains("</project.build.sourceEncoding>\n <foo>bar</foo> </properties>")); assertTrue(xmlAfter.contains("</project.build.sourceEncoding><foo>bar</foo></properties>")); } |
### Question:
TemplateUtils { public static Boolean evalBoolean(String expr, Map<String, Object> variableMap) { final String text = evalPlainText(expr, variableMap); if (text == null) { return Boolean.FALSE; } return Boolean.valueOf(text); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); }### Answer:
@Test public void testEvalBoolean() { assertEquals(Boolean.TRUE, evalBoolean("foo", Collections.singletonMap("foo", "true"))); assertEquals(Boolean.TRUE, evalBoolean("foo", Collections.singletonMap("foo", true))); assertEquals(Boolean.FALSE, evalBoolean("foo", Collections.singletonMap("foo", null))); }
@Test public void testEvalBooleanVariable() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}}"); map.put("bar", "true"); assertEquals(Boolean.TRUE, evalBoolean("foo", map)); }
@Test public void testEvalBooleanRecursive() { final Map<String, Object> map = new HashMap<>(); map.put("foo", Collections.singletonMap("bar", "true")); assertEquals(Boolean.TRUE, evalBoolean("foo.bar", map)); } |
### Question:
RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer:
@Test(expected = AzureExecutionException.class) public void checkStageDirectoryExistenceWhenNotExisting() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doReturn("./NotExistFile").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.checkStageDirectoryExistence(); }
@Test(expected = AzureExecutionException.class) public void checkStageDirectoryExistenceWhenIsNotDirectory() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doReturn("./RunMojoTest.java").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.checkStageDirectoryExistence(); } |
### Question:
TemplateUtils { public static String evalPlainText(String expr, Map<String, Object> variableMap) { String text = expr.contains(".") ? evalInline(expr, variableMap) : Objects.toString(variableMap.get(expr), null); int evalCount = 0; while (text != null && text.contains("{{")) { text = eval(text, variableMap); evalCount++; if (evalCount > 5) { break; } } return text; } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); }### Answer:
@Test public void testEvalPlainText() { final Map<String, Object> map = new HashMap<>(); map.put("foo", Collections.singletonMap("bar", "true")); assertEquals("true", evalPlainText("foo.bar", map)); map.put("foo", Collections.singletonMap("bar", true)); assertEquals("true", evalPlainText("foo.bar", map)); }
@Test public void testEvalPlainTextVariable() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}}"); map.put("bar", "hello world"); assertEquals("hello world", evalPlainText("foo", map)); }
@Test public void testEndlessEval() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "hello {{name}}"); map.put("name", "{{foo}}"); assertEquals("hello hello hello hello {{name}}", evalPlainText("foo", map)); }
@Test public void testBadExpression() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "{{bar}"); map.put("bar", "hello world"); try { evalPlainText("foo", map); fail("Should report error when evaluate text is not valid."); } catch (ParseException ex) { } } |
### Question:
TemplateUtils { public static String evalText(String expr, Map<String, Object> variableMap) { return evalPlainText(expr, variableMap).replaceAll("\\*\\*\\*(.*?)\\*\\*\\*", TextUtils.blue("$1")); } private TemplateUtils(); static Boolean evalBoolean(String expr, Map<String, Object> variableMap); static String evalText(String expr, Map<String, Object> variableMap); static String evalPlainText(String expr, Map<String, Object> variableMap); }### Answer:
@Test public void testEvalText() { final Map<String, Object> map = new HashMap<>(); map.put("foo", "hello ***{{name}}***"); map.put("name", "Jack"); assertEquals(String.format("hello %s", TextUtils.blue("Jack")), evalText("foo", map)); } |
### Question:
ResourcesUtils { public static List<Resource> getDefaultResources() { final Resource resource = new Resource(); resource.setDirectory(DEFAULT_DIRECTORY); resource.addInclude(DEFAULT_INCLUDE); return Collections.singletonList(resource); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); }### Answer:
@Test public void testGetDefaultResources() { final List<Resource> resources = ResourcesUtils.getDefaultResources(); assertEquals(1, resources.size()); final Resource resource = resources.get(0); assertNotNull(resource); assertEquals("${project.basedir}/target", resource.getDirectory()); assertNull(resource.getFiltering()); assertEquals(0, resource.getExcludes().size()); assertEquals(1, resource.getIncludes().size()); assertEquals("*.jar", resource.getIncludes().get(0)); } |
### Question:
ResourcesUtils { public static void applyDefaultResourcesToDom4j(Element root) { final DOMElement resourceRootNode = new DOMElement("resources"); for (final Resource resource : getDefaultResources()) { final DOMElement resourceNode = new DOMElement("resource"); XmlUtils.addDomWithKeyValue(resourceNode, "filtering", resource.getFiltering()); XmlUtils.addDomWithKeyValue(resourceNode, "mergeId", resource.getMergeId()); XmlUtils.addDomWithKeyValue(resourceNode, "targetPath", resource.getTargetPath()); XmlUtils.addDomWithKeyValue(resourceNode, "directory", resource.getDirectory()); XmlUtils.addDomWithValueList(resourceNode, "includes", "include", resource.getIncludes()); XmlUtils.addDomWithValueList(resourceNode, "excludes", "exclude", resource.getExcludes()); resourceRootNode.add(resourceNode); } root.add(resourceRootNode); } private ResourcesUtils(); static List<Resource> getDefaultResources(); static void applyDefaultResourcesToDom4j(Element root); }### Answer:
@Test public void testApplyDefaultResourcesToDom4j() throws Exception { final SAXReader reader = new SAXReader(); final Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream("test-2.xml")); final Element rootNode = document.getRootElement(); ResourcesUtils.applyDefaultResourcesToDom4j(rootNode); assertTrue(rootNode.asXML().contains( "<resources><resource><filtering/><mergeId/><targetPath/><directory>${project.basedir}/target</directory>" + "<includes><include>*.jar</include></includes></resource></resources>")); } |
### Question:
DeployMojo extends AbstractSpringMojo { protected boolean checkProjectPackaging(MavenProject project) throws MojoExecutionException { if (Utils.isJarPackagingProject(project)) { return true; } else if (Utils.isPomPackagingProject(project)) { getLog().info(PROJECT_SKIP); return false; } else { throw new MojoExecutionException(String.format(PROJECT_NOT_SUPPORT, project.getPackaging())); } } }### Answer:
@Test public void testCheckProjectPackaging() throws MojoExecutionException { final MavenProject mockProject = mock(MavenProject.class); doReturn("jar").when(mockProject).getPackaging(); assertTrue(checkProjectPackaging(mockProject)); doReturn("pom").when(mockProject).getPackaging(); assertFalse(checkProjectPackaging(mockProject)); doReturn("war").when(mockProject).getPackaging(); try { checkProjectPackaging(mockProject); fail("Check project packaging should throw exception when project packing is war"); } catch (MojoExecutionException exception) { } } |
### Question:
RunMojo extends AbstractFunctionMojo { protected void checkRuntimeExistence(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); Log.info(RUNTIME_FOUND); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer:
@Test public void checkRuntimeExistence() throws Exception { final RunMojo mojo = getMojoFromPom(); final CommandHandler commandHandlerMock = mock(CommandHandlerImpl.class); mojo.checkRuntimeExistence(commandHandlerMock); verify(commandHandlerMock, times(1)) .runCommandWithReturnCodeCheck( mojo.getCheckRuntimeCommand(), false, null, CommandUtils.getDefaultValidReturnCodes(), RUNTIME_NOT_FOUND ); } |
### Question:
SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterException(String.format(NO_CLUSTER, cluster, subscriptionId))); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); }### Answer:
@Test public void getClusterByName() { final ServiceResourceInner mockCluster = mock(ServiceResourceInner.class); doReturn("existCluster").when(mockCluster).name(); final List<ServiceResourceInner> mockClusterList = new ArrayList<>(); mockClusterList.add(mockCluster); doReturn(mockClusterList).when(spyClient).getAvailableClusters(); assertSame(spyClient.getClusterByName("existCluster"), mockCluster); try { spyClient.getClusterByName("unExistCluster"); fail("Should throw IPE when cluster doesn't exist"); } catch (InvalidParameterException e) { } } |
### Question:
SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent, LogLevel logLevel); SpringAppClient newSpringAppClient(String subscriptionId, String cluster, String app); SpringAppClient newSpringAppClient(SpringConfiguration configuration); List<ServiceResourceInner> getAvailableClusters(); ServiceResourceInner getClusterByName(String cluster); String getResourceGroupByCluster(String clusterName); String getResourceGroupByCluster(ServiceResourceInner cluster); String getSubscriptionId(); AppPlatformManager getSpringManager(); }### Answer:
@Test public void getResourceGroupByCluster() { final ServiceResourceInner mockCluster = mock(ServiceResourceInner.class); doReturn("/resourceGroups/test").when(mockCluster).id(); doReturn(mockCluster).when(spyClient).getClusterByName(any()); assertEquals("test", spyClient.getResourceGroupByCluster("cluster")); } |
### Question:
SchemaValidator { public void collectSingleProperty(String resource, String property, JsonNode schema) throws JsonProcessingException { Preconditions.checkArgument(StringUtils.isNotBlank(resource), "Parameter 'resource' should not be null or empty."); Preconditions.checkArgument(StringUtils.isNotBlank(property), "Parameter 'property' should not be null or empty."); Preconditions.checkArgument(!schemaMap.containsKey(combineToKey(resource, property)), String.format("Duplicate property '%s'.", combineToKey(resource, property))); schemas.put(combineToKey(resource, property), schema); schemaMap.put(combineToKey(resource, property), mapper.treeToValue(schema, Map.class)); } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); }### Answer:
@Test public void testDuplicateAdd() throws IOException { try { this.validator.collectSingleProperty("Deployment", "cpu", Mockito.mock(JsonNode.class)); fail("should throw IAE"); } catch (IllegalArgumentException ex) { } } |
### Question:
SchemaValidator { public String validateSingleProperty(String resource, String property, String value) { checkExistSchema(resource, property); final JsonNode schema = this.schemas.get(combineToKey(resource, property)); final String type = (String) schemaMap.get(combineToKey(resource, property)).get("type"); try { final ProcessingReport reports = validator.validate(schema, stringToJsonObject(type, value)); return formatValidationResults(reports); } catch (IllegalArgumentException | ProcessingException e) { return e.getMessage(); } } SchemaValidator(); void collectSingleProperty(String resource, String property, JsonNode schema); Map<String, Object> getSchemaMap(String resource, String property); String validateSingleProperty(String resource, String property, String value); }### Answer:
@Test public void testTypeNotSupported() throws Exception { final String err = validator.validateSingleProperty("Deployment", "testProperties", "foo"); assertTrue(err.contains("Type 'array' is not supported in schema validation.")); }
@Test public void testMoreThanOneViolations() throws Exception { final String err = validator.validateSingleProperty("App", "appName", "_thisisaverylonglonglonglonglongtext"); assertTrue(err.contains("The input violates the validation rules")); } |
### Question:
ZIPArtifactHandlerImpl extends ArtifactHandlerBase { protected File getZipFile() { final File zipFile = new File(stagingDirectoryPath + ".zip"); final File stagingDirectory = new File(stagingDirectoryPath); ZipUtil.pack(stagingDirectory, zipFile); ZipUtil.removeEntry(zipFile, LOCAL_SETTINGS_FILE); return zipFile; } protected ZIPArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget target); }### Answer:
@Test public void getZipFile() { final File zipTestDirectory = new File("src/test/resources/ziptest"); buildHandler(); assertEquals(zipTestDirectory.getAbsolutePath() + ".zip", handlerSpy.getZipFile().getAbsolutePath()); }
@Test(expected = ZipException.class) public void getZipFileThrowException() { handler = builder.stagingDirectoryPath("").build(); handlerSpy = spy(handler); handlerSpy.getZipFile(); } |
### Question:
RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer:
@Test public void runFunctions() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); final CommandHandler commandHandlerMock = mock(CommandHandlerImpl.class); doNothing().when(commandHandlerMock).runCommandWithReturnCodeCheck(anyString(), anyBoolean(), anyString(), ArgumentMatchers.anyList(), anyString()); doReturn("buildDirectory").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.runFunctions(commandHandlerMock); verify(commandHandlerMock, times(1)) .runCommandWithReturnCodeCheck( mojoSpy.getStartFunctionHostCommand(), true, mojoSpy.getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } |
### Question:
ArtifactHandlerBase implements ArtifactHandler { protected void assureStagingDirectoryNotEmpty() throws AzureExecutionException { final File stagingDirectory = new File(stagingDirectoryPath); final File[] files = stagingDirectory.listFiles(); if (!stagingDirectory.exists() || !stagingDirectory.isDirectory() || files == null || files.length == 0) { throw new AzureExecutionException(String.format(STAGING_FOLDER_EMPTY, stagingDirectory.getAbsolutePath())); } } protected ArtifactHandlerBase(Builder<?> builder); }### Answer:
@Test(expected = AzureExecutionException.class) public void assureStagingDirectoryNotEmptyThrowException() throws AzureExecutionException { handler = builder.project(mock(IProject.class)) .stagingDirectoryPath("") .build(); handler.assureStagingDirectoryNotEmpty(); }
@Test public void assureStagingDirectoryNotEmpty() throws AzureExecutionException { buildHandler(); doNothing().when(handlerSpy).assureStagingDirectoryNotEmpty(); handlerSpy.assureStagingDirectoryNotEmpty(); verify(handlerSpy, times(1)).assureStagingDirectoryNotEmpty(); verifyNoMoreInteractions(handlerSpy); } |
### Question:
FTPArtifactHandlerImpl extends ArtifactHandlerBase { protected void uploadDirectoryToFTP(DeployTarget target) throws AzureExecutionException { final FTPUploader uploader = getUploader(); final PublishingProfile profile = target.getPublishingProfile(); final String serverUrl = profile.ftpUrl().split("/", 2)[0]; uploader.uploadDirectoryWithRetries(serverUrl, profile.ftpUsername(), profile.ftpPassword(), stagingDirectoryPath, DEFAULT_WEBAPP_ROOT, DEFAULT_MAX_RETRY_TIMES); } private FTPArtifactHandlerImpl(final Builder builder); @Override void publish(final DeployTarget target); }### Answer:
@Test public void uploadDirectoryToFTP() throws Exception { final String ftpUrl = "ftp.azurewebsites.net/site/wwwroot"; final PublishingProfile profile = mock(PublishingProfile.class); final WebApp app = mock(WebApp.class); final DeployTarget deployTarget = new DeployTarget(app, DeployTargetType.WEBAPP); final FTPUploader uploader = mock(FTPUploader.class); doReturn(ftpUrl).when(profile).ftpUrl(); doReturn(profile).when(app).getPublishingProfile(); buildHandler(); doReturn(uploader).when(handlerSpy).getUploader(); handlerSpy.uploadDirectoryToFTP(deployTarget); verify(app, times(1)).getPublishingProfile(); verifyNoMoreInteractions(app); verify(profile, times(1)).ftpUrl(); verify(profile, times(1)).ftpUsername(); verify(profile, times(1)).ftpPassword(); verifyNoMoreInteractions(profile); verify(uploader, times(1)) .uploadDirectoryWithRetries("ftp.azurewebsites.net", null, null, "target/classes", "/site/wwwroot", 3); verifyNoMoreInteractions(uploader); } |
### Question:
InputValidateResult { public static <T> InputValidateResult<T> wrap(T obj) { final InputValidateResult<T> res = new InputValidateResult<>(); res.obj = obj; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); }### Answer:
@Test public void testWrap() { final Object obj = new Object(); final InputValidateResult<Object> wrapper = InputValidateResult.wrap(obj); assertNotNull(wrapper); assertSame(obj, wrapper.getObj()); assertNull(wrapper.getErrorMessage()); } |
### Question:
InputValidateResult { public static <T> InputValidateResult<T> error(String errorMessage) { final InputValidateResult<T> res = new InputValidateResult<>(); res.errorMessage = errorMessage; return res; } T getObj(); String getErrorMessage(); static InputValidateResult<T> wrap(T obj); static InputValidateResult<T> error(String errorMessage); }### Answer:
@Test public void testError() { final InputValidateResult<Object> wrapper = InputValidateResult.error("message"); assertNotNull(wrapper); assertEquals("message", wrapper.getErrorMessage()); assertNull(wrapper.getObj()); } |
### Question:
RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer:
@Test public void getCheckRuntimeCommand() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); assertEquals(FUNC_CMD, mojoSpy.getCheckRuntimeCommand()); } |
### Question:
DefaultPrompter implements IPrompter { public void close() { try { reader.close(); } catch (IOException e) { } } String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired); Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired); List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities,
Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue); T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc,
boolean isRequired); void close(); }### Answer:
@Test public void testClose() throws Exception { PowerMockito.doNothing().when(reader).close(); this.prompter.close(); } |
### Question:
TextUtils { public static String blue(String message) { return applyColorToText(message, Color.BLUE); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testBlue() { System.out.println("This is a " + TextUtils.blue("blue") + " text."); assertEquals("1b5b33346d611b5b6d", Hex.encodeHexString(TextUtils.blue("a").getBytes())); } |
### Question:
TextUtils { public static String red(String message) { return applyColorToText(message, Color.RED); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testRed() { System.out.println("This is a " + TextUtils.red("red") + " text."); assertEquals("1b5b33316d611b5b6d", Hex.encodeHexString(TextUtils.red("a").getBytes())); } |
### Question:
RunMojo extends AbstractFunctionMojo { protected String getStartFunctionHostCommand() { final String enableDebug = System.getProperty("enableDebug"); if (StringUtils.isNotEmpty(enableDebug) && enableDebug.equalsIgnoreCase("true")) { return getStartFunctionHostWithDebugCommand(); } else { return FUNC_HOST_START_CMD; } } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer:
@Test public void getStartFunctionHostCommand() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); assertEquals(FUNC_HOST_START_CMD, mojoSpy.getStartFunctionHostCommand()); System.setProperty("enableDebug", "true"); assertTrue(mojoSpy.getStartFunctionHostCommand().contains("-agentlib:jdwp")); } |
### Question:
TextUtils { public static String yellow(String message) { return applyColorToText(message, Color.YELLOW); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testYellow() { System.out.println("This is a " + TextUtils.yellow("yellow") + " text."); assertEquals("1b5b33336d611b5b6d", Hex.encodeHexString(TextUtils.yellow("a").getBytes())); } |
### Question:
TextUtils { public static String green(String message) { return applyColorToText(message, Color.GREEN); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testGreen() { System.out.println("This is a " + TextUtils.green("green") + " text."); assertEquals("1b5b33326d611b5b6d", Hex.encodeHexString(TextUtils.green("a").getBytes())); } |
### Question:
TextUtils { public static String applyColorToText(String text, Color colorCode) { if (StringUtils.isBlank(text)) { return text; } return Ansi.ansi().fg(colorCode).a(text).reset().toString(); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testApplyColorToText() { System.out.println("This is a " + TextUtils.applyColorToText("magenta", Color.MAGENTA) + " text."); assertEquals("1b5b33356d611b5b6d", Hex.encodeHexString(TextUtils.applyColorToText("a", Color.MAGENTA).getBytes())); assertEquals(" ", TextUtils.applyColorToText(" ", Color.MAGENTA)); assertNull(TextUtils.applyColorToText(null, Color.MAGENTA)); } |
### Question:
TextUtils { public static String[] splitLines(String text) { Preconditions.checkNotNull(text, "The parameter 'text' cannot be null"); return text.split("\\r?\\n"); } private TextUtils(); static String applyColorToText(String text, Color colorCode); static String yellow(String message); static String green(String message); static String blue(String message); static String red(String message); static String[] splitLines(String text); }### Answer:
@Test public void testSplitLines() { final String[] lines = TextUtils.splitLines("foo \n bar \n baz"); assertEquals(3, lines.length); assertEquals("foo ", lines[0]); assertEquals(" bar ", lines[1]); assertEquals(" baz", lines[2]); }
@Test public void testSplitLinesCRLF() { final String[] lines = TextUtils.splitLines("foo \r\n bar \r\n baz"); assertEquals(3, lines.length); assertEquals("foo ", lines[0]); assertEquals(" bar ", lines[1]); assertEquals(" baz", lines[2]); }
@Test public void testSplitLinesMixtureCRLF() { final String[] lines = TextUtils.splitLines("foo \n bar \r\n baz"); assertEquals(3, lines.length); assertEquals("foo ", lines[0]); assertEquals(" bar ", lines[1]); assertEquals(" baz", lines[2]); }
@Test public void testSplitLinesNull() { try { TextUtils.splitLines(null); fail("Should throw NPE"); } catch (NullPointerException ex) { } }
@Test public void testSplitLinesEmpty() { assertEquals(1, TextUtils.splitLines("").length); assertEquals(1, TextUtils.splitLines(" ").length); } |
### Question:
JsonUtils { public static <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException { return GSON.fromJson(json, classOfT); } private JsonUtils(); static T fromJson(String json, Class<T> classOfT); static String toJson(Object src); }### Answer:
@Test public void testFromJson() { final String testFailure = "{{{{{{{{{{{"; Object obj = null; try { obj = JsonUtils.fromJson(testString, Map.class); } catch (final Exception e) { fail("Fail to parse a json to java.util.Map."); } assertTrue(((Map<String, Object>) obj).containsKey("id")); assertTrue(((Map<String, Object>) obj).get("id") instanceof Number); try { obj = JsonUtils.fromJson(testString, ObjectForJson.class); } catch (final Exception e) { fail("Fail to parse a json to java.util.Map."); } final ObjectForJson objForJson = (ObjectForJson) obj; assertEquals(1, objForJson.id); assertEquals("hello", objForJson.title); assertEquals(1, objForJson.children.length); assertEquals(2, objForJson.children[0].id); try { obj = JsonUtils.fromJson(testFailure, Map.class); fail("Should fail for invalid json."); } catch (final Exception e) { } } |
### Question:
JsonUtils { public static String toJson(Object src) { return GSON.toJson(src); } private JsonUtils(); static T fromJson(String json, Class<T> classOfT); static String toJson(Object src); }### Answer:
@Test public void testToJson() { final ObjectForJson objForJson = JsonUtils.fromJson(testString, ObjectForJson.class); final String json = JsonUtils.toJson(objForJson); assertEquals(testString, json); } |
### Question:
AnnotationHandlerImpl implements AnnotationHandler { @Override public Set<Method> findFunctions(final List<URL> urls) { return new Reflections( new ConfigurationBuilder() .addUrls(urls) .setScanners(new MethodAnnotationsScanner()) .addClassLoader(getClassLoader(urls))) .getMethodsAnnotatedWith(FunctionName.class); } @Override Set<Method> findFunctions(final List<URL> urls); @Override Map<String, FunctionConfiguration> generateConfigurations(final Set<Method> methods); @Override FunctionConfiguration generateConfiguration(final Method method); }### Answer:
@Test public void findFunctions() throws Exception { final AnnotationHandler handler = getAnnotationHandler(); final Set<Method> functions = handler.findFunctions(Arrays.asList(getClassUrl())); assertEquals(13, functions.size()); final List<String> methodNames = functions.stream().map(f -> f.getName()).collect(Collectors.toList()); assertTrue(methodNames.contains(HTTP_TRIGGER_METHOD)); assertTrue(methodNames.contains(QUEUE_TRIGGER_METHOD)); assertTrue(methodNames.contains(TIMER_TRIGGER_METHOD)); assertTrue(methodNames.contains(MULTI_OUTPUT_METHOD)); assertTrue(methodNames.contains(BLOB_TRIGGER_METHOD)); assertTrue(methodNames.contains(EVENTHUB_TRIGGER_METHOD)); assertTrue(methodNames.contains(SERVICE_BUS_QUEUE_TRIGGER_METHOD)); assertTrue(methodNames.contains(SERVICE_BUS_TOPIC_TRIGGER_METHOD)); assertTrue(methodNames.contains(COSMOSDB_TRIGGER_METHOD)); assertTrue(methodNames.contains(EVENTGRID_TRIGGER_METHOD)); assertTrue(methodNames.contains(CUSTOM_BINDING_METHOD)); assertTrue(methodNames.contains(EXTENDING_CUSTOM_BINDING_METHOD)); assertTrue(methodNames.contains(EXTENDING_CUSTOM_BINDING_WITHOUT_NAME_METHOD)); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.