method2testcases
stringlengths
118
6.63k
### Question: AttractionRepository { @VisibleForTesting static AttractionCollection buildNightLifeCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.social, R.string.social_title, R.string.creative_cocktails, R.string.social_detailed_desc, R.string.mq_social ) ); attractions.add(new Attraction( R.drawable.mayor_old_town, R.string.mayor_old_town_title, R.string.mayor_great_selction, R.string.mayor_of_old_town_detailed_desc, R.string.mq_mayor_old_town ) ); attractions.add(new Attraction( R.drawable.colorado_room, R.string.colorado_room_title, R.string.colorado_beers_and_spirits, R.string.the_colorado_room_detailed_desc, R.string.mq_the_colorado_room ) ); attractions.add(new Attraction( R.drawable.ace_gilletts, R.string.ace_gilletts_title, R.string.gilletts_crafted_beers, R.string.ace_gilletts_detailed_desc, R.string.mq_ace_gilletts ) ); attractions.add(new Attraction( R.drawable.elliot_martini_bar, R.string.elliots_martini_title, R.string.elliot_martini_variety, R.string.elliot_martini_bar_detailed_desc, R.string.mq_elliot_martini_bar ) ); return new AttractionCollection(R.string.top_bars_nightlife, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }### Answer: @Test public void saveAsAttractionCollection_buildNightLifeCollection() { assertThat(AttractionRepository.buildNightLifeCollection(), instanceOf(AttractionCollection.class)); }
### Question: AttractionCollection { public List<Attraction> getAttractions() { return listOfAttractions; } AttractionCollection(int headerTextResId, List<Attraction> listOfAttractions); int getHeaderTitle(); List<Attraction> getAttractions(); }### Answer: @Test public void savesAttractionType_getAttractions() { assertThat(subject.getAttractions().get(0), isA(Attraction.class)); } @Test public void returnsAList_getAttractions() { assertThat(subject.getAttractions(), instanceOf(List.class)); }
### Question: Attraction implements Parcelable { public int getImageResourceId() { return imageResourceId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }### Answer: @Test public void storesResIdForImage() { assertThat(subject.getImageResourceId(), is(TEST_IMAGE)); }
### Question: Attraction implements Parcelable { public int getTitle() { return titleTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }### Answer: @Test public void storesResIdAsTitle() { assertThat(subject.getTitle(), is(TEST_TITLE)); }
### Question: Attraction implements Parcelable { public int getShortDesc() { return shortDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }### Answer: @Test public void storesResIdAsShortDesc() { assertThat(subject.getShortDesc(), is(TEST_SHORT_DESC)); }
### Question: Attraction implements Parcelable { public int getLongDesc() { return longDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }### Answer: @Test public void storesResIdAsLongDesc() { assertThat(subject.getLongDesc(), is(TEST_LONG_DESC)); }
### Question: AttractionRepository { @VisibleForTesting static AttractionCollection buildActivityCollection() { List<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.horsetooth_mountain_park, R.string.horsetooth_mountain_title, R.string.scenic_open_space, R.string.horsetooth_mountain_park_detailed_desc, R.string.mq_horestooth_mountain_park ) ); attractions.add(new Attraction( R.drawable.whitewater_rafting, R.string.mountain_whitewater_title, R.string.white_water_rafting, R.string.mountain_whitewater_descents_detailed_desc, R.string.mq_mountain_whitewater ) ); attractions.add(new Attraction( R.drawable.flower_trail_garden, R.string.flower_trial_garden_title, R.string.horticulture_display, R.string.flower_trail_garden_detailed_desc, R.string.mq_annual_flower_trial_garden ) ); attractions.add(new Attraction( R.drawable.horsetooth_reservoir, R.string.horsetooth_reservoir_title, R.string.best_outdoors, R.string.horsetooth_reservoir_detailed_desc, R.string.mq_horestooth_reservoir ) ); attractions.add(new Attraction( R.drawable.city_park, R.string.city_park_title, R.string.ideal_relaxing_spot, R.string.city_park_detailed_desc, R.string.mq_city_park ) ); return new AttractionCollection(R.string.top_activities, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }### Answer: @Test public void saveAsAttractionCollection_buildActivityCollection() { assertThat(AttractionRepository.buildActivityCollection(), instanceOf(AttractionCollection.class)); }
### Question: AttractionRepository { @VisibleForTesting static AttractionCollection buildRestaurantsCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.the_melting_pot, R.string.melting_pot_title, R.string.amazing_fondue, R.string.the_melting_pot_detailed_desc, R.string.mq_the_melting_pot ) ); attractions.add(new Attraction( R.drawable.maza_kabob, R.string.maza_kabob_title, R.string.afghan_specialty, R.string.maza_kabob_detailed_desc, R.string.mq_maza_kabob ) ); attractions.add(new Attraction( R.drawable.rio_grande, R.string.rio_grande_title, R.string.amazing_margarita, R.string.rio_grande_detailed_desc, R.string.mq_rio_grande ) ); attractions.add(new Attraction( R.drawable.star_of_india, R.string.star_of_india_title, R.string.indian_buffet, R.string.star_of_india_detailed_desc, R.string.mq_star_of_india ) ); attractions.add(new Attraction( R.drawable.lucile_creole, R.string.lucile_title, R.string.breakfast_place, R.string.lucile_creole_detailed_desc, R.string.mq_lucile ) ); attractions.add(new Attraction( R.drawable.cafe_athens, R.string.cafe_athens_title, R.string.greek_mediterranean, R.string.cafe_athens_detailed_desc, R.string.mq_cafe_athens ) ); attractions.add(new Attraction( R.drawable.cafe_de_bangkok, R.string.cafe_de_bangkok_title, R.string.traditional_thai, R.string.cafe_de_bangkok_detailed_desc, R.string.mq_cafe_de_bangkok ) ); return new AttractionCollection(R.string.top_restaurants, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }### Answer: @Test public void saveAsAttractionCollection_buildRestaurantsCollection() { assertThat(AttractionRepository.buildRestaurantsCollection(), instanceOf(AttractionCollection.class)); }
### Question: AttractionRepository { @VisibleForTesting static AttractionCollection buildBreweriesCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.new_belgium, R.string.new_belgium_title, R.string.new_belgium_free_tours, R.string.new_belgium_detailed_desc, R.string.mq_new_belgium ) ); attractions.add(new Attraction( R.drawable.odell_brewing, R.string.odell_brewing_title, R.string.odell_microbrew, R.string.odell_brewing_detailed_desc, R.string.mq_odell_brewing ) ); attractions.add(new Attraction( R.drawable.anheuser_busch, R.string.anheuser_busch_title, R.string.grand_tour, R.string.anheuser_busch_detailed_desc, R.string.mq_anheuser_busch ) ); attractions.add(new Attraction( R.drawable.coopersmith_brewing, R.string.coopersmith_title, R.string.coopersmith_mixed_desc, R.string.coopersmith_detailed_desc, R.string.mq_coopersmith ) ); return new AttractionCollection(R.string.top_breweries, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }### Answer: @Test public void saveAsAttractionCollection_buildBreweriesCollection() { assertThat(AttractionRepository.buildBreweriesCollection(), instanceOf(AttractionCollection.class)); }
### Question: CompositeValidator extends Validator<T> { @Override public void validate(T t) throws CompositeValidationException { List<ValidationException> exceptions = new ArrayList<>(); for (Validator<? super T> validator : validators) { try { validator.validate(t); } catch (ValidationException e) { exceptions.add(e); } } if (!exceptions.isEmpty()) { if (exceptions.size() == 1) { throw exceptions.get(0); } else { throw new CompositeValidationException(exceptions); } } } private CompositeValidator(List<Validator<? super T>> validators); @SafeVarargs static CompositeValidator<T> of(Validator<? super T>... validators); static CompositeValidator<T> of(Iterable<Validator<? super T>> validators); static CompositeValidator<T> of(List<Validator<? super T>> validators); @Override void validate(T t); }### Answer: @Test public void concrete_valid() { try { concreteValidator.validate(5); concreteValidator.validate(6); concreteValidator.validate(7); concreteValidator.validate(8); concreteValidator.validate(9); concreteValidator.validate(10); } catch (ValidationException e) { throw new AssertionError("This should be valid!"); } } @Test public void concrete_invalid() { try { concreteValidator.validate(4); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was less than 5"); } try { concreteValidator.validate(11); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was greater than 10"); } } @Test public void concrete_compositeValidation() { try { concreteValidator.validate(-1); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).isInstanceOf(CompositeValidationException.class); CompositeValidationException ce = (CompositeValidationException) e; assertThat(ce.getExceptions()).hasSize(2); assertThat(e).hasMessageThat() .contains("Was less than 5"); assertThat(e).hasMessageThat() .contains("Was negative"); } } @Test public void reflective_valid() { try { reflectiveValidator.validate(new Foo(5)); reflectiveValidator.validate(new Foo(6)); reflectiveValidator.validate(new Foo(7)); reflectiveValidator.validate(new Foo(8)); reflectiveValidator.validate(new Foo(9)); reflectiveValidator.validate(new Foo(10)); } catch (ValidationException e) { throw new AssertionError("This should be valid!"); } } @Test public void reflective_invalid() { try { reflectiveValidator.validate(new Foo(4)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was less than 5"); } try { reflectiveValidator.validate(new Foo(11)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was greater than 10"); } } @Test public void reflective_compositeValidation() { try { reflectiveValidator.validate(new Foo(-1)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).isInstanceOf(CompositeValidationException.class); CompositeValidationException ce = (CompositeValidationException) e; assertThat(ce.getExceptions()).hasSize(2); assertThat(e).hasMessageThat() .contains("Was less than 5"); assertThat(e).hasMessageThat() .contains("Was negative"); } }
### Question: Inspector { public <T> Validator<T> validator(Type type) { return validator(type, Util.NO_ANNOTATIONS); } Inspector(Builder builder); Validator<T> validator(Type type); Validator<T> validator(Class<T> type); Validator<T> validator(Type type, Class<? extends Annotation> annotationType); @SuppressWarnings("unchecked") // Factories are required to return only matching Validators. Validator<T> validator(Type type, Set<? extends Annotation> annotations); @SuppressWarnings("unchecked") // Factories are required to return only matching Validators. Validator<T> nextValidator(Validator.Factory skipPast, Type type, Set<? extends Annotation> annotations); Inspector.Builder newBuilder(); }### Answer: @Test public void test() { Inspector inspector = new Inspector.Builder() .build(); Data data = new Data(); try { inspector.validator(Data.class).validate(data); fail("No validation was run"); } catch (ValidationException e) { assertThat(e).hasMessageThat().contains("thing() was null"); } List<Data> dataList = Arrays.asList(new Data()); try { inspector.validator(Types.newParameterizedType(List.class, Data.class)).validate(dataList); fail("No validation was run"); } catch (ValidationException e) { assertThat(e).hasMessageThat().contains("thing() was null"); } } @Test public void testSelfValidating() { Inspector inspector = new Inspector.Builder() .build(); SelfValidatingType selfValidatingType = new SelfValidatingType(); try { inspector.validator(SelfValidatingType.class).validate(selfValidatingType); fail("This should throw a validation exception!"); } catch (ValidationException e) { assertThat(e).hasMessageThat().isEqualTo(VALIDATION_MESSAGE); } NestedInheritedSelfValidating nested = new NestedInheritedSelfValidating(); try { inspector.validator(NestedInheritedSelfValidating.class).validate(nested); fail("This should throw a validation exception!"); } catch (ValidationException e) { assertThat(e).hasMessageThat().isEqualTo(VALIDATION_MESSAGE); } }
### Question: SPARQLValidator { public Model validate(OntModel toBeValidated, String query) { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); NIFNamespaces.addRLOGPrefix(model); model.setNsPrefix("mylog", logPrefix); QueryExecution qe = QueryExecutionFactory.create(query, toBeValidated); ResultSet rs = qe.execSelect(); for (; rs.hasNext(); ) { QuerySolution qs = rs.next(); Resource relatedResource = qs.getResource("resource"); Resource logLevel = qs.getResource("logLevel"); Literal message = qs.getLiteral("message"); RLOGIndividuals rli; String uri = logLevel.getURI(); if (RLOGIndividuals.FATAL.getUri().equals(uri)) { rli = RLOGIndividuals.FATAL; } else if (RLOGIndividuals.ERROR.getUri().equals(uri)) { rli = RLOGIndividuals.ERROR; } else if (RLOGIndividuals.WARN.getUri().equals(uri)) { rli = RLOGIndividuals.WARN; } else if (RLOGIndividuals.INFO.getUri().equals(uri)) { rli = RLOGIndividuals.INFO; } else if (RLOGIndividuals.DEBUG.getUri().equals(uri)) { rli = RLOGIndividuals.DEBUG; } else if (RLOGIndividuals.TRACE.getUri().equals(uri)) { rli = RLOGIndividuals.TRACE; } else { rli = RLOGIndividuals.ALL; } String m = (message == null) ? "null at " + relatedResource : message.getString(); model.add(RLOGSLF4JBinding.log(logPrefix, m, rli, this.getClass().getCanonicalName(), relatedResource.getURI(), (quiet) ? null : log)); } return model; } SPARQLValidator(OntModel testsuite, String logPrefix); static SPARQLValidator getInstance(); static SPARQLValidator getInstance(String suiteresource); static SPARQLValidator getInstance(File suiteresource); Model validate(OntModel toBeValidated, String query); OntModel validate(OntModel toBeValidated); static String getQuery(String file); static String convertStreamToString(InputStream is); String getLogPrefix(); boolean isQuiet(); void setQuiet(boolean quiet); OntModel getTestsuite(); String getVersion(); List<String> getTests(); String getSparqlPrefix(); }### Answer: @Test public void testValidate() { OntModel output = null; OntModel correct = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); correct.read(SPARQLValidator.class.getClassLoader().getResourceAsStream("nif-correct-model.ttl"), "", "Turtle"); output = SPARQLValidator.getInstance().validate(correct); assertTrue(output.isEmpty()); OntModel erroneous = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); erroneous.read(SPARQLValidator.class.getClassLoader().getResourceAsStream("nif-erroneous-model.ttl"), "", "Turtle"); output = SPARQLValidator.getInstance().validate(erroneous); assertFalse(output.isEmpty()); }
### Question: ToDoController { @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") public String dashboard() { return "dashboard"; } @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") String dashboard(); @RequestMapping(value = "/todo/listdata", method = RequestMethod.GET, produces = "application/json") @ResponseBody Page<ToDo> listData(Pageable pageable, Authentication authentication); static Predicate constructPredicate(ToDoShareAccount toDoShareAccount); @RequestMapping(value = "/todo/list", method = RequestMethod.GET, produces = "text/html") String list(Model model, Authentication authentication); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.GET, produces = "text/html") String edit(@PathVariable("toDoId") @ModelAttribute("toDoForm") ToDoForm toDoForm, Model model); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.PUT, produces = "text/html") String update(@Valid ToDoForm toDoForm, BindingResult bindingResult, Authentication authentication, ModelMap model, RedirectAttributes redirectAttributes); @RequestMapping(value = "/todo/", method = RequestMethod.POST, produces = "text/html") String save(@Valid ToDoForm toDoForm, BindingResult bindingResult, Authentication authentication, ModelMap model, RedirectAttributes redirectAttributes); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.DELETE, produces = "text/html") String delete(@PathVariable("toDoId") @ModelAttribute("toDoForm") ToDoForm toDoForm, RedirectAttributes redirectAttributes); }### Answer: @Test public void testDashboard() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("dashboard")); }
### Question: ProfileController { @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") public String showProfile() { return "profile"; } @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") String showProfile(); }### Answer: @Test public void testShowProfile() throws Exception { mockMvc.perform(get("/profile")) .andExpect(status().isOk()); }
### Question: TracingKafkaUtils { public static void inject(SpanContext spanContext, Headers headers, Tracer tracer) { tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new HeadersMapInjectAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanContext, Headers headers, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent, Collection<SpanDecorator> spanDecorators); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider, Collection<SpanDecorator> spanDecorators); static final String TO_PREFIX; static final String FROM_PREFIX; }### Answer: @Test public void inject() { MockSpan span = mockTracer.buildSpan("test").start(); Headers headers = new RecordHeaders(); assertEquals(0, headers.toArray().length); TracingKafkaUtils.inject(span.context(), headers, mockTracer); assertTrue(headers.toArray().length > 0); }
### Question: TracingKafkaUtils { public static SpanContext extractSpanContext(Headers headers, Tracer tracer) { return tracer .extract(Format.Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanContext, Headers headers, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent, Collection<SpanDecorator> spanDecorators); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider, Collection<SpanDecorator> spanDecorators); static final String TO_PREFIX; static final String FROM_PREFIX; }### Answer: @Test public void extract_no_context() { Headers headers = new RecordHeaders(); MockSpan.MockContext spanContext = (MockSpan.MockContext) TracingKafkaUtils .extractSpanContext(headers, mockTracer); assertNull(spanContext); }
### Question: HeadersMapExtractAdapter implements TextMap { @Override public Iterator<Entry<String, String>> iterator() { return map.entrySet().iterator(); } HeadersMapExtractAdapter(Headers headers); @Override Iterator<Entry<String, String>> iterator(); @Override void put(String key, String value); }### Answer: @Test public void verifyNullHeaderHandled() { Headers headers = new RecordHeaders(); headers.add("test_null_header", null); HeadersMapExtractAdapter headersMapExtractAdapter = new HeadersMapExtractAdapter(headers); Entry<String, String> header = headersMapExtractAdapter.iterator().next(); assertNotNull(header); assertEquals(header.getKey(), "test_null_header"); assertNull(header.getValue()); }
### Question: TracingCallback implements Callback { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception != null) { for (SpanDecorator decorator : spanDecorators) { decorator.onError(exception, span); } } try (Scope ignored = tracer.scopeManager().activate(span)) { if (callback != null) { callback.onCompletion(metadata, exception); } } finally { span.finish(); } } TracingCallback(Callback callback, Span span, Tracer tracer); TracingCallback(Callback callback, Span span, Tracer tracer, Collection<SpanDecorator> spanDecorators); @Override void onCompletion(RecordMetadata metadata, Exception exception); }### Answer: @Test public void onCompletionWithError() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer); callback.onCompletion(null, new RuntimeException("test")); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(1, finished.get(0).logEntries().size()); assertEquals(true, finished.get(0).tags().get(Tags.ERROR.getKey())); } @Test public void onCompletionWithCustomErrorDecorators() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer, Arrays.asList(SpanDecorator.STANDARD_TAGS, createDecorator())); callback.onCompletion(null, new RuntimeException("test")); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(true, finished.get(0).tags().get(Tags.ERROR.getKey())); assertEquals("overwritten", finished.get(0).tags().get("error.of")); assertEquals("error-test", finished.get(0).tags().get("new.error.tag")); } @Test public void onCompletion() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer); callback.onCompletion(null, null); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(0, finished.get(0).logEntries().size()); assertNull(finished.get(0).tags().get(Tags.ERROR.getKey())); }
### Question: RateThisApp { @Deprecated public static void onStart(Context context) { onCreate(context); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(final Context context); static boolean showRateDialogIfNeeded(final Context context, int themeId); static boolean shouldShowRateDialog(); static void showRateDialog(final Context context); static void showRateDialog(final Context context, int themeId); static void stopRateDialog(final Context context); static int getLaunchCount(final Context context); static final boolean DEBUG; }### Answer: @Test public void onStart_isSuccess() { Context context = RuntimeEnvironment.application.getApplicationContext(); RateThisApp.onStart(context); SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE); long expectedInstallDate = 0L; PackageManager packMan = context.getPackageManager(); try { PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0); expectedInstallDate = new Date(pkgInfo.firstInstallTime).getTime(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } Assert.assertEquals(expectedInstallDate, sharedPreferences.getLong(KEY_INSTALL_DATE, 0L)); Assert.assertEquals(1, sharedPreferences.getInt(KEY_LAUNCH_TIMES, 0)); }
### Question: RateThisApp { public static void stopRateDialog(final Context context){ setOptOut(context, true); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(final Context context); static boolean showRateDialogIfNeeded(final Context context, int themeId); static boolean shouldShowRateDialog(); static void showRateDialog(final Context context); static void showRateDialog(final Context context, int themeId); static void stopRateDialog(final Context context); static int getLaunchCount(final Context context); static final boolean DEBUG; }### Answer: @Test public void stopRateDialog_IsSuccess() { Context context = RuntimeEnvironment.application.getApplicationContext(); RateThisApp.stopRateDialog(context); SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE); Assert.assertTrue(sharedPreferences.getBoolean(KEY_OPT_OUT, false)); }
### Question: DateTrigger implements Trigger { @Override public Date nextExecutionTime(TriggerContext triggerContext) { Date result = null; if (nextFireDates.size() > 0) { try { result = nextFireDates.remove(0); } catch (IndexOutOfBoundsException e) { logger.debug(e.getMessage()); } } return result; } DateTrigger(Date... dates); @Override Date nextExecutionTime(TriggerContext triggerContext); }### Answer: @Test public void testConstructor() { Date epoch = new Date(0); Calendar currentCalendar = Calendar.getInstance(); Date current = currentCalendar.getTime(); currentCalendar.add(Calendar.HOUR, -1); Date past = currentCalendar.getTime(); currentCalendar.add(Calendar.HOUR, 2); Date future = currentCalendar.getTime(); DateTrigger dateTrigger = new DateTrigger(current, epoch, future, past); Date nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return epoch", nextExecutionTime); assertTrue("Should be epoch", epoch.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return past", nextExecutionTime); assertTrue("Should be past", past.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return current", nextExecutionTime); assertTrue("Should be current", current.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return future", nextExecutionTime); assertTrue("Should be future", future.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNull("All entries should have been pulled, the nextExecutionTime should have been null.", nextExecutionTime); }
### Question: UiUtils { public static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth) { final Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("Parameter")); final TableHeader tableHeader2 = new TableHeader("Value (Configured or Default)"); tableHeader2.setMaxWidth(lastColumnMaxWidth); table.getHeaders().put(COLUMN_2, tableHeader2); for (Entry<String, String> entry : parameters.entrySet()) { final TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(entry.getKey().length()); tableRow.addValue(COLUMN_1, entry.getKey()); int width = entry.getValue() != null ? entry.getValue().length() : 0; table.getHeaders().get(COLUMN_2).updateWidth(width); tableRow.addValue(COLUMN_2, entry.getValue()); table.getRows().add(tableRow); } return renderTextTable(table, withHeader); } private UiUtils(); static String renderMapDataAsTable(List<Map<String, Object>> data, List<String> columns); static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth); static String renderParameterInfoDataAsTable(Map<String, String> parameters); static String renderTextTable(Table table); static String renderTextTable(Table table, boolean withHeader); static String getHeaderBorder(Map<Integer, TableHeader> headers); static final String HORIZONTAL_LINE; static final int COLUMN_1; static final int COLUMN_2; static final int COLUMN_3; static final int COLUMN_4; static final int COLUMN_5; static final int COLUMN_6; }### Answer: @Test public void testRenderParameterInfoDataAsTableWithMaxWidth() { final Map<String, String> values = new TreeMap<String, String>(); values.put("Key1", "Lorem ipsum dolor sit posuere."); values.put("My super key 2", "Lorem ipsum"); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderParameterInfoDataAsTableWithMaxWidth.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderParameterInfoDataAsTable(values, false, 20); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); }
### Question: ShellWordsParser { List<String> parse(String s) { List<String> words = new ArrayList<>(); String field = ""; Matcher matcher = SHELLWORDS.matcher(s); while (matcher.find()) { String word = matcher.group(1); String sq = matcher.group(2); String dq = matcher.group(3); String esc = matcher.group(4); String garbage = matcher.group(5); String sep = matcher.group(6); if (garbage != null) { throw new IllegalArgumentException("Unmatched double quote: " + s); } if (word != null) { field = word; } else if (sq != null) { field = sq; } else if (dq != null) { field = dq.replaceAll("\\\\(?=.)", ""); } else if (esc != null) { field = esc.replaceAll("\\\\(?=.)", ""); } if (sep != null) { words.add(field); field = ""; } } return words; } }### Answer: @Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenDoubleQuotedStringsAreMisQuoted() { this.parser.parse("a \"b c d e"); } @Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenSingleQuotedStringsAreMisQuoted() { this.parser.parse("a 'b c d e"); }
### Question: MappedAnalytic implements Analytic<I, O> { @Override @SuppressWarnings("unchecked") public O evaluate(I input) { Assert.notNull(input, "input"); MI modelInput = inputMapper.mapInput((A) this, input); MO modelOutput = evaluateInternal(modelInput); O output = outputMapper.mapOutput((A) this, input, modelOutput); return output; } MappedAnalytic(InputMapper<I, A, MI> inputMapper, OutputMapper<I, O, A, MO> outputMapper); @Override @SuppressWarnings("unchecked") O evaluate(I input); }### Answer: @Test public void testEvaluateDummyMappedAnalytic() { Tuple input = TupleBuilder.tuple().of("k1", "v1", "k2", "v2"); Tuple output = analytic.evaluate(input); assertNotSame(input, output); assertThat(output.getString("k1"), is("V1")); assertThat(output.getString("k2"), is("V2")); }
### Question: AbstractFieldMappingAwareDataMapper implements Mapper { protected Map<String,String> extractFieldNameMappingFrom(List<String> fieldNameMappingPairs){ Assert.notNull(fieldNameMappingPairs, "fieldNameMappingPairs"); Map<String,String> mapping = new LinkedHashMap<String,String>(); for (String fieldNameMapping : fieldNameMappingPairs) { String fieldNameFrom = fieldNameMapping; String fieldNameTo = fieldNameMapping; if (fieldNameMapping.contains(fieldMappingEntrySplitToken)) { String[] fromTo = fieldNameMapping.split(fieldMappingEntrySplitToken); fieldNameFrom = fromTo[0]; fieldNameTo = fromTo[1]; } mapping.put(fieldNameFrom,fieldNameTo); } return mapping; } AbstractFieldMappingAwareDataMapper(); AbstractFieldMappingAwareDataMapper(String fieldMappingEntrySplitToken); String getFieldMappingEntrySplitToken(); static final String DEFAULT_FIELD_NAME_MAPPING_SPLIT_TOKEN; }### Answer: @Test public void testExtractMixedFieldNameMappingFromWithDefaultSplitToken() throws Exception { Map<String, String> mapping = mapperWithDefaultSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo:bar", "mambo", "bubu:gaga", "salsa")); assertThat(mapping.size(),is(4)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); assertThat(mapping.get("mambo"), is("mambo")); assertThat(mapping.get("salsa"), is("salsa")); } @Test public void testExtractFieldNameMappingFromWithDefaultSplitToken() throws Exception { Map<String, String> mapping = mapperWithDefaultSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo:bar", "bubu:gaga")); assertThat(mapping.size(),is(2)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); } @Test public void testExtractFieldNameMappingFromWithCustomSplitToken() throws Exception { Map<String, String> mapping = mapperWithCustomSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo->bar", "bubu->gaga")); assertThat(mapping.size(),is(2)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); }
### Question: CommonUtils { public static boolean isValidEmail(String emailAddress) { return emailAddress.matches(EMAIL_VALIDATION_REGEX); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }### Answer: @Test public void testValidEmailAddress() { assertTrue(CommonUtils.isValidEmail("[email protected]")); } @Test public void testInValidEmailAddress() { assertFalse(CommonUtils.isValidEmail("test123")); }
### Question: CommonUtils { public static String padRight(String inputString, int size, char paddingChar) { final String stringToPad; if (inputString == null) { stringToPad = ""; } else { stringToPad = inputString; } StringBuilder padded = new StringBuilder(stringToPad); while (padded.length() < size) { padded.append(paddingChar); } return padded.toString(); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }### Answer: @Test public void testPadRightWithNullString() { assertEquals(" ", CommonUtils.padRight(null, 5)); } @Test public void testPadRightWithEmptyString() { assertEquals(" ", CommonUtils.padRight("", 5)); } @Test public void testPadRight() { assertEquals("foo ", CommonUtils.padRight("foo", 5)); }
### Question: CommonUtils { public static String maskPassword(String password) { int lengthOfPassword = password.length(); StringBuilder stringBuilder = new StringBuilder(lengthOfPassword); for (int i = 0; i < lengthOfPassword; i++) { stringBuilder.append('*'); } return stringBuilder.toString(); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }### Answer: @Test public void testMaskPassword() { assertEquals("******", CommonUtils.maskPassword("foobar")); }
### Question: UiUtils { public static String renderTextTable(Table table) { return renderTextTable(table, true); } private UiUtils(); static String renderMapDataAsTable(List<Map<String, Object>> data, List<String> columns); static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth); static String renderParameterInfoDataAsTable(Map<String, String> parameters); static String renderTextTable(Table table); static String renderTextTable(Table table, boolean withHeader); static String getHeaderBorder(Map<Integer, TableHeader> headers); static final String HORIZONTAL_LINE; static final int COLUMN_1; static final int COLUMN_2; static final int COLUMN_3; static final int COLUMN_4; static final int COLUMN_5; static final int COLUMN_6; }### Answer: @Test public void testRenderTextTable() { final Table table = new Table(); table.addHeader(1, new TableHeader("Tap Name")) .addHeader(2, new TableHeader("Stream Name")) .addHeader(3, new TableHeader("Tap Definition")); for (int i = 1; i <= 3; i++) { final TableRow row = new TableRow(); row.addValue(1, "tap" + i) .addValue(2, "ticktock") .addValue(3, "tap@ticktock|log"); table.getRows().add(row); } String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); } @Test public void testRenderTextTableWithSingleColumn() { final Table table = new Table(); table.addHeader(1, new TableHeader("Gauge name")); final TableRow row = new TableRow(); row.addValue(1, "simplegauge"); table.getRows().add(row); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-single-column-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); } @Test public void testRenderTextTableWithSingleColumnAndWidthOf4() { final Table table = new Table(); final TableHeader tableHeader = new TableHeader("Gauge name"); tableHeader.setMaxWidth(4); table.addHeader(1, tableHeader); final TableRow row = new TableRow(); row.addValue(1, "simplegauge"); table.getRows().add(row); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-single-column-width4-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); }
### Question: LibreOfficeLauncherHelper { public static String getOperatingSystem(String operatingSystemIndentifier) { if ("linux".equalsIgnoreCase(operatingSystemIndentifier)) { return OS_LINUX; } if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("windows")) { return OS_WINDOWS; } else if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("mac os x")) { return OS_MACOSX; } else { return OS_UNSUPPORTED; } } static String getOperatingSystem(String operatingSystemIndentifier); static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath); static final String OS_WINDOWS; static final String OS_LINUX; static final String OS_MACOSX; static final String OS_UNSUPPORTED; }### Answer: @Test public void testGetOperatingSystem() { assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("linux")); assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("Linux")); assertEquals(LibreOfficeLauncherHelper.OS_WINDOWS, LibreOfficeLauncherHelper.getOperatingSystem("Windows XP")); assertEquals(LibreOfficeLauncherHelper.OS_WINDOWS, LibreOfficeLauncherHelper.getOperatingSystem("windows 5.1")); assertEquals(LibreOfficeLauncherHelper.OS_MACOSX, LibreOfficeLauncherHelper.getOperatingSystem("mac os x")); assertEquals(LibreOfficeLauncherHelper.OS_MACOSX, LibreOfficeLauncherHelper.getOperatingSystem("Mac OS X")); assertEquals(LibreOfficeLauncherHelper.OS_UNSUPPORTED, LibreOfficeLauncherHelper.getOperatingSystem("Solaris")); assertEquals(LibreOfficeLauncherHelper.OS_UNSUPPORTED, LibreOfficeLauncherHelper.getOperatingSystem("")); }
### Question: LibreOfficeLauncherHelper { public static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath) throws UnsupportedEncodingException { StringBuilder openUrlSb = new StringBuilder(); openUrlSb.append(LibreOfficeLauncherHelper.LIBREOFFICE_HANDLER); openUrlSb.append(": StringBuilder cmisUrlSb = new StringBuilder(); cmisUrlSb.append(cmisUrl); cmisUrlSb.append("#"); cmisUrlSb.append(repositoryId); String urlEncodedString = URLEncoder.encode(cmisUrlSb.toString(), "UTF-8").replaceAll("\\+", "%20"); openUrlSb.append(urlEncodedString + filePath); return openUrlSb.toString(); } static String getOperatingSystem(String operatingSystemIndentifier); static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath); static final String OS_WINDOWS; static final String OS_LINUX; static final String OS_MACOSX; static final String OS_UNSUPPORTED; }### Answer: @Test public void testGenerateLibreOfficeOpenUrl() throws UnsupportedEncodingException { assertEquals("vnd.libreoffice.cmis: LibreOfficeLauncherHelper.generateLibreOfficeOpenUrl("http: "/Sites/libreoffice-test/documentLibrary/Testdocument.odt")); }
### Question: PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public String IsDR(Platform platform) { String activeCloudsListForPlatform = platform.getActiveClouds().toString().toLowerCase(); log.info("activeCloudsListForPlatform: " + activeCloudsListForPlatform.toString()); int i = 0; for (String dataCenter : dataCentersArr) { if (activeCloudsListForPlatform.contains(dataCenter)) { i++; } } if (i >= 2) { return "DR"; } return "Non-DR"; } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }### Answer: @Test(enabled = true) private void test_IsDR() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); activeClouds.add("dc1-TestCloud2"); activeClouds.add("dc2-TestCloud1"); activeClouds.add("dc2-TestCloud2"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "DR"); } @Test(enabled = true) private void test_IsNonDR() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); activeClouds.add("dc1-TestCloud2"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "Non-DR"); } @Test(enabled = true) private void test_IsNonHA() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "Non-DR"); }
### Question: NotificationMessage implements Serializable { public String getPayloadString(String name) { return payload.get(name) == null ? null : String.valueOf(payload.get(name)); } static String buildSubjectPrefix(String nsPath); Map<String, Object> getPayload(); String getPayloadString(String name); void putPayloadEntry(String name, Object value); void putPayloadEntries(Map<String, Object> payloadEntries); String getNsPath(); void setNsPath(String nsPath); String getSource(); void setSource(String source); long getTimestamp(); void setTimestamp(long timestamp); long getCmsId(); void setCmsId(long cmsId); NotificationSeverity getSeverity(); void setSeverity(NotificationSeverity severity); NotificationType getType(); void setType(NotificationType type); String getSubject(); void setSubject(String subject); String getTemplateName(); void setTemplateName(String templateName); String getTemplateParams(); void setTemplateParams(String templateParams); String getText(); void setText(String text); String getEnvironmentProfileName(); void setEnvironmentProfileName(String envProfile); String getAdminStatus(); void setAdminStatus(String adminStatus); long getManifestCiId(); void setManifestCiId(long manifestCiId); String getCloudName(); void setCloudName(String cloudName); void appendText(String notes); String asString(); List<CmsCISimple> getCis(); void setCis(List<CmsCISimple> cis); }### Answer: @Test public void testGetPayloadStringForNull() { assertNull(new NotificationMessage().getPayloadString(ENTRY_NAME)); }
### Question: CmsCryptoDES implements CmsCrypto { public void init() throws IOException, GeneralSecurityException { Security.addProvider(new BouncyCastleProvider()); this.secretKeyFile = System.getenv("CMS_DES_PEM"); if (this.secretKeyFile == null) { this.secretKeyFile = System.getProperty("com.kloopz.crypto.cms_des_pem"); } if (this.secretKeyFile == null) { logger.error(">>>>>>>>>>>>>>Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!"); throw new FileNotFoundException("Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!"); } initEncryptorDecryptor(); } @Override String encrypt(String instr); @Override String decrypt(String instr); @Override String decryptVars(String instr); void init(); static void generateDESKey(String file); static void main(String[] args); void setSecretKeyFile(String secretKeyFile); void init(String secretKeyFile); }### Answer: @Test(expectedExceptions = CmsException.class) public void badDESEnvTest() throws Exception { CmsCryptoDES crypto1 = new CmsCryptoDES(); try { crypto1.init(); } catch (FileNotFoundException e) { throw new CmsException(33, "File not found, likely a devbox, throwing CmsException"); } } @Test(expectedExceptions = IOException.class) public void badFileTest() throws Exception { CmsCryptoDES crypto1 = new CmsCryptoDES(); crypto1.init("this-is-not-a-key-file"); }
### Question: CmsCryptoDES implements CmsCrypto { @Override public String decrypt(String instr) throws GeneralSecurityException { if (instr.startsWith(ENC_PREFIX)) { instr = instr.substring(ENC_PREFIX.length()); } return decryptStr(instr); } @Override String encrypt(String instr); @Override String decrypt(String instr); @Override String decryptVars(String instr); void init(); static void generateDESKey(String file); static void main(String[] args); void setSecretKeyFile(String secretKeyFile); void init(String secretKeyFile); }### Answer: @Test(threadPoolSize = 10, invocationCount = 3, timeOut = 10000) public void testDecrypt() throws Exception { String decryptedUUID = crypto.decrypt(encryptedString); Assert.assertTrue(rawString.equals(decryptedUUID)); } @Test public void testEmptyString() throws Exception { String decryptedText = crypto.decrypt(CmsCrypto.ENC_PREFIX); Assert.assertTrue(StringUtils.EMPTY.equals(decryptedText)); }
### Question: ListUtils { public <V> Map<K, V> toMap(List<V> list, String keyField) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String accessor = convertFieldToAccessor(keyField); Map<K, V> map = new HashMap<K, V>(); for(V obj : list) { Method method = obj.getClass().getMethod(accessor); @SuppressWarnings("unchecked") K key = (K)method.invoke(obj); map.put(key, obj); } return map; } Map<K, V> toMap(List<V> list, String keyField); Map<K, List<V>> toMapOfList(List<V> list, String keyField); }### Answer: @Test public void testList1() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { List<MyBean> listOfBeans = new ArrayList<MyBean>(LIST_SIZE); for (int i = 1; i <= LIST_SIZE; i++) { MyBean m = new MyBean(String.valueOf(i)); listOfBeans.add(m); } Map<String, MyBean> outMap = util.toMap(listOfBeans, KEY_FIELD); assertEquals(LIST_SIZE, outMap.size()); for(MyBean listMember : listOfBeans){ assertEquals(listMember, outMap.get(listMember.getSpecialValue())); } System.out.println(outMap); }
### Question: EventConverter { public static OpsBaseEvent convert(OpsEvent oEvent) { OpsBaseEvent bEvent = new OpsBaseEvent(); bEvent.setCiId(oEvent.getCiId()); bEvent.setBucket(oEvent.getBucket()); bEvent.setCiState(oEvent.getCiState()); bEvent.setName(oEvent.getName()); bEvent.setManifestId(oEvent.getManifestId()); bEvent.setSource(oEvent.getSource()); bEvent.setState(oEvent.getState()); bEvent.setType(oEvent.getType()); bEvent.setMetrics(oEvent.getMetrics()); bEvent.setTimestamp(oEvent.getTimestamp()); bEvent.setCount(oEvent.getCount()); bEvent.setStatus(oEvent.getStatus()); bEvent.setCoolOff(oEvent.getCoolOff()); return bEvent; } static OpsBaseEvent convert(OpsEvent oEvent); static OpsBaseEvent convert(OpsCloseEvent oEvent); }### Answer: @Test public void testEventClosed(){ OpsCloseEvent opsCloseEvent = new OpsCloseEvent(); opsCloseEvent.setBucket(BUCKET); opsCloseEvent.setCiId(CI_ID); opsCloseEvent.setCiState(CI_STATE); opsCloseEvent.setManifestId(CI_MANIFEST_ID); opsCloseEvent.setSource(CI_SOURCE); opsCloseEvent.setType(CI_TYPE); opsCloseEvent.setTimestamp(CI_TIMESTAMP); PerfEventPayload metrics = new PerfEventPayload(); Map<String, Double> countMap = new HashMap<String, Double>(1); countMap.put(P_KEY, P_VAL); metrics.setCount(countMap); opsCloseEvent.setMetrics(metrics); OpsBaseEvent convertedOut = EventConverter.convert(opsCloseEvent); assertEquals(convertedOut.getBucket(),BUCKET); assertEquals(convertedOut.getCiState(),CI_STATE); assertEquals(convertedOut.getSource(),CI_SOURCE); assertEquals(convertedOut.getType(),CI_TYPE); assertEquals(convertedOut.getMetrics(),metrics); assert(CI_TIMESTAMP.equals(convertedOut.getTimestamp())); assert(CI_MANIFEST_ID.equals(convertedOut.getManifestId())); assert(CI_ID.equals(convertedOut.getCiId() )); } @Test public void testEvent(){ OpsEvent oe = new OpsEvent(); oe.setBucket(BUCKET); oe.setCiId(CI_ID); oe.setCiState(CI_STATE); oe.setManifestId(CI_MANIFEST_ID); oe.setSource(CI_SOURCE); oe.setType(CI_TYPE); oe.setTimestamp(CI_TIMESTAMP); PerfEventPayload metrics = new PerfEventPayload(); Map<String, Double> countMap = new HashMap<String, Double>(1); countMap.put(P_KEY, P_VAL); metrics.setCount(countMap); oe.setMetrics(metrics); OpsBaseEvent convertedOut = EventConverter.convert(oe); assertEquals(convertedOut.getBucket(),BUCKET); assertEquals(convertedOut.getCiState(),CI_STATE); assertEquals(convertedOut.getSource(),CI_SOURCE); assertEquals(convertedOut.getType(),CI_TYPE); assertEquals(convertedOut.getMetrics(),metrics); assert(CI_TIMESTAMP.equals(convertedOut.getTimestamp())); assert(CI_MANIFEST_ID.equals(convertedOut.getManifestId())); assert(CI_ID.equals(convertedOut.getCiId() )); }
### Question: CmsDJValidator { public CIValidationResult validateRfcCi(CmsRfcCI rfcCi) { CIValidationResult result = new CIValidationResult(); result.setValidated(true); if (rfcCi.getCiName() == null || rfcCi.getCiName().length()==0) { result.setValidated(false); result.setErrorMsg("CI Name can not be empty!"); return result; } CmsClazz clazz = getClazz(rfcCi.getCiClassName()); if (clazz == null) { result.setValidated(false); result.setErrorMsg("There is no class definition for " + rfcCi.getCiClassName()); return result; } rfcCi.setCiClassId(clazz.getClassId()); if (rfcCi.getNsId() == 0) { CmsNamespace ns = getNs(rfcCi.getNsPath()); if (ns == null) { result.setValidated(false); result.setErrorMsg("The namespace must be specified"); return result; } rfcCi.setNsId(ns.getNsId()); } Map<String, CmsClazzAttribute> clazzAttrsMap = new HashMap<String, CmsClazzAttribute>(); for (CmsClazzAttribute clazzAttr : clazz.getMdAttributes()) { clazzAttrsMap.put(clazzAttr.getAttributeName(), clazzAttr); } if ("add".equalsIgnoreCase(rfcCi.getRfcAction())) { for (CmsClazzAttribute clazzAttr : clazz.getMdAttributes()) { if (clazzAttr.getIsMandatory() && (rfcCi.getAttribute(clazzAttr.getAttributeName()) == null)) { result.setValidated(false); result.addErrorMsg("Attribute " + clazzAttr.getAttributeName() + " is required for ci type of " + clazz.getClassName()); } } } for (CmsRfcAttribute attr : rfcCi.getAttributes().values()) { if (!clazzAttrsMap.containsKey(attr.getAttributeName())) { result.setValidated(false); result.addErrorMsg("Attribute " + attr.getAttributeName() + " is not defined in class " + clazz.getClassName()); } else { attr.setAttributeId(clazzAttrsMap.get(attr.getAttributeName()).getAttributeId()); } } if (!result.isValidated()) return result; encryptRfcAttrs(clazzAttrsMap, rfcCi, result); return result; } void setCmsMdProcessor(CmsMdProcessor cmsMdProcessor); void setCmsNsProcessor(CmsNsProcessor cmsNsProcessor); void setCmsCrypto(CmsCrypto cmsCrypto); CIValidationResult validateRfcCi(CmsRfcCI rfcCi); CIValidationResult validateRfcCiAttrs(CmsRfcCI rfcCi); CIValidationResult validateRfcRelation(CmsRfcRelation rfcRelation, int fromClassId, int toClassId); CIValidationResult validateRfcRelationAttrs(CmsRfcRelation rfcRelation); boolean rfcCisEqual(CmsRfcCI ci1, CmsRfcCI ci2); boolean rfcAttrsEqual(CmsRfcAttribute attr1, CmsRfcAttribute attr2); boolean equalStrs(String str1, String str2); }### Answer: @Test public void testEmptyName(){ CmsRfcCI rfcCi = new CmsRfcCI(); rfcCi.setCiName(""); CIValidationResult result = this.validator.validateRfcCi(rfcCi); assertTrue(result.getErrorMsg().startsWith("CI Name can not be empty!"),"unex:"+result.getErrorMsg()); assertEquals(result.isValidated(),false); }
### Question: CapacityProcessor { public boolean isCapacityManagementEnabled(String nsPath) { CmsVar softQuotaEnabled = cmProcessor.getCmSimpleVar(CAPACITY_MANAGEMENT_VAR_NAME); if (softQuotaEnabled != null) { String value = softQuotaEnabled.getValue(); if (Boolean.TRUE.toString().equalsIgnoreCase(value)) return true; if (nsPath != null && !value.isEmpty()) { return Arrays.stream(value.split(",")).anyMatch(nsPath::startsWith); } } return false; } void setCmProcessor(CmsCmProcessor cmProcessor); void setRfcProcessor(CmsRfcProcessor rfcProcessor); void setTektonClient(TektonClient tektonClient); boolean isCapacityManagementEnabled(String nsPath); CapacityEstimate estimateCapacity(String nsPath, Collection<CmsRfcCI> cis, Collection<CmsRfcRelation> deployedToRels); void reserveCapacityForDeployment(CmsDeployment deployment); void discardCapacityForDeployment(CmsDeployment deployment); void commitCapacity(CmsWorkOrder workOrder); void releaseCapacity(CmsWorkOrder workOrder); }### Answer: @Test public void capacityManagementEnabled() { cmsVarCapacityManagement.setValue("false"); boolean enabled = capacityProcessor.isCapacityManagementEnabled(null); assertEquals(enabled, false, "Capacity Management should be disabled when CAPACITY_MANAGEMENT=false"); cmsVarCapacityManagement.setValue("true"); enabled = capacityProcessor.isCapacityManagementEnabled(null); assertEquals(enabled, true, "Capacity Management should be enabled when CAPACITY_MANAGEMENT=true"); cmsVarCapacityManagement.setValue("/org1,/org2,/org3"); enabled = capacityProcessor.isCapacityManagementEnabled("/org2/a1/e1"); assertEquals(enabled, true, "Capacity Management should be enabled for ns included in CAPACITY_MANAGEMENT"); enabled = capacityProcessor.isCapacityManagementEnabled("/org4/a1"); assertEquals(enabled, false, "Capacity Management should be disabled for ns when not included in CAPACITY_MANAGEMENT"); }
### Question: CapacityProcessor { public void commitCapacity(CmsWorkOrder workOrder) { CmsRfcCI rfcCi = workOrder.getRfcCi(); String nsPath = getReservationNsPath(rfcCi.getNsPath()); if (!isCapacityManagementEnabled(nsPath)) return; Map<String, Object> mappings = getCloudProviderMappings(); if (mappings == null) return; List<CmsRfcRelation> deployedTos = rfcProcessor.getOpenRfcRelationBy2NoAttrs(rfcCi.getCiId(), null, "base.DeployedTo", null); CloudInfo cloudInfo = getDeployedToCloudInfo(deployedTos.get(0).getToCiId()); Map<String, Integer> capacity = getCapacityForCi(rfcCi, cloudInfo, mappings); if (!capacity.isEmpty()) { tektonClient.commitReservation(capacity, nsPath, cloudInfo.getSubscriptionId()); } } void setCmProcessor(CmsCmProcessor cmProcessor); void setRfcProcessor(CmsRfcProcessor rfcProcessor); void setTektonClient(TektonClient tektonClient); boolean isCapacityManagementEnabled(String nsPath); CapacityEstimate estimateCapacity(String nsPath, Collection<CmsRfcCI> cis, Collection<CmsRfcRelation> deployedToRels); void reserveCapacityForDeployment(CmsDeployment deployment); void discardCapacityForDeployment(CmsDeployment deployment); void commitCapacity(CmsWorkOrder workOrder); void releaseCapacity(CmsWorkOrder workOrder); }### Answer: @Test public void testCommit() throws IOException { long deploymentId = 1L; bomCIs.clear(); bomRels.clear(); createComputeRfc(1L, "add", "M", azureCloud); CmsWorkOrder workOrder = new CmsWorkOrder(); workOrder.setRfcCi(bomCIs.get(0)); workOrder.setCloud(azureCloud); workOrder.setDeploymentId(deploymentId); Map<String, Integer> expectedCapacity = new HashMap<>(); expectedCapacity.put("Dv2", 2); expectedCapacity.put("vm", 1); expectedCapacity.put("nic", 1); ArgumentCaptor<HashMap> argument = ArgumentCaptor.forClass(HashMap.class); capacityProcessor.commitCapacity(workOrder); Mockito.verify(tektonClientMock, Mockito.times(1)) .commitReservation(argument.capture(), Mockito.eq(ENV_NS_PATH), Mockito.eq(AZURE_CLOUD_LOCATION + ":" + AZURE_SUBSCRIPTION_ID)); Assert.assertEquals(argument.getValue(), expectedCapacity); }
### Question: CapacityProcessor { public void releaseCapacity(CmsWorkOrder workOrder) { CmsRfcCI rfcCi = workOrder.getRfcCi(); String nsPath = getReservationNsPath(rfcCi.getNsPath()); if (!isCapacityManagementEnabled(nsPath)) return; Map<String, Object> mappings = getCloudProviderMappings(); if (mappings == null) return; List<CmsCIRelation> deployedTos = cmProcessor.getFromCIRelationsNakedNoAttrs(rfcCi.getCiId(), "base.DeployedTo", null, null); CloudInfo cloudInfo = getDeployedToCloudInfo(deployedTos.get(0).getToCiId()); Map<String, Integer> capacity = getCapacityForCi(rfcCi, cloudInfo, mappings); if (!capacity.isEmpty()) { tektonClient.releaseResources(capacity, nsPath, cloudInfo.getSubscriptionId()); } } void setCmProcessor(CmsCmProcessor cmProcessor); void setRfcProcessor(CmsRfcProcessor rfcProcessor); void setTektonClient(TektonClient tektonClient); boolean isCapacityManagementEnabled(String nsPath); CapacityEstimate estimateCapacity(String nsPath, Collection<CmsRfcCI> cis, Collection<CmsRfcRelation> deployedToRels); void reserveCapacityForDeployment(CmsDeployment deployment); void discardCapacityForDeployment(CmsDeployment deployment); void commitCapacity(CmsWorkOrder workOrder); void releaseCapacity(CmsWorkOrder workOrder); }### Answer: @Test public void testRelease() throws IOException { long deploymentId = 1L; bomCIs.clear(); bomRels.clear(); createComputeRfc(1L, "add", "M", azureCloud); CmsWorkOrder workOrder = new CmsWorkOrder(); workOrder.setRfcCi(bomCIs.get(0)); workOrder.setCloud(azureCloud); workOrder.setDeploymentId(deploymentId); Map<String, Integer> expectedCapacity = new HashMap<>(); expectedCapacity.put("Dv2", 2); expectedCapacity.put("vm", 1); expectedCapacity.put("nic", 1); ArgumentCaptor<HashMap> argument= ArgumentCaptor.forClass(HashMap.class); capacityProcessor.releaseCapacity(workOrder); Mockito.verify(tektonClientMock, Mockito.times(1)) .releaseResources(argument.capture(), Mockito.eq(ENV_NS_PATH), Mockito.eq(AZURE_CLOUD_LOCATION + ":" + AZURE_SUBSCRIPTION_ID)); Assert.assertEquals(argument.getValue(), expectedCapacity); }
### Question: SubscriberService { public List<BasicSubscriber> getSubscribersForNs(String nsPath) { try { return sinkCache.instance().get(new SinkKey(nsPath)); } catch (Exception e) { logger.error("Can't retrieve subscribers for nspath " + nsPath + " from sink cache", e); return Collections.singletonList(defaultSystemSubscriber); } } @Autowired SubscriberService(URLSubscriber defaultSystemSubscriber, SinkCache sinkCache); List<BasicSubscriber> getSubscribersForNs(String nsPath); }### Answer: @Test public void getSubscribersForNsTest() { }
### Question: ChatPresence { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ChatPresence other = (ChatPresence) obj; if (chatConference == null) { if (other.chatConference != null) { return false; } } else if (!chatConference.equals(other.chatConference)) { return false; } if (stationName == null) { if (other.stationName != null) { return false; } } else if (!stationName.equals(other.stationName)) { return false; } if (chatPort != other.chatPort) { return false; } if (chatRoom == null) { if (other.chatRoom != null) { return false; } } else if (!chatRoom.equals(other.chatRoom)) { return false; } if (chatServer == null) { if (other.chatServer != null) { return false; } } else if (!chatServer.equals(other.chatServer)) { return false; } if (chatUser == null) { if (other.chatUser != null) { return false; } } else if (!chatUser.equals(other.chatUser)) { return false; } return true; } ChatPresence(String chatServer, int chatPort, String chatConference, String chatRoom, String chatUser, String stationName); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void equalsTest() { ChatPresence c1 = new ChatPresence(chatServer, chatPort, chatConference, chatRoom, chatUser, chatPassword); ChatPresence c2 = new ChatPresence(chatServer, chatPort, chatConference, chatRoom, chatUser, chatPassword); assertEquals(c1, c2); } @Test public void unequalsTest() { ChatPresence localCp1 = new ChatPresence(chatServer + "X", chatPort, chatConference, chatRoom, chatUser, chatPassword); assertFalse(classCp1.equals(localCp1)); localCp1 = new ChatPresence(chatServer, chatPort + 100, chatConference, chatRoom, chatUser, chatPassword); assertFalse(classCp1.equals(localCp1)); localCp1 = new ChatPresence(chatServer, chatPort, chatConference + "XXXX", chatRoom, chatUser, chatPassword); assertFalse(classCp1.equals(localCp1)); localCp1 = new ChatPresence(chatServer, chatPort, chatConference, chatRoom + "yyy", chatUser, chatPassword); assertFalse(classCp1.equals(localCp1)); localCp1 = new ChatPresence(chatServer, chatPort, chatConference, chatRoom, chatUser + "cuser", chatPassword); assertFalse(classCp1.equals(localCp1)); localCp1 = new ChatPresence(chatServer, chatPort, chatConference, chatRoom, chatUser, null); assertFalse(classCp1.equals(localCp1)); }
### Question: HTTPMsgService implements NotificationSender { @Override public boolean postMessage(NotificationMessage msg, BasicSubscriber sub) { URLSubscriber urlSub = (URLSubscriber) sub; boolean isHpom = urlSub.hasHpomXfmr(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost req = new HttpPost(urlSub.getUrl()); req.setEntity(new StringEntity(gson.toJson(msg), ContentType.APPLICATION_JSON)); int timeout = urlSub.getTimeout(); req.setConfig(RequestConfig.custom().setSocketTimeout(timeout > 0 ? timeout : 2000).build()); String userName = urlSub.getUserName(); if (userName != null && StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(urlSub.getPassword()) ) { String auth = userName + ":" + urlSub.getPassword(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64(auth.getBytes()))); } try (CloseableHttpResponse res = httpClient.execute(req)) { if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { countOK(isHpom); return true; } else { logger.warn(isHpom ? "HPOM" : "HTTP" + " message post response code: " + res.getStatusLine().getStatusCode() + " for URL sink: " + urlSub.getName()); } } catch (IOException ex) { logger.error(isHpom ? "HPOM" : "HTTP" + " message post failed." + ex.getMessage()); } countErr(isHpom); return false; } @Autowired HTTPMsgService(MetricRegistry metrics); @PostConstruct void init(); @Override boolean postMessage(NotificationMessage msg, BasicSubscriber sub); }### Answer: @Test public void badHttpMessageUrlPost() { URLSubscriber sub = new URLSubscriber(); sub.setUserName(this.getClass().getName()); sub.setUrl("this-is-not-valid: boolean result = service.postMessage(null, sub); assertEquals(result, false); } @Test public void testEmailNotification() { URLSubscriber sub = new URLSubscriber(); sub.setUserName("admin"); sub.setUrl("http: sub.setPassword("****"); NotificationMessage n = new NotificationMessage(); n.setSeverity(info); n.setNsPath("/testing/rel0402/testmon/bom/tom/1"); n.setCmsId(20401024); n.setSubject("TEST :ci:artifact-app-3529131-1; Procedure ci_repair complete"); n.setSource("procedure"); n.setTimestamp(1405569317585l); n.setType(ci); n.setText("Assembly: rel0402; Environment: testmon; ci:artifact-app-3529131-1; " + "Procedure ci_repair complete!"); assertFalse(service.postMessage(n, sub)); }
### Question: EmailService implements NotificationSender { @Override public boolean postMessage(NotificationMessage msg, BasicSubscriber subscriber) { EmailSubscriber esub; if (subscriber instanceof EmailSubscriber) { esub = (EmailSubscriber) subscriber; } else { throw new ClassCastException("invalid subscriber " + subscriber.getClass().getName()); } List<String> emails = new ArrayList<>(); if (esub.getEmail() != null) { emails.add(esub.getEmail()); } if (emails.size() > 0) { EmailMessage emsg = buildEMessage(msg, emails); return sendEmail(emsg); } return true; } String getAwsAccessKey(); void setAwsAccessKey(String awsAccessKey); String getAwsSecretKey(); void setAwsSecretKey(String awsSecretKey); void init(); @Override boolean postMessage(NotificationMessage msg, BasicSubscriber subscriber); boolean sendEmail(EmailMessage eMsg); }### Answer: @Test public void postMessage() { NotificationMessage msg = new NotificationMessage(); EmailSubscriber sub = mock(EmailSubscriber.class); when(sub.getEmail()).thenReturn(null); boolean result = this.emailService.postMessage(msg, sub); assertTrue(result); }
### Question: Dispatcher { public void dispatch(NotificationMessage msg) { if (msg.getNsPath() == null) { String nsPath = getNsPath(msg); if (nsPath != null) { msg.setNsPath(nsPath); } else { logger.error("Can not figure out nsPath for msg " + gson.toJson(msg)); return; } } List<BasicSubscriber> subscribers = sbrService.getSubscribersForNs(msg.getNsPath()); try { for (BasicSubscriber sub : subscribers) { NotificationMessage nMsg = msg; if (sub.hasFilter() && !sub.getFilter().accept(nMsg)) { continue; } if (sub.hasTransformer()) { nMsg = sub.getTransformer().transform(nMsg); } if (sub instanceof EmailSubscriber) { eSender.postMessage(nMsg, sub); } else if (sub instanceof SNSSubscriber) { snsSender.postMessage(nMsg, sub); } else if (sub instanceof URLSubscriber) { if (sub.getFilter() instanceof NotificationFilter) { NotificationFilter nFilter = NotificationFilter.class.cast(sub.getFilter()); if (nFilter.isIncludeCi() && ArrayUtils.isNotEmpty(nFilter.getClassNames())) { final List<Long> ciIds = dpmtMapper .getDeploymentRfcCIs(msg.getCmsId(), null, null, nFilter.getClassNames(), nFilter.getActions()) .stream() .map(rfc -> rfc.getCiId()) .collect(Collectors.toList()); if(ciIds.isEmpty()){ continue; } final List<CmsCISimple> cis = cmProcessor.getCiByIdList(ciIds).stream() .map(ci -> cmsUtil.custCI2CISimple(ci, "df")).collect( Collectors.toList()); nMsg.setCis(cis); } } if(logger.isDebugEnabled()){ logger.debug("nMsg " + gson.toJson(nMsg)); } urlSender.postMessage(nMsg, sub); } else if (sub instanceof XMPPSubscriber) { xmppSender.postMessage(nMsg, sub); } else if (sub instanceof SlackSubscriber) { slackSender.postMessage(nMsg, sub); } } } catch (Exception e) { logger.error("Message dispatching failed.", e); } } @Autowired Dispatcher(Gson gson, SubscriberService sbrService, NotificationSender eSender, NotificationSender snsSender, NotificationSender urlSender, NotificationSender xmppSender, NotificationSender slackSender, CmsCmProcessor cmProcessor, CmsDpmtProcessor dpmtProcessor, OpsProcedureProcessor procProcessor, DJDpmtMapper dpmtMapper, CmsMdProcessor mdProcessor, CmsUtil cmsUtil); void dispatch(NotificationMessage msg); }### Answer: @Test public void testDispatch() { NotificationMessage notificationMessage = new NotificationMessage(); notificationMessage.setNsPath("/a/b"); notificationMessage.setType(NotificationType.ci); notificationMessage.setCmsId(TEST_CID); this.dispatcher.dispatch(notificationMessage); } @Test public void testDispatchNulNs() { NotificationMessage notificationMessage = new NotificationMessage(); notificationMessage.setNsPath(null); notificationMessage.setCmsId(TEST_CID); notificationMessage.setType(NotificationType.deployment); this.dispatcher.dispatch(notificationMessage); notificationMessage.setType(NotificationType.procedure); this.dispatcher.dispatch(notificationMessage); notificationMessage.setType(NotificationType.ci); this.dispatcher.dispatch(notificationMessage); }
### Question: AntennaListener implements MessageListener { public void onMessage(Message msg) { msgs.mark(); Context tc = msgTime.time(); try { NotificationMessage notify = null; if (msg instanceof TextMessage) { try { notify = parseMsg((TextMessage) msg); } catch (JsonParseException e) { logger.error("Got the bad message, not a valid json format - \n" + ((TextMessage) msg).getText() + "\n" + e.getMessage()); msg.acknowledge(); } } else if (msg instanceof ObjectMessage) { notify = (NotificationMessage) ((ObjectMessage) msg).getObject(); } if (notify != null) { logger.debug("Notification message received: " + notify.getText()); if (notify.getTimestamp() == 0) { notify.setTimestamp(System.currentTimeMillis()); } dispatcher.dispatch(notify); } msg.acknowledge(); } catch (Exception ex) { logger.error("Can't process the notification message.", ex); } finally { tc.stop(); } } @Autowired AntennaListener(Dispatcher dispatcher, Gson gson, MetricRegistry metrics); @Autowired void setDmlc(DefaultMessageListenerContainer dmlc); @PostConstruct void init(); void onMessage(Message msg); @Override String toString(); }### Answer: @Test public void onBadMessage() { TextMessage mockMessage = mock(TextMessage.class); try { when(mockMessage.getText()).thenReturn(""); } catch (JMSException e) { ; } this.listener.onMessage(mockMessage); }
### Question: CMSClient { public void updateProcedureState(DelegateExecution exec, CmsOpsProcedure proc) { NotificationMessage notify = new NotificationMessage(); notify.setType(NotificationType.procedure); if (proc.getProcedureState().equals(OpsProcedureState.active)) { proc.setProcedureState(OpsProcedureState.complete); } logger.info("Client: put:update ops procedure state to " + proc.getProcedureState()); try { opsProcedureProcessor.updateOpsProcedure(proc); deploymentNotifier.sendProcNotification(proc, exec); } catch (CmsBaseException e) { logger.error("CmsBaseException in updateProcedureState", e); e.printStackTrace(); throw e; } } void setCmsDpmtProcessor(CmsDpmtProcessor cmsDpmtProcessor); void setCmsCmProcessor(CmsCmProcessor cmsCmProcessor); void setOpsProcedureProcessor(OpsProcedureProcessor opsProcedureProcessor); void setCmsUtil(CmsUtil cmsUtil); void setControllerUtil(ControllerUtil controllerUtil); void setCmsWoProvider(CmsWoProvider cmsWoProvider); void setStepWoLimit(int stepWoLimit); void setRetryTemplate(RetryTemplate retryTemplate); void setRestTemplate(RestTemplate restTemplate); void setServiceUrl(String serviceUrl); void setTransUrl(String transUrl); void setCmsCrypto(CmsCrypto cmsCrypto); void getWorkOrderIds(DelegateExecution exec); List<CmsWorkOrderSimple> getWorkOrderIdsNoLimit(CmsDeployment dpmt, int execOrder); CmsWorkOrderSimple getWorkOrder(DelegateExecution exec, CmsWorkOrderSimple dpmtRec); CmsWorkOrderSimple getWorkOrder(CmsDeployment dpmt, WorkOrderContext woContext); void checkDpmt(DelegateExecution exec); void updateWoState(DelegateExecution exec, CmsWorkOrderSimple wo, String newState); void updateWoState(CmsDeployment dpmt, CmsWorkOrderSimple wo, String newState, String error); void updateWoState(CmsWorkOrderSimple wo, String newState, CmsDeployment dpmt, String execContextName, String error, Consumer<CmsDeployment> updateDpmtFunc); void setDpmtProcessId(DelegateExecution exec, CmsDeployment dpmt); void updateDeploymentAndNotify(CmsDeployment dpmt, String processId, String dpmtModel); void updateDpmtState(DelegateExecution exec, CmsDeployment dpmt, String newState); void updateDpmtState(CmsDeployment dpmt, String newState); void incExecOrder(DelegateExecution exec); List<CmsActionOrderSimple> getActionOrders(CmsOpsProcedure proc, int execOrder); void getActionOrders(DelegateExecution exec); void updateProcedureState(DelegateExecution exec, CmsOpsProcedure proc); void updateActionOrderState(DelegateExecution exec, CmsActionOrderSimple aos, String newState); void updateActionOrderState(CmsActionOrderSimple aos, OpsActionState newState); void failActionOrder(CmsActionOrder ao); void getEnv4Release(DelegateExecution exec); void commitAndDeployRelease(DelegateExecution exec); void setDeploymentNotifier(DeploymentNotifier deploymentNotifier); boolean getVarByMatchingCriteriaBoolean(String varNameLike, String criteria); static final String INPROGRESS; static final String CANCELLED; static final String COMPLETE; static final String FAILED; static final String PAUSED; static final String PENDING; static final String DPMT; static final String ONEOPS_SYSTEM_USER; }### Answer: @Test(priority=33) public void updateProcedureStateTest(){ DelegateExecution exec = mock(DelegateExecution.class); CmsCI anchorCi = mock( CmsCI.class); when(anchorCi.getCiId()).thenReturn(TEST_CI_ID); when(anchorCi.getNsPath()).thenReturn("/x/y/z.1"); when(anchorCi.getCiName()).thenReturn("CI_NAME_A"); when(anchorCi.getCiClassName()).thenReturn("CI_CLASS_A"); when(exec.getVariable("procanchor")).thenReturn(anchorCi); CmsOpsProcedure proc = new CmsOpsProcedure(); proc.setProcedureState(OpsProcedureState.active); cc.updateProcedureState(exec, proc); }
### Question: InductorPublisher { protected String getCtxtId(CmsWorkOrderSimpleBase wo) { String ctxtId = ""; if (wo instanceof CmsWorkOrderSimple) { CmsWorkOrderSimple woSimple = CmsWorkOrderSimple.class.cast(wo); ctxtId = "d-" + woSimple.getDeploymentId() + "-" + woSimple.rfcCi.getRfcId() + "-" + woSimple.rfcCi.getExecOrder() + "-" + woSimple.rfcCi.getCiId(); } else if (wo instanceof CmsActionOrderSimple) { CmsActionOrderSimple ao = CmsActionOrderSimple.class.cast(wo); ctxtId = "a-" + ao.getProcedureId() + "-" + ao.getActionId() + "-" + ao.getCiId(); } return ctxtId; } void setConnFactory(ActiveMQConnectionFactory connFactory); void init(); void publishMessage(DelegateExecution exec, String waitTaskName, String woType); void publishMessage(String processId, String execId, CmsWorkOrderSimpleBase wo, String waitTaskName, String woType); void getConnectionStats(); void cleanup(); void closeConnection(); }### Answer: @Test public void getCtxtId(){ CmsActionOrderSimple ao = new CmsActionOrderSimple(); ao.setProcedureId(1234); ao.setActionId(456); ao.setCiId(789); Assert.assertEquals("a-1234-456-789",publisher.getCtxtId(ao)); } @Test public void getCtxtIdForDeployment(){ CmsWorkOrderSimple wo = new CmsWorkOrderSimple(); wo.setDeploymentId(1234); CmsRfcCISimple rfc = new CmsRfcCISimple(); rfc.setRfcId(456); rfc.setCiId(789); rfc.setExecOrder(5); wo.rfcCi=rfc; Assert.assertEquals("d-1234-456-5-789",publisher.getCtxtId(wo)); }
### Question: InductorPublisher { String getQueue(CmsWorkOrderSimpleBase wo) { String queueName = null; String location = wo.getCloud().getCiAttributes().get("location"); if ("true".equals(System.getProperty(USE_SHARED_FLAG))) { String cloudName = StringUtils.substringAfterLast(location, "/"); if (StringUtils.isNotBlank(cloudName)) { String prefix = StringUtils.substringBefore(cloudName, "-"); String queuePrefix = System.getProperty(SHARED_QUEUE_PREFIX + prefix); if (StringUtils.isNotBlank(queuePrefix)) { queueName = queuePrefix + "." + SHARED_QUEUE; } } if (queueName == null) queueName = SHARED_QUEUE; } else { queueName = (location.replaceAll("/", ".") + QUEUE_SUFFIX).substring( 1); } return queueName; } void setConnFactory(ActiveMQConnectionFactory connFactory); void init(); void publishMessage(DelegateExecution exec, String waitTaskName, String woType); void publishMessage(String processId, String execId, CmsWorkOrderSimpleBase wo, String waitTaskName, String woType); void getConnectionStats(); void cleanup(); void closeConnection(); }### Answer: @Test public void getQueueForWo() { CmsWorkOrderSimple wo = new CmsWorkOrderSimple(); CmsCISimple cloud = new CmsCISimple(); cloud.setCiName("openstack-cld1"); wo.setCloud(cloud); cloud.addCiAttribute("location", "/public/oneops/clouds/openstack-cld1"); String queue = publisher.getQueue(wo); Assert.assertEquals(queue, "public.oneops.clouds.openstack-cld1.ind-wo"); cloud.addCiAttribute("location", "/public/oneops/clouds/azure-japaneast-test"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "public.oneops.clouds.azure-japaneast-test.ind-wo"); System.setProperty("com.oneops.controller.use-shared-queue", "true"); cloud.addCiAttribute("location", "/public/oneops/clouds/openstack-cld1"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "shared.ind-wo"); cloud.addCiAttribute("location", "/public/oneops/clouds/azure-japaneast-test"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "shared.ind-wo"); System.setProperty("com.oneops.controller.queue.prefix.azure", "azure"); cloud.addCiAttribute("location", "/public/oneops/clouds/openstack-cld1"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "shared.ind-wo"); cloud.addCiAttribute("location", "/public/oneops/clouds/azure-japaneast-test"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "azure.shared.ind-wo"); cloud.addCiAttribute("location", "/public/oneops/clouds/testcloud"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "shared.ind-wo"); cloud.addCiAttribute("location", "cld2"); queue = publisher.getQueue(wo); Assert.assertEquals(queue, "shared.ind-wo"); }
### Question: InductorPublisher { public void cleanup() { logger.info("Closing AMQ connection"); closeConnection(); } void setConnFactory(ActiveMQConnectionFactory connFactory); void init(); void publishMessage(DelegateExecution exec, String waitTaskName, String woType); void publishMessage(String processId, String execId, CmsWorkOrderSimpleBase wo, String waitTaskName, String woType); void getConnectionStats(); void cleanup(); void closeConnection(); }### Answer: @Test (priority=2) public void cleanupTest() throws Exception{ publisher.getConnectionStats(); publisher.cleanup(); }
### Question: CmsListener implements MessageListener { public void onMessage(Message message) { try { if (message instanceof TextMessage) { try { logger.info("got message: " + ((TextMessage) message).getText()); processMessage((TextMessage) message); } catch (ActivitiException ae) { logger.error("ActivityException in onMessage", ae); throw ae; } } } catch (JMSException e) { logger.error("JMSException in onMessage", e); } } void init(); void onMessage(Message message); void getConnectionStats(); void cleanup(); void setConsumerName(String consumerName); void setCmsClient(CMSClient cmsClient); void setDeployerEnabled(boolean deployerEnabled); void setExecutionManager(ExecutionManager executionManager); void setNotifier(DeploymentNotifier notifier); void setConnFactory(ActiveMQConnectionFactory connFactory); void setWfController(WorkflowController wfController); }### Answer: @Test public void msgOpsProcedure() throws Exception{ TextMessage message = mock(TextMessage.class); when(message.getStringProperty("source")).thenReturn("opsprocedure"); when(message.getJMSCorrelationID()).thenReturn(null); String msgJson = gson.toJson(createCmsOpsProcedure(OpsProcedureState.active)); when(message.getText()).thenReturn(msgJson); listener.onMessage(message); when(message.getText()).thenReturn(gson.toJson(createCmsOpsProcedure(OpsProcedureState.discarded))); listener.onMessage(message); } @Test public void msgRelease() throws Exception{ TextMessage message = mock(TextMessage.class); when(message.getStringProperty("source")).thenReturn("release"); String msgJson = gson.toJson(createCmsRelease("active")); when(message.getText()).thenReturn(msgJson); listener.onMessage(message); when(message.getText()).thenReturn(gson.toJson(createCmsRelease("aintactive"))); listener.onMessage(message); } @Test public void testBadMessage() throws Exception{ TextMessage message = mock(TextMessage.class); when (message.getText()).thenThrow(new JMSException("mock-forces-errorJMS")); listener.onMessage(message); }
### Question: InductorListener implements MessageListener { public void onMessage(Message message) { try { if (message instanceof TextMessage) { if (logger.isDebugEnabled()) { logger.debug("got message: " + ((TextMessage) message).getText()); } try { processResponseMessage((TextMessage) message); } catch (ActivitiException ae) { logger.error("ActivityException in onMessage ", ae); logger.error("Will retry in 10 seconds \n" + ((TextMessage) message).getText()); throw ae; } } } catch (JMSException e) { logger.error("JMSException in onMessage", e); } } SensorClient getSensorClient(); void setSensorClient(SensorClient sensorClient); void setControllerUtil(ControllerUtil controllerUtil); void setWfController(WorkflowController wfController); void setConnFactory(ActiveMQConnectionFactory connFactory); void setWoPublisher(WoPublisher woPublisher); void init(); void onMessage(Message message); void getConnectionStats(); void cleanup(); void setExecutionManager(ExecutionManager executionManager); }### Answer: @Test public void testBadMessage() throws JMSException { TextMessage message = mock(TextMessage.class); when(message.getJMSCorrelationID()).thenThrow(new JMSException("mock-force")); listener.onMessage(message); }
### Question: WorkflowController { public String startReleaseProcess(String processKey, Map<String,Object> params){ logger.info("starting process for " + processKey + " with params: " + params.toString()); ProcessInstance pi = runtimeService.startProcessInstanceByKey(processKey, params); logger.info("started process with id - " + pi.getId()); return pi.getId(); } DeploymentNotifier getNotifier(); void setNotifier(DeploymentNotifier notifier); void setRuntimeService(RuntimeService runtimeService); String startDpmtProcess(String processKey, Map<String,Object> params); String startReleaseProcess(String processKey, Map<String,Object> params); String startOpsProcess(String processKey, Map<String,Object> params); void pokeProcess(String processId); void pokeSubProcess(String processId, String executionId, Map<String,Object> params); void checkSyncWait(String processId, String executionId); static final String WO_SUBMITTED; static final String WO_FAILED; static final String WO_RECEIVED; static final String WO_STATE; static final String SUB_PROC_END_VAR; }### Answer: @Test public void startReleaseProcessTest(){ Map<String, Object> params = new HashMap<String, Object>(); params.put("k", "v"); wfc.setRuntimeService(runtimeServiceExecutionMock); String pid = wfc.startReleaseProcess(RUNNER_PID, params); assertEquals(pid,NEW_PID); }
### Question: WorkflowController { public String startOpsProcess(String processKey, Map<String,Object> params){ logger.info("starting process for " + processKey + " with params: " + params.toString()); ProcessInstance pi = runtimeService.startProcessInstanceByKey(processKey, params); logger.info("started process with id - " + pi.getId()); return pi.getId(); } DeploymentNotifier getNotifier(); void setNotifier(DeploymentNotifier notifier); void setRuntimeService(RuntimeService runtimeService); String startDpmtProcess(String processKey, Map<String,Object> params); String startReleaseProcess(String processKey, Map<String,Object> params); String startOpsProcess(String processKey, Map<String,Object> params); void pokeProcess(String processId); void pokeSubProcess(String processId, String executionId, Map<String,Object> params); void checkSyncWait(String processId, String executionId); static final String WO_SUBMITTED; static final String WO_FAILED; static final String WO_RECEIVED; static final String WO_STATE; static final String SUB_PROC_END_VAR; }### Answer: @Test public void startOpsProcessTest(){ Map<String, Object> params = new HashMap<String, Object>(); params.put("k", "v"); wfc.setRuntimeService(runtimeServiceExecutionMock); String pid = wfc.startOpsProcess(RUNNER_PID, params); assertEquals(pid,NEW_PID); }
### Question: WoDispatcher { public void processWOResult(WoProcessResponse woResult) { String[] props = woResult.getProcessId().split("!"); String processId = props[0]; String executionId = props[1]; logger.info("Got inductor respose"); logger.info(gson.toJson(woResult)); Map<String, Object> params = new HashMap<String, Object>(); params.put("wo", woResult.getWo()); params.put(WorkflowController.WO_STATE, woResult.getWoProcessResult()); wfController.pokeSubProcess(processId, executionId, params); } void setCmsClient(CMSClient cmsClient); void setInductorPublisher(InductorPublisher inductorPublisher); void setWfController(WorkflowController wfController); void dispatchAndUpdate(CmsDeployment dpmt, WorkOrderContext woContext); void dispatchWO(WorkOrderContext woContext, CmsWorkOrderSimple assembledWo); void publishMessage(CmsActionOrderSimple ao, String woType); void dispatchWO(DelegateExecution exec, CmsWorkOrderSimple wo, String waitTaskName); void processWOResult(WoProcessResponse woResult); void getAndDispatch(DelegateExecution exec, CmsWorkOrderSimple dpmtRec); void setSensorClient(SensorClient sensorClient); }### Answer: @Test public void processWORResultTest(){ WoProcessResponse woResultOut = new WoProcessResponse(); woResultOut.setWoProcessResult("result-mocked"); woResultOut.setProcessId("11!22!33"); CmsWorkOrderSimple woResult = new CmsWorkOrderSimple(); woResultOut.setWo(woResult); wod.processWOResult(woResultOut); }
### Question: WoDispatcher { public void dispatchWO(WorkOrderContext woContext, CmsWorkOrderSimple assembledWo) throws Exception { try { if (assembledWo.rfcCi.getImpl() == null) { inductorPublisher.publishMessage( Long.toString(assembledWo.getDeploymentId()), Long.toString(assembledWo.getDpmtRecordId()), assembledWo, "", "deploybom"); } else { String[] implParts = assembledWo.rfcCi.getImpl().split("::"); if ("class".equalsIgnoreCase(implParts[0])) { WoProcessor wop = (WoProcessor) Class.forName(implParts[1]).newInstance(); String processComplexId = Integer.toString(woContext.getExecOrder()); WoProcessRequest wopr = new WoProcessRequest(); wopr.setProcessId(processComplexId); wopr.setWo(assembledWo); wop.processWo(wopr); } else { inductorPublisher.publishMessage( Long.toString(assembledWo.getDeploymentId()), Long.toString(assembledWo.getDpmtRecordId()), assembledWo, "", "deploybom"); } } } catch (Exception e) { logger.error("unable to dispatch", e); woContext.setWoDispatchError(e.getMessage()); throw e; } } void setCmsClient(CMSClient cmsClient); void setInductorPublisher(InductorPublisher inductorPublisher); void setWfController(WorkflowController wfController); void dispatchAndUpdate(CmsDeployment dpmt, WorkOrderContext woContext); void dispatchWO(WorkOrderContext woContext, CmsWorkOrderSimple assembledWo); void publishMessage(CmsActionOrderSimple ao, String woType); void dispatchWO(DelegateExecution exec, CmsWorkOrderSimple wo, String waitTaskName); void processWOResult(WoProcessResponse woResult); void getAndDispatch(DelegateExecution exec, CmsWorkOrderSimple dpmtRec); void setSensorClient(SensorClient sensorClient); }### Answer: @Test public void distachWOTest(){ DelegateExecution delegateExecution = mock(DelegateExecution.class); CmsWorkOrderSimple cmsWorkOrderSimple = new CmsWorkOrderSimple(); CmsRfcCISimple rfcCi = new CmsRfcCISimple(); rfcCi.setImpl("class::com.oneops.controller.workflow.WoProcessorMockImpl::rfc::impl"); cmsWorkOrderSimple.rfcCi= rfcCi; when(delegateExecution.getVariable("wo")).thenReturn(cmsWorkOrderSimple); when(delegateExecution.getId()).thenReturn("88888"); when(delegateExecution.getProcessInstanceId()).thenReturn("55555"); wod.dispatchWO(delegateExecution, cmsWorkOrderSimple, "mock-waiter"); }
### Question: StmtBuilder { public ThresholdStatements getThresholdStatements(long manifestId, String source, long checksum, String thresholdsJson, boolean isHeartbeat, String hbDuration) { ThresholdStatements trStatements = new ThresholdStatements(); trStatements.setChecksum(checksum); if (thresholdsJson != null && thresholdsJson.length() > THRESHOLDS_JSON_SIZE_FLOOR) { Type mapType = new TypeToken<Map<String, ThresholdDef>>() { }.getType(); Map<String, ThresholdDef> trsholds = gson.fromJson(thresholdsJson, mapType); for (String trsName : trsholds.keySet()) { ThresholdDef trDef = trsholds.get(trsName); if (trDef.getTrigger() != null) { String eplStmt = buildTriggerStmt(manifestId, source, trsName, trDef); String eplName = source + ":" + trsName + "-" + manifestId + "-trigger"; SensorStatement stmt = new SensorStatement(eplName, eplStmt, "OpsEventListener"); trStatements.addStatement(stmt); } if (trDef.getReset() != null) { String eplStmt = buildResetStmt(manifestId, source, trsName, trDef); String eplName = source + ":" + trsName + "-" + manifestId + "-reset"; SensorStatement stmt = new SensorStatement(eplName, eplStmt, null); trStatements.addStatement(stmt); } } } if (isHeartbeat) { String eplStmt = buildHeartbeatStmt(manifestId, source, hbDuration); trStatements.setHeartbeat(true); trStatements.setHbDuration(hbDuration); String eplName = source + ":Heartbeat-" + manifestId; SensorStatement stmt = new SensorStatement(eplName, eplStmt, "OpsEventListener"); trStatements.addStatement(stmt); } return trStatements; } StmtBuilder(); String buildTriggerStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildResetStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildHeartbeatStmt(long manifestId, String source, String duration); ThresholdStatements getThresholdStatements(long manifestId, String source, long checksum, String thresholdsJson, boolean isHeartbeat, String hbDuration); static final int THRESHOLDS_JSON_SIZE_FLOOR; final static String STMT_RESET; final static String STMT_RESET_HEARTBEAT; final static String STMT_RETRIGGER_HEARTBEAT; final static String STMT_TRIGGER_CHANNELDOWN; final static String STMT_DELAY_PERF_EVENT; }### Answer: @Test public void getThreshStmtTest() { StmtBuilder builder = new StmtBuilder(); Gson gson = new Gson(); Map<String, ThresholdDef> trsholds = new HashMap<>(); trsholds.put(NAME_THRESH, THRESH_DEF); String thresholdsJson = gson.toJson(trsholds); ThresholdStatements stmt = builder.getThresholdStatements(MANI_ID, SOURCE, 1414141410, thresholdsJson, true, String.valueOf(DURATION)); assertTrue(stmt.getStatements().size() > 1); }
### Question: CtrlrServlet { @RequestMapping(method=RequestMethod.POST, value="/wo/result") @ResponseBody public Map<String, String> createCIRelation( @RequestBody WoProcessResponse woResult) { woDispatcher.processWOResult(woResult); return null; } void setRuntimeService(RuntimeService runtimeService); void setWoDispatcher(WoDispatcher woDispatcher); void init(); @RequestMapping(method=RequestMethod.POST, value="/wo/result") @ResponseBody Map<String, String> createCIRelation( @RequestBody WoProcessResponse woResult); @RequestMapping(method=RequestMethod.GET, value="/resumeall") @ResponseBody String test(); }### Answer: @Test public void createCIRTest(){ this.servlet.createCIRelation(null); }
### Question: CtrlrServlet { @RequestMapping(method=RequestMethod.GET, value="/resumeall") @ResponseBody public String test() { logger.info("Resuming crashed processes!!!"); List<ProcessInstance> processes = runtimeService.createProcessInstanceQuery().active().list(); for (ProcessInstance process : processes) { ExecutionEntity exec = (ExecutionEntity)process; if (exec.isActive() && exec.getActivityId().equals("ackStart")) { exec.getId(); runtimeService.signal(exec.getId()); } } return "Resumed all processes"; } void setRuntimeService(RuntimeService runtimeService); void setWoDispatcher(WoDispatcher woDispatcher); void init(); @RequestMapping(method=RequestMethod.POST, value="/wo/result") @ResponseBody Map<String, String> createCIRelation( @RequestBody WoProcessResponse woResult); @RequestMapping(method=RequestMethod.GET, value="/resumeall") @ResponseBody String test(); }### Answer: @Test public void test(){ String message= this.servlet.test(); assertEquals(message,"Resumed all processes"); }
### Question: FqdnExecutor implements ComponentWoExecutor { @Override public Response execute(CmsWorkOrderSimple wo, String dataDir) { String logKey = woHelper.getLogKey(wo); if (isFqdnInstance(wo) && isLocalWo(wo) && isGdnsEnabled(wo) && isTorbitServiceType(wo)) { executeInternal(wo, logKey, "deployment", dataDir, (t, i) -> { if (isGslbDeleteAction(wo)) { GslbResponse response = gslbProvider.delete(provisionedGslb(wo, t, i, logKey)); updateWoResult(wo, response, logKey); } else { GslbProvisionResponse response = gslbProvider.create(getGslbRequestFromWo(wo, t, i, logKey)); updateWoResult(wo, response, logKey); } }); return woHelper.formResponse(wo, logKey); } logger.info(logKey + "not executing by FqdnExecutor as these conditions are not met :: " + "[fqdn service_type set as torbit && gdns enabled for env && local workorder && torbit cloud service configured]"); return Response.getNotMatchingResponse(); } FqdnExecutor(); @Override List<String> getComponentClasses(); @Override Response execute(CmsWorkOrderSimple wo, String dataDir); @Override Response execute(CmsActionOrderSimple ao, String dataDir); @Override Response verify(CmsWorkOrderSimple wo, Response response); static final String LB_PAYLOAD; static final String CLOUDS_PAYLOAD; static final String ATTRIBUTE_DNS_RECORD; }### Answer: @Test public void shouldNotMatchIfGdnsDisabled() { CmsWorkOrderSimple wo = woWith2Clouds(); wo.getPayLoadEntry("Environment").get(0).addCiAttribute("global_dns", "false"); Response response = fqdnExecutor.execute(wo, "/tmp"); assertThat(response.getResult(), is(Result.NOT_MATCHED)); } @Test public void shouldNotMatchForLocalWo() { CmsWorkOrderSimple wo = woWith2Clouds(); wo.getPayLoadEntry("Environment").get(0).addCiAttribute("global_dns", "false"); wo.addPayLoadEntry("ManagedVia", new CmsRfcCISimple()); Response response = fqdnExecutor.execute(wo, "/tmp"); assertThat(response.getResult(), is(Result.NOT_MATCHED)); } @Test public void failForMissingGdnsConfig() { CmsWorkOrderSimple wo = woWith2Clouds(); wo.getRfcCi().setRfcAction("update"); wo.services.remove("torbit"); Response response = fqdnExecutor.execute(wo, "/tmp"); assertThat(response.getResult(), is(Result.FAILED)); } @Test public void failForMissingDnsConfig() { CmsWorkOrderSimple wo = woWith2Clouds(); wo.services.remove("dns"); Response response = fqdnExecutor.execute(wo, "/tmp"); assertThat(response.getResult(), is(Result.FAILED)); } @Test public void dontMatchAoWithDifferentServiceType() { CmsActionOrderSimple ao = ao(); ao.getCi().getCiAttributes().put("service_type", "netscaler"); Response response = fqdnExecutor.execute(ao, "/tmp"); assertThat(response.getResult(), is(Result.NOT_MATCHED)); } @Test public void failAoForMissingGdnsService() { CmsActionOrderSimple ao = ao(); ao.getServices().remove("torbit"); Response response = fqdnExecutor.execute(ao, "/tmp"); assertThat(response.getResult(), is(Result.FAILED)); } @Test public void failAoWithMissingDnsService() { CmsActionOrderSimple ao = ao(); ao.getServices().remove("dns"); Response response = fqdnExecutor.execute(ao, "/tmp"); assertThat(response.getResult(), is(Result.FAILED)); }
### Question: ProcessRunner { public ProcessResult executeProcessRetry(ExecutionContext executionContext) { boolean shutdown = config.hasCloudShutdownFor(executionContext.getWo()); int maxRetries = executionContext.getRetryCount(); if (shutdown) { maxRetries = 0; long timeout = config.getCmdTimeout(); for (int i = 0; i < executionContext.getCmd().length; i++) { if (executionContext.getCmd()[i].startsWith("--timeout=")) { executionContext.getCmd()[i] = "--timeout=" + timeout; } } } ProcessResult result = executeProcessRetry(executionContext.getCmd(), executionContext.getLogKey(), maxRetries, InductorConstants.PRIVATE_IP); if (shutdown) { logger.warn(executionContext.getLogKey() + " ### Set the result code to 0 as the cloud resource for this component is already released."); result.setResultCode(0); } return result; } ProcessRunner(Config config); int getTimeoutInSeconds(); void setTimeoutInSeconds(int timeoutInSeconds); ProcessResult executeProcessRetry(ExecutionContext executionContext); ProcessResult executeProcessRetry(String[] cmd, String logKey, int max_retries); ProcessResult executeProcessRetry(String[] cmd, String logKey); ProcessResult executeProcessRetry(String[] cmd, String logKey, int max_retries, String ip_attribute); void executeProcess(String[] cmd, String logKey, ProcessResult result, Map<String, String> additionalEnvVars, File workingDir); Map<String, String> getEnvVars(String[] cmd, Map<String, String> extraVars); }### Answer: @Test public void testExecuteProcessRetry() { Config c = new Config(); c.setChefTimeout(10); ProcessRunner pr = new ProcessRunner(c); String[] cmd = new String[2]; cmd[0] = "echo"; cmd[1] = "\"hey there \""; ProcessResult procResult = pr.executeProcessRetry(cmd, "", 3); assertTrue(procResult.getResultCode() == 0); } @Test public void testExecuteProcessTimeout() { Config c = new Config(); c.setChefTimeout(1); ProcessRunner pr = new ProcessRunner(c); String[] cmd = new String[2]; cmd[0] = "sleep"; cmd[1] = "10s"; ProcessResult procResult = pr.executeProcessRetry(cmd, "", 3); assertTrue(procResult.getResultCode() == 143); }
### Question: StmtBuilder { public String buildTriggerStmt(long manifestId, String source, String trsName, ThresholdDef def) { String name = source + ":" + trsName; int duration = def.getTrigger().getDuration(); duration = (duration > WNDW_SIZE_MAX) ? WNDW_SIZE_MAX : duration; String coolOff = def.getCooloff(); coolOff = (coolOff != null) ? coolOff : "15"; return new StringBuilder(450) .append("insert into OpsEvent select ciId, manifestId, timestamp, bucket, metrics, 'open' as state, 'metric' as type, source, ") .append(coolOff).append(" as coolOff, ") .append("'").append(name).append("'") .append(" as name, ") .append("'").append(def.getState()).append("'") .append(" as ciState, count(1) as count from PerfEvent(manifestId = ") .append(manifestId) .append(" and bucket = ") .append("'").append(def.getBucket()).append("'") .append(" and source = ") .append("'").append(source).append("'") .append(" and (metrics.") .append(def.getStat()) .append("('").append(def.getMetric()).append("') ") .append(def.getTrigger().getOperator()) .append(" ").append(def.getTrigger().getValue()).append(")).") .append("win:time(") .append(duration) .append(" min) group by ciId having count(1)>=") .append(def.getTrigger().getNumocc()) .append(" output first every ") .append(coolOff) .append(" minutes").toString(); } StmtBuilder(); String buildTriggerStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildResetStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildHeartbeatStmt(long manifestId, String source, String duration); ThresholdStatements getThresholdStatements(long manifestId, String source, long checksum, String thresholdsJson, boolean isHeartbeat, String hbDuration); static final int THRESHOLDS_JSON_SIZE_FLOOR; final static String STMT_RESET; final static String STMT_RESET_HEARTBEAT; final static String STMT_RETRIGGER_HEARTBEAT; final static String STMT_TRIGGER_CHANNELDOWN; final static String STMT_DELAY_PERF_EVENT; }### Answer: @Test public void buildTriggerStmtTest() { String triggerStmt = "insert into OpsEvent select ciId, manifestId, timestamp, bucket, metrics, 'open' as state, 'metric' " + "as type, source, 15 as coolOff, 'opsmq-compute-cpu:HighCpuUtil' as name, 'notify' as ciState, count(1) as count from " + "PerfEvent(manifestId = 4823266 and bucket = '1h' and source = 'opsmq-compute-cpu' and (metrics.avg('CpuIdle') " + "<= 20.0)).win:time(5 min) group by ciId having count(1)>=1 output first every 15 minutes"; ThresholdDef thrDef = new ThresholdDef(); thrDef.setBucket("1h"); thrDef.setCooloff("15"); thrDef.setMetric("CpuIdle"); thrDef.setName("sum"); thrDef.setStat("avg"); thrDef.setState("notify"); StmtParams params = thrDef.new StmtParams(); params.setNumocc(1); params.setOperator("<="); params.setValue(20.0); params.setDuration(5); thrDef.setTrigger(params); StmtBuilder builder = new StmtBuilder(); String stmt = builder.buildTriggerStmt(4823266, "opsmq-compute-cpu", "HighCpuUtil", thrDef); System.out.println(stmt); assertEquals(triggerStmt, stmt); }
### Question: OpampWsController { @RequestMapping(value="/status/{ciId}", method = RequestMethod.GET) @ResponseBody public String getCIOpenEvents(@PathVariable long ciId) { logger.info(ciId); return null; } @RequestMapping(value="/status/{ciId}", method = RequestMethod.GET) @ResponseBody String getCIOpenEvents(@PathVariable long ciId); @RequestMapping(value = "/cache/stats", method = RequestMethod.GET) @ResponseBody Map<String, Object> getCacheStats(); @RequestMapping(value = "/cache/clear", method = RequestMethod.DELETE) @ResponseBody Map<String, Object> clearCache(); @RequestMapping(value = "/cache/entries", method = RequestMethod.GET) @ResponseBody ResponseEntity<Map<String, Object>> getCacheEntries(); @RequestMapping(value = "/cache/entry", method = RequestMethod.GET) @ResponseBody ResponseEntity<Map<String, Object>> getCacheEntry( @RequestParam(value = "key", required = true) String key); @RequestMapping(value = "/cache/entry", method = RequestMethod.DELETE) @ResponseBody ResponseEntity<Map<String, Object>> deleteCacheEntry(@RequestParam(value = "key", required = true) String key); }### Answer: @Test public void testController(){ OpampWsController wsController = new OpampWsController(); String eventsOut = wsController.getCIOpenEvents(-1); assertNull(eventsOut); }
### Question: BadStateProcessor { public void processGoodState( CiChangeStateEvent event) { notifier.sendOpsEventNotification(event); } void setOpsProcProcessor(OpsProcedureProcessor opsProcProcessor); void setCoProcessor(CiOpsProcessor coProcessor); void setEnvProcessor(EnvPropsProcessor envProcessor); void setCmProcessor(CmsCmProcessor cmProcessor); OpsManager getOpsManager(); void setOpsManager(OpsManager opsManager); CmsCmManager getCmManager(); void setCmManager(CmsCmManager cmManager); void setNotifier(Notifications notifier); RestTemplate getRestTemplate(); void setRestTemplate(RestTemplate restTemplate); String getTransistorUrl(); void setTransistorUrl(String transistorUrl); void processUnhealthyState(CiChangeStateEvent event); void replace(long ciId, CmsCI env, String userId, String description); void processGoodState( CiChangeStateEvent event); void submitRepairProcedure(CiChangeStateEvent event, boolean exponentialDelay, long unhealthyStartTime, long repairRetriesCount, long coolOffPeriodMillis); static long getNextRepairTime(long delayStartTime, long coolOffPeriod, double exponentialFactor, long repairRetriesCountSinceDelay, long repairRetriesMaxPeriod); void processDefunctState(CiChangeStateEvent event); Map<String, Integer> replaceByCid(long ciId, String XCmsUser, String description); EventUtil getEventUtil(); void setEventUtil(EventUtil eventUtil); int getStartExponentialDelayAfterProcedures(); void setStartExponentialDelayAfterProcedures(int startExponentialDelayAfterProcedures); double getExponentialBackoffFactor(); void setExponentialBackoffFactor(double exponentialBackoffFactor); int getMaxDaysRepair(); void setMaxDaysRepair(int maxDaysRepair); void setMaxPastDaysForProcedureCount(int maxPastDaysForProcedureCount); }### Answer: @Test public void processGoodStateTest(){ Long aCid = 678L; BadStateProcessor bsp = new BadStateProcessor(); bsp.setNotifier(mock(Notifications.class)); EnvPropsProcessor envProcessorMock= mock(EnvPropsProcessor.class); CmsCI cmsCI = new CmsCI(); when(envProcessorMock.isAutorepairEnabled(aCid)).thenReturn(true); bsp.setEnvProcessor(envProcessorMock); CmsCmProcessor cmProcessor = mock(CmsCmProcessor.class); List<CmsCIRelation> dependsList =new ArrayList<CmsCIRelation>(); CmsCIRelation relation=new CmsCIRelation(); relation.setFromCiId(aCid ); dependsList.add(relation); when(cmProcessor.getToCIRelationsNakedNoAttrs(aCid, null, "DependsOn", null)).thenReturn(dependsList); bsp.setCmProcessor(cmProcessor); when(cmProcessor.getFromCIRelationsNakedNoAttrs(aCid, null, "DependsOn", null)).thenReturn(dependsList); CiOpsProcessor copMock=mock(CiOpsProcessor.class); when(copMock.getCIstate(aCid)).thenReturn("unhealthy"); bsp.setCoProcessor(copMock); CiChangeStateEvent changeEvent = new CiChangeStateEvent(); OpsBaseEvent event = new OpsBaseEvent(); event.setCiId(aCid); EventUtil eventUtil = mock(EventUtil.class); bsp.setEventUtil(eventUtil); when(eventUtil.getOpsEvent(changeEvent)).thenReturn(event); bsp.processGoodState(changeEvent); }
### Question: FlexStateProcessor { public void processOverutilized(CiChangeStateEvent event, boolean isNewState) throws OpampException{ long ciId = event.getCiId(); if (CI_STATE_OVERUTILIZED.equals(coProcessor.getCIstate(ciId))) { CmsCI env; if (envProcessor.isAutoscaleEnabled(ciId) && (env = envProcessor.getEnv4Bom(ciId)) != null) { if (envProcessor.isCloudActive4Bom(ciId)) { growPool(event, env, isNewState); } else { notifier.sendFlexNotificationInactiveCloud(event, CI_STATE_OVERUTILIZED); } } else { notifier.sendFlexNotificationNoRepair(event, CI_STATE_OVERUTILIZED); } } else { logger.info("Ci is good now - " + ciId); } } void setCmProcessor(CmsCmProcessor cmProcessor); void setEnvProcessor(EnvPropsProcessor envProcessor); void setCoProcessor(CiOpsProcessor coProcessor); void setNotifier(Notifications notifier); void setRestTemplate(RestTemplate restTemplate); void setTransistorUrl(String transistorUrl); void processOverutilized(CiChangeStateEvent event, boolean isNewState); void processUnderutilized(CiChangeStateEvent event, boolean isNewState, long originalEventTimestamp); static final String CI_STATE_OVERUTILIZED; static final String CI_STATE_UNDERUTILIZED; }### Answer: @Test public void processOverutilized(){ CiOpsProcessor cop = mock(CiOpsProcessor.class); when(cop.getCIstate(ID_WITH_AUTO_SCALING)).thenReturn("overutilized"); when(cop.getCIstate(ID_WITHOUT_AUTO_SCALING)).thenReturn("other-state"); FlexStateProcessor fsp = new FlexStateProcessor(); fsp.setCoProcessor(cop); fsp.setEnvProcessor(envProcessorMock); fsp.setCmProcessor(cmProcessorMock); fsp.setNotifier(notifierMock); fsp.setRestTemplate(restTemplateMock); fsp.setTransistorUrl(null); try { CiChangeStateEvent event = new CiChangeStateEvent(); event.setCiId(ID_WITH_AUTO_SCALING); fsp.processOverutilized(event, true); event = new CiChangeStateEvent(); event.setCiId(ID_WITHOUT_AUTO_SCALING); fsp.processOverutilized(event, true); event = new CiChangeStateEvent(); event.setCiId(ID_WITHOUT_AUTO_REPAIR); fsp.processOverutilized(event, true); } catch (OpampException e) { logger.warn("Not expected to catch here ",e); throw new RuntimeException(e); } }
### Question: FlexStateProcessor { public void processUnderutilized(CiChangeStateEvent event, boolean isNewState, long originalEventTimestamp) throws OpampException{ long ciId = event.getCiId(); if ("underutilized".equals(coProcessor.getCIstate(ciId))) { CmsCI env; if (envProcessor.isAutoscaleEnabled(ciId) && (env = envProcessor.getEnv4Bom(ciId))!=null){ if (envProcessor.isCloudActive4Bom(ciId)) { shrinkPool(event, env, isNewState, originalEventTimestamp); } else { notifier.sendFlexNotificationInactiveCloud(event, "underutilized"); } } else { notifier.sendFlexNotificationNoRepair(event, "underutilized"); } } else { logger.info("Ci is good now - " + ciId); } } void setCmProcessor(CmsCmProcessor cmProcessor); void setEnvProcessor(EnvPropsProcessor envProcessor); void setCoProcessor(CiOpsProcessor coProcessor); void setNotifier(Notifications notifier); void setRestTemplate(RestTemplate restTemplate); void setTransistorUrl(String transistorUrl); void processOverutilized(CiChangeStateEvent event, boolean isNewState); void processUnderutilized(CiChangeStateEvent event, boolean isNewState, long originalEventTimestamp); static final String CI_STATE_OVERUTILIZED; static final String CI_STATE_UNDERUTILIZED; }### Answer: @Test public void processUnderutilized(){ CiOpsProcessor cop = mock(CiOpsProcessor.class); when(cop.getCIstate(ID_WITH_AUTO_SCALING)).thenReturn("underutilized"); when(cop.getCIstate(0L)).thenReturn("other-state"); FlexStateProcessor processor = new FlexStateProcessor(); processor.setCoProcessor(cop); processor.setEnvProcessor(envProcessorMock); System.out.println(" lets set up the mock ....."+ cmProcessorMock); processor.setNotifier(notifierMock); processor.setRestTemplate(restTemplateMock); processor.setTransistorUrl(null); processor.setCmProcessor(cmProcessorMock); try { CiChangeStateEvent event = new CiChangeStateEvent(); event.setCiId(0L); processor.processUnderutilized(event, true, System.currentTimeMillis()); event = new CiChangeStateEvent(); event.setCiId(ID_WITH_AUTO_REPAIR); processor.processUnderutilized(event, true, System.currentTimeMillis()); event = new CiChangeStateEvent(); event.setCiId(ID_WITH_AUTO_SCALING); processor.processUnderutilized(event, true, System.currentTimeMillis()); } catch (OpampException e) { logger.warn("Not expected to catch here ",e); throw new RuntimeException(e); } }
### Question: StmtBuilder { public String buildResetStmt(long manifestId, String source, String trsName, ThresholdDef def) { String name = source + ":" + trsName; int duration = def.getReset().getDuration(); duration = (duration > WNDW_SIZE_MAX) ? WNDW_SIZE_MAX : duration; return new StringBuilder(400) .append("insert into OpsEvent select ciId, manifestId, timestamp, bucket, metrics, 'reset' as state, 'metric' as type, source, ") .append("'").append(name).append("'") .append(" as name, ") .append("'").append(def.getState()).append("'") .append(" as ciState, count(1) as count from PerfEvent(manifestId = ") .append(manifestId) .append(" and bucket = ") .append("'").append(def.getBucket()).append("'") .append(" and source = ") .append("'").append(source).append("'") .append(" and (metrics.") .append(def.getStat()) .append("('").append(def.getMetric()).append("') ") .append(def.getReset().getOperator()) .append(" ").append(def.getReset().getValue()).append(")).") .append("win:time(") .append(duration) .append(" min) group by ciId having count(1)>=") .append(def.getReset().getNumocc()).toString(); } StmtBuilder(); String buildTriggerStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildResetStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildHeartbeatStmt(long manifestId, String source, String duration); ThresholdStatements getThresholdStatements(long manifestId, String source, long checksum, String thresholdsJson, boolean isHeartbeat, String hbDuration); static final int THRESHOLDS_JSON_SIZE_FLOOR; final static String STMT_RESET; final static String STMT_RESET_HEARTBEAT; final static String STMT_RETRIGGER_HEARTBEAT; final static String STMT_TRIGGER_CHANNELDOWN; final static String STMT_DELAY_PERF_EVENT; }### Answer: @Test public void buildResetStmtTest() { String resetStmt = "insert into OpsEvent select ciId, manifestId, timestamp, bucket, metrics, 'reset' as state, 'metric' " + "as type, source, 'daqws-compute-disk:LowDiskSpace' as name, 'notify' as ciState, count(1) as count from " + "PerfEvent(manifestId = 5351305 and bucket = '5m' and source = 'daqws-compute-disk' and (metrics.avg('space_used') " + "< 90.0)).win:time(5 min) group by ciId having count(1)>=1"; ThresholdDef thrDef = new ThresholdDef(); thrDef.setBucket("5m"); thrDef.setMetric("space_used"); thrDef.setName("sum"); thrDef.setStat("avg"); thrDef.setState("notify"); StmtParams params = thrDef.new StmtParams(); params.setNumocc(1); params.setOperator("<"); params.setValue(90.0); params.setDuration(5); thrDef.setReset(params); StmtBuilder builder = new StmtBuilder(); String stmt = builder.buildResetStmt(5351305, "daqws-compute-disk", "LowDiskSpace", thrDef); assertEquals(resetStmt, stmt); }
### Question: StmtBuilder { public String buildHeartbeatStmt(long manifestId, String source, String duration) { return new StringBuilder(100) .append("insert into OpsEvent select lastEvent.ciId as ciId, lastEvent.manifestId as manifestId, lastEvent.channel as channel, lastEvent.timestamp as timestamp, 'open' as state, 'heartbeat' as type, lastEvent.source as source, lastEvent.source || ':Heartbeat' as name, ") .append("'unhealthy'") .append(" as ciState from pattern [(every lastEvent=PerfEvent(source = ") .append("'").append(source).append("'") .append(" and manifestId = ") .append(manifestId) .append(")) -> (timer:interval(") .append(duration) .append(" min) and not PerfEvent(ciId = lastEvent.ciId and source = lastEvent.source))]").toString(); } StmtBuilder(); String buildTriggerStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildResetStmt(long manifestId, String source, String trsName, ThresholdDef def); String buildHeartbeatStmt(long manifestId, String source, String duration); ThresholdStatements getThresholdStatements(long manifestId, String source, long checksum, String thresholdsJson, boolean isHeartbeat, String hbDuration); static final int THRESHOLDS_JSON_SIZE_FLOOR; final static String STMT_RESET; final static String STMT_RESET_HEARTBEAT; final static String STMT_RETRIGGER_HEARTBEAT; final static String STMT_TRIGGER_CHANNELDOWN; final static String STMT_DELAY_PERF_EVENT; }### Answer: @Test public void buildHeartbeatStmtTest() { String hbStmt = "insert into OpsEvent select lastEvent.ciId as ciId, lastEvent.manifestId as manifestId, lastEvent.channel " + "as channel, lastEvent.timestamp as timestamp, 'open' as state, 'heartbeat' as type, lastEvent.source as source, " + "lastEvent.source || ':Heartbeat' as name, 'unhealthy' as ciState from pattern [(every lastEvent=PerfEvent(source = " + "'inductor-compute-load' and manifestId = 4815892)) -> (timer:interval(5 min) and not PerfEvent(ciId = lastEvent.ciId" + " and source = lastEvent.source))]"; StmtBuilder builder = new StmtBuilder(); String stmt = builder.buildHeartbeatStmt(4815892, "inductor-compute-load", "5"); assertEquals(hbStmt, stmt); }
### Question: Sensor { public Map<String, String> getAllLoadedStmts() { Map<String, String> stmts = new HashMap<>(); for (String stmtName : epService.getEPAdministrator().getStatementNames()) { stmts.put(stmtName, epService.getEPAdministrator().getStatement(stmtName).getText()); } return stmts; } void setStmtBuilder(StmtBuilder stmtBuilder); void setCoProcessor(CiOpsProcessor coProcessor); EPServiceProvider getEpService(); void setTsDao(ThresholdsDao tsDao); void setOpsEventDao(OpsEventDao opsEventsDao); void setListeners(Map<String, UpdateListener> listeners); void init(int instanceId, int poolSize); void cleanup(); void stop(); void addCiThresholdsList(long ciId, long manifestId, List<CmsRfcCISimple> monitors); void removeCi(long ciId, long manifestId); void insertFakeEvent(long ciId, long manifestId, String source); void insertFakeEventWithDelay(long ciId, long manifestId, String source, int delay); void insertOpenCloseFakeEvent(long ciId, long manifestId, String source); void sendCEPEvent(BasicEvent event); boolean loadStatements(long manifestId, String source); static void main(String[] args); Map<String, String> getAllLoadedStmts(); boolean isManagedByThisInstance(long manifestId); void handleReplace(long ciId, long manifestId); void setMinHeartbeatSeedDelay(int minHeartbeatSeedDelay); void setHeartbeatRandomDelay(int heartbeatRandomDelay); void setCiStateProcessor(CiStateProcessor ciStateProcessor); void setReplacedInstances(ReplacedInstances replacedInstances); int getLoadStatementTimeOut(); void setLoadStatementTimeOut(int loadStatementTimeOut); static final String ROW_COUNT; static final int READ_ROWCOUNT; }### Answer: @Test public void checkAllLoadedStatements() { Map<String, String> outMap = baseSensor.getAllLoadedStmts(); assert (outMap.size() > 0); }
### Question: Sensor { public boolean loadStatements(long manifestId, String source) { Threshold tr = getThreshold(manifestId, source); if (tr == null) { return false; } ThresholdStatements stmts = stmtBuilder.getThresholdStatements( manifestId, source, tr.getCrc(), tr.getThresholdJson(), tr.isHeartbeat(), tr.getHbDuration()); for (String stmtName : stmts.getStatements().keySet()) { SensorStatement stmt = stmts.getStatements().get(stmtName); addStatementToEngine(stmt.getStmtName(), stmt.getStmtText(), stmt.getListenerName()); } if (!loadedThresholds.containsKey(manifestId)) { loadedThresholds.put(manifestId, new HashMap<String, ThresholdStatements>()); } loadedThresholds.get(manifestId).put(source, stmts); return true; } void setStmtBuilder(StmtBuilder stmtBuilder); void setCoProcessor(CiOpsProcessor coProcessor); EPServiceProvider getEpService(); void setTsDao(ThresholdsDao tsDao); void setOpsEventDao(OpsEventDao opsEventsDao); void setListeners(Map<String, UpdateListener> listeners); void init(int instanceId, int poolSize); void cleanup(); void stop(); void addCiThresholdsList(long ciId, long manifestId, List<CmsRfcCISimple> monitors); void removeCi(long ciId, long manifestId); void insertFakeEvent(long ciId, long manifestId, String source); void insertFakeEventWithDelay(long ciId, long manifestId, String source, int delay); void insertOpenCloseFakeEvent(long ciId, long manifestId, String source); void sendCEPEvent(BasicEvent event); boolean loadStatements(long manifestId, String source); static void main(String[] args); Map<String, String> getAllLoadedStmts(); boolean isManagedByThisInstance(long manifestId); void handleReplace(long ciId, long manifestId); void setMinHeartbeatSeedDelay(int minHeartbeatSeedDelay); void setHeartbeatRandomDelay(int heartbeatRandomDelay); void setCiStateProcessor(CiStateProcessor ciStateProcessor); void setReplacedInstances(ReplacedInstances replacedInstances); int getLoadStatementTimeOut(); void setLoadStatementTimeOut(int loadStatementTimeOut); static final String ROW_COUNT; static final int READ_ROWCOUNT; }### Answer: @Test public void loadStatementsTest() { baseSensor.setTsDao(mock(ThresholdsDao.class)); baseSensor.loadStatements(0, "mock-source"); }
### Question: OpsEventPublisher { public void cleanup() { logger.info("Closing AMQ connection"); closeConnection(); } void setConnectionFactory(ActiveMQConnectionFactory connectionFactory); void setQueue(String queue); void setPersistent(boolean persistent); void setTimeToLive(long timeToLive); void init(); void publishCiStateMessage(CiChangeStateEvent event); void cleanup(); void closeConnection(); }### Answer: @Test public void cleanupTest(){ OpsEventPublisher oep = new OpsEventPublisher(); oep.cleanup(); }
### Question: CloudUtil { public Set<String> getMissingServices(long manifestPlatformId){ Set<String> requiredServices = getServicesForPlatform(manifestPlatformId); return getMissingCloudServices(manifestPlatformId,requiredServices).keySet(); } void check4missingServices(Set<Long> platformIds); Set<String> getMissingServices(long manifestPlatformId); boolean isCloudActive(CmsCIRelation platformCloudRel); boolean isCloudOffline(CmsCIRelation platformCloudRel); void setCmRfcMrgProcessor(CmsCmRfcMrgProcessor cmRfcMrgProcessor); void setCmProcessor(CmsCmProcessor cmProcessor); }### Answer: @Test public void testGetMissingServices() throws Exception { }
### Question: BomRfcBulkProcessor { void processAndValidateVars(List<CmsCI> cis, Map<String, String> cloudVars, Map<String, String> globalVars, Map<String, String> localVars) { ExceptionConsolidator ec = CIValidationException.consolidator(CmsError.TRANSISTOR_CM_ATTRIBUTE_HAS_BAD_GLOBAL_VAR_REF, cmsUtil.getCountOfErrorsToReport()); for (CmsCI ci : cis) { ec.invokeChecked(() -> cmsUtil.processAllVars(ci, cloudVars, globalVars, localVars)); } ec.rethrowExceptionIfNeeded(); } void setCmsUtil(CmsUtil cmsUtil); void setTrUtil(TransUtil trUtil); void setCmProcessor(CmsCmProcessor cmProcessor); void setRfcProcessor(CmsRfcProcessor rfcProcessor); void setCmRfcMrgProcessor(CmsCmRfcMrgProcessor cmRfcMrgProcessor); int processManifestPlatform(EnvBomGenerationContext ec, PlatformBomGenerationContext pc, CmsCIRelation bindingRel, int startExecOrder, boolean usePercent); int deleteManifestPlatform(EnvBomGenerationContext ec, PlatformBomGenerationContext pc, CmsCIRelation bindingRel, int startExecOrder); }### Answer: @Test public void processAndValidateVars(){ ArrayList<CmsCI> cis = new ArrayList<>(); CmsCI ci = new CmsCI(); ci.setCiName("testCi"); ci.setNsPath("/path"); CmsCIAttribute attribute1 = new CmsCIAttribute(); attribute1.setAttributeName("testAttribute1"); attribute1.setDjValue("$OO_GLOBAL{test1}"); attribute1.setDfValue("$OO_GLOBAL{test1}"); CmsCIAttribute attribute2 = new CmsCIAttribute(); attribute2.setAttributeName("testAttribute2"); attribute2.setDjValue("$OO_GLOBAL{test2}"); attribute2.setDfValue("$OO_GLOBAL{test2}"); ci.addAttribute(attribute1); ci.addAttribute(attribute2); cis.add(ci); try { proc.processAndValidateVars(cis, new HashMap<>(), new HashMap<>(), new HashMap<>()); fail(); } catch (CIValidationException exception){ String message = exception.getMessage(); assertNotNull(message); assertTrue(message.contains("testAttribute1") && message.contains("testAttribute2") && message.contains("test1") && message.contains("test2")); } catch (Exception e){ fail(); } }
### Question: BomManagerImpl implements BomManager { SortedMap<Integer, SortedMap<Integer, List<CmsCIRelation>>> getOrderedClouds(List<CmsCIRelation> cloudRels, boolean reverse) { SortedMap<Integer, SortedMap<Integer, List<CmsCIRelation>>> result = reverse ? new TreeMap<>(Collections.reverseOrder()) : new TreeMap<>(); for (CmsCIRelation binding : cloudRels) { Integer priority = Integer.valueOf(binding.getAttribute("priority").getDjValue()); Integer order = 1; if (binding.getAttributes().containsKey("dpmt_order") && !binding.getAttribute("dpmt_order").getDjValue().isEmpty()) { order = Integer.valueOf(binding.getAttribute("dpmt_order").getDjValue()); } if (!result.containsKey(priority)) { result.put(priority, new TreeMap<>()); } if (!result.get(priority).containsKey(order)) { result.get(priority).put(order, new ArrayList<>()); } result.get(priority).get(order).add(binding); } return result; } void setCloudUtil(CloudUtil cloudUtil); void setCmsUtil(CmsUtil cmsUtil); void setTrUtil(TransUtil trUtil); void setCmProcessor(CmsCmProcessor cmProcessor); void setManifestRfcProcessor(CmsRfcProcessor manifestRfcProcessor); void setBomRfcProcessor(CmsRfcProcessor bomRfcProcessor); void setBomGenerationProcessor(BomRfcBulkProcessor bomGenerationProcessor); void setDpmtProcessor(CmsDpmtProcessor dpmtProcessor); @Override Map<String, Object> generateAndDeployBom(long envId, String userId, Set<Long> excludePlats, CmsDeployment dpmt, boolean commit); @Override Map<String, Object> generateBom(long envId, String userId, Set<Long> excludePlats, String desc, boolean commit); @Override long submitDeployment(long releaseId, String userId, String desc); @Override void check4openDeployment(String nsPath); }### Answer: @Test public void testEmptyDeploymentOrderDoesNotThrowNFE(){ CmsCmProcessor cmProcessor =mock(CmsCmProcessor.class); BomManagerImpl impl = getInstance(cmProcessor); String[] primaryClouds = {"c1", "c2"}; List<CmsCIRelation> platformCloudRels = Stream.of(primaryClouds) .map(s -> (createPrimaryCloud(s))) .collect(toList()); platformCloudRels.get(0).getAttribute("dpmt_order").setDjValue(""); try { impl.getOrderedClouds(platformCloudRels, false); } catch (NumberFormatException e){ fail("Shouldn't throw NFE"); } }
### Question: PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public String IsHA(Platform platform) { if (platform.getActiveClouds().size() >= 2) { return "HA"; } return "Non-HA"; } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }### Answer: @Test(enabled = true) private void test_IsHA() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); activeClouds.add("dc1-TestCloud2"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsHA(platform), "HA"); }
### Question: PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public String parseAssemblyNameFromNsPath(String path) { if (path != null && !path.isEmpty()) { String[] parsedArray = path.split("/"); return parsedArray[2]; } else { return ""; } } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }### Answer: @Test(enabled = true) private void test_parseAssemblyNameFromNsPath() { plugin = new PlatformHADRCrawlerPlugin(); String nsPath = "/orgname/assemblyname/platformname/bom/env-dev/1"; assertEquals(plugin.parseAssemblyNameFromNsPath(nsPath), "assemblyname"); }
### Question: PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public String getOOURL(String path) { return oo_baseUrl + "/r/ns?path=" + path; } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }### Answer: @Test(enabled = true) private void test_getOOURL() { System.setProperty("hadr.oo.baseurl", "https: plugin = new PlatformHADRCrawlerPlugin(); String nsPath = "/orgname/assemblyname/platformname/bom/env-dev/1"; String expectedOOURLString = "https: assertEquals(plugin.getOOURL(nsPath), expectedOOURLString); } @Test(enabled = true) private void test_getOOURL_DefaultToBlank() { System.clearProperty("hadr.oo.baseurl"); plugin = new PlatformHADRCrawlerPlugin(); String nsPath = "/orgname/assemblyname/platformname/bom/env-dev/1"; String expectedOOURLString = "/r/ns?path=/orgname/assemblyname/platformname/bom/env-dev/1"; assertEquals(plugin.getOOURL(nsPath), expectedOOURLString); }
### Question: PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap) { for (String prodCloudName : produtionCloudsArr) { return cloudsMap.keySet().toString().toLowerCase().contains(prodCloudName); } return false; } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }### Answer: @Test(enabled = true) private void testIsNonProdEnvUsingProdutionClouds() { plugin = new PlatformHADRCrawlerPlugin(); Map<String, Cloud> cloudsMap= new HashMap<String, Cloud>(); Cloud cloud1 = new Cloud(); cloud1.setId("dc1-ProdCloud1"); cloud1.setPriority(1); cloud1.setAdminstatus("active"); cloud1.setDeploymentorder(1); cloud1.setScalepercentage(100);; Cloud cloud2 = new Cloud(); cloud2.setId("dc1-ProdCloud2"); cloud2.setPriority(0); cloud2.setAdminstatus("Offline"); cloud2.setDeploymentorder(1); cloud2.setScalepercentage(100);; assertEquals(plugin.isNonProdEnvUsingProdutionClouds(cloudsMap), false); cloudsMap.put("dc1-ProdCloud1", cloud1); cloudsMap.put("dc1-ProdCloud2", cloud2); assertEquals(plugin.isNonProdEnvUsingProdutionClouds(cloudsMap), true); }
### Question: ManifestRfcBulkProcessor { protected void addTripplet(List<ManifestRfcRelationTriplet> rfcRelTripletList, ManifestRfcRelationTriplet manifestRfcRelationTriplet, Set<String> existingGoIds) { String goId = getGoId(manifestRfcRelationTriplet); if (!existingGoIds.contains(goId)){ rfcRelTripletList.add(manifestRfcRelationTriplet); existingGoIds.add(goId); } else { logger.info("Skipping duplicate: "+ goId); } } void setTrUtil(TransUtil trUtil); void setMdProcessor(CmsMdProcessor mdProcessor); void setCmRfcMrgProcessor(CmsCmRfcMrgProcessor cmRfcMrgProcessor); void setCmProcessor(CmsCmProcessor cmProcessor); void setRfcProcessor(CmsRfcProcessor rfcProcessor); void setDjValidator(CmsDJValidator djValidator); void setRfcUtil(CmsRfcUtil rfcUtil); long deleteManifestPlatform(CmsRfcCI manifestPlatform, String userId); void processLinkedTo(Map<Long, CmsRfcCI> design2manifestPlatMap, String nsPath, String userId); void processGlobalVars(long assemblyId, CmsCI env, String nsPath, String userId); ManifestRfcContainer processPlatform(CmsCI designPlatform, CmsCI env, String nsPath, String userId, String availMode); long disablePlatform(long platformCiId, String userId); long enablePlatform(long platformCiId, String userId); void processClouds(CmsCI env, CmsRfcCI manifestPlatRfc, String platNsPath, String releasePath, String userId, Map<Long, CmsCI> existingManifestCIs, Map<String, Map<String, CmsCIRelation>> existingManifestPlatRels, ManifestRfcContainer platformRfcs); long setPlatformActive(long platCiId, String userId); void updateCloudAdminStatus(long cloudId, long envId, String adminstatus, String userId); void updatePlatfomCloudStatus(CmsRfcRelation cloudRel, String userId); CmsRfcCI processIaas(CmsCI templIaas, long envId, String nsPath, String userId); CmsRfcRelation bootstrapRelationRfcWithAttrs(long fromCiId, long toCiId, String relName, String nsPath, String releaseNsPath, Set<String> attrs); void setCiId(CmsRfcCI rfc); void setCiRelationId(CmsRfcRelation rfc); }### Answer: @Test public void testAddTripplet() throws Exception { Set<String> existingGoIds = new HashSet<>(); List<ManifestRfcRelationTriplet> list = new ArrayList<>(); ManifestRfcRelationTriplet triplet = new ManifestRfcRelationTriplet(); CmsRfcRelation rfcRelation = new CmsRfcRelation(); rfcRelation.setRelationId(1); CmsRfcCI rfcCI = new CmsRfcCI(); rfcCI.setNsPath("/test"); rfcCI.setCiName("test"); triplet.setToRfcCI(rfcCI); triplet.setFromRfcCI(rfcCI); triplet.setRfcRelation(rfcRelation); manifestRfcBulkProcessor.addTripplet(list, triplet, existingGoIds); assertEquals(existingGoIds.size(), 1); assertEquals(list.size(), 1); manifestRfcBulkProcessor.addTripplet(list, triplet, existingGoIds); assertEquals(existingGoIds.size(), 1); assertEquals(list.size(), 1); }
### Question: SensorPublisher { public void init() throws JMSException { Properties properties = new Properties(); try { properties.load(this.getClass().getResourceAsStream("/sink.properties")); } catch (IOException e) { logger.error("got: " + e.getMessage()); } user = properties.getProperty("amq.user"); password = System.getenv("KLOOPZ_AMQ_PASS"); if (password == null) { throw new JMSException("missing KLOOPZ_AMQ_PASS env var"); } AMQConnectorURI connectStringGenerator = new AMQConnectorURI(); connectStringGenerator.setHost("opsmq"); connectStringGenerator.setProtocol("tcp"); connectStringGenerator.setPort(61616); connectStringGenerator.setTransport("failover"); connectStringGenerator.setDnsResolve(true); connectStringGenerator.setKeepAlive(true); HashMap<String, String> transportOptions = new HashMap<>(); transportOptions.put("initialReconnectDelay", "1000"); transportOptions.put("startupMaxReconnectAttempts", mqConnectionStartupRetries); transportOptions.put("timeout", mqConnectionTimeout); transportOptions.put("useExponentialBackOff", "false"); connectStringGenerator.setTransportOptions(transportOptions); url = connectStringGenerator.build(); showParameters(); ActiveMQConnectionFactory amqConnectionFactory = new ActiveMQConnectionFactory(user, password, url); amqConnectionFactory.setUseAsyncSend(true); PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(amqConnectionFactory); pooledConnectionFactory.setMaxConnections(amqConnectionPoolSize); pooledConnectionFactory.setIdleTimeout(10000); for (int i = 0; i < poolsize; i++) { JmsTemplate producerTemplate = new JmsTemplate(pooledConnectionFactory); producerTemplate.setSessionTransacted(false); int shard = i + 1; Destination perfin = new org.apache.activemq.command.ActiveMQQueue(queueBase + "-" + shard); producerTemplate.setDefaultDestination(perfin); producerTemplate.setDeliveryPersistent(false); producers[i] = producerTemplate; } } void setThresholdDao(ThresholdsDao thresholdDao); void init(); @SuppressWarnings("unused") void enrichAndPublish(PerfEvent event); void publishMessage(final BasicEvent event); void cleanup(); void closeConnection(); long getMissingManifestCounter(); long getFailedThresholdLoadCounter(); long getPublishedCounter(); }### Answer: @Test(priority=1, expectedExceptions = JMSException.class ,enabled = false) public void testInitWithNoSetup() throws JMSException { SensorPublisher publisher = new SensorPublisher(); try { publisher.init(); } catch (JMSException e) { logger.info("I expected an exception, and yes I caught it " + e.getMessage()); assertEquals(e.getMessage(),NO_ENV_EXC_MSG); throw e; } } @Test(priority=2) public void testInitAfterSetup() throws Exception { SensorPublisher publisher = new SensorPublisher(); setIntoEnvVariables(); try { publisher.init(); } catch (JMSException e) { logger.info("I expected this, and yes I caught it " + e.getMessage()); throw e; } finally { setIntoEnvVariables(); } }
### Question: OneopsAuthBroker extends BrokerFilter { public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { String clientId = info.getClientId(); String usr = info.getUserName(); String pass = info.getPassword(); logger.info("Add new connection { Remote Address: " + context.getConnection().getRemoteAddress() + ", User: " + usr + ", ClientID: " + clientId + " } "); if (usr != null && pass != null) { if (SYSTEM_USER.equals(usr) || (SUPER_USER.equals(usr) && superpass.equals(pass))) { userMap.put(clientId, "*"); } else { String[] parts = usr.split(":"); if (parts.length > 1) { String ns = parts[0]; String cloudName = parts[1]; CmsCISimple cloud = cmsClient.getCloudCi(ns, cloudName); if (cloud != null) { String authkey = cloud.getCiAttributes().get("auth"); if (authkey.equals(pass)) { String queueName = (ns.replaceAll("/", ".") + "." + cloudName + QUEUE_SUFFIX).substring(1); userMap.put(clientId, queueName); } else { logger.error("Got bad password for cloud " + cloudName + ", NsPath: " + ns); throw new CmsAuthException("Bad password for user: " + usr); } } else { logger.error("Got null cloud object for user: " + usr); throw new CmsAuthException("Bad user/pass combination"); } } else { throw new CmsAuthException("Bad user/pass combination"); } } } else { logger.error("Got null user/pass"); throw new CmsAuthException("Got null user/pass"); } super.addConnection(context, info); } OneopsAuthBroker(Broker next, CMSClient cms); void addConnection(ConnectionContext context, ConnectionInfo info); Subscription addConsumer(ConnectionContext context, ConsumerInfo info); void addProducer(ConnectionContext context, ProducerInfo info); }### Answer: @Test(priority=3, expectedExceptions = CmsAuthException.class) public void addConnectionBadPasswordTest() throws Exception{ try { this.oneopsAuthBroker.addConnection(connectionContextMock, connectionBadInfo); } catch (CmsAuthException e) { throw(e); } catch (Exception ee){ throw(ee); } } @Test(priority=3, expectedExceptions = CmsAuthException.class) public void addConnectionNullUserTest() throws Exception{ ConnectionInfo connWithNullUser = mock(ConnectionInfo.class); when(connWithNullUser.getClientId()).thenReturn(MOCK_CLIENT_ID); when(connWithNullUser.getUserName()).thenReturn(null); when(connWithNullUser.getPassword()).thenReturn(CONN_INFO_PASS_BAD); this.oneopsAuthBroker.addConnection(connectionContextMock, connWithNullUser); } @Test(priority=3, expectedExceptions = CmsAuthException.class) public void addConnectionNullCloudTest() throws Exception{ Broker broker = mock(Broker.class); CMSClient oddClient = mock(CMSClient.class); CmsCISimple cmsCISimple = new CmsCISimple(); Map<String, String> ciAttributes = new HashMap<String, String>(1); ciAttributes.put(AUTH_ATTR_KEY, AUTH_KEY_VALUE); cmsCISimple.setCiAttributes(ciAttributes); when(oddClient.getCloudCi(CLOUD_NAME, CLOUD_NAME)).thenReturn( cmsCISimple); when(oddClient.getCloudCi(anyString(), anyString())).thenReturn(null); OneopsAuthBroker oneopsAuthBroker = new OneopsAuthBroker(broker,oddClient); oneopsAuthBroker.addConnection(connectionContextMock, connectionBadInfo); } @Test(priority=4) public void addConnectionTest(){ try { this.oneopsAuthBroker.addConnection(connectionContextMock, connectionInfoUser); } catch (Exception e) { logger.warn("caught exception, make sure Broker is mocked",e); throw new RuntimeException(e); } }
### Question: OneopsAuthBroker extends BrokerFilter { public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { ActiveMQDestination dest = info.getDestination(); Connection conn = context.getConnection(); if (dest != null) { String destName = info.getDestination().getPhysicalName(); String clientId = context.getClientId(); String allowedDest = userMap.get(clientId); logger.info(">>> Got Consumer Add request { Destination: " + destName + ", Remote Address: " + conn.getRemoteAddress() + ", ClientID: " + clientId + " }"); if (allowedDest != null && (allowedDest.equals("*") || allowedDest.equals(destName) || destName.startsWith("ActiveMQ"))) { logger.info(">>> Subscription allowed"); } else { logger.error(">>> Destination not allowed. Subscription denied!"); throw new CmsAuthException(">>> Subscription denied!"); } } else { logger.error("<<< Got Consumer Add request from Remote Address:" + conn.getRemoteAddress() + ". But destination is NULL."); } return super.addConsumer(context, info); } OneopsAuthBroker(Broker next, CMSClient cms); void addConnection(ConnectionContext context, ConnectionInfo info); Subscription addConsumer(ConnectionContext context, ConsumerInfo info); void addProducer(ConnectionContext context, ProducerInfo info); }### Answer: @Test(priority=5, expectedExceptions=RuntimeException.class) public void addConsumerTestDenied(){ try { this.oneopsAuthBroker.addConsumer(connectionContextMock, consumerInfo); } catch (Exception e) { logger.warn("caught exception, make sure Broker is mocked",e); throw new RuntimeException(e); } } @Test(priority=5) public void addConsumerTest(){ ActiveMQDestination activeMQDestinationMQ = ActiveMQDestination.createDestination("mockMQDestionation", (byte) 1 ); activeMQDestinationMQ.setPhysicalName(MQ_PHYSICAL_NAME); ConsumerInfo consumerInfoActiveMQ = mock(ConsumerInfo.class); when(consumerInfoActiveMQ.getDestination()).thenReturn(activeMQDestinationMQ); producerInfo = mock(ProducerInfo.class); when(producerInfo.getDestination()).thenReturn(activeMQDestination); try { this.oneopsAuthBroker.addConsumer(connectionContextMock, consumerInfoActiveMQ); } catch (Exception e) { logger.warn("caught exception, make sure Broker is mocked",e); throw new RuntimeException(e); } }
### Question: OneopsAuthBroker extends BrokerFilter { public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception { Connection conn = context.getConnection(); ActiveMQDestination dest = info.getDestination(); if (dest != null) { String destName = dest.getPhysicalName(); String clientId = context.getClientId(); logger.info(">>> Got Producer Add request { Destination: " + destName + ", Remote Address: " + conn.getRemoteAddress() + ", ClientID: " + clientId + " }"); String allowedDest = userMap.get(context.getClientId()); if (allowedDest != null && (allowedDest.equals("*") || "controller.response".equals(destName))) { logger.info("<<< Producer allowed"); } else { logger.error("<<< Destination not allowed. Producer denied!"); throw new CmsAuthException("<<< Producer denied!"); } } else { logger.error("<<< Got Producer Add request from Remote Address:" + conn.getRemoteAddress() + ". But destination is NULL."); } super.addProducer(context, info); } OneopsAuthBroker(Broker next, CMSClient cms); void addConnection(ConnectionContext context, ConnectionInfo info); Subscription addConsumer(ConnectionContext context, ConsumerInfo info); void addProducer(ConnectionContext context, ProducerInfo info); }### Answer: @Test(priority = 6) public void addProducerTest() { try { this.oneopsAuthBroker.addProducer(connectionContextMock, producerInfo); } catch (Exception e) { logger.warn("caught exception, make sure Broker is mocked",e); throw new RuntimeException(e); } } @Test(priority = 6, expectedExceptions = RuntimeException.class) public void addProducerTestProducerDenied() { ConnectionContext ccForbidden = mock(ConnectionContext.class); when(ccForbidden.getClientId()).thenReturn("this-is-not-in-user-map"); final Connection connectionMock = mock(Connection.class); when(connectionMock.getRemoteAddress()).thenReturn(MOCK_REMOTE_ADDR); when(ccForbidden.getConnection()).thenAnswer(new Answer<Connection>() { @Override public Connection answer(InvocationOnMock invocation) throws Throwable { return connectionMock; } }); try { this.oneopsAuthBroker.addProducer(ccForbidden, producerInfo); } catch (Exception e) { logger.warn("caught exception, make sure Broker is mocked",e); throw new RuntimeException(e); } }
### Question: CMSClient { public void setServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } void setRestTemplate(RestTemplate restTemplate); void setServiceUrl(String serviceUrl); CmsCISimple _getZoneCi(String ns, String ciName); CmsCISimple getCloudCi(String ns, String ciName); }### Answer: @Test(priority=1) public void initializationTests(){ this.cmsClient.setServiceUrl(SERVICE_URL); CmsAuthException tryConstructorResult = new CmsAuthException(); Assert.assertNotNull(tryConstructorResult); CmsAuthException e = new CmsAuthException(); Assert.assertNotNull(e); }
### Question: Iso9660FileSystem extends AbstractBlockFileSystem<Iso9660FileEntry> { byte[] getBytes(Iso9660FileEntry entry) throws IOException { int size = (int) entry.getSize(); byte[] buf = new byte[size]; readBytes(entry, 0, buf, 0, size); return buf; } Iso9660FileSystem(File file, boolean readOnly); Iso9660FileSystem(SeekableInput seekable, boolean readOnly); String getEncoding(); InputStream getInputStream(Iso9660FileEntry entry); }### Answer: @Test public void shouldReadAllBytesWhenSeekableInputPartiallyReads() throws IOException { SeekableInputFile input = new PartiallyReadSeekableInput(); Iso9660FileSystem fs = new Iso9660FileSystem(input, true); Iso9660FileEntry entry = Iterables.getLast(fs); byte[] bytes = fs.getBytes(entry); assertThat("All bytes should have been read", new String(bytes), is("Goodbye")); }
### Question: Iso9660Archiver extends AbstractArchiver { @Override protected String getArchiveType() { return "iso9660"; } String getSystemId(); void setSystemId(String systemId); String getVolumeId(); void setVolumeId(String volumeId); String getVolumeSetId(); void setVolumeSetId(String volumeSetId); String getPublisher(); void setPublisher(String publisher); String getPreparer(); void setPreparer(String preparer); String getApplication(); void setApplication(String application); }### Answer: @Test public void testGetArchiveType() { assertEquals("iso9660", new Iso9660Archiver().getArchiveType()); }
### Question: RSAUtils { public static Map<String, Object> getKeys() throws NoSuchAlgorithmException { Map<String, Object> map = new HashMap<>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map; } static Map<String, Object> getKeys(); static RSAPublicKey getPublicKey(String modulus, String exponent); static RSAPrivateKey getPrivateKey(String modulus, String exponent); static String encryptByPublicKey(String data, RSAPublicKey publicKey); static String decryptByPrivateKey(String data, RSAPrivateKey privateKey); static byte[] ASCII_To_BCD(byte[] ascii, int asc_len); static byte asc_to_bcd(byte asc); static String bcd2Str(byte[] bytes); static String[] splitString(String string, int len); static byte[][] splitArray(byte[] data,int len); }### Answer: @Test public void testGenerateKey()throws Exception { Map<String, Object> keys= RSAUtils.getKeys(); RSAPublicKey rsaPublicKey=(RSAPublicKey)keys.get("public"); System.out.println(rsaPublicKey.getAlgorithm()); System.out.println(rsaPublicKey.toString()); }
### Question: RandomKeysUtil { public static String getRandomString(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } static String getRandomString(int length); }### Answer: @Test public void testGeneratePassword() { String keys=RandomKeysUtil.getRandomString(128); System.out.println(keys); Assert.assertTrue(keys.length()==128); }
### Question: PlaceHolderManager { public static void registerPlaceholder(BungeeChatPlaceHolder... placeholder) { for (BungeeChatPlaceHolder p : placeholder) { registerPlaceholder(p); } } static Stream<BungeeChatPlaceHolder> getPlaceholderStream(); static Stream<BungeeChatPlaceHolder> getApplicableStream(BungeeChatContext context); static String processMessage(String message, BungeeChatContext context); static void registerPlaceholder(BungeeChatPlaceHolder... placeholder); static void registerPlaceholder(BungeeChatPlaceHolder placeholder); static void clear(); static final char placeholderChar; }### Answer: @Test(expected = IllegalArgumentException.class) public void duplicatePlaceholderTest() { final HelperPlaceholder placeholder = new HelperPlaceholder("dummy", null); PlaceHolderManager.registerPlaceholder(placeholder, placeholder); }
### Question: PlaceHolderManager { public static String processMessage(String message, BungeeChatContext context) { final StringBuilder builder = new StringBuilder(); final List<BungeeChatPlaceHolder> placeholders = getApplicableStream(context).collect(Collectors.toList()); processMessageInternal(message, context, builder, placeholders); return builder.toString(); } static Stream<BungeeChatPlaceHolder> getPlaceholderStream(); static Stream<BungeeChatPlaceHolder> getApplicableStream(BungeeChatContext context); static String processMessage(String message, BungeeChatContext context); static void registerPlaceholder(BungeeChatPlaceHolder... placeholder); static void registerPlaceholder(BungeeChatPlaceHolder placeholder); static void clear(); static final char placeholderChar; }### Answer: @Test(timeout = TIMEOUT) public void escapeTest() { final String message = "Test %% Test"; assertEquals("Test % Test", PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); } @Test(timeout = TIMEOUT) public void hangingPlaceholderTest() { final String message = "Test %xxx"; assertEquals(message, PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); } @Test(timeout = TIMEOUT) public void hangingDelimiterTest() { final String message = "Test %"; assertEquals(message, PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); } @Test(timeout = TIMEOUT) public void unknownPlaceholderTest() { final String message = "Test %xxx% %hi%"; assertEquals(message, PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); } @Test(timeout = TIMEOUT) public void placeholderTest() { final String message = "Test %test% Test"; assertEquals("Test HAIII Test", PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); } @Test(timeout = TIMEOUT) public void recusivePlaceholderTest() { final String message = "Test %recursive2% Test"; assertEquals( "Test hihi xxx HAIII xxx hihi Test", PlaceHolderManager.processMessage(message, EMPTY_CONTEXT)); }
### Question: MockableClient implements Client { @Override public Response execute(Request request) throws IOException { if (shouldMockRequest(request)) { return mockClient.execute(request); } else { return realClient.execute(request); } } MockableClient(Registry registry, Client realClient, Client mockClient, BooleanFunction mockWhenFunction); static MockableClient.Builder build(String mockEndpointUrl); @Override Response execute(Request request); }### Answer: @Test public void callRealClient_NotInRegistry() throws Exception { givenEndpointInRegistry(false); testee.execute(REQUEST); verifyRealClientCalled(); verifyZeroInteractions(lookupFunction); } @Test public void callRealClient_WhenLookupFalse_InRegistry() throws Exception { givenEndpointInRegistry(true); givenWhenFunctionReturns(false); testee.execute(REQUEST); verifyRealClientCalled(); } @Test public void callMockClient_WhenLookupTrue_InRegistry() throws Exception { givenEndpointInRegistry(true); givenWhenFunctionReturns(true); testee.execute(REQUEST); verifyMockClientCalled(); }
### Question: ReplaceEndpointClient implements Client { @Override public Response execute(Request request) throws IOException { return realClient.execute( withReplacedEndpoint(request) ); } ReplaceEndpointClient(String newEndpoint, Client realClient); @Override Response execute(Request request); }### Answer: @Test public void replaceUrl() throws Exception { Request request = new Request("GET", "https: testee.execute(request); verify(realClient).execute(argThat(new ArgumentMatcher<Request>() { @Override public boolean matches(Request argument) { return argument.getUrl().equals("http: } })); }
### Question: Resolver { static String getSha1Url(String url, String extension) { return url.replaceAll(".pom$", "." + extension + ".sha1"); } @VisibleForTesting Resolver( DefaultModelResolver modelResolver, VersionResolver versionResolver, List<Rule> aliases); Resolver(DefaultModelResolver resolver, List<Rule> aliases); Collection<Rule> getRules(); String resolvePomDependencies(String projectPath, Set<String> scopes); void resolveArtifact(String artifactCoord); }### Answer: @Test public void testGetSha1Url() throws Exception { assertThat(Resolver.getSha1Url("http: .isEqualTo("http: assertThat(Resolver.getSha1Url("http: .isEqualTo("http: } @Test public void testGetSha1UrlOnlyAtEOL() throws Exception { assertThat(Resolver.getSha1Url("http: .isEqualTo("http: }
### Question: VersionResolver { String resolveVersion(String groupId, String artifactId, String versionSpec) throws InvalidArtifactCoordinateException { List<String> versions; try { versions = requestVersionList(groupId, artifactId, versionSpec); } catch (VersionRangeResolutionException e) { String errorMessage = messageForInvalidArtifact(groupId, artifactId, versionSpec, e.getMessage()); throw new InvalidArtifactCoordinateException(errorMessage); } if (isInvalidRangeResult(versions)) { String errorMessage = messageForInvalidArtifact(groupId, artifactId, versionSpec, "Invalid Range Result"); throw new InvalidArtifactCoordinateException(errorMessage); } return selectVersion(versionSpec, versions); } VersionResolver(Aether aether); static VersionResolver defaultResolver(); }### Answer: @Test public void selectsHighestVersion() throws InvalidArtifactCoordinateException, VersionRangeResolutionException { Aether aether = Mockito.mock(Aether.class); Artifact artifact; artifact = ArtifactBuilder.fromCoords("com.hello:something:[,)"); Mockito.when( aether.requestVersionRange(artifact)).thenReturn(newArrayList("1.0", "1.2", "1.3")); VersionResolver resolver = new VersionResolver(aether); String version = resolver.resolveVersion("com.hello", "something", "[,)"); assertThat(version).isEqualTo("1.3"); } @Test(expected = ArtifactBuilder.InvalidArtifactCoordinateException.class) public void failsOnResolutionException() throws InvalidArtifactCoordinateException, VersionRangeResolutionException { Aether aether = Mockito.mock(Aether.class); Mockito.when(aether.requestVersionRange(any())) .thenThrow(new VersionRangeResolutionException(any())); VersionResolver resolver = new VersionResolver(aether); resolver.resolveVersion("something", "something", "1.0"); } @Test(expected = ArtifactBuilder.InvalidArtifactCoordinateException.class) public void failsOnInvalidVersionRange() throws VersionRangeResolutionException, InvalidArtifactCoordinateException { Aether aether = Mockito.mock(Aether.class); Mockito.when(aether.requestVersionRange(any())) .thenReturn(anyList()); VersionResolver resolver = new VersionResolver(aether); resolver.resolveVersion("something", "something", "1.0"); } @Test public void softPinnedVersion_versionExists() throws InvalidArtifactCoordinateException, VersionRangeResolutionException { Aether aether = Mockito.mock(Aether.class); Artifact artifact = ArtifactBuilder.fromCoords("something:something:[1.0,)"); Mockito.when(aether.requestVersionRange(artifact)).thenReturn(newArrayList("1.0", "1.2")); VersionResolver resolver = new VersionResolver(aether); String version = resolver.resolveVersion("something", "something", "1.0"); assertThat(version).isEqualTo("1.0"); } @Test public void softPinnedVersion_versionDoesNotExist() throws InvalidArtifactCoordinateException, VersionRangeResolutionException { Aether aether = Mockito.mock(Aether.class); Artifact artifact = ArtifactBuilder.fromCoords("something:something:[1.0,)"); Mockito.when(aether.requestVersionRange(artifact)).thenReturn(newArrayList("1.2", "2.0", "3.0")); VersionResolver resolver = new VersionResolver(aether); String version = resolver.resolveVersion("something", "something", "1.0"); assertThat(version).isEqualTo("1.2"); }
### Question: VersionResolver { @VisibleForTesting static boolean isVersionRange(String versionSpec) { return versionSpec.charAt(0) == '(' || versionSpec.charAt(0) == '['; } VersionResolver(Aether aether); static VersionResolver defaultResolver(); }### Answer: @Test public void identifiesVersionRange() { assertThat(isVersionRange("[3]")).isTrue(); assertThat(isVersionRange("[3,4]")).isTrue(); assertThat(isVersionRange("[3,4)")).isTrue(); assertThat(isVersionRange("(3,4)")).isTrue(); assertThat(isVersionRange("(3,4]")).isTrue(); assertThat(isVersionRange("(,)")).isTrue(); assertThat(isVersionRange("[3,)")).isTrue(); assertThat(isVersionRange("(3,)")).isTrue(); assertThat(isVersionRange("3.0")).isFalse(); }
### Question: WorkspaceWriter extends AbstractWriter { public void writeWorkspace(PrintStream outputStream, Collection<Rule> rules) { writeHeader(outputStream, args); for (Rule rule : rules) { outputStream.println(formatMavenJar(rule, "maven_jar", "")); } } WorkspaceWriter(String[] args, String outputDirStr); @Override void write(Collection<Rule> rules); void writeWorkspace(PrintStream outputStream, Collection<Rule> rules); void writeBuild(PrintStream outputStream, Collection<Rule> rules); }### Answer: @Test public void testHeaders() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); WorkspaceWriter writer = new WorkspaceWriter( new String[]{"--artifact=x:y:1.2.3", "--artifact=a:b:3.2.1"}, System.getenv("TEST_TMPDIR")); writer.writeWorkspace(ps, Sets.newHashSet()); assertThat(baos.toString(String.valueOf(Charset.defaultCharset()))).contains( "# generate_workspace --artifact=x:y:1.2.3 --artifact=a:b:3.2.1"); }
### Question: BzlWriter extends AbstractWriter { @Override public void write(Collection<Rule> rules) { try { createParentDirectory(generatedFile); } catch (IOException | NullPointerException e) { logger.severe("Could not create directories for " + generatedFile + ": " + e.getMessage()); return; } try (PrintStream outputStream = new PrintStream(generatedFile.toFile())) { writeBzl(outputStream, rules); } catch (FileNotFoundException e) { logger.severe("Could not write " + generatedFile + ": " + e.getMessage()); return; } System.err.println("Wrote " + generatedFile.toAbsolutePath()); } BzlWriter(String[] argv, String outputDirStr); @Override void write(Collection<Rule> rules); }### Answer: @Test public void writeEmpty() throws Exception { BzlWriter writer = new BzlWriter(new String[]{}, System.getenv("TEST_TMPDIR")); writer.write(createRules()); String fileContents = Files.toString( new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"), Charset.defaultCharset()); assertThat(fileContents).contains(String.format("def generated_maven_jars():%n pass%n")); assertThat(fileContents).contains(String.format("def generated_java_libraries():%n pass%n")); } @Test public void automaticallyCreateParentDirectories() throws Exception { Path outputDirs = Paths.get(System.getenv("TEST_TMPDIR")).resolve("child/dir"); BzlWriter writer = new BzlWriter(new String[]{}, outputDirs.toString()); List<Rule> rules = createRules("x:y:1.2.3"); writer.write(rules); File generatedFile = new File(outputDirs.resolve("generate_workspace.bzl").toString()); assert(generatedFile.exists() && !generatedFile.isDirectory()); } @Test public void writeRules() throws Exception { BzlWriter writer = new BzlWriter(new String[]{}, System.getenv("TEST_TMPDIR")); writer.write(createRules("x:y:1.2.3")); String fileContents = Files.toString( new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"), Charset.defaultCharset()); assertThat(fileContents).contains(String.format( "def generated_maven_jars():%n native.maven_jar(%n" + " name = \"x_y\",%n" + " artifact = \"x:y:1.2.3\",%n" + " )%n")); assertThat(fileContents).contains(String.format( "def generated_java_libraries():%n native.java_library(%n" + " name = \"x_y\",%n" + " visibility = [\" + " exports = [\"@x_y + " )%n")); } @Test public void writeAlias() throws Exception { BzlWriter writer = new BzlWriter(new String[]{}, System.getenv("TEST_TMPDIR")); writer.write(ImmutableList.of(new Rule(new DefaultArtifact("x:y:1.2.3"), "z"))); String fileContents = Files.toString( new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"), Charset.defaultCharset()); assertThat(fileContents).doesNotContain("x:y:1.2.3"); assertThat(fileContents).contains("exports = [\"@z } @Test public void writeCommand() throws Exception { BzlWriter writer = new BzlWriter(new String[]{"x", "y", "z"}, System.getenv("TEST_TMPDIR")); writer.write(createRules()); String fileContents = Files.toString( new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"), Charset.defaultCharset()); assertThat(fileContents).contains("# generate_workspace x y z"); }
### Question: Resolver { static String extractSha1(String sha1Contents) { return sha1Contents.split("\\s+")[0]; } @VisibleForTesting Resolver( DefaultModelResolver modelResolver, VersionResolver versionResolver, List<Rule> aliases); Resolver(DefaultModelResolver resolver, List<Rule> aliases); Collection<Rule> getRules(); String resolvePomDependencies(String projectPath, Set<String> scopes); void resolveArtifact(String artifactCoord); }### Answer: @Test public void testExtractSha1() { assertThat(Resolver.extractSha1("5fe28b9518e58819180a43a850fbc0dd24b7c050")) .isEqualTo("5fe28b9518e58819180a43a850fbc0dd24b7c050"); assertThat(Resolver.extractSha1("5fe28b9518e58819180a43a850fbc0dd24b7c050\n")) .isEqualTo("5fe28b9518e58819180a43a850fbc0dd24b7c050"); assertThat( Resolver.extractSha1( "83cd2cd674a217ade95a4bb83a8a14f351f48bd0 /home/maven/repository-staging/to-ibiblio/maven2/antlr/antlr/2.7.7/antlr-2.7.7.jar")) .isEqualTo("83cd2cd674a217ade95a4bb83a8a14f351f48bd0"); }
### Question: GraphSerializer { public static Set<MavenJarRule> generateBuildRules(DependencyNode root) { MutableGraph<MavenJarRule> graph = GraphBuilder.directed().allowsSelfLoops(false).build(); DependencyVisitor visitor = new AetherGraphTraverser(graph); root.getChildren().forEach(c -> c.accept(visitor)); return graph.nodes(); } static Set<MavenJarRule> generateBuildRules(DependencyNode root); }### Answer: @Test public void testBasicParentChildRelations() { DependencyNode sentinel = dependencyNode("dummy:dummy:0"); DependencyNode parentNode = dependencyNode("a:a:1"); DependencyNode childNode = dependencyNode("a:2:1"); sentinel.setChildren(ImmutableList.of(parentNode)); parentNode.setChildren(ImmutableList.of(childNode)); MavenJarRule parent = new MavenJarRule(parentNode); MavenJarRule child = new MavenJarRule(childNode); addDependency(parent, child); Set<MavenJarRule> actual = GraphSerializer.generateBuildRules(sentinel); assertRuleSetContainsExactly(actual, parent, child); } @Test public void testMultipleDirectDependencies() { DependencyNode sentinel = dependencyNode("dummy:dummy:0"); DependencyNode nodeA = dependencyNode("a:a:1"); DependencyNode nodeA1 = dependencyNode("a:1:1"); DependencyNode nodeB = dependencyNode("b:b:1"); DependencyNode nodeC = dependencyNode("c:c:1"); sentinel.setChildren(ImmutableList.of(nodeA, nodeB, nodeC)); nodeA.setChildren(ImmutableList.of(nodeA1)); Set<MavenJarRule> rules = GraphSerializer.generateBuildRules(sentinel); MavenJarRule ruleA = new MavenJarRule(nodeA); MavenJarRule ruleA1 = new MavenJarRule(nodeA1); MavenJarRule ruleB = new MavenJarRule(nodeB); MavenJarRule ruleC = new MavenJarRule(nodeC); addDependency(ruleA, ruleA1); assertRuleSetContainsExactly(rules, ruleA, ruleA1, ruleB, ruleC); } @Test public void testSharedChild() { DependencyNode sentinel = dependencyNode("dummy:dummy:0"); DependencyNode nodeA = dependencyNode("a:a:1"); DependencyNode nodeB = dependencyNode("b:b:1"); DependencyNode child = dependencyNode("child:child:1"); sentinel.setChildren(ImmutableList.of(nodeA, nodeB)); nodeA.setChildren(ImmutableList.of(child)); nodeB.setChildren(ImmutableList.of(child)); Set<MavenJarRule> rules = GraphSerializer.generateBuildRules(sentinel); MavenJarRule ruleA = new MavenJarRule(nodeA); MavenJarRule ruleB = new MavenJarRule(nodeB); MavenJarRule childRule = new MavenJarRule(child); addDependency(ruleA, childRule); addDependency(ruleB, childRule); assertRuleSetContainsExactly(rules, ruleA, ruleB, childRule); }