src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
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 r... | @Test public void get() throws Exception { Rate r1 = Rate.of(0.0567f); assertEquals(BigDecimal.valueOf(0.0567d), r1.get()); } |
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(BigDe... | @Test public void testToString() throws Exception { Rate r1 = Rate.of(0.0567f); assertEquals("Rate[0.0567]", r1.toString()); } |
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 o... | @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)); } |
FutureValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { public static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods) { return new FutureValueOfAnnuity(rateAndPeriods); } private FutureValueOfAnnuity(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods); static ... | @Test public void getRate() throws Exception { FutureValueOfAnnuity val = FutureValueOfAnnuity.of( RateAndPeriods.of(0.03,1) ); assertEquals(val.getRate(), Rate.of(0.03)); }
@Test public void getPeriods() throws Exception { FutureValueOfAnnuity val = FutureValueOfAnnuity.of( RateAndPeriods.of(0.03,3654) ); assertEquals... |
FutureValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public MonetaryAmount apply(MonetaryAmount amount) { return calculate(amount, rateAndPeriods); } private FutureValueOfAnnuity(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount ... | @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)); } |
FutureValueOfAnnuity extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "FutureValueOfAnnuity{" + "\n " + rateAndPeriods + '}'; } private FutureValueOfAnnuity(RateAndPeriods rateAndPeriods); static FutureValueOfAnnuity of(RateAndPeriods rateAndPeriods); static MonetaryAmount calcu... | @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()); } |
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 amoun... | @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... |
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(RateAn... | @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(... |
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, RateAndP... | @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(RateAndPe... |
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()... | @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.val... |
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 getA... | @Test public void receivableTurnover() throws Exception { assertEquals(BigDecimal.valueOf(2.854812398042414), AverageCollectionPeriod.receivablesTurnover( Money.of(3.678, "CHF"), BigDecimal.valueOf(10.5))); } |
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); } | @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))); } |
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 BigDecima... | @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); assertE... |
PresentValueContinuousCompounding extends AbstractRateAndPeriodBasedOperator { public static PresentValueContinuousCompounding of(RateAndPeriods rateAndPeriods) { return new PresentValueContinuousCompounding(rateAndPeriods); } private PresentValueContinuousCompounding(RateAndPeriods rateAndPeriods); static PresentValu... | @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(95.12), "CHF"), money.with(PresentValueContinuousCompounding.of... |
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(); ... | @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(mone... |
PresentValueContinuousCompounding extends AbstractRateAndPeriodBasedOperator { @Override public String toString() { return "PresentValueContinuousCompounding{" + "\n " + rateAndPeriods + '}'; } private PresentValueContinuousCompounding(RateAndPeriods rateAndPeriods); static PresentValueContinuousCompounding of(RateAnd... | @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"... |
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<We... | @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)); } |
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();... | @Test public void getValues() throws Exception { } |
DiscountFactor { public static BigDecimal calculate(RateAndPeriods rateAndPeriods) { Objects.requireNonNull(rateAndPeriods); final BigDecimal ONE = CalculationContext.one(); BigDecimal div = ONE.min(ONE.add(rateAndPeriods.getRate().get())); BigDecimal factor = ONE.subtract(ONE.add(rateAndPeriods.getRate().get()).pow(ra... | @Test public void calculate_Negative() { assertEquals(1, DiscountFactor.calculate(RateAndPeriods.of(-0.05,0)).doubleValue(), 0.0d); assertEquals(1.0526315789473684, DiscountFactor.calculate(RateAndPeriods.of(-0.05,1)).doubleValue(), 0.0d); assertEquals(1.422382169222759, DiscountFactor.calculate(RateAndPeriods.of(-0.05... |
SimpleInterest extends AbstractRateAndPeriodBasedOperator { public static SimpleInterest of(RateAndPeriods rateAndPeriods) { return new SimpleInterest(rateAndPeriods); } private SimpleInterest(RateAndPeriods rateAndPeriods); static SimpleInterest of(RateAndPeriods rateAndPeriods); static MonetaryAmount calculate(Monet... | @Test public void of_notNull() throws Exception { SimpleInterest ci = SimpleInterest.of( RateAndPeriods.of(0.05,1) ); assertNotNull(ci); }
@Test public void of_correctRate() throws Exception { SimpleInterest ci = SimpleInterest.of( RateAndPeriods.of(0.0234,1) ); assertNotNull(ci.getRate()); assertEquals(ci.getRate(), R... |
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(Monetary... | @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")); } |
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(Monet... | @Test public void testOf() { BasisPoint perc = BasisPoint.of(BigDecimal.ONE); assertNotNull(perc); } |
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 Mo... | @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)); } |
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 app... | @Test public void testToString() { assertEquals("15\u2031", BasisPoint.of(BigDecimal.valueOf(15)) .toString()); } |
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()) ), Ca... | @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); assertEqual... |
RangeSorter { static List<Range> sort(List<Range> list) { RangeSorter sorter = new RangeSorter(list); sorter.sortRanges(); return sorter.ranges; } private RangeSorter(List<Range> ranges); } | @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 ... |
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(... | @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... |
RangeOverlapMerger { static List<Range> join(List<Range> ranges) { RangeOverlapMerger calculator = new RangeOverlapMerger(ranges); return calculator.joinOverlappingRanges(); } private RangeOverlapMerger(@NonNull List<Range> ranges); } | @Test public void should_join_overlapping_ranges() throws Exception { List<Range> ranges = asList( range(from(2017, Calendar.JANUARY, 1), from(2017, Calendar.JANUARY, 4)), range(from(2017, Calendar.JANUARY, 2), from(2017, Calendar.JANUARY, 5)) ); assertEquals(2, ranges.size()); List<Range> result = RangeOverlapMerger.j... |
WakelockMonitor extends Monitor { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) boolean released() { long endTime = clock.currentTimeMillis(); if (endTime < startTime) { logger.e(TAG, label + " Likely error in timer schedule to mark end of a wakelock session"); endTime = startTime; } logger.d(Logger.TAG, la... | @Test public void sessionTestErrorCase() throws Exception { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); WakelockMonitor monitor = new WakelockMonitor(testUtilComponent, stateObservable(), EVENT_WAK... |
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(... | @Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<RealtimeMessagingActivity> rtMessagingPublishSubject = Publ... |
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... | @Test public void testObservable() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .testLoggerModule(new TestLoggerModule()) .build(); PublishSubject<NetworkActivity> networkActivityPublishSubject = PublishSub... |
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 + "... | @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, M... |
FalxApi { public void enableLogging(boolean enable) { logger.setEnabled(enable); if (falxInterceptor != null) { falxInterceptor.enableLogging(enable); } } private FalxApi(@NonNull Context context); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) FalxApi(@NonNull Context context, @NonNull UtilComponent utilC... | @Test public void testEnableLogging() { TestUtilComponent testUtilComponent = DaggerTestUtilComponent.builder() .appModule(new AppModule(mockContext)) .fakeDateTimeModule(new FakeDateTimeModule()) .build(); FalxApi api = new FalxApi(mockContext, testUtilComponent); Assert.assertNotNull(api); api.enableLogging(true); Fa... |
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.getTit... | @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=ma... |
ArticlesPresenter implements ArticlesContract.Presenter,
IArticlesConfig.Callback { @Override public void start() { fetchData(); } @Inject ArticlesPresenter(@NonNull IRepository<Article> repository,
@NonNull BaseSchedulerProvider schedulerProvider,
@Non... | @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... |
ArticleRepository implements IRepository<Article> { @Override public Observable<Article> get(int id) { if(!cacheStore.isInCache(id)) { if (isNetworkConnection()) { return remoteSource.get(id) .doOnNext(this::saveToLocal) .map(mapper::map) .doOnNext(this::saveInCache); } return localSource.get(id) .map(mapper::map) .doO... | @Test public void getsAllArticlesIfThereIsNetwork(){ setNetworkAvailable(); setDataSourceResult(remote); repository.get() .observeOn(SCHEDULER.io()) .subscribeOn(SCHEDULER.ui()) .subscribe(this::resultShouldNotBeNull); verify(remote).get(); verify(mapper).map(anyList()); verify(manager).getActiveNetworkInfo(); verify(c... |
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); } | @Test public void returnsNullIfThereIsNoValueInCache(){ assertThat(cacheStore.get(FakeProvider.FAKE_ID),nullValue()); } |
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); } | @Test public void checksIfItemIsInCache(){ putIn(); assertTrue(cacheStore.isInCache(FakeProvider.FAKE_ID)); } |
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,
... | @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)); p... |
WikidataHyponyms extends JCasAnnotator_ImplBase { public String getWikidataId(String language, String title) throws JSONException, IOException { if(title.contains("#")) return null; String url = "https: language+ ".wikipedia.org/w/api.php?action=query&titles="+title+"&ppprop=wikibase_item&prop=pageprops&format=json&red... | @Test public void getWikipediaLink() throws UIMAException, IOException{ WikidataHyponyms WikidataHyponyms = new WikidataHyponyms(); assertEquals("Q4692", WikidataHyponyms.getWikidataId("de", "Renaissance")); assertEquals("Q169243", WikidataHyponyms.getWikidataId("en","Protagoras")); } |
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); } | @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("Forma... |
MavenUtils { public static Xpp3Dom getPluginConfiguration(MavenProject mavenProject, String pluginKey) { final Plugin plugin = getPluginFromMavenModel(mavenProject.getModel(), pluginKey); return plugin == null ? null : (Xpp3Dom) plugin.getConfiguration(); } private MavenUtils(); static Xpp3Dom getPluginConfiguration(M... | @Test public void testPluginConfigurationFromBuild() throws Exception { final File pom = new File(this.getClass().getClassLoader().getResource("pom-1.xml").getFile()); final Model model = TestHelper.readMavenModel(pom); final MavenProject project = Mockito.mock(MavenProject.class); Mockito.when(project.getModel()).then... |
PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", v... | @Test public void testHandleSelectOnePromoteYesNo() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("i... |
PromptWrapper { public <T> List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc) throws IOException, NoResourcesAvailableException { final Map<String, Object> variables = createVariableTables(templateId); final boolean allowEmpty = TemplateUtils.evalBoolean("allow_empty", varia... | @Test public void testHandleSelectMany() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId... |
PromptWrapper { public void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction) throws IOException { final Map<String, Object> variables = createVariableTables("confirm"); System.out.println(TemplateUtils.evalText("promote.header", variables)); for (final Map.Entry<String, String> en... | @Test public void testConfirmChanges() throws Exception { final Map<String, String> changesToConfirm = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("foo", "bar"), new DefaultMapEntry<>("count", "1"), new DefaultMapEntry<>("blank", ""), new DefaultMapEntry<>("update", "true"), }); final... |
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); Lis... | @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); ... |
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 ... | @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... |
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 n... | @Test public void testGetChildValue() { assertEquals("1.8\n", XmlUtils.getChildValue(propertiesNode, "maven.compiler.target")); } |
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 pre... | @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]); } |
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.setTex... | @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 xmlBefo... |
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> variab... | @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 voi... |
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 + getDepl... | @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(); }
@... |
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+... | @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 publi... |
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(... | @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)); } |
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 voi... | @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.getFilterin... |
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", res... | @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(roo... |
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 MojoExecutionExc... | @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(m... |
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 getL... | @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()... |
SpringServiceClient { public ServiceResourceInner getClusterByName(String cluster) { final List<ServiceResourceInner> clusterList = getAvailableClusters(); return clusterList.stream().filter(appClusterResourceInner -> appClusterResourceInner.name().equals(cluster)) .findFirst() .orElseThrow(() -> new InvalidParameterEx... | @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).getAvaila... |
SpringServiceClient { public String getResourceGroupByCluster(String clusterName) { final ServiceResourceInner cluster = getClusterByName(clusterName); return this.getResourceGroupByCluster(cluster); } SpringServiceClient(AzureTokenCredentials azureTokenCredentials, String subscriptionId, String userAgent); SpringServ... | @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")); } |
PomXmlUpdater { public void updateSettings(AppSettings app, DeploymentSettings deploy) throws DocumentException, IOException { final File pom = this.project.getFile(); final SAXReader reader = new CustomSAXReader(); reader.setDocumentFactory(new LocatorAwareDocumentFactory()); final Document doc = reader.read(new Input... | @Test public void testSaveXml() throws Exception { final File pomFile = new File(this.getClass().getClassLoader().getResource("pom-4.xml").getFile()); final File tempFile = Files.createTempFile("azure-spring-cloud-plugin-test", ".xml").toFile(); FileUtils.copyFile(pomFile, tempFile); final Model model = TestHelper.read... |
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), "Param... | @Test public void testDuplicateAdd() throws IOException { try { this.validator.collectSingleProperty("Deployment", "cpu", Mockito.mock(JsonNode.class)); fail("should throw IAE"); } catch (IllegalArgumentException ex) { } } |
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... | @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 = v... |
ZIPArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(DeployTarget target) throws AzureExecutionException { assureStagingDirectoryNotEmpty(); final File zipFile = getZipFile(); Log.prompt(String.format(DEPLOY_START, target.getName())); int retryCount = 0; while (retryCount < DEFAULT_MAX_RET... | @Test public void publish() throws AzureExecutionException, IOException { final WebApp app = mock(WebApp.class); final DeployTarget target = new DeployTarget(app, DeployTargetType.WEBAPP); final File file = mock(File.class); buildHandler(); doReturn(file).when(handlerSpy).getZipFile(); doNothing().when(app).zipDeploy(f... |
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; } pro... | @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.s... |
RunMojo extends AbstractFunctionMojo { protected void runFunctions(final CommandHandler handler) throws AzureExecutionException { handler.runCommandWithReturnCodeCheck( getStartFunctionHostCommand(), true, getDeploymentStagingDirectoryPath(), CommandUtils.getValidReturnCodes(), RUN_FUNCTIONS_FAILURE ); } String getLoc... | @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(), ArgumentMatch... |
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 ==... | @Test(expected = AzureExecutionException.class) public void assureStagingDirectoryNotEmptyThrowException() throws AzureExecutionException { handler = builder.project(mock(IProject.class)) .stagingDirectoryPath("") .build(); handler.assureStagingDirectoryNotEmpty(); }
@Test public void assureStagingDirectoryNotEmpty() t... |
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... | @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 FTPUploa... |
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); } | @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()); } |
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... | @Test public void testError() { final InputValidateResult<Object> wrapper = InputValidateResult.error("message"); assertNotNull(wrapper); assertEquals("message", wrapper.getErrorMessage()); assertNull(wrapper.getObj()); } |
DefaultPrompter implements IPrompter { public String promoteString(String message, String defaultValue, Function<String, InputValidateResult<String>> verify, boolean isRequired) throws IOException { final boolean hasDefaultValue = StringUtils.isNotBlank(defaultValue); System.out.print(message); System.out.flush(); retu... | @Test public void testPromoteStringRequired() throws Exception { when(reader.readLine()).thenReturn("bar"); String result = prompter.promoteString("Please input a string", "foo", input -> { if (StringUtils.equals("bar", input)) { try { when(reader.readLine()).thenReturn(" 10 "); } catch (IOException e) { SneakyThrowUti... |
DefaultPrompter implements IPrompter { public Boolean promoteYesNo(String message, Boolean defaultValue, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultValue != null; System.out.print(message); System.out.flush(); return loopInput(defaultValue, hasDefaultValue, isRequired, "", message, ... | @Test public void testPromoteYesNo() throws Exception { when(reader.readLine()).thenReturn("Y").thenReturn("y").thenReturn("n"); Boolean result = prompter.promoteYesNo("Do you want to continue(y/n)", null, true); assertNotNull(result); assertTrue(result); result = prompter.promoteYesNo("Do you want to continue(y/n)", n... |
RunMojo extends AbstractFunctionMojo { protected String getCheckRuntimeCommand() { return FUNC_CMD; } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | @Test public void getCheckRuntimeCommand() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); assertEquals(FUNC_CMD, mojoSpy.getCheckRuntimeCommand()); } |
DefaultPrompter implements IPrompter { public <T> List<T> promoteMultipleEntities(String header, String promotePrefix, String selectNoneMessage, List<T> entities, Function<T, String> getNameFunc, boolean allowEmpty, String enterPromote, List<T> defaultValue) throws IOException { final boolean hasDefaultValue = defaultV... | @Test public void testPromoteMultipleEntities() throws Exception { when(reader.readLine()).thenReturn("1").thenReturn("1-2").thenReturn("1-2,3-5").thenReturn("3-1000000,1-2,3-5"); final List<Integer> integers = new ArrayList<>(); for (int i = 0; i < 10; i++) { integers.add(i); } List<Integer> selected = prompter.promot... |
DefaultPrompter implements IPrompter { public <T> T promoteSingleEntity(String header, String message, List<T> entities, T defaultEntity, Function<T, String> getNameFunc, boolean isRequired) throws IOException { final boolean hasDefaultValue = defaultEntity != null; printOptionList(header, entities, defaultEntity, getN... | @Test public void testPromoteSingle() throws Exception { when(reader.readLine()).thenReturn("1").thenReturn("10001111111111111111111111111").thenReturn("1000").thenReturn("2").thenReturn(""); final List<Integer> integers = new ArrayList<>(); for (int i = 1; i <= 3; i++) { integers.add(i); } Integer value = prompter.pro... |
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 isRequ... | @Test public void testClose() throws Exception { PowerMockito.doNothing().when(reader).close(); this.prompter.close(); } |
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(Str... | @Test public void testBlue() { System.out.println("This is a " + TextUtils.blue("blue") + " text."); assertEquals("1b5b33346d611b5b6d", Hex.encodeHexString(TextUtils.blue("a").getBytes())); } |
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(Strin... | @Test public void testRed() { System.out.println("This is a " + TextUtils.red("red") + " text."); assertEquals("1b5b33316d611b5b6d", Hex.encodeHexString(TextUtils.red("a").getBytes())); } |
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; } }... | @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("-ag... |
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... | @Test public void testYellow() { System.out.println("This is a " + TextUtils.yellow("yellow") + " text."); assertEquals("1b5b33336d611b5b6d", Hex.encodeHexString(TextUtils.yellow("a").getBytes())); } |
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(S... | @Test public void testGreen() { System.out.println("This is a " + TextUtils.green("green") + " text."); assertEquals("1b5b33326d611b5b6d", Hex.encodeHexString(TextUtils.green("a").getBytes())); } |
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); stati... | @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.MAGEN... |
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 messa... | @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("f... |
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); } | @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, Objec... |
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); } | @Test public void testToJson() { final ObjectForJson objForJson = JsonUtils.fromJson(testString, ObjectForJson.class); final String json = JsonUtils.toJson(objForJson); assertEquals(testString, json); } |
DeployMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { try { parseConfiguration(); checkArtifactCompileVersion(); final WebAppBase target = createOrUpdateResource(); if (target == null) { throw new AzureExecutionException( String.format("Failed to get the deploy ... | @Test public void doExecute() throws Exception { final ArtifactHandler handler = mock(ArtifactHandler.class); final FunctionRuntimeHandler runtimeHandler = mock(FunctionRuntimeHandler.class); final FunctionApp app = mock(FunctionApp.class); doReturn(app).when(mojoSpy).getFunctionApp(); doReturn(app).when(mojoSpy).updat... |
IndentUtil { public static String calcXmlIndent(String[] lines, int row, int column) { Preconditions.checkNotNull(lines, "The parameter 'lines' cannot be null"); Preconditions.checkArgument(lines.length > row && row >= 0, "The parameter 'row' overflows."); final String line = lines[row]; Preconditions.checkArgument(lin... | @Test public void testXmlIndent() { final String[] lines = TextUtils.splitLines("<foo> \n <bar> \n \t<test></test></bar> \r\n </foo>"); assertEquals(" ", IndentUtil.calcXmlIndent(lines, 1, 2)); assertEquals(" \t", IndentUtil.calcXmlIndent(lines, 2, 12)); }
@Test public void testXmlIndentBadArgument() { final String[] l... |
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); } @... | @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(Collecto... |
AnnotationHandlerImpl implements AnnotationHandler { @Override public Map<String, FunctionConfiguration> generateConfigurations(final Set<Method> methods) throws AzureExecutionException { final Map<String, FunctionConfiguration> configMap = new HashMap<>(); for (final Method method : methods) { final FunctionName funct... | @Test public void generateConfigurations() throws Exception { final AnnotationHandler handler = getAnnotationHandler(); final Set<Method> functions = handler.findFunctions(Arrays.asList(getClassUrl())); final Map<String, FunctionConfiguration> configMap = handler.generateConfigurations(functions); configMap.values().fo... |
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(final DeployTarget target) throws AzureExecutionException { final File zipPackage = createZipPackage(); final CloudStorageAccount storageAccount = FunctionArtifactHelper.getCloudStorageAccount(target); final String blobName = getBlo... | @Test public void publish() throws Exception { final DeployTarget deployTarget = mock(DeployTarget.class); final Map mapSettings = mock(Map.class); final File file = mock(File.class); final AppSetting storageSetting = mock(AppSetting.class); mapSettings.put(INTERNAL_STORAGE_KEY, storageSetting); doReturn(mapSettings).w... |
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected File createZipPackage() throws AzureExecutionException { Log.prompt(""); Log.prompt(CREATE_ZIP_START); final File zipPackage = FunctionArtifactHelper.createFunctionArtifact(stagingDirectoryPath); Log.prompt(CREATE_ZIP_DONE + stagingDirectoryPath.concat... | @Test public void createZipPackage() throws Exception { buildHandler(); final File zipPackage = handlerSpy.createZipPackage(); assertTrue(zipPackage.exists()); } |
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected String uploadPackageToAzureStorage(final File zipPackage, final CloudStorageAccount storageAccount, final String blobName) throws AzureExecutionException { Log.prompt(UPLOAD_PACKAGE_START); final CloudBlockBlob blob = AzureStorageHelper.uploadFileAsBlo... | @Test public void uploadPackageToAzureStorage() throws Exception { final CloudStorageAccount storageAccount = mock(CloudStorageAccount.class); final CloudBlobClient blobClient = mock(CloudBlobClient.class); doReturn(blobClient).when(storageAccount).createCloudBlobClient(); final CloudBlobContainer blobContainer = mock(... |
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected void deployWithPackageUri(final DeployTarget target, final String packageUri, Runnable onDeployFinish) { try { Log.prompt(DEPLOY_PACKAGE_START); target.msDeploy(packageUri, false); Log.prompt(DEPLOY_PACKAGE_DONE); } finally { onDeployFinish.run(); } } ... | @Test public void deployWithPackageUri() throws Exception { final FunctionApp app = mock(FunctionApp.class); final DeployTarget deployTarget = mock(DeployTarget.class); final WithPackageUri withPackageUri = mock(WithPackageUri.class); doReturn(withPackageUri).when(app).deploy(); final WithExecute withExecute = mock(Wit... |
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected void deletePackageFromAzureStorage(final CloudStorageAccount storageAccount, final String blobName) { try { Log.prompt(DELETE_PACKAGE_START); AzureStorageHelper.deleteBlob(storageAccount, DEPLOYMENT_PACKAGE_CONTAINER, blobName); Log.prompt(DELETE_PACKA... | @Test public void deletePackageFromAzureStorage() throws Exception { final CloudStorageAccount storageAccount = mock(CloudStorageAccount.class); final CloudBlobClient blobClient = mock(CloudBlobClient.class); doReturn(blobClient).when(storageAccount).createCloudBlobClient(); final CloudBlobContainer blobContainer = moc... |
FunctionArtifactHelper { public static CloudStorageAccount getCloudStorageAccount(final DeployTarget target) throws AzureExecutionException { final Map<String, AppSetting> settingsMap = target.getAppSettings(); if (settingsMap != null) { final AppSetting setting = settingsMap.get(INTERNAL_STORAGE_KEY); if (setting != n... | @Test public void testGetCloudStorageAccount() throws Exception { final String storageConnection = "DefaultEndpointsProtocol=https;AccountName=123456;AccountKey=12345678;EndpointSuffix=core.windows.net"; final Map mapSettings = mock(Map.class); final DeployTarget deployTarget = mock(DeployTarget.class); final AppSettin... |
DeployMojo extends AbstractFunctionMojo { protected FunctionApp updateFunctionApp(final FunctionApp app, final FunctionRuntimeHandler runtimeHandler) throws AzureAuthFailureException, AzureExecutionException { Log.info(FUNCTION_APP_UPDATE); runtimeHandler.updateAppServicePlan(app); final Update update = runtimeHandler.... | @Test public void updateFunctionApp() throws Exception { final FunctionApp app = mock(FunctionApp.class); final Update update = mock(Update.class); doNothing().when(mojoSpy).configureAppSettings(any(Consumer.class), anyMap()); final FunctionRuntimeHandler functionRuntimeHandler = mock(WindowsFunctionRuntimeHandler.clas... |
FunctionArtifactHelper { public static void updateAppSetting(final DeployTarget deployTarget, final String key, final String value) throws AzureExecutionException { final WebAppBase targetApp = deployTarget.getApp(); if (targetApp instanceof FunctionApp) { ((FunctionApp) targetApp).update().withAppSetting(key, value).a... | @Test public void testUpdateAppSetting() throws Exception { final DeployTarget deployTarget = mock(DeployTarget.class); final FunctionApp functionApp = mock(FunctionApp.class); doReturn(functionApp).when(deployTarget).getApp(); final FunctionApp.Update update = mock(FunctionApp.Update.class); doReturn(update).when(func... |
FunctionArtifactHelper { public static File createFunctionArtifact(final String stagingDirectoryPath) throws AzureExecutionException { final File stageDirectory = new File(stagingDirectoryPath); final File zipPackage = new File(stagingDirectoryPath.concat(Constants.ZIP_EXT)); if (!stageDirectory.exists() || !stageDirec... | @Test public void testCreateFunctionArtifactWithException() { String exceptionMessage = null; try { FunctionArtifactHelper.createFunctionArtifact(""); } catch (Exception e) { exceptionMessage = e.getMessage(); } finally { assertEquals("Azure Functions stage directory not found. Please run 'mvn clean" + " azure-function... |
FunctionCoreToolsHandlerImpl implements FunctionCoreToolsHandler { @Override public void installExtension(File stagingDirectory, File basedir) throws AzureExecutionException { assureRequirementAddressed(); installFunctionExtension(stagingDirectory, basedir); } FunctionCoreToolsHandlerImpl(final CommandHandler commandHa... | @Test public void installExtension() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(functionCoreTools... |
FunctionCoreToolsHandlerImpl implements FunctionCoreToolsHandler { protected String getLocalFunctionCoreToolsVersion() { try { final String localVersion = commandHandler.runCommandAndGetOutput( GET_LOCAL_VERSION_CMD, false, null ); Version.valueOf(localVersion); return localVersion; } catch (Exception e) { Log.warn(GET... | @Test public void getLocalFunctionCoreToolsVersion() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.