src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
AdmitToSpecificLocationDispositionAction implements DispositionAction { @Override public void action(EncounterDomainWrapper encounterDomainWrapper, Obs dispositionObsGroupBeingCreated, Map<String, String[]> requestParameters) { VisitDomainWrapper visitDomainWrapper = adtService.wrap(encounterDomainWrapper.getVisit()); if (visitDomainWrapper.isAdmitted(encounterDomainWrapper.getEncounterDatetime()) || visitDomainWrapper.isAdmitted()) { return; } else { Location admissionLocation = dispositionService.getDispositionDescriptor().getAdmissionLocation(dispositionObsGroupBeingCreated, locationService); if (admissionLocation != null) { AdtAction admission = new AdtAction(encounterDomainWrapper.getVisit(), admissionLocation, encounterDomainWrapper.getProviders(), ADMISSION); admission.setActionDatetime(encounterDomainWrapper.getEncounter().getEncounterDatetime()); adtService.createAdtEncounterFor(admission); } else { log.warn("Unable to create admission action, no admission location specified in obsgroup " + dispositionObsGroupBeingCreated); } } } @Override void action(EncounterDomainWrapper encounterDomainWrapper, Obs dispositionObsGroupBeingCreated, Map<String, String[]> requestParameters); void setLocationService(LocationService locationService); void setAdtService(AdtService adtService); void setDispositionService(DispositionService dispositionService); }
@Test public void testAction() throws Exception { final Location toLocation = new Location(); final Visit visit = new Visit(); final Encounter encounter = new Encounter(); final Date encounterDate = (new DateTime(2013, 05, 13, 20, 26)).toDate(); encounter.setVisit(visit); encounter.addProvider(new EncounterRole(), new Provider()); encounter.setEncounterDatetime(encounterDate); final Obs dispositionObsGroup = new Obs(); dispositionObsGroup.setConcept(dispositionObsGroupConcept); encounter.addObs(dispositionObsGroup); when(visitDomainWrapper.isAdmitted(encounterDate)).thenReturn(false); when(dispositionDescriptor.getAdmissionLocation(dispositionObsGroup, locationService)).thenReturn(toLocation); action.action(new EncounterDomainWrapper(encounter), dispositionObsGroup, null); verify(adtService).createAdtEncounterFor(argThat(new ArgumentMatcher<AdtAction>() { @Override public boolean matches(Object argument) { AdtAction actual = (AdtAction) argument; return actual.getVisit().equals(visit) && actual.getLocation().equals(toLocation) && TestUtils.sameProviders(actual.getProviders(), encounter.getProvidersByRoles()) && actual.getActionDatetime().equals(encounterDate) && actual.getType().equals(AdtAction.Type.ADMISSION); } })); } @Test public void testActionWhenAlreadyAdmitted() throws Exception { final Visit visit = new Visit(); final Encounter encounter = new Encounter(); final Date encounterDate = (new DateTime(2013, 05, 13, 20, 26)).toDate(); encounter.setVisit(visit); encounter.addProvider(new EncounterRole(), new Provider()); encounter.setEncounterDatetime(encounterDate); when(visitDomainWrapper.isAdmitted(encounterDate)).thenReturn(false); action.action(new EncounterDomainWrapper(encounter), new Obs(), new HashMap<String, String[]>()); verify(adtService, never()).createAdtEncounterFor(any(AdtAction.class)); }
MarkPatientDeadDispositionAction implements DispositionAction { @Override public void action(EncounterDomainWrapper encounterDomainWrapper, Obs dispositionObsGroupBeingCreated, Map<String, String[]> requestParameters) { Date deathDate = dispositionService.getDispositionDescriptor().getDateOfDeath(dispositionObsGroupBeingCreated); Concept causeOfDeath = emrApiProperties.getUnknownCauseOfDeathConcept(); Patient patient = encounterDomainWrapper.getEncounter().getPatient(); patient.setDead(true); if (deathDate != null) { patient.setDeathDate(deathDate); } patient.setCauseOfDeath(causeOfDeath); patientService.savePatient(patient); } @Override void action(EncounterDomainWrapper encounterDomainWrapper, Obs dispositionObsGroupBeingCreated, Map<String, String[]> requestParameters); void setPatientService(PatientService patientService); void setDispositionService(DispositionService dispositionService); void setEmrApiProperties(EmrApiProperties emrApiProperties); }
@Test public void testActionShouldMarkPatientAsDead() throws Exception { Concept unknown = new Concept(); when(emrApiProperties.getUnknownCauseOfDeathConcept()).thenReturn(unknown); Date expectedDeathDate = (new DateTime(2013, 05, 10, 20, 26)).toDate(); Patient patient = new Patient(); final Visit visit = new Visit(); final Encounter encounter = new Encounter(); final Date encounterDate = (new DateTime(2013, 05, 13, 20, 26)).toDate(); encounter.setVisit(visit); encounter.addProvider(new EncounterRole(), new Provider()); encounter.setEncounterDatetime(encounterDate); encounter.setPatient(patient); final Obs dispositionObsGroup = new Obs(); dispositionObsGroup.setConcept(dispositionObsGroupConcept); encounter.addObs(dispositionObsGroup); when(dispositionDescriptor.getDateOfDeath(dispositionObsGroup)).thenReturn(expectedDeathDate); action.action(new EncounterDomainWrapper(encounter), dispositionObsGroup, null); assertThat(patient.isDead(), is(true)); assertThat(patient.getDeathDate(), is(expectedDeathDate)); assertThat(patient.getCauseOfDeath(), is(unknown)); verify(patientService).savePatient(patient); }
CodedOrFreeTextAnswer { public String format(Locale locale) { if (nonCodedAnswer != null) { return "\"" + nonCodedAnswer + "\""; } else if (codedAnswer == null) { return "?"; } else if (specificCodedAnswer == null) { return codedAnswer.getName(locale).getName(); } else { if (specificCodedAnswer.isLocalePreferred() && specificCodedAnswer.getLocale().equals(locale)) { return specificCodedAnswer.getName(); } ConceptName preferredName = codedAnswer.getName(locale); if (preferredName == null || preferredName.getName().equals(specificCodedAnswer.getName())) { return specificCodedAnswer.getName(); } else { return specificCodedAnswer.getName() + " → " + preferredName.getName(); } } } CodedOrFreeTextAnswer(); CodedOrFreeTextAnswer(String spec, ConceptService conceptService); CodedOrFreeTextAnswer(Obs codedOrNonCodedValue); CodedOrFreeTextAnswer(Concept codedAnswer); CodedOrFreeTextAnswer(ConceptName specificCodedAnswer); CodedOrFreeTextAnswer(String nonCodedAnswer); CodedOrFreeTextAnswer(Concept codedAnswer, ConceptName specificCodedAnswer, String nonCodedAnswer); String toClientString(); Object getValue(); Concept getCodedAnswer(); @JsonDeserialize(using = ConceptCodeDeserializer.class) void setCodedAnswer(Concept codedAnswer); ConceptName getSpecificCodedAnswer(); void setSpecificCodedAnswer(ConceptName specificCodedAnswer); String getNonCodedAnswer(); void setNonCodedAnswer(String nonCodedAnswer); @Override boolean equals(Object o); @Override int hashCode(); String formatWithoutSpecificAnswer(Locale locale); String format(Locale locale); String formatWithCode(Locale locale, List<ConceptSource> codeFromSources); static final String CONCEPT_NAME_PREFIX; static final String CONCEPT_UUID_PREFIX; static final String CONCEPT_PREFIX; static final String NON_CODED_PREFIX; }
@Test public void testFormatFreeText() throws Exception { String actual = new CodedOrFreeTextAnswer("Free text").format(Locale.ENGLISH); assertThat(actual, is("\"Free text\"")); } @Test public void testFormatCoded() throws Exception { Concept concept = new Concept(); concept.addName(new ConceptName("English", Locale.ENGLISH)); String actual = new CodedOrFreeTextAnswer(concept).format(Locale.ENGLISH); assertThat(actual, is("English")); } @Test public void testFormatSpecificCoded() throws Exception { ConceptName preferredEnglishName = new ConceptName("English", Locale.ENGLISH); preferredEnglishName.setLocalePreferred(true); preferredEnglishName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED); ConceptName frenchSynonym = new ConceptName("Français", Locale.FRENCH); Concept concept = new Concept(); concept.addName(preferredEnglishName); concept.addName(frenchSynonym); String actual = new CodedOrFreeTextAnswer(frenchSynonym).format(Locale.ENGLISH); assertThat(actual, is("Français → English")); } @Test public void testFormatSpecificCodedWhenItIsLocalePreferred() throws Exception { ConceptName preferred = new ConceptName("Preferred", Locale.ENGLISH); preferred.setLocalePreferred(true); preferred.setConceptNameType(ConceptNameType.FULLY_SPECIFIED); ConceptName synonym = new ConceptName("Synonym", Locale.ENGLISH); Concept concept = new Concept(); concept.addName(preferred); concept.addName(synonym); String actual = new CodedOrFreeTextAnswer(preferred).format(Locale.ENGLISH); assertThat(actual, is(preferred.getName())); } @Test public void testFormatSpecificCodedWithIdenticalName() throws Exception { ConceptName preferredEnglishName = new ConceptName("English", Locale.ENGLISH); preferredEnglishName.setLocalePreferred(true); preferredEnglishName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED); ConceptName ukEnglishSynonym = new ConceptName("English", Locale.UK); Concept concept = new Concept(); concept.addName(preferredEnglishName); concept.addName(ukEnglishSynonym); String actual = new CodedOrFreeTextAnswer(ukEnglishSynonym).format(Locale.ENGLISH); assertThat(actual, is("English")); }
ConceptSetDescriptor { protected void setup(ConceptService conceptService, String conceptSourceName, ConceptSetDescriptorField primaryConceptField, ConceptSetDescriptorField... memberConceptFields) { try { String primaryConceptCode = primaryConceptField.getConceptCode(); Concept primaryConcept = conceptService.getConceptByMapping(primaryConceptCode, conceptSourceName); if (primaryConcept == null) { throw new MissingConceptException("Couldn't find primary concept for " + getClass().getSimpleName() + " which should be mapped as " + conceptSourceName + ":" + primaryConceptCode); } PropertyUtils.setProperty(this, primaryConceptField.getName(), primaryConcept); for (ConceptSetDescriptorField conceptSetDescriptorField : memberConceptFields) { String propertyName = conceptSetDescriptorField.getName(); String mappingCode = conceptSetDescriptorField.getConceptCode(); Concept childConcept = conceptService.getConceptByMapping(mappingCode, conceptSourceName); if(conceptSetDescriptorField.isRequired()) { if (childConcept == null) { throw new MissingConceptException("Couldn't find " + propertyName + " concept for " + getClass().getSimpleName() + " which should be mapped as " + conceptSourceName + ":" + mappingCode); } if (!primaryConcept.getSetMembers().contains(childConcept)) { throw new IllegalStateException("Concept mapped as " + conceptSourceName + ":" + mappingCode + " needs to be a set member of concept " + primaryConcept.getConceptId() + " which is mapped as " + conceptSourceName + ":" + primaryConceptCode); } } PropertyUtils.setProperty(this, propertyName, childConcept); } } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new IllegalStateException(ex); } } } }
@Test public void shouldProperlySetupConcepts() { ConceptSetDescriptorImpl conceptSetDescriptorImpl = new ConceptSetDescriptorImpl(); conceptSetDescriptorImpl.setup(conceptService, "someConceptSource", ConceptSetDescriptorField.required("setConcept", "setConceptCode"), ConceptSetDescriptorField.required("firstMemberConcept", "firstMemberConceptCode"), ConceptSetDescriptorField.required("secondMemberConcept", "secondMemberConceptCode")); assertThat(conceptSetDescriptorImpl.getSetConcept(), is(setConcept)); assertThat(conceptSetDescriptorImpl.getFirstMemberConcept(), is(firstMemberConcept)); assertThat(conceptSetDescriptorImpl.getSecondMemberConcept(), is(secondMemberConcept)); } @Test(expected = IllegalStateException.class) public void shouldRaiseExceptionIfRequiredConceptDoesNotExist() { ConceptSetDescriptorImpl conceptSetDescriptorImpl = new ConceptSetDescriptorImpl(); conceptSetDescriptorImpl.setup(conceptService, "someConceptSource", ConceptSetDescriptorField.required("setConcept", "setConceptCode"), ConceptSetDescriptorField.required("firstMemberConcept", "nonExistingConceptCode")); } @Test public void shouldNotRaiseExceptionIfOptionalConceptDoesNotExist() { ConceptSetDescriptorImpl conceptSetDescriptorImpl = new ConceptSetDescriptorImpl(); conceptSetDescriptorImpl.setup(conceptService, "someConceptSource", ConceptSetDescriptorField.required("setConcept", "setConceptCode"), ConceptSetDescriptorField.optional("firstMemberConcept", "nonExistingConceptCode")); assertThat(conceptSetDescriptorImpl.getSetConcept(), is(setConcept)); assertThat(conceptSetDescriptorImpl.getFirstMemberConcept(), IsNull.nullValue()); }
EmrApiVisitAssignmentHandler extends BaseEncounterVisitHandler implements EncounterVisitHandler { @Override public void beforeCreateEncounter(Encounter encounter) { if (encounter.getVisit() != null) { return; } Date when = encounter.getEncounterDatetime(); if (when == null) { when = new Date(); } if (encounter.getLocation() == null) { return; } List<Patient> patient = Collections.singletonList(encounter.getPatient()); List<Visit> candidates = visitService.getVisits(null, patient, null, null, null, new DateTime(when).withTime(23, 59, 59, 999).toDate(), null, null, null, true, false); if (candidates != null) { for (Visit candidate : candidates) { if (emrApiProperties.getVisitAssignmentHandlerAdjustEncounterTimeOfDayIfNecessary()) { if (adtService.isSuitableVisitIgnoringTime(candidate, encounter.getLocation(), when)) { if (when.before(candidate.getStartDatetime())) { encounter.setEncounterDatetime(candidate.getStartDatetime()); } else if (candidate.getStopDatetime() != null && when.after(candidate.getStopDatetime())) { encounter.setEncounterDatetime(candidate.getStopDatetime()); } candidate.addEncounter(encounter); return; } } else { if (adtService.isSuitableVisit(candidate, encounter.getLocation(), when)) { candidate.addEncounter(encounter); return; } } } } if (StringUtils.isNotBlank(administrationService.getGlobalProperty(EmrApiConstants.GP_VISIT_ASSIGNMENT_HANDLER_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAP))) { VisitType visitType = getEncounterTypetoVisitTypeMapper().getVisitTypeForEncounter(encounter); if (visitType != null) { Visit visit = new Visit(); visit.setStartDatetime(encounter.getEncounterDatetime()); visit.setLocation(adtService.getLocationThatSupportsVisits(encounter.getLocation())); visit.setPatient(encounter.getPatient()); visit.setVisitType(visitType); if (!DateUtils.isSameDay(encounter.getEncounterDatetime(), new Date())) { visit.setStopDatetime(OpenmrsUtil.getLastMomentOfDay(encounter.getEncounterDatetime())); } visit.addEncounter(encounter); } } } EmrApiVisitAssignmentHandler(); @Override String getDisplayName(Locale locale); @Override void beforeCreateEncounter(Encounter encounter); void setVisitService(VisitService visitService); void setAdtService(AdtService adtService); void setAdministrationService(AdministrationService administrationService); void setEmrApiProperties(EmrApiProperties emrApiProperties); EncounterTypetoVisitTypeMapper getEncounterTypetoVisitTypeMapper(); void setEncounterTypetoVisitTypeMapper( EncounterTypetoVisitTypeMapper encounterTypetoVisitTypeMapper); }
@Ignore("TEMP HACK: disable this while we decide whether or not we want this functionality") @Test(expected = IllegalStateException.class) public void testThrowsExceptionIfNoSuitableVisitExists() throws Exception { Patient patient = new Patient(); Location location = new Location(); Visit notSuitable = new Visit(); notSuitable.setPatient(patient); notSuitable.setStartDatetime(DateUtils.addDays(new Date(), -7)); notSuitable.setStopDatetime(DateUtils.addDays(new Date(), -6)); notSuitable.setLocation(location); when( visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class), any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class), any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Collections.singletonList(notSuitable)); Encounter encounter = new Encounter(); encounter.setPatient(patient); encounter.setLocation(location); handler.beforeCreateEncounter(encounter); } @Test public void testAssigningASuitableVisitWhenOneExists() throws Exception { Patient patient = new Patient(); Location location = new Location(); Visit notSuitable = new Visit(); notSuitable.setPatient(patient); notSuitable.setStartDatetime(DateUtils.addDays(new Date(), -7)); notSuitable.setStopDatetime(DateUtils.addDays(new Date(), -6)); notSuitable.setLocation(location); Visit suitable = new Visit(); suitable.setPatient(patient); suitable.setStartDatetime(DateUtils.addDays(new Date(), -1)); suitable.setLocation(location); when( visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class), any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class), any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Arrays.asList(notSuitable, suitable)); Date encounterDatetime = new Date(); Encounter encounter = new Encounter(); encounter.setPatient(patient); encounter.setLocation(location); encounter.setEncounterDatetime(encounterDatetime); handler.beforeCreateEncounter(encounter); encounter.setEncounterDatetime(encounterDatetime); Assert.assertThat(encounter.getVisit(), is(suitable)); Assert.assertThat(suitable.getEncounters(), contains(encounter)); Assert.assertThat(encounter.getEncounterDatetime(), is(encounterDatetime)); } @Test public void testAdjustingEncounterTimeToStartOfVisitWhenAssignedToVisit() throws Exception { Patient patient = new Patient(); Location location = new Location(); Visit suitable = new Visit(); suitable.setPatient(patient); suitable.setStartDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(12).toDate()); suitable.setStopDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(16).toDate()); suitable.setLocation(location); when( visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class), any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class), any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Arrays.asList(suitable)); Encounter encounter = new Encounter(); encounter.setPatient(patient); encounter.setLocation(location); encounter.setEncounterDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(10).toDate()); handler.beforeCreateEncounter(encounter); Assert.assertThat(encounter.getVisit(), is(suitable)); Assert.assertThat(suitable.getEncounters(), contains(encounter)); Assert.assertThat(encounter.getEncounterDatetime(), is(suitable.getStartDatetime())); } @Test public void testAdjustingEncounterTimeToEndOfVisitWhenAssignedToVisit() throws Exception { Patient patient = new Patient(); Location location = new Location(); Visit suitable = new Visit(); suitable.setPatient(patient); suitable.setStartDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(12).toDate()); suitable.setStopDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(16).toDate()); suitable.setLocation(location); when( visitService.getVisits(any(Collection.class), any(Collection.class), any(Collection.class), any(Collection.class), any(Date.class), any(Date.class), any(Date.class), any(Date.class), any(Map.class), anyBoolean(), anyBoolean())).thenReturn(Arrays.asList(suitable)); Encounter encounter = new Encounter(); encounter.setPatient(patient); encounter.setLocation(location); encounter.setEncounterDatetime(new DateTime().withTimeAtStartOfDay().minusDays(1).plusHours(20).toDate()); handler.beforeCreateEncounter(encounter); Assert.assertThat(encounter.getVisit(), is(suitable)); Assert.assertThat(suitable.getEncounters(), contains(encounter)); Assert.assertThat(encounter.getEncounterDatetime(), is(suitable.getStopDatetime())); }
NoteFrequencyCalculator { public double getFrequency(Note note) { int semitonesPerOctave = 12; int referenceOctave = 4; double distance = semitonesPerOctave * (note.getOctave() - referenceOctave); distance += notes.indexOf(note.getName() + note.getSign()) - notes.indexOf("A"); return referenceFrequency * Math.pow(2, distance / 12); } NoteFrequencyCalculator(float referenceFrequency); double getFrequency(Note note); }
@Test public void TestCalc() { InputStream resourceAsStream = getClass().getResourceAsStream("note_frequencies.csv"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream))) { while (reader.ready()) { String line = reader.readLine(); String[] components = line.split(","); String noteWithOctave = components[0].split("/")[0]; String frequency = components[1]; String noteName = noteWithOctave.substring(0, 1); String octave = noteWithOctave.substring(1); String sign = ""; if (noteWithOctave.contains("#")) { noteName = noteWithOctave.substring(0, 1); octave = noteWithOctave.substring(2); sign = "#"; } String finalNoteName = noteName; String finalOctave = octave; String finalSign = sign; Note note = new Note() { @Override public NoteName getName() { return NoteName.fromScientificName(finalNoteName); } @Override public int getOctave() { return Integer.parseInt(finalOctave); } @Override public String getSign() { return finalSign; } }; NoteFrequencyCalculator noteFrequencyCalculator = new NoteFrequencyCalculator(440); double expectedFrequency = Double.parseDouble(frequency); double actualFrequency = noteFrequencyCalculator.getFrequency(note); Assert.assertEquals(expectedFrequency, actualFrequency, 0.01); } } catch (IOException e) { Assert.fail(e.getMessage()); } }
PitchComparator { static PitchDifference retrieveNote(float pitch) { Tuning tuning = MainActivity.getCurrentTuning(); int referencePitch = MainActivity.getReferencePitch(); Note[] notes = tuning.getNotes(); NoteFrequencyCalculator noteFrequencyCalculator = new NoteFrequencyCalculator(referencePitch); Arrays.sort(notes, (o1, o2) -> Double.compare(noteFrequencyCalculator.getFrequency(o1), noteFrequencyCalculator.getFrequency(o2))); double minCentDifference = Float.POSITIVE_INFINITY; Note closest = notes[0]; for (Note note : notes) { double frequency = noteFrequencyCalculator.getFrequency(note); double centDifference = 1200d * log2(pitch / frequency); if (Math.abs(centDifference) < Math.abs(minCentDifference)) { minCentDifference = centDifference; closest = note; } } return new PitchDifference(closest, minCentDifference); } }
@Test public void retrieveNote() { PowerMockito.mockStatic(MainActivity.class); Mockito.when(MainActivity.getCurrentTuning()).thenReturn(new GuitarTuning()); Mockito.when(MainActivity.getReferencePitch()).thenReturn(440); Map<Float, PitchDifference> expectations = new HashMap<>(); expectations.put(20f, new PitchDifference(E2, -2451.3202694972874)); expectations.put(500f, new PitchDifference(E4, 721.3071582323822)); expectations.put(197.67f, new PitchDifference(G3, 14.705999652460953)); expectations.put(128.415f, new PitchDifference(D3, -232.0232233030192)); for (Float pitch : expectations.keySet()) { PitchDifference actual = PitchComparator.retrieveNote(pitch); PitchDifference expected = expectations.get(pitch); assertNotNull(expected); assertThat(actual.closest, is(expected.closest)); assertThat(actual.deviation, closeTo(expected.deviation, 0.01)); } }
Sampler { static PitchDifference calculateAverageDifference(List<PitchDifference> samples) { Note mostFrequentNote = extractMostFrequentNote(samples); List<PitchDifference> filteredSamples = filterByNote(samples, mostFrequentNote); double deviationSum = 0; int sameNoteCount = 0; for (PitchDifference pitchDifference : filteredSamples) { deviationSum += pitchDifference.deviation; sameNoteCount++; } if (sameNoteCount > 0) { double averageDeviation = deviationSum / sameNoteCount; return new PitchDifference(mostFrequentNote, averageDeviation); } return null; } }
@Test public void the_average_difference_is_calculated_correctly() { List<PitchDifference> samples = new ArrayList<>(); samples.add(new PitchDifference(E2, 2.46D)); samples.add(new PitchDifference(E2, -10.3D)); samples.add(new PitchDifference(E2, 5.71D)); samples.add(new PitchDifference(E2, 12.532D)); samples.add(new PitchDifference(E2, -0.414D)); PitchDifference pitchDifference = calculateAverageDifference(samples); double average = (2.46D - 10.3D + 5.71D + 12.532D - 0.414D) / 5D; assertNotNull(pitchDifference); assertThat(pitchDifference.closest.getName(), is(E2.getName())); assertThat(pitchDifference.deviation, closeTo(average, 0.001)); }
Sampler { static List<PitchDifference> filterByNote(List<PitchDifference> samples, Note note) { List<PitchDifference> filteredSamples = new ArrayList<>(); for (PitchDifference sample : samples) { if (sample.closest == note) { filteredSamples.add(sample); } } return filteredSamples; } }
@Test public void samples_are_filtered_correctly() { List<PitchDifference> samples = new ArrayList<>(); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(B3, 3D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(G3, 4D)); samples.add(new PitchDifference(B3, 3D)); List<PitchDifference> filteredSamples = filterByNote(samples, B3); for (PitchDifference sample : filteredSamples) { assertThat(sample.closest.getName(), is(B3.getName())); } }
Sampler { static Note extractMostFrequentNote(List<PitchDifference> samples) { Map<Note, Integer> noteFrequencies = new HashMap<>(); for (PitchDifference pitchDifference : samples) { Note closest = pitchDifference.closest; if (noteFrequencies.containsKey(closest)) { Integer count = noteFrequencies.get(closest); noteFrequencies.put(closest, count + 1); } else { noteFrequencies.put(closest, 1); } } Note mostFrequentNote = null; int mostOccurrences = 0; for (Note note : noteFrequencies.keySet()) { Integer occurrences = noteFrequencies.get(note); if (occurrences > mostOccurrences) { mostFrequentNote = note; mostOccurrences = occurrences; } } return mostFrequentNote; } }
@Test public void the_most_frequent_note_is_extracted_correctly() { List<PitchDifference> samples = new ArrayList<>(); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(B3, 3D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(G3, 4D)); samples.add(new PitchDifference(B3, 3D)); Note note = extractMostFrequentNote(samples); assertThat(note.getName(), is(E2.getName())); } @Test public void if_there_are_notes_with_the_same_number_of_occurrences_one_of_them_is_returned() { List<PitchDifference> samples = new ArrayList<>(); samples.add(new PitchDifference(G3, 2D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(B3, 3D)); samples.add(new PitchDifference(E2, 2D)); samples.add(new PitchDifference(B3, 3D)); Note note = extractMostFrequentNote(samples); assertThat(note.getName(), either(is(E2.getName())).or(is(B3.getName()))); }
FormatService { public static SerializationFormat getInputFormat(String name) { for (SerializationFormat ft : Instance.serializationFormats) { if (ft.isAcceptedAsInput(name)) { return ft; } } return null; } private FormatService(); static SerializationFormat getInputFormat(String name); static SerializationFormat getOutputFormat(String name); static String getFormatFromExtension(String filename); }
@Test public void testGetInputFormat() { assertEquals(FormatService.getInputFormat("turtle"), SerializationFormatFactory.createTurtle()); assertEquals(FormatService.getInputFormat("ttl"), SerializationFormatFactory.createTurtle()); assertEquals(FormatService.getInputFormat("ntriples"), SerializationFormatFactory.createNTriples()); assertEquals(FormatService.getInputFormat("N-Triple"), SerializationFormatFactory.createNTriples()); assertEquals(FormatService.getInputFormat("n3"), SerializationFormatFactory.createN3()); assertEquals(FormatService.getInputFormat("RDF/XML"), SerializationFormatFactory.createRDFXMLIn()); assertEquals(FormatService.getInputFormat("rdfxml"), SerializationFormatFactory.createRDFXMLIn()); assertEquals(FormatService.getInputFormat("RDF/XML-ABBREV"), SerializationFormatFactory.createRDFXMLIn()); assertEquals(FormatService.getInputFormat("RDFA"), SerializationFormatFactory.createRDFa()); }
RDFUnitUtils { public static void fillSchemaServiceFromLOV() throws IOException { log.info("Loading cached schema entries from LOV!"); RDFUnitUtils.fillSchemaServiceFromResource("org/aksw/rdfunit/configuration/schemaLOV.csv"); } private RDFUnitUtils(); static void fillSchemaServiceFromFile(String additionalCSV); static void fillSchemaServiceWithStandardVocabularies(); static void fillSchemaServiceFromSchemaDecl(); static void fillSchemaServiceFromLOV(); static Optional<T> getFirstItemInCollection(Collection<T> collection); static List<SchemaSource> augmentWithOwlImports(Set<SchemaSource> originalSources); }
@Test public void fillSchemaServiceFromLOVTest() throws IOException { int currentSize = SchemaService.getSize(); RDFUnitUtils.fillSchemaServiceFromLOV(); assertThat(SchemaService.getSize()) .isGreaterThan(currentSize); }
RDFUnitUtils { public static void fillSchemaServiceFromSchemaDecl() throws IOException { log.info("Adding manual schema entries (or overriding LOV)!"); RDFUnitUtils.fillSchemaServiceFromResource("org/aksw/rdfunit/configuration/schemaDecl.csv"); } private RDFUnitUtils(); static void fillSchemaServiceFromFile(String additionalCSV); static void fillSchemaServiceWithStandardVocabularies(); static void fillSchemaServiceFromSchemaDecl(); static void fillSchemaServiceFromLOV(); static Optional<T> getFirstItemInCollection(Collection<T> collection); static List<SchemaSource> augmentWithOwlImports(Set<SchemaSource> originalSources); }
@Test public void fillSchemaServiceFromDeclTest() throws IOException { int currentSize = SchemaService.getSize(); RDFUnitUtils.fillSchemaServiceFromSchemaDecl(); assertThat(SchemaService.getSize()) .isGreaterThan(currentSize); }
RDFUnitStaticValidator { public static TestExecution validate(final Model inputModel) throws Exception { return validate(inputModel, TestCaseExecutionType.shaclTestCaseResult); } private RDFUnitStaticValidator(); static void initWrapper(@NonNull RDFUnitTestSuiteGenerator testSuiteGenerator); static TestSuite getTestSuite(); static TestExecution validate(final Model inputModel); static TestExecution validate(final Model inputModel, final TestCaseExecutionType executionType); static TestExecution validate(final Model inputModel, final String inputURI); static TestExecution validate(final Model inputModel, final TestCaseExecutionType executionType, final String inputURI); static TestExecution validate(final Model inputModel, final TestCaseExecutionType executionType, final String inputURI, DatasetOverviewResults overviewResults); static TestExecution validate(final TestCaseExecutionType testCaseExecutionType, final Model model, final TestSuite testSuite); static TestExecution validate(final TestCaseExecutionType testCaseExecutionType, final TestSource testSource, final TestSuite testSuite); static TestExecution validate(final TestCaseExecutionType testCaseExecutionType, final TestSource testSource, final TestSuite testSuite, DatasetOverviewResults overviewResults); static TestExecution validate(final TestCaseExecutionType testCaseExecutionType, final TestSource testSource, final TestSuite testSuite, final String agentID, DatasetOverviewResults overviewResults); }
@Test public void testValidateModel() throws Exception { RDFUnitStaticValidator.validate(ModelFactory.createDefaultModel(), testCaseExecutionType); }
PrefixNSService { public static String getNSFromPrefix(final String prefix) { return MapInstance.prefixNsBidiMap.get(prefix); } private PrefixNSService(); static String getNSFromPrefix(final String prefix); static String getPrefixFromNS(final String namespace); static void setNSPrefixesInModel(Model model); static String getSparqlPrefixDecl(); static String getURIFromAbbrev(final String abbreviation); static String getLocalName(final String uri, final String prefix); }
@Test public void testGetPrefix() throws IOException { Model prefixModel = ModelFactory.createDefaultModel(); try (InputStream is = org.aksw.rdfunit.services.PrefixNSService.class.getResourceAsStream(Resources.PREFIXES)) { prefixModel.read(is, null, "TURTLE"); } Map<String, String> prefixes = prefixModel.getNsPrefixMap(); for (Map.Entry<String, String> entry : prefixes.entrySet()) { String uri = org.aksw.rdfunit.services.PrefixNSService.getNSFromPrefix(entry.getKey()); Assert.assertEquals("All prefixed should be initialized", uri, entry.getValue()); } }
ValidateUtils { public static RDFUnitConfiguration getConfigurationFromArguments(CommandLine commandLine) throws ParameterException { checkIfRequiredParametersMissing(commandLine); RDFUnitConfiguration configuration = readDatasetUriAndInitConfiguration(commandLine); setDumpOrSparqlEndpoint(commandLine, configuration); loadSchemaDecl(configuration); setExcludeSchemata(commandLine, configuration); setSchemas(commandLine, configuration); setEnrichedSchemas(commandLine, configuration); setTestExecutionType(commandLine, configuration); setOutputFormats(commandLine, configuration); setTestAutogetCacheManual(commandLine, configuration); setQueryTtlCachePaginationLimit(commandLine, configuration); setCoverageCalculation(commandLine, configuration); return configuration; } private ValidateUtils(); static Options getCliOptions(); static CommandLine parseArguments(String[] args); static RDFUnitConfiguration getConfigurationFromArguments(CommandLine commandLine); }
@Test public void testGetConfigurationFromArguments() throws ParseException, ParameterException { Options cliOptions = ValidateUtils.getCliOptions(); String args; RDFUnitConfiguration configuration; CommandLine commandLine; CommandLineParser cliParser = new DefaultParser(); SchemaService.addSchemaDecl("rdfs", "http: SchemaService.addSchemaDecl("owl", "http: SchemaService.addSchemaDecl("dataid", "http: SchemaService.addSchemaDecl("prov", "http: SchemaService.addSchemaDecl("foaf", "http: SchemaService.addSchemaDecl("void", "http: SchemaService.addSchemaDecl("dcat", "http: args = " -d http: commandLine = cliParser.parse(cliOptions, args.split(" ")); configuration = ValidateUtils.getConfigurationFromArguments(commandLine); assertEquals(configuration.getDatasetURI(), "http: assertEquals(configuration.getPrefix(), "dbpedia.org"); assertTrue(configuration.isAugmentWithOwlImports()); assertEquals(configuration.getEndpointURI(), "http: assertNull(configuration.getCustomDereferenceURI()); assertTrue(configuration.getTestSource() instanceof EndpointTestSource); assertEquals(configuration.getEndpointGraphs(), Collections.singletonList("http: assertEquals(configuration.getAllSchemata().size(), 8); assertNotNull(configuration.getEnrichedSchema()); assertEquals(configuration.getDataFolder(), "data/"); assertEquals(configuration.getTestFolder(), "data/tests/"); assertEquals(configuration.getOutputFormats().size(), 1); assertTrue(configuration.isManualTestsEnabled()); assertFalse(configuration.isAutoTestsEnabled()); assertFalse(configuration.isTestCacheEnabled()); EndpointTestSource endpointTestSource = (EndpointTestSource) configuration.getTestSource(); assertEquals(configuration.getEndpointQueryCacheTTL(), 10L * 60L * 1000L); assertEquals(configuration.getEndpointQueryCacheTTL(), endpointTestSource.getCacheTTL()); assertEquals(configuration.getEndpointQueryDelayMS(), 10L); assertEquals(configuration.getEndpointQueryDelayMS(), endpointTestSource.getQueryDelay()); assertEquals(configuration.getEndpointQueryPagination(), 10L); assertEquals(configuration.getEndpointQueryPagination(), endpointTestSource.getPagination()); assertEquals(configuration.getEndpointQueryLimit(), 10L); assertEquals(configuration.getEndpointQueryLimit(), endpointTestSource.getQueryLimit()); args = " -d http: commandLine = cliParser.parse(cliOptions, args.split(" ")); configuration = ValidateUtils.getConfigurationFromArguments(commandLine); assertEquals(configuration.getDatasetURI(), "http: assertEquals(configuration.getCustomDereferenceURI(), "http: assertEquals(configuration.getAllSchemata().size(), 1); assertNull(configuration.getEnrichedSchema()); assertEquals(configuration.getOutputFormats().size(), 2); assertEquals(configuration.getDataFolder(), "/home/rdfunit/"); assertEquals(configuration.getTestFolder(), "/home/rdfunit/tests/"); assertFalse(configuration.isManualTestsEnabled()); assertTrue(configuration.isAutoTestsEnabled()); assertTrue(configuration.isTestCacheEnabled()); assertFalse(configuration.isCalculateCoverageEnabled()); assertTrue(configuration.getTestSource() instanceof DumpTestSource); args = " -d http: commandLine = cliParser.parse(cliOptions, args.split(" ")); configuration = ValidateUtils.getConfigurationFromArguments(commandLine); assertTrue(configuration.isManualTestsEnabled()); assertFalse(configuration.isTestCacheEnabled()); assertTrue(configuration.isCalculateCoverageEnabled()); HashMap<String, String> exceptionsExpected = new HashMap<>(); exceptionsExpected.put( " -s rdf ", "Expected exception for missing -d"); exceptionsExpected.put( " -d http: "Expected exception for defining both -e & -u"); exceptionsExpected.put( " -d http: "Expected exception for asking unsupported -l"); exceptionsExpected.put( " -d http: "Expected exception for asking for undefined 'ex' schema "); exceptionsExpected.put( " -d http: "Expected exception for asking for undefined serialization 'htmln'"); exceptionsExpected.put( " -d http: "Expected exception for asking for undefined serialization 'turtle123'"); exceptionsExpected.put( " -d http: "Expected exception for asking for excluding both manual & auto test cases"); exceptionsExpected.put( " -d http: "Expected exception for asking for excluding auto tests & specifying -C"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting -P without an Endpoint"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting -T without an Endpoint"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting -D without an Endpoint"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting non-numeric in -P"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting non-numeric in -T"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting non-numeric in -D"); exceptionsExpected.put( " -d http: "Expected exception for asking for setting non-numeric in -L"); for (Map.Entry<String, String> entry : exceptionsExpected.entrySet()) { try { commandLine = cliParser.parse(cliOptions, entry.getKey().split(" ")); configuration = ValidateUtils.getConfigurationFromArguments(commandLine); fail(entry.getValue()); } catch (ParameterException e) { } } }
PatternWriter implements ElementWriter { @Override public Resource write(Model model) { Resource resource = ElementWriter.copyElementResourceInModel(pattern, model); resource .addProperty(RDF.type, RDFUNITv.Pattern) .addProperty(DCTerms.identifier, pattern.getId()) .addProperty(DCTerms.description, pattern.getDescription()) .addProperty(RDFUNITv.sparqlWherePattern, pattern.getSparqlWherePattern()); if (pattern.getSparqlPatternPrevalence().isPresent()) { resource.addProperty(RDFUNITv.sparqlPrevalencePattern, pattern.getSparqlPatternPrevalence().get()); } for (PatternParameter patternParameter: pattern.getParameters()) { Resource parameter = PatternParameterWriter.create(patternParameter).write(model); resource.addProperty(RDFUNITv.parameter, parameter); } for (ResultAnnotation resultAnnotation: pattern.getResultAnnotations()) { Resource annotationResource = ResultAnnotationWriter.create(resultAnnotation).write(model); resource.addProperty(RDFUNITv.resultAnnotation, annotationResource); } return resource; } private PatternWriter(Pattern pattern); static PatternWriter create(Pattern pattern); @Override Resource write(Model model); }
@Test public void testWrite() throws RdfReaderException, RdfWriterException { Model inputModel = RdfReaderFactory.createResourceReader(Resources.PATTERNS).read(); Collection<Pattern> patterns = BatchPatternReader.create().getPatternsFromModel(inputModel); Model outputModel = ModelFactory.createDefaultModel(); for (Pattern pattern: patterns) { PatternWriter.create(pattern).write(outputModel); } assertThat(inputModel.isIsomorphicWith(outputModel)).isTrue(); }
ShaclModel { public Set<GenericTestCase> generateTestCases() { return allShapeGroup.stream().flatMap(groupShape -> getGenericTestCase(groupShape).values().stream().flatMap(Collection::stream)).collect(Collectors.toSet()); } ShaclModel(Model inputShaclGraph); Set<GenericTestCase> generateTestCases(); }
@Test public void testRead() throws RdfReaderException { ShaclModel shaclModel = new ShaclModel(RdfReaderFactory.createResourceReader(shapeResource).read()); Set<GenericTestCase> tests = shaclModel.generateTestCases(); assertThat(tests) .isNotEmpty(); }
ShapeReader implements ElementReader<Shape> { @Override public Shape read(Resource resource) { checkNotNull(resource); ShapeImpl.ShapeImplBuilder shapeBuilder = ShapeImpl.builder(); shapeBuilder .element(resource) .propertyValuePairSets(PropertyValuePairSet.createFromResource(resource)); Resource path = resource.getPropertyResourceValue(SHACL.path); if (path != null) { shapeBuilder.shaclPath( ShapePathReader.create().read(path) ); } return shapeBuilder.build(); } private ShapeReader(); static ShapeReader create(); @Override Shape read(Resource resource); }
@Test public void testRead() throws RdfReaderException { Model shapesModel = RdfReaderFactory.createResourceReader(shapeResource).read(); List<Shape> shapes = shapesModel.listResourcesWithProperty(RDF.type, SHACL.Shape).toList() .stream() .map( r -> ShapeReader.create().read(r)) .collect(Collectors.toList()); assertThat(shapes) .hasSize(1); Shape sh = shapes.get(0); checkTarget(sh); }
ComponentReader implements ElementReader<Component> { @Override public Component read(Resource resource) { checkNotNull(resource); ComponentImpl.ComponentImplBuilder componentBuilder = ComponentImpl.builder(); componentBuilder.element(resource); for (Statement smt : resource.listProperties(SHACL.parameter).toList()) { Resource obj = smt.getObject().asResource(); ComponentParameter cp = ComponentParameterReader.create().read(obj); componentBuilder.parameter(cp); } for (Statement smt : resource.listProperties(SHACL.validator).toList()) { Resource obj = smt.getObject().asResource(); ComponentValidator cv = ComponentValidatorReader.create(ComponentValidatorType.ASK_VALIDATOR).read(obj); componentBuilder.validator(cv); } for (Statement smt : resource.listProperties(SHACL.nodeValidator).toList()) { Resource obj = smt.getObject().asResource(); ComponentValidator cv = ComponentValidatorReader.create(ComponentValidatorType.NODE_VALIDATOR).read(obj); componentBuilder.validator(cv); } for (Statement smt : resource.listProperties(SHACL.propertyValidator).toList()) { Resource obj = smt.getObject().asResource(); ComponentValidator cv = ComponentValidatorReader.create(ComponentValidatorType.PROPERTY_VALIDATOR).read(obj); componentBuilder.validator(cv); } return componentBuilder.build(); } private ComponentReader(); static ComponentReader create(); @Override Component read(Resource resource); }
@Test public void testRead() { Component c = ComponentReader.create().read(resource); int i = 0; }
SparqlValidatorReader implements ElementReader<Validator> { @Override public Validator read(Resource resource) { checkNotNull(resource); SparqlValidatorImpl.SparqlValidatorImplBuilder validatorBuilder = SparqlValidatorImpl.builder(); validatorBuilder.element(resource); for (Statement smt : resource.listProperties(SHACL.message).toList()) { validatorBuilder.message(smt.getObject().asLiteral()); } for (Statement smt : resource.listProperties(SHACL.prefixes).toList()) { RDFNode obj = smt.getObject(); if (obj.isResource()) { validatorBuilder.prefixDeclarations(BatchPrefixDeclarationReader.create().getPrefixDeclarations(obj.asResource())); } } for (Statement smt : resource.listProperties(SHACL.select).toList()) { validatorBuilder.sparqlQuery(smt.getObject().asLiteral().getLexicalForm()); } return validatorBuilder.build(); } private SparqlValidatorReader(); static SparqlValidatorReader create(); @Override Validator read(Resource resource); }
@Test public void testRead() { SparqlValidatorReader.create().read(resource); }
FormatService { public static SerializationFormat getOutputFormat(String name) { for (SerializationFormat ft : Instance.serializationFormats) { if (ft.isAcceptedAsOutput(name)) { return ft; } } return null; } private FormatService(); static SerializationFormat getInputFormat(String name); static SerializationFormat getOutputFormat(String name); static String getFormatFromExtension(String filename); }
@Test public void testGetOutputFormat() { assertEquals(FormatService.getOutputFormat("turtle"), SerializationFormatFactory.createTurtle()); assertEquals(FormatService.getOutputFormat("ttl"), SerializationFormatFactory.createTurtle()); assertEquals(FormatService.getOutputFormat("ntriples"), SerializationFormatFactory.createNTriples()); assertEquals(FormatService.getOutputFormat("N-Triple"), SerializationFormatFactory.createNTriples()); assertEquals(FormatService.getOutputFormat("n3"), SerializationFormatFactory.createN3()); assertEquals(FormatService.getOutputFormat("RDF/XML"), SerializationFormatFactory.createRDFXMLOut()); assertEquals(FormatService.getOutputFormat("rdfxml"), SerializationFormatFactory.createRDFXMLOut()); assertEquals(FormatService.getOutputFormat("RDF/XML-ABBREV"), SerializationFormatFactory.createRDFXMLAbbrevOut()); }
ShapePathReader implements ElementReader<ShapePath> { @Override public ShapePath read(Resource resource) { checkNotNull(resource); ShapePathImpl.ShapePathImplBuilder shapePathBuilder = ShapePathImpl.builder(); shapePathBuilder.element(resource); shapePathBuilder.jenaPath(readPath(resource)); return shapePathBuilder.build(); } private ShapePathReader(); static ShapePathReader create(); @Override ShapePath read(Resource resource); }
@Test public void testRead() { assertThat(ShapePathReader.create().read(shaclPath).asSparqlPropertyPath()) .isEqualTo(propertyPathString); }
ComponentValidatorReader implements ElementReader<ComponentValidator> { @Override public ComponentValidator read(Resource resource) { checkNotNull(resource); ComponentValidatorImpl.ComponentValidatorImplBuilder validatorBuilder = ComponentValidatorImpl.builder(); validatorBuilder.element(resource); validatorBuilder.type(type); for (Statement smt : resource.listProperties(SHACL.message).toList()) { validatorBuilder.message(smt.getObject().asLiteral()); } for (Statement smt : resource.listProperties(SHACL.prefixes).toList()) { RDFNode obj = smt.getObject(); if (obj.isResource()) { validatorBuilder.prefixDeclarations(BatchPrefixDeclarationReader.create().getPrefixDeclarations(obj.asResource())); } } for (Statement smt : resource.listProperties(SHACL.ask).toList()) { checkArgument(type.equals(ComponentValidatorType.ASK_VALIDATOR), "SPARQL SELECT-Based Validator contains ASK query: %s", smt.getObject().asLiteral().getLexicalForm()); validatorBuilder.sparqlQuery(smt.getObject().asLiteral().getLexicalForm()); } for (Statement smt : resource.listProperties(SHACL.select).toList()) { checkArgument(!type.equals(ComponentValidatorType.ASK_VALIDATOR), "SPARQL ASK-Based Validator contains SELECT query %s", smt.getObject().asLiteral().getLexicalForm()); validatorBuilder.sparqlQuery(smt.getObject().asLiteral().getLexicalForm()); } for (Statement smt : resource.listProperties(RDFUNIT_SHACL_EXT.filter).toList()) { validatorBuilder.filter(smt.getObject().asLiteral().getLexicalForm()); } return validatorBuilder.build(); } private ComponentValidatorReader(ComponentValidatorType type); static ComponentValidatorReader create(ComponentValidatorType type); @Override ComponentValidator read(Resource resource); }
@Test public void testRead() { ComponentValidatorReader.create(ComponentValidatorType.ASK_VALIDATOR).read(resource); }
ComponentParameterReader implements ElementReader<ComponentParameter> { @Override public ComponentParameter read(Resource resource) { checkNotNull(resource); ComponentParameterImpl.ComponentParameterImplBuilder argumentBuilder = ComponentParameterImpl.builder(); argumentBuilder.element(resource); for (Statement smt : resource.listProperties(SHACL.path).toList()) { argumentBuilder = argumentBuilder.predicate(ResourceFactory.createProperty(smt.getObject().asResource().getURI())); } checkNotNull(argumentBuilder); for (Statement smt : resource.listProperties(SHACL.defaultValue).toList()) { argumentBuilder.defaultValue(smt.getObject()); } for (Statement smt : resource.listProperties(SHACL.optional).toList()) { argumentBuilder.isOptional(smt.getObject().asLiteral().getBoolean()); } return argumentBuilder.build(); } private ComponentParameterReader(); static ComponentParameterReader create(); @Override ComponentParameter read(Resource resource); }
@Test public void testRead() { ComponentParameterReader.create().read(resource); }
BatchShapeTargetReader { public Set<ShapeTarget> read(Resource resource) { checkNotNull(resource); ImmutableSet.Builder<ShapeTarget> targetBuilder = ImmutableSet.builder(); targetBuilder.addAll(collectExplicitTargets(resource)); return targetBuilder.build(); } private BatchShapeTargetReader(); static BatchShapeTargetReader create(); Set<ShapeTarget> read(Resource resource); }
@Test public void testRead() throws RdfReaderException { Model shapesModel = RdfReaderFactory.createResourceReader(shapeResource).read(); Resource r1 = shapesModel.getResource("http: Set<ShapeTarget> targets1 = BatchShapeTargetReader.create().read(r1); assertThat(targets1) .hasSize(2); }
PatternReader implements ElementReader<Pattern> { @Override public Pattern read(Resource resource) { checkNotNull(resource); PatternImpl.Builder patternBuilder = new PatternImpl.Builder(); patternBuilder.setElement(resource); int count; count = 0; for (Statement smt : resource.listProperties(DCTerms.identifier).toList()) { checkArgument(++count == 1, "Cannot have more than one identifier in Pattern %s", resource.getURI()); patternBuilder.setId(smt.getObject().asLiteral().getLexicalForm()); } count = 0; for (Statement smt : resource.listProperties(DCTerms.description).toList()) { checkArgument(++count == 1, "Cannot have more than one description in Pattern %s", resource.getURI()); patternBuilder.setDescription(smt.getObject().asLiteral().getLexicalForm()); } count = 0; for (Statement smt : resource.listProperties(RDFUNITv.sparqlWherePattern).toList()) { checkArgument(++count == 1, "Cannot have more than one SPARQL query in Pattern %s", resource.getURI()); patternBuilder.setSparqlWherePattern(smt.getObject().asLiteral().getLexicalForm()); } count = 0; for (Statement smt : resource.listProperties(RDFUNITv.sparqlPrevalencePattern).toList()) { checkArgument(++count == 1, "Cannot have more than one prevalence query in Pattern %s", resource.getURI()); patternBuilder.setSparqlPatternPrevalence(smt.getObject().asLiteral().getLexicalForm()); } Collection<PatternParameter> patternParameters = resource.listProperties(RDFUNITv.parameter).toList().stream() .map(smt -> PatternParameterReader.create().read(smt.getResource())) .collect(Collectors.toCollection(ArrayList::new)); patternBuilder.setParameters(patternParameters); Collection<ResultAnnotation> patternAnnotations = resource.listProperties(RDFUNITv.resultAnnotation).toList().stream() .map(smt -> ResultAnnotationReader.create().read(smt.getResource())) .collect(Collectors.toList()); patternBuilder.setAnnotations(patternAnnotations); return patternBuilder.build(); } private PatternReader(); static PatternReader create(); @Override Pattern read(Resource resource); }
@Test public void testRead() { PatternReader.create().read(resource); }
PatternParameterReader implements ElementReader<PatternParameter> { @Override public PatternParameter read(Resource resource) { checkNotNull(resource); PatternParameterImpl.Builder parameterBuilder = new PatternParameterImpl.Builder(); parameterBuilder.setElement(resource); for (Statement smt : resource.listProperties(DCTerms.identifier).toList()) { parameterBuilder.setID(smt.getObject().asLiteral().getLexicalForm()); } for (Statement smt : resource.listProperties(RDFUNITv.parameterConstraint).toList()) { parameterBuilder.setPatternParameterConstraints(smt.getObject().asResource().getURI()); } for (Statement smt : resource.listProperties(RDFUNITv.constraintPattern).toList()) { parameterBuilder.setConstraintPattern(smt.getObject().asLiteral().getLexicalForm()); } return parameterBuilder.build(); } private PatternParameterReader(); static PatternParameterReader create(); @Override PatternParameter read(Resource resource); }
@Test public void testRead() { PatternParameterReader.create().read(resource); }
SelectVar { public static SelectVar create(String name) { return new SelectVar(name, name); } static SelectVar create(String name); static SelectVar create(String name, String label); String asString(); }
@Test public void testCreate() { String varName = "test"; SelectVar selectVar = SelectVar.create(varName); assertThat(selectVar.getName()) .isEqualTo(varName); assertThat(selectVar.getLabel()) .isEqualTo(varName); assertThat(selectVar.asString()) .isEqualTo(" ?" + varName + " "); } @Test(expected=NullPointerException.class) public void testNull() { SelectVar.create(null); }
AnnotationTemplate { public void addTemplateMin(Property property, int minOccurs) { template.put(property, Range.atLeast(minOccurs)); } private AnnotationTemplate(); static AnnotationTemplate create(); void addTemplateMin(Property property, int minOccurs); void addTemplateMax(Property property, int maxOccurs); void addTemplateMinMax(Property property, int minOccurs, int maxOccurs); Set<Property> getPropertiesAsSet(); boolean existsInTemplate(PropertyValuePair propertyValuePair); boolean isValidAccordingToTemplate(PropertyValuePair propertyValuePair); }
@Test public void testAddTemplateMin() { AnnotationTemplate at = AnnotationTemplate.create(); assertThat(at.existsInTemplate(sa1)).isFalse(); at.addTemplateMin(RDF.type, 2); assertThat(at.existsInTemplate(sa1)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa1)).isFalse(); assertThat(at.existsInTemplate(sa2)).isFalse(); at.addTemplateMin(RDF.predicate, 2); assertThat(at.existsInTemplate(sa2)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa2)).isTrue(); }
AnnotationTemplate { public void addTemplateMax(Property property, int maxOccurs) { template.put(property, Range.atMost(maxOccurs)); } private AnnotationTemplate(); static AnnotationTemplate create(); void addTemplateMin(Property property, int minOccurs); void addTemplateMax(Property property, int maxOccurs); void addTemplateMinMax(Property property, int minOccurs, int maxOccurs); Set<Property> getPropertiesAsSet(); boolean existsInTemplate(PropertyValuePair propertyValuePair); boolean isValidAccordingToTemplate(PropertyValuePair propertyValuePair); }
@Test public void testAddTemplateMax() { AnnotationTemplate at = AnnotationTemplate.create(); assertThat(at.existsInTemplate(sa1)).isFalse(); at.addTemplateMax(RDF.type, 1); assertThat(at.existsInTemplate(sa1)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa1)).isTrue(); assertThat(at.existsInTemplate(sa2)).isFalse(); assertThat(at.isValidAccordingToTemplate(sa2)).isFalse(); at.addTemplateMax(RDF.predicate, 1); assertThat(at.existsInTemplate(sa2)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa2)).isFalse(); }
FormatService { public static String getFormatFromExtension(String filename) { String format = "TURTLE"; try { String extension; Lang jenaLang = RDFLanguages.filenameToLang(filename); if (jenaLang != null) { extension = jenaLang.getFileExtensions().get(0); } else { int index = filename.lastIndexOf('.'); extension = filename.substring(index + 1, filename.length()); } SerializationFormat f = FormatService.getInputFormat(extension); if (f != null) { format = f.getName(); } } catch (Exception e) { log.debug("No format found, using the default one", e); return "TURTLE"; } return format; } private FormatService(); static SerializationFormat getInputFormat(String name); static SerializationFormat getOutputFormat(String name); static String getFormatFromExtension(String filename); }
@Test public void testGetFormatFromExtension() { Map<String, String> testVals = new HashMap<>(); testVals.put("asdf.ttl", "TURTLE"); testVals.put("asdf.nt", "N-TRIPLE"); testVals.put("asdf.n3", "N3"); testVals.put("asdf.jsonld", "JSON-LD"); testVals.put("asdf.rj", "RDF/JSON"); testVals.put("asdf.rdf", "RDF/XML"); testVals.put("asdf.nq", "NQuads"); testVals.put("asdf.trix", "TriX"); testVals.put("asdf.trig", "TriG"); testVals.put("asdf.html", "RDFA"); for (Map.Entry<String, String> entry: testVals.entrySet()) { assertEquals("Should be equal", entry.getValue(), FormatService.getFormatFromExtension(entry.getKey())); } }
AnnotationTemplate { public void addTemplateMinMax(Property property, int minOccurs, int maxOccurs) { template.put(property, Range.closed(minOccurs, maxOccurs)); } private AnnotationTemplate(); static AnnotationTemplate create(); void addTemplateMin(Property property, int minOccurs); void addTemplateMax(Property property, int maxOccurs); void addTemplateMinMax(Property property, int minOccurs, int maxOccurs); Set<Property> getPropertiesAsSet(); boolean existsInTemplate(PropertyValuePair propertyValuePair); boolean isValidAccordingToTemplate(PropertyValuePair propertyValuePair); }
@Test public void testAddTemplateMinMax() { AnnotationTemplate at = AnnotationTemplate.create(); assertThat(at.existsInTemplate(sa1)).isFalse(); at.addTemplateMinMax(RDF.type, 1, 2); assertThat(at.existsInTemplate(sa1)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa1)).isTrue(); assertThat(at.existsInTemplate(sa2)).isFalse(); at.addTemplateMinMax(RDF.predicate, 3, 5); assertThat(at.existsInTemplate(sa2)).isTrue(); assertThat(at.isValidAccordingToTemplate(sa2)).isFalse(); }
AnnotationTemplate { public Set<Property> getPropertiesAsSet() { return template.keySet(); } private AnnotationTemplate(); static AnnotationTemplate create(); void addTemplateMin(Property property, int minOccurs); void addTemplateMax(Property property, int maxOccurs); void addTemplateMinMax(Property property, int minOccurs, int maxOccurs); Set<Property> getPropertiesAsSet(); boolean existsInTemplate(PropertyValuePair propertyValuePair); boolean isValidAccordingToTemplate(PropertyValuePair propertyValuePair); }
@Test public void testGetPropertiesAsSet() { AnnotationTemplate at = AnnotationTemplate.create(); at.addTemplateMinMax(RDF.type, 1,2); at.addTemplateMinMax(RDF.predicate, 3,5); assertThat(at.getPropertiesAsSet()).isNotEmpty(); assertThat(at.getPropertiesAsSet().size()).isEqualTo(2); }
ShapeTargetCore implements ShapeTarget { public static ShapeTarget create(@NonNull ShapeTargetType targetType, @NonNull RDFNode node) { switch (targetType) { case ClassTarget: return new ShapeTargetCore(targetType, node, ShapeTargetCore::classTargetPattern); case NodeTarget: return new ShapeTargetCore(targetType, node, ShapeTargetCore::nodeTargetPattern); case ObjectsOfTarget: return new ShapeTargetCore(targetType, node, ShapeTargetCore::objectsOfTargetPattern); case SubjectsOfTarget: return new ShapeTargetCore(targetType, node, ShapeTargetCore::subjectsOfTargetPattern); default: throw new IllegalArgumentException("Something wrong with the input"); } } private ShapeTargetCore(ShapeTargetType targetType, RDFNode node, Function<RDFNode, String> generatePattern); @Override String getPattern(); @Override Set<Resource> getRelatedOntologyResources(); static ShapeTarget create(@NonNull ShapeTargetType targetType, @NonNull RDFNode node); }
@Test(expected=NullPointerException.class) public void testCreateNullType() { ShapeTargetCore.create(null, null); } @Test public void testPatternUnique() { List<String> targetPatterns = Arrays.stream(ShapeTargetType.values() ) .filter( sct -> !sct.equals(ShapeTargetType.ValueShapeTarget)) .map( s -> ShapeTargetCore.create(s, ResourceFactory.createResource("http: .map(ShapeTarget::getPattern) .collect(Collectors.toList()); assertThat(targetPatterns.size()) .isEqualTo(new HashSet<>(targetPatterns).size()); }
ComponentParameterImpl implements ComponentParameter { @Override public Optional<RDFNode> getDefaultValue() { return Optional.ofNullable(defaultValue); } @Override Optional<RDFNode> getDefaultValue(); }
@Test public void testGetDefaultValue() { assertThat(argDef.getDefaultValue().isPresent()) .isFalse(); RDFNode node = ResourceFactory.createResource("http: ComponentParameterImpl arg2 = ComponentParameterImpl.builder().element(element).predicate(predicate).defaultValue(node).build(); assertThat(arg2.getDefaultValue().get()) .isEqualTo(node); }
RdfUnitJunitRunner extends ParentRunner<RdfUnitJunitTestCase> { protected RdfReader getAdditionalDataModel() { return additionalData; } RdfUnitJunitRunner(Class<?> testClass); static final Class<?> INPUT_DATA_RETURN_TYPE; }
@Test public void returnsVocabulary() throws InitializationError { final RdfUnitJunitRunner rdfUnitJunitRunner = new RdfUnitJunitRunner(ControlledVocabularyTest.class); assertThat(rdfUnitJunitRunner.getAdditionalDataModel()).isSameAs(CONTROLLED_VOCABULARY); }
MetricMapper { public static MetricMapper createDefault() { Model model; try { model = RdfReaderFactory.createResourceReader("/org/aksw/rdfunit/dqv/metricMappings.ttl").read(); } catch (RdfReaderException e) { throw new IllegalArgumentException("Cannot read default metric mappings", e); } ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>(); model.listStatements().toList().stream() .filter(smt -> smt.getPredicate().equals(RDFUNITv.metric)) .filter(smt -> smt.getObject().isResource()) .forEach(smt -> builder.put(smt.getSubject().getURI(), smt.getObject().asResource().getURI())); return new MetricMapper(builder.build()); } private MetricMapper(ImmutableMap<String, String> metricMap); Map<String, String> getMetricMap(); static MetricMapper createDefault(); }
@Test public void testCreateDefault() { MetricMapper metricMapper = MetricMapper.createDefault(); int DEFAULT_MAP_SIZE = 16; assertThat(metricMapper.getMetricMap().size()) .isEqualTo(DEFAULT_MAP_SIZE); }
RdfFirstSuccessReader implements RdfReader { @Override public void read(Model model) throws RdfReaderException { StringBuilder message = new StringBuilder(); for (RdfReader r : readers) { try { r.read(model); return; } catch (RdfReaderException e) { message.append('\n'); if (e.getMessage() != null) { message.append(e.getMessage()); } else { message.append(e); } } } throw new RdfReaderException("Cannot read from any reader: " + message.toString()); } RdfFirstSuccessReader(Collection<RdfReader> readers); @Override void read(Model model); @Override void readDataset(Dataset dataset); @Override String toString(); }
@Test public void testNotExceptionRead() { ArrayList<RdfReader> rdfReaders = new ArrayList<>(); rdfReaders.add(new RdfStreamReader("")); rdfReaders.add(RdfReaderFactory.createResourceReader("/org/aksw/rdfunit/io/empty.ttl")); RdfFirstSuccessReader reader = new RdfFirstSuccessReader(rdfReaders); try { reader.read(); } catch (RdfReaderException e) { fail("Should have NOT raised a TripleReaderException"); } }
RdfFirstSuccessReader implements RdfReader { @Override public void readDataset(Dataset dataset) throws RdfReaderException { StringBuilder message = new StringBuilder(); for (RdfReader r : readers) { try { r.readDataset(dataset); return; } catch (RdfReaderException e) { message.append("\n"); if (e.getMessage() != null) { message.append(e.getMessage()); } else { message.append(e); } } } throw new RdfReaderException("Cannot read from any reader: " + message.toString()); } RdfFirstSuccessReader(Collection<RdfReader> readers); @Override void read(Model model); @Override void readDataset(Dataset dataset); @Override String toString(); }
@Test public void testNotExceptionReadDataset() { ArrayList<RdfReader> rdfReaders = new ArrayList<>(); rdfReaders.add(new RdfStreamReader("")); rdfReaders.add(RdfReaderFactory.createResourceReader("/org/aksw/rdfunit/io/empty.ttl")); RdfFirstSuccessReader reader = new RdfFirstSuccessReader(rdfReaders); try { reader.readDataset(); } catch (RdfReaderException e) { Assert.fail("Should have NOT raised a TripleReaderException"); } }
RdfStreamReader implements RdfReader { @Override public void read(Model model) throws RdfReaderException { try { RDFDataMgr.read(model, inputStream, null, RDFLanguages.nameToLang(format)); } catch (Exception e) { throw new RdfReaderException(e.getMessage(), e); } } RdfStreamReader(String filename); RdfStreamReader(String filename, String format); RdfStreamReader(InputStream inputStream, String format); @Override void read(Model model); @Override void readDataset(Dataset dataset); @Override String toString(); }
@Test public void testReader() throws Exception{ Model readModel = RdfReaderFactory.createResourceReader(resourceName).read(); assertTrue("Models not the same", model.isIsomorphicWith(readModel)); }
RdfReaderFactory { public static RdfReader createReaderFromText(String text, String format) { InputStream is; is = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); return new RdfStreamReader(is, format); } private RdfReaderFactory(); static RdfReader createFileOrDereferenceReader(String filename, String uri); static RdfReader createResourceReader(String resource); static RdfReader createFileOrResourceReader(String filename, String resource); static RdfReader createResourceOrFileOrDereferenceReader(String uri); static RdfReader createDereferenceReader(String uri); static RdfReader createReaderFromText(String text, String format); static RdfReader createEmptyReader(); }
@Test public void testCreateReaderFromText() throws IOException, RdfReaderException { URL url = Resources.getResource(this.getClass(),"/org/aksw/rdfunit/io/onetriple.ttl"); String content = Resources.toString(url, Charsets.UTF_8); RdfReader reader = RdfReaderFactory.createReaderFromText(content, "TTL"); Model model = reader.read(); assertThat(model.isIsomorphicWith(ReaderTestUtils.createOneTripleModel())).isTrue(); }
NamespaceStatistics { public Collection<SchemaSource> getNamespaces(QueryExecutionFactory qef) { Set<String> namespaces = new HashSet<>(); for (DatasetStatistics dt : datasetStatistics) { namespaces.addAll(dt.getStatisticsMap(qef).keySet().stream() .map(this::getNamespaceFromURI) .collect(Collectors.toList())); } return getIdentifiedSchemata(namespaces); } private NamespaceStatistics(Collection<DatasetStatistics> datasetStatisticses, boolean skipUnknownNamespaces, RDFUnitConfiguration conf); static NamespaceStatistics createOntologyNSStatisticsKnown(RDFUnitConfiguration conf); static NamespaceStatistics createOntologyNSStatisticsAll(RDFUnitConfiguration conf); static NamespaceStatistics createCompleteNSStatisticsKnown(RDFUnitConfiguration conf); static NamespaceStatistics createCompleteNSStatisticsAll(RDFUnitConfiguration conf); Collection<SchemaSource> getNamespaces(QueryExecutionFactory qef); String getNamespaceFromURI(String uri); }
@Test public void testGetNamespaces() { assertEquals(13, NamespaceStatistics.createCompleteNSStatisticsAll(null).getNamespaces(qef).size()); assertEquals(0, NamespaceStatistics.createCompleteNSStatisticsKnown(null).getNamespaces(qef).size()); assertEquals(8, NamespaceStatistics.createOntologyNSStatisticsAll(null).getNamespaces(qef).size()); assertEquals(0, NamespaceStatistics.createOntologyNSStatisticsKnown(null).getNamespaces(qef).size()); }
NamespaceStatistics { public String getNamespaceFromURI(String uri) { String breakChar = "/"; if (uri.contains("#")) { breakChar = "#"; } else { if (uri.substring(6).contains(":")) { breakChar = ":"; } } int pos = Math.min(uri.lastIndexOf(breakChar), uri.length()); return uri.substring(0, pos + 1); } private NamespaceStatistics(Collection<DatasetStatistics> datasetStatisticses, boolean skipUnknownNamespaces, RDFUnitConfiguration conf); static NamespaceStatistics createOntologyNSStatisticsKnown(RDFUnitConfiguration conf); static NamespaceStatistics createOntologyNSStatisticsAll(RDFUnitConfiguration conf); static NamespaceStatistics createCompleteNSStatisticsKnown(RDFUnitConfiguration conf); static NamespaceStatistics createCompleteNSStatisticsAll(RDFUnitConfiguration conf); Collection<SchemaSource> getNamespaces(QueryExecutionFactory qef); String getNamespaceFromURI(String uri); }
@Test public void testGetNamespaceFromURI() { Map<String, String> examples = new HashMap<>(); examples.put("http: examples.put("http: examples.put("http: NamespaceStatistics namespaceStatistics = NamespaceStatistics.createCompleteNSStatisticsAll(null); for (Map.Entry<String, String> entry : examples.entrySet()) { String namespace = entry.getValue(); assertEquals("All prefixed should be initialized", namespace, namespaceStatistics.getNamespaceFromURI(entry.getKey())); } }
LOVEndpoint { public SchemaEntry extractResourceLocation(SchemaEntry entry) { Optional<String> actualResourceUri = Optional.empty(); if (! entry.getVocabularyDefinedBy().equals(entry.getVocabularyNamespace())) { actualResourceUri = getContentLocation(entry.getVocabularyDefinedBy(), GENERALFORMAT, Lists.newArrayList()); } if(! actualResourceUri.isPresent()) { actualResourceUri = getContentLocation(entry.getVocabularyURI(), GENERALFORMAT, Lists.newArrayList()); } if (! actualResourceUri.isPresent() && ! entry.getVocabularyDefinedBy().equals(entry.getVocabularyNamespace())) { actualResourceUri = getContentLocation(entry.getVocabularyDefinedBy(), TEXTHTML, Lists.newArrayList()); } if(! actualResourceUri.isPresent()) { actualResourceUri = getContentLocation(entry.getVocabularyURI(), TEXTHTML, Lists.newArrayList()); } if(! actualResourceUri.isPresent()) { log.info("Could not find resource for " + entry.getVocabularyURI()); return entry; } return new SchemaEntry(entry.getPrefix(), entry.getVocabularyURI(), entry.getVocabularyNamespace(), actualResourceUri.get()); } List<SchemaEntry> getAllLOVEntries(); void writeAllLOVEntriesToFile(String filename); SchemaEntry extractResourceLocation(SchemaEntry entry); static void main(String[] args); }
@Ignore @Test public void testExtractResourceLocation() { LOVEndpoint endpoint = new LOVEndpoint(); SchemaEntry entry5 = new SchemaEntry("agr", "https: SchemaEntry result5 = endpoint.extractResourceLocation(entry5); Assert.assertEquals( "https: SchemaEntry entry1 = new SchemaEntry("SAN", "http: SchemaEntry result1 = endpoint.extractResourceLocation(entry1); Assert.assertEquals( entry1.getVocabularyURI().replace("http: SchemaEntry entry9 = new SchemaEntry("medred", "http: SchemaEntry result9 = endpoint.extractResourceLocation(entry9); Assert.assertEquals( "https: SchemaEntry entry8 = new SchemaEntry("comm", "http: SchemaEntry result8 = endpoint.extractResourceLocation(entry8); Assert.assertEquals( "http: SchemaEntry entry3 = new SchemaEntry("af", "http: SchemaEntry result3 = endpoint.extractResourceLocation(entry3); Assert.assertEquals( "http: SchemaEntry entry7 = new SchemaEntry("ssn", "http: SchemaEntry result7 = endpoint.extractResourceLocation(entry7); Assert.assertEquals( "https: SchemaEntry entry6 = new SchemaEntry("agrelon", "http: SchemaEntry result6 = endpoint.extractResourceLocation(entry6); Assert.assertEquals( "https: SchemaEntry entry4 = new SchemaEntry("brk", "http: SchemaEntry result4 = endpoint.extractResourceLocation(entry4); Assert.assertEquals( "https: SchemaEntry entry2 = new SchemaEntry("acco", "http: SchemaEntry result2 = endpoint.extractResourceLocation(entry2); Assert.assertEquals( "http: }
LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void onStart() { mLoginRepository.getUser() .subscribeOn(mSchedulerProvider.io()) .observeOn(mSchedulerProvider.ui()) .subscribe(new OnceObserver<User>() { @Override protected void onResponse(User value) { mView.setUserName(value.getName()); } }); } @Inject LoginPresenter(@NonNull LoginRepository loginRepository, @NonNull ISchedulerProvider schedulerProvider); @Override void onStart(); @Override void onEdtUserNameChanged(String userName); @Override void onBtnClearUserNameClick(); @Override void onBtnShowOrHidePasswordClick(boolean needShow); @Override void login(User user); }
@Test public void onStartFirst() { when(mLoginRepository.getUser()).thenReturn(Observable.<User>empty()); mLoginPresenter.onStart(); verify(mLoginRepository).getUser(); verify(mLoginView, never()).setUserName(anyString()); verify(mLoginView, never()).setPassword(anyString()); } @Test public void onStartNotFirst() { when(mLoginRepository.getUser()).thenReturn(Observable.just(mUser)); when(mLoginRepository.loginRemote(mUser)).thenReturn(Observable.just(mUser)); mLoginPresenter.onStart(); verify(mLoginRepository).getUser(); verify(mLoginView).setUserName(mUser.getName()); }
LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void login(User user) { if (user.isUserNameEmpty()) { mView.showUserNameEmpty(); return; } mLoginRepository.loginRemote(user) .subscribeOn(mSchedulerProvider.io()) .doOnNext(new Consumer<User>() { @Override public void accept(User value) throws Exception { value.setLogin(true); mLoginRepository.saveUser(value); } }) .observeOn(mSchedulerProvider.ui()) .subscribe(new OnceLoadingObserver<User>(mView) { @Override protected void onResponse(User value) { mView.openHomePage(); mView.finishActivity(); } }); } @Inject LoginPresenter(@NonNull LoginRepository loginRepository, @NonNull ISchedulerProvider schedulerProvider); @Override void onStart(); @Override void onEdtUserNameChanged(String userName); @Override void onBtnClearUserNameClick(); @Override void onBtnShowOrHidePasswordClick(boolean needShow); @Override void login(User user); }
@Test public void loginWithError() { String errorMessage = "error"; when(mLoginRepository.loginRemote(mUser)).thenReturn(Observable.<User>error(new MyRuntimeException(errorMessage))); mLoginPresenter.login(mUser); verify(mLoginView).showErrorMessage(errorMessage); verify(mLoginView).hideLoadingDialog(); } @Test public void loginOk() { when(mLoginRepository.loginRemote(mUser)).thenReturn(Observable.just(mUser)); mLoginPresenter.login(mUser); verify(mLoginRepository).saveUser((User) any()); verify(mLoginView, never()).showErrorMessage(anyString()); verify(mLoginView, never()).showNetWorkError(); verify(mLoginView).hideLoadingDialog(); verify(mLoginView).openHomePage(); verify(mLoginView).finishActivity(); } @Test public void loginWithUserNameIsEmpty() { mLoginPresenter.login(mEmptyNameUser); verify(mLoginView).showUserNameEmpty(); verify(mLoginRepository, never()).loginRemote(mEmptyNameUser); } @Test public void loginWithUserNameIsNotEmpty() { when(mLoginRepository.loginRemote(mUser)).thenReturn(Observable.just(mUser)); mLoginPresenter.login(mUser); verify(mLoginView, never()).showUserNameEmpty(); verify(mLoginView).showLoadingDialog(anyBoolean()); verify(mLoginRepository).loginRemote(mUser); } @Test public void loginWithNetworkError() { when(mLoginRepository.loginRemote(mUser)).thenReturn(Observable.<User>error(new ConnectException())); mLoginPresenter.login(mUser); verify(mLoginView).showNetWorkError(); verify(mLoginView).hideLoadingDialog(); }
LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void onEdtUserNameChanged(String userName) { if (!TextUtil.isEmpty(userName)) { mView.showClearUserNameButton(); } else { mView.hideClearUserNameButton(); } } @Inject LoginPresenter(@NonNull LoginRepository loginRepository, @NonNull ISchedulerProvider schedulerProvider); @Override void onStart(); @Override void onEdtUserNameChanged(String userName); @Override void onBtnClearUserNameClick(); @Override void onBtnShowOrHidePasswordClick(boolean needShow); @Override void login(User user); }
@Test public void onUserNameAfterTextChangedEmpty() { mLoginPresenter.onEdtUserNameChanged(""); verify(mLoginView).hideClearUserNameButton(); } @Test public void onUserNameAfterTextChangedNotEmpty() { mLoginPresenter.onEdtUserNameChanged("a"); verify(mLoginView).showClearUserNameButton(); }
LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void onBtnClearUserNameClick() { mView.setUserNameEmpty(); } @Inject LoginPresenter(@NonNull LoginRepository loginRepository, @NonNull ISchedulerProvider schedulerProvider); @Override void onStart(); @Override void onEdtUserNameChanged(String userName); @Override void onBtnClearUserNameClick(); @Override void onBtnShowOrHidePasswordClick(boolean needShow); @Override void login(User user); }
@Test public void onClearUserNameBtnClick() { mLoginPresenter.onBtnClearUserNameClick(); verify(mLoginView).setUserNameEmpty(); }
LoginPresenter extends BaseRxJavaPresenter<LoginContract.View> implements LoginContract.Presenter { @Override public void onBtnShowOrHidePasswordClick(boolean needShow) { if (needShow) { mView.showPassword(); } else { mView.hidePassword(); } } @Inject LoginPresenter(@NonNull LoginRepository loginRepository, @NonNull ISchedulerProvider schedulerProvider); @Override void onStart(); @Override void onEdtUserNameChanged(String userName); @Override void onBtnClearUserNameClick(); @Override void onBtnShowOrHidePasswordClick(boolean needShow); @Override void login(User user); }
@Test public void onShowPasswordButtonClickTrue() { mLoginPresenter.onBtnShowOrHidePasswordClick(true); verify(mLoginView).showPassword(); } @Test public void onShowPasswordButtonClickFalse() { mLoginPresenter.onBtnShowOrHidePasswordClick(false); verify(mLoginView).hidePassword(); }
PrometheusPublisher extends Collector implements Collector.Describable, MetricsInitializer { @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { this.globalRegistry = globalRegistry; String address = DynamicPropertyFactory.getInstance().getStringProperty(METRICS_PROMETHEUS_ADDRESS, "0.0.0.0:9696").get(); try { InetSocketAddress socketAddress = getSocketAddress(address); register(); this.httpServer = new HTTPServer(socketAddress, CollectorRegistry.defaultRegistry, true); LOGGER.info("Prometheus httpServer listened : {}.", address); } catch (Exception e) { throw new ServiceCombException("create http publish server failed,may bad address : " + address, e); } } @Override void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config); @Override List<MetricFamilySamples> describe(); @Override List<MetricFamilySamples> collect(); @Override void destroy(); }
@Test public void testBadPublishAddress() { thrown.expect(ServiceCombException.class); ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "a:b:c"); publisher.init(globalRegistry, null, null); } @Test public void testBadPublishAddress_BadPort() { thrown.expect(ServiceCombException.class); ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:xxxx"); publisher.init(globalRegistry, null, null); } @Test public void testBadPublishAddress_TooLargePort() { thrown.expect(ServiceCombException.class); ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:9999999"); publisher.init(globalRegistry, null, null); }
AbstractRestInvocation { @SuppressWarnings("deprecation") protected void sendResponse(Response response) { RestServerCodecFilter.copyHeadersToHttpResponse(response.getHeaders().getHeaderMap(), responseEx); responseEx.setStatus(response.getStatusCode(), response.getReasonPhrase()); responseEx.setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE, response); responseEx.setAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR, produceProcessor); executeHttpServerFilters(response); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void sendResponseStatusAndContentTypeAndHeader(@Mocked Response response) { new Expectations() { { response.getStatusCode(); result = 123; response.getReasonPhrase(); result = "reason"; response.getResult(); result = "result"; } }; Map<String, Object> result = new HashMap<>(); responseEx = new MockUp<HttpServletResponseEx>() { private Map<String, Object> attributes = new HashMap<>(); @Mock public void setAttribute(String key, Object value) { this.attributes.put(key, value); } @Mock public Object getAttribute(String key) { return this.attributes.get(key); } @Mock void setStatus(int sc, String sm) { result.put("statusCode", sc); result.put("reasonPhrase", sm); } @Mock void setContentType(String type) { result.put("contentType", type); } }.getMockInstance(); Map<String, Object> expected = new HashMap<>(); expected.put("statusCode", 123); expected.put("reasonPhrase", "reason"); expected.put("contentType", "application/json; charset=utf-8"); invocation.onStart(0); initRestInvocation(); restInvocation.sendResponse(response); assertEquals(expected, result); } @Test public void testDoSendResponseHeaderNull(@Mocked Response response) { Headers headers = new Headers(); new Expectations() { { response.getResult(); result = new RuntimeExceptionWithoutStackTrace("stop"); response.getHeaders(); result = headers; } }; Headers resultHeaders = new Headers(); responseEx = new MockUp<HttpServletResponseEx>() { private Map<String, Object> attributes = new HashMap<>(); @Mock public void setAttribute(String key, Object value) { this.attributes.put(key, value); } @Mock public Object getAttribute(String key) { return this.attributes.get(key); } @Mock void addHeader(String name, String value) { resultHeaders.addHeader(name, value); } }.getMockInstance(); invocation.onStart(0); initRestInvocation(); try { restInvocation.sendResponse(response); Assert.fail("must throw exception"); } catch (Error e) { Assert.assertNull(resultHeaders.getHeaderMap()); } } @Test public void testDoSendResponseHeaderNormal(@Mocked Response response) { Headers headers = new Headers(); headers.addHeader("h1", "h1v1"); headers.addHeader("h1", "h1v2"); headers.addHeader("h2", "h2v"); new Expectations() { { response.getResult(); result = new RuntimeExceptionWithoutStackTrace("stop"); response.getHeaders(); result = headers; } }; Headers resultHeaders = new Headers(); responseEx = new MockUp<HttpServletResponseEx>() { private Map<String, Object> attributes = new HashMap<>(); @Mock public void setAttribute(String key, Object value) { this.attributes.put(key, value); } @Mock public Object getAttribute(String key) { return this.attributes.get(key); } @Mock void addHeader(String name, String value) { resultHeaders.addHeader(name, value); } }.getMockInstance(); invocation.onStart(0); initRestInvocation(); try { restInvocation.sendResponse(response); Assert.fail("must throw exception"); } catch (Error e) { assertEquals(headers.getHeaderMap(), resultHeaders.getHeaderMap()); } } @Test public void testDoSendResponseResultOK(@Mocked Response response) { new Expectations() { { response.getResult(); result = "ok"; } }; Buffer buffer = Buffer.buffer(); responseEx = new MockUp<HttpServletResponseEx>() { private Map<String, Object> attributes = new HashMap<>(); @Mock public void setAttribute(String key, Object value) { this.attributes.put(key, value); } @Mock public Object getAttribute(String key) { return this.attributes.get(key); } @Mock void setBodyBuffer(Buffer bodyBuffer) { buffer.appendBuffer(bodyBuffer); } }.getMockInstance(); invocation.onStart(0); initRestInvocation(); restInvocation.sendResponse(response); assertEquals("\"ok\"", buffer.toString()); assertEquals(nanoTime, invocation.getInvocationStageTrace().getFinishServerFiltersResponse()); }
AbstractRestInvocation { protected void findRestOperation(MicroserviceMeta microserviceMeta) { ServicePathManager servicePathManager = ServicePathManager.getServicePathManager(microserviceMeta); if (servicePathManager == null) { LOGGER.error("No schema defined for {}:{}.", microserviceMeta.getAppId(), microserviceMeta.getMicroserviceName()); throw new InvocationException(Status.NOT_FOUND, Status.NOT_FOUND.getReasonPhrase()); } OperationLocator locator = locateOperation(servicePathManager); requestEx.setAttribute(RestConst.PATH_PARAMETERS, locator.getPathVarMap()); this.restOperationMeta = locator.getOperation(); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void findRestOperationServicePathManagerNull(@Mocked MicroserviceMeta microserviceMeta) { new Expectations(ServicePathManager.class) { { requestEx.getHeader(Const.TARGET_MICROSERVICE); result = "ms"; ServicePathManager.getServicePathManager(microserviceMeta); result = null; } }; expectedException.expect(InvocationException.class); expectedException.expectMessage("CommonExceptionData [message=Not Found]"); restInvocation.findRestOperation(microserviceMeta); } @Test public void findRestOperationNormal(@Mocked MicroserviceMeta microserviceMeta, @Mocked ServicePathManager servicePathManager, @Mocked OperationLocator locator) { restInvocation = new AbstractRestInvocationForTest() { @Override protected OperationLocator locateOperation(ServicePathManager servicePathManager) { return locator; } }; requestEx = new AbstractHttpServletRequest() { }; restInvocation.requestEx = requestEx; Map<String, String> pathVars = new HashMap<>(); new Expectations(ServicePathManager.class) { { ServicePathManager.getServicePathManager(microserviceMeta); result = servicePathManager; locator.getPathVarMap(); result = pathVars; locator.getOperation(); result = restOperation; } }; restInvocation.findRestOperation(microserviceMeta); Assert.assertSame(restOperation, restInvocation.restOperationMeta); Assert.assertSame(pathVars, requestEx.getAttribute(RestConst.PATH_PARAMETERS)); }
AbstractRestInvocation { protected void scheduleInvocation() { try { createInvocation(); } catch (Throwable e) { sendFailResponse(e); return; } invocation.onStart(requestEx, start); invocation.getInvocationStageTrace().startSchedule(); OperationMeta operationMeta = restOperationMeta.getOperationMeta(); try { this.setContext(); } catch (Exception e) { LOGGER.error("failed to set invocation context", e); sendFailResponse(e); return; } Holder<Boolean> qpsFlowControlReject = checkQpsFlowControl(operationMeta); if (qpsFlowControlReject.value) { return; } try { operationMeta.getExecutor().execute(() -> { synchronized (this.requestEx) { try { if (isInQueueTimeout()) { throw new InvocationException(Status.INTERNAL_SERVER_ERROR, "Timeout when processing the request."); } if (requestEx.getAttribute(RestConst.REST_REQUEST) != requestEx) { LOGGER.error("Rest request already timeout, abandon execute, method {}, operation {}.", operationMeta.getHttpMethod(), operationMeta.getMicroserviceQualifiedName()); return; } runOnExecutor(); } catch (Throwable e) { LOGGER.error("rest server onRequest error", e); sendFailResponse(e); } } }); } catch (Throwable e) { LOGGER.error("failed to schedule invocation, message={}, executor={}.", e.getMessage(), e.getClass().getName()); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void scheduleInvocationException(@Mocked OperationMeta operationMeta) { Executor executor = new ReactiveExecutor(); requestEx = new AbstractHttpServletRequestForTest(); requestEx.setAttribute(RestConst.REST_REQUEST, requestEx); new Expectations() { { restOperation.getOperationMeta(); result = operationMeta; operationMeta.getExecutor(); result = executor; } }; Holder<Throwable> result = new Holder<>(); RuntimeException error = new RuntimeExceptionWithoutStackTrace("run on executor"); restInvocation = new AbstractRestInvocationForTest() { @Override protected void runOnExecutor() { throw error; } @Override public void sendFailResponse(Throwable throwable) { result.value = throwable; invocation.onFinish(Response.ok(null)); } }; restInvocation.requestEx = requestEx; restInvocation.restOperationMeta = restOperation; restInvocation.scheduleInvocation(); Assert.assertSame(error, result.value); } @Test public void threadPoolReject(@Mocked OperationMeta operationMeta) { RejectedExecutionException rejectedExecutionException = new RejectedExecutionException("reject"); Executor executor = (task) -> { throw rejectedExecutionException; }; new Expectations() { { restOperation.getOperationMeta(); result = operationMeta; operationMeta.getExecutor(); result = executor; } }; Holder<Throwable> holder = new Holder<>(); requestEx = new AbstractHttpServletRequestForTest(); restInvocation = new AbstractRestInvocationForTest() { @Override public void sendFailResponse(Throwable throwable) { holder.value = throwable; invocation.onFinish(Response.ok(null)); } }; restInvocation.requestEx = requestEx; restInvocation.restOperationMeta = restOperation; restInvocation.scheduleInvocation(); Assert.assertSame(rejectedExecutionException, holder.value); } @Test public void scheduleInvocationNormal(@Mocked OperationMeta operationMeta) { Holder<InvocationStartEvent> eventHolder = new Holder<>(); Object subscriber = new ScheduleInvocationEventHandler(eventHolder); EventManager.register(subscriber); Executor executor = new ReactiveExecutor(); requestEx = new AbstractHttpServletRequestForTest(); requestEx.setAttribute(RestConst.REST_REQUEST, requestEx); new Expectations(requestEx) { { restOperation.getOperationMeta(); result = operationMeta; operationMeta.getExecutor(); result = executor; requestEx.getHeader(Const.TRACE_ID_NAME); result = "tid"; } }; Holder<Boolean> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void runOnExecutor() { result.value = true; invocation.onFinish(Response.ok(null)); } }; restInvocation.requestEx = requestEx; restInvocation.restOperationMeta = restOperation; restInvocation.scheduleInvocation(); EventManager.unregister(subscriber); Assert.assertTrue(result.value); assertEquals(nanoTime, invocation.getInvocationStageTrace().getStart()); assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartSchedule()); Assert.assertSame(invocation, eventHolder.value.getInvocation()); assertEquals("tid", invocation.getTraceId()); } @Test public void scheduleInvocation_invocationContextDeserializeError(@Mocked AsyncContext asyncContext) { requestEx = new AbstractHttpServletRequest() { @Override public String getHeader(String name) { return "{\"x-cse-src-microservice\":'source\"}"; } @Override public AsyncContext getAsyncContext() { return asyncContext; } }; Holder<Integer> status = new Holder<>(); Holder<String> reasonPhrase = new Holder<>(); Holder<Integer> endCount = new Holder<>(0); responseEx = new AbstractHttpServletResponse() { @SuppressWarnings("deprecation") @Override public void setStatus(int sc, String sm) { status.value = sc; reasonPhrase.value = sm; } @Override public void flushBuffer() { endCount.value = endCount.value + 1; } @Override public void setContentType(String type) { assertEquals("application/json; charset=utf-8", type); } }; restInvocation.requestEx = requestEx; restInvocation.responseEx = responseEx; restInvocation.scheduleInvocation(); assertEquals(Integer.valueOf(590), status.value); assertEquals("Unexpected producer error, please check logs for details", reasonPhrase.value); assertEquals(Integer.valueOf(1), endCount.value); } @SuppressWarnings("deprecation") @Test public void scheduleInvocation_flowControlReject() { new Expectations(operationMeta) { { operationMeta.getProviderQpsFlowControlHandler(); result = (Handler) (invocation, asyncResp) -> asyncResp.producerFail(new InvocationException( new HttpStatus(429, "Too Many Requests"), new CommonExceptionData("rejected by qps flowcontrol"))); } }; Holder<Integer> status = new Holder<>(); Holder<String> reasonPhrase = new Holder<>(); Holder<Integer> endCount = new Holder<>(0); Holder<String> responseBody = new Holder<>(); responseEx = new AbstractHttpServletResponse() { @SuppressWarnings("deprecation") @Override public void setStatus(int sc, String sm) { status.value = sc; reasonPhrase.value = sm; } @Override public void flushBuffer() { endCount.value = endCount.value + 1; } @Override public void setContentType(String type) { assertEquals("application/json; charset=utf-8", type); } @Override public void setBodyBuffer(Buffer bodyBuffer) { responseBody.value = bodyBuffer.toString(); } }; initRestInvocation(); restInvocation.scheduleInvocation(); assertEquals(Integer.valueOf(429), status.value); assertEquals("Too Many Requests", reasonPhrase.value); assertEquals("{\"message\":\"rejected by qps flowcontrol\"}", responseBody.value); assertEquals(Integer.valueOf(1), endCount.value); }
AbstractRestInvocation { protected void runOnExecutor() { invocation.onExecuteStart(); invoke(); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void runOnExecutor() { long time = 123; new MockUp<System>() { @Mock long nanoTime() { return time; } }; Holder<Boolean> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override public void invoke() { result.value = true; } }; restInvocation.createInvocation(); restInvocation.requestEx = requestEx; restInvocation.restOperationMeta = restOperation; restInvocation.runOnExecutor(); Assert.assertTrue(result.value); Assert.assertSame(invocation, restInvocation.invocation); assertEquals(time, invocation.getInvocationStageTrace().getStartExecution()); }
EnvAdapterManager extends RegisterManager<String, EnvAdapter> { public void processMicroserviceWithAdapters(Microservice microservice) { getObjMap().forEach((name, adapter) -> { LOGGER.info("Start process microservice with adapter {}", name); adapter.beforeRegisterService(microservice); }); } EnvAdapterManager(); void processMicroserviceWithAdapters(Microservice microservice); void processSchemaWithAdapters(String schemaId, String content); void processInstanceWithAdapters(MicroserviceInstance instance); static final EnvAdapterManager INSTANCE; }
@Test public void testProcessMicroservice() { Microservice microservice = new Microservice(); manager.processMicroserviceWithAdapters(microservice); assertEquals("order=0", microservice.getProperties().get("cas_env_one")); assertEquals("order=0", microservice.getProperties().get("cas_env_two")); assertNull(microservice.getProperties().get("default-env-adapter")); }
AbstractRestInvocation { protected void doInvoke() throws Throwable { invocation.getInvocationStageTrace().startHandlersRequest(); invocation.next(resp -> sendResponseQuietly(resp)); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void doInvoke(@Mocked Endpoint endpoint, @Mocked OperationMeta operationMeta, @Mocked Object[] swaggerArguments, @Mocked SchemaMeta schemaMeta) throws Throwable { Response response = Response.ok("ok"); Handler handler = (invocation, asyncResp) -> asyncResp.complete(response); List<Handler> handlerChain = Arrays.asList(handler); Deencapsulation.setField(invocation, "handlerList", handlerChain); Holder<Response> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void sendResponse(Response response) { result.value = response; } }; restInvocation.invocation = invocation; restInvocation.doInvoke(); Assert.assertSame(response, result.value); assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartHandlersRequest()); assertEquals(nanoTime, invocation.getInvocationStageTrace().getFinishHandlersResponse()); }
ClassPathStaticResourceHandler extends StaticResourceHandler { protected Part findResource(String path) throws IOException { URL url = this.getClass().getClassLoader().getResource(path); if (url == null) { return null; } return new InputStreamPart(null, url.openStream()).setSubmittedFileName(path); } }
@Test public void readContentFailed() throws IOException { new Expectations(handler) { { handler.findResource(anyString); result = new RuntimeExceptionWithoutStackTrace("read content failed."); } }; try (LogCollector logCollector = new LogCollector()) { Response response = handler.handle("index.html"); Assert.assertEquals("failed to process static resource, path=web-root/index.html", logCollector.getLastEvents().getMessage()); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR, invocationException.getStatus()); Assert.assertEquals("failed to process static resource.", ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), response.getReasonPhrase()); } }
ServicePathManager { public static ServicePathManager getServicePathManager(MicroserviceMeta microserviceMeta) { return microserviceMeta.getExtData(REST_PATH_MANAGER); } ServicePathManager(MicroserviceMeta microserviceMeta); static ServicePathManager getServicePathManager(MicroserviceMeta microserviceMeta); OperationLocator consumerLocateOperation(String path, String httpMethod); OperationLocator producerLocateOperation(String path, String httpMethod); void addResource(RestOperationMeta swaggerRestOperation); void sortPath(); void buildProducerPaths(); }
@Test public void testBuildProducerPathsNoPrefix() { SCBEngine scbEngine = SCBBootstrap.createSCBEngineForTest() .addProducerMeta("sid1", new TestPathSchema()) .run(); ServicePathManager spm = ServicePathManager.getServicePathManager(scbEngine.getProducerMicroserviceMeta()); Assert.assertSame(spm.producerPaths, spm.swaggerPaths); scbEngine.destroy(); }
MicroservicePaths { public Map<String, OperationGroup> getStaticPathOperationMap() { return staticPathOperations; } void sortPath(); void addResource(RestOperationMeta swaggerRestOperation); Map<String, OperationGroup> getStaticPathOperationMap(); List<RestOperationMeta> getDynamicPathOperationList(); void printPaths(); }
@Test public void staticGroup() { RestOperationMeta meta = paths.getStaticPathOperationMap().get("/static/").findValue("POST"); Assert.assertSame("postStatic", meta.getOperationMeta().getOperationId()); meta = paths.getStaticPathOperationMap().get("/static/").findValue("GET"); Assert.assertSame("getStatic", meta.getOperationMeta().getOperationId()); }
MicroservicePaths { public void addResource(RestOperationMeta swaggerRestOperation) { if (swaggerRestOperation.isAbsoluteStaticPath()) { addStaticPathResource(swaggerRestOperation); return; } dynamicPathOperationsList.add(swaggerRestOperation); } void sortPath(); void addResource(RestOperationMeta swaggerRestOperation); Map<String, OperationGroup> getStaticPathOperationMap(); List<RestOperationMeta> getDynamicPathOperationList(); void printPaths(); }
@Test public void testAddResourceStaticDuplicatedHttpMethod(@Mocked RestOperationMeta staticResPost) { new Expectations() { { staticResPost.getHttpMethod(); result = "POST"; staticResPost.getAbsolutePath(); result = "/static/"; staticResPost.isAbsoluteStaticPath(); result = true; } }; expectedException.expect(ServiceCombException.class); expectedException.expectMessage("operation with url /static/, method POST is duplicated."); paths.addResource(staticResPost); }
MicroservicePaths { public List<RestOperationMeta> getDynamicPathOperationList() { return dynamicPathOperationsList; } void sortPath(); void addResource(RestOperationMeta swaggerRestOperation); Map<String, OperationGroup> getStaticPathOperationMap(); List<RestOperationMeta> getDynamicPathOperationList(); void printPaths(); }
@Test public void dynamicPath() { Assert.assertEquals("dynamicExId", paths.getDynamicPathOperationList().get(0).getOperationMeta().getOperationId()); Assert.assertEquals("dynamicId", paths.getDynamicPathOperationList().get(1).getOperationMeta().getOperationId()); }
MicroservicePaths { public void printPaths() { for (Entry<String, OperationGroup> entry : staticPathOperations.entrySet()) { OperationGroup operationGroup = entry.getValue(); printPath(operationGroup.values()); } printPath(getDynamicPathOperationList()); } void sortPath(); void addResource(RestOperationMeta swaggerRestOperation); Map<String, OperationGroup> getStaticPathOperationMap(); List<RestOperationMeta> getDynamicPathOperationList(); void printPaths(); }
@Test public void testPrintPaths() { try (LogCollector collector = new LogCollector()) { paths.printPaths(); StringBuilder sb = new StringBuilder(); collector.getEvents().stream() .forEach(e -> sb.append(e.getMessage()).append("\n")); Assert.assertEquals( "Swagger mapped \"{[/static/], method=[POST], produces=[application/json]}\" onto public void org.apache.servicecomb.common.rest.locator.TestPathSchema.postStatic()\n" + "Swagger mapped \"{[/static/], method=[GET], produces=[application/json]}\" onto public void org.apache.servicecomb.common.rest.locator.TestPathSchema.getStatic()\n" + "Swagger mapped \"{[/staticEx/], method=[GET], produces=[application/json]}\" onto public void org.apache.servicecomb.common.rest.locator.TestPathSchema.getStaticEx()\n" + "Swagger mapped \"{[/dynamicEx/{id}/], method=[GET], produces=[application/json]}\" onto public void org.apache.servicecomb.common.rest.locator.TestPathSchema.dynamicExId(java.lang.String)\n" + "Swagger mapped \"{[/dynamic/{id}/], method=[GET], produces=[application/json]}\" onto public void org.apache.servicecomb.common.rest.locator.TestPathSchema.dynamicId(java.lang.String)\n", sb.toString()); } }
RestOperationMeta { public ProduceProcessor ensureFindProduceProcessor(HttpServletRequestEx requestEx) { String acceptType = requestEx.getHeader(HttpHeaders.ACCEPT); return ensureFindProduceProcessor(acceptType); } void init(OperationMeta operationMeta); boolean isDownloadFile(); boolean isFormData(); void setOperationMeta(OperationMeta operationMeta); String getAbsolutePath(); void setAbsolutePath(String absolutePath); PathRegExp getAbsolutePathRegExp(); boolean isAbsoluteStaticPath(); RestParam getParamByName(String name); RestParam getParamByIndex(int index); OperationMeta getOperationMeta(); URLPathBuilder getPathBuilder(); List<RestParam> getParamList(); ProduceProcessor findProduceProcessor(String type); ProduceProcessor ensureFindProduceProcessor(HttpServletRequestEx requestEx); ProduceProcessor ensureFindProduceProcessor(String acceptType); String getHttpMethod(); List<String> getFileKeys(); List<String> getProduces(); }
@Test public void testCreateProduceProcessorsTextAndWildcard() { findOperation("textPlain"); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), operationMeta.ensureFindProduceProcessor(MediaType.WILDCARD)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), operationMeta.ensureFindProduceProcessor(MediaType.TEXT_PLAIN)); Assert.assertNull(operationMeta.ensureFindProduceProcessor(MediaType.APPLICATION_JSON)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), operationMeta.ensureFindProduceProcessor( MediaType.APPLICATION_JSON + "," + MediaType.APPLICATION_XML + "," + MediaType.WILDCARD)); } @Test public void testCreateProduceProcessorsTextAndWildcardWithView() { findOperation("textPlainWithView"); Assert.assertSame(ProduceProcessorManager.INSTANCE.findPlainProcessorByViewClass(Object.class), operationMeta.ensureFindProduceProcessor(MediaType.WILDCARD)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findPlainProcessorByViewClass(Object.class), operationMeta.ensureFindProduceProcessor(MediaType.TEXT_PLAIN)); Assert.assertNull(operationMeta.ensureFindProduceProcessor(MediaType.APPLICATION_JSON)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findPlainProcessorByViewClass(Object.class), operationMeta.ensureFindProduceProcessor( MediaType.APPLICATION_JSON + "," + MediaType.APPLICATION_XML + "," + MediaType.WILDCARD)); } @Test public void testCreateProduceProcessorsWithSemicolon() { findOperation("textCharJsonChar"); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), operationMeta.ensureFindProduceProcessor(MediaType.TEXT_PLAIN)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultJsonProcessor(), operationMeta.ensureFindProduceProcessor(MediaType.APPLICATION_JSON)); } @Test public void testCreateProduceProcessorsWithSemicolonWithView() { findOperation("textCharJsonCharWithView"); Assert.assertSame(ProduceProcessorManager.INSTANCE.findPlainProcessorByViewClass(Object.class), operationMeta.ensureFindProduceProcessor(MediaType.TEXT_PLAIN)); Assert.assertSame(ProduceProcessorManager.INSTANCE.findJsonProcessorByViewClass(Object.class), operationMeta.ensureFindProduceProcessor(MediaType.APPLICATION_JSON)); } @Test public void testEnsureFindProduceProcessorAcceptNotFound() { findOperation("textCharJsonChar"); Assert.assertNull(operationMeta.ensureFindProduceProcessor("notSupport")); } @Test public void testEnsureFindProduceProcessorAcceptNotFoundWithView() { findOperation("textCharJsonCharWithView"); Assert.assertNull(operationMeta.ensureFindProduceProcessor("notSupport")); }
EnvAdapterManager extends RegisterManager<String, EnvAdapter> { public void processInstanceWithAdapters(MicroserviceInstance instance) { getObjMap().forEach((name, adapter) -> { LOGGER.info("Start process instance with adapter {}", name); adapter.beforeRegisterInstance(instance); }); } EnvAdapterManager(); void processMicroserviceWithAdapters(Microservice microservice); void processSchemaWithAdapters(String schemaId, String content); void processInstanceWithAdapters(MicroserviceInstance instance); static final EnvAdapterManager INSTANCE; }
@Test public void testProcessInstance() { MicroserviceInstance instance = new MicroserviceInstance(); manager.processInstanceWithAdapters(instance); assertEquals("order=0", instance.getProperties().get("cas_env_one")); assertEquals("order=0", instance.getProperties().get("cas_env_two")); assertNull(instance.getProperties().get("default-env-adapter")); }
RestOperationMeta { public String getAbsolutePath() { return this.absolutePath; } void init(OperationMeta operationMeta); boolean isDownloadFile(); boolean isFormData(); void setOperationMeta(OperationMeta operationMeta); String getAbsolutePath(); void setAbsolutePath(String absolutePath); PathRegExp getAbsolutePathRegExp(); boolean isAbsoluteStaticPath(); RestParam getParamByName(String name); RestParam getParamByIndex(int index); OperationMeta getOperationMeta(); URLPathBuilder getPathBuilder(); List<RestParam> getParamList(); ProduceProcessor findProduceProcessor(String type); ProduceProcessor ensureFindProduceProcessor(HttpServletRequestEx requestEx); ProduceProcessor ensureFindProduceProcessor(String acceptType); String getHttpMethod(); List<String> getFileKeys(); List<String> getProduces(); }
@Test public void generatesAbsolutePathWithRootBasePath() { findOperation("textCharJsonChar"); assertThat(operationMeta.getAbsolutePath(), is("/textCharJsonChar/")); }
RestOperationMeta { public boolean isFormData() { return formData; } void init(OperationMeta operationMeta); boolean isDownloadFile(); boolean isFormData(); void setOperationMeta(OperationMeta operationMeta); String getAbsolutePath(); void setAbsolutePath(String absolutePath); PathRegExp getAbsolutePathRegExp(); boolean isAbsoluteStaticPath(); RestParam getParamByName(String name); RestParam getParamByIndex(int index); OperationMeta getOperationMeta(); URLPathBuilder getPathBuilder(); List<RestParam> getParamList(); ProduceProcessor findProduceProcessor(String type); ProduceProcessor ensureFindProduceProcessor(HttpServletRequestEx requestEx); ProduceProcessor ensureFindProduceProcessor(String acceptType); String getHttpMethod(); List<String> getFileKeys(); List<String> getProduces(); }
@Test public void testFormDataFlagTrue() { findOperation("form"); assertThat(operationMeta.isFormData(), is(true)); } @Test public void testFormDataFlagFalse() { findOperation("json"); assertThat(operationMeta.isFormData(), is(false)); }
PathVarParamWriter extends AbstractUrlParamWriter { @Override public void write(URLPathStringBuilder builder, Map<String, Object> args) throws Exception { if (getParamValue(args) == null) { throw new IllegalArgumentException("path parameter can not be null."); } String encodedPathParam = encodeNotNullValue(getParamValue(args)); builder.appendPath(encodedPathParam); } PathVarParamWriter(RestParam param); @Override void write(URLPathStringBuilder builder, Map<String, Object> args); }
@Test public void writePlainPath() throws Exception { PathVarParamWriter pathVarParamWriter = createPathVarParamWriter(); URLPathStringBuilder pathBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", "abc"); pathVarParamWriter.write(pathBuilder, parameters); Assert.assertEquals("abc", pathBuilder.build()); } @Test public void writePathWithSpace() throws Exception { PathVarParamWriter pathVarParamWriter = createPathVarParamWriter(); URLPathStringBuilder pathBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", "a 20bc"); pathVarParamWriter.write(pathBuilder, parameters); Assert.assertEquals("a%2020bc", pathBuilder.build()); } @Test public void writePathWithPercentage() throws Exception { PathVarParamWriter pathVarParamWriter = createPathVarParamWriter(); URLPathStringBuilder pathBuilder = new URLPathStringBuilder(); pathBuilder.appendPath("/api/"); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", "a%%bc"); pathVarParamWriter.write(pathBuilder, parameters); Assert.assertEquals("/api/a%25%25bc", pathBuilder.build()); } @Test public void writePathParamWithSlash() throws Exception { PathVarParamWriter pathVarParamWriter = createPathVarParamWriter(); URLPathStringBuilder pathBuilder = new URLPathStringBuilder(); pathBuilder.appendPath("/api/"); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", "a/bc"); pathVarParamWriter.write(pathBuilder, parameters); Assert.assertEquals("/api/a%2Fbc", pathBuilder.build()); } @Test public void writeIntegerParam() throws Exception { PathVarParamWriter pathVarParamWriter = createPathVarParamWriter(); URLPathStringBuilder pathBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", 12); pathVarParamWriter.write(pathBuilder, parameters); Assert.assertEquals("12", pathBuilder.build()); }
ZeroConfigClient { public boolean register() { String serviceInstanceId = doRegister( ClientUtil.convertToRegisterDataModel(selfMicroserviceInstance, selfMicroservice)); return StringUtils.isNotEmpty(serviceInstanceId); } private ZeroConfigClient(ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); @VisibleForTesting ZeroConfigClient initZeroConfigClientWithMocked( ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); void init(); boolean register(); boolean unregister(); List<Microservice> getAllMicroservices(); Microservice getMicroservice(String microserviceId); String getSchema(String microserviceId, String schemaId); MicroserviceInstance findMicroserviceInstance(String serviceId, String instanceId); MicroserviceInstances findServiceInstances(String appId, String providerServiceName, String strVersionRule); Microservice getSelfMicroservice(); @VisibleForTesting void setSelfMicroservice( Microservice selfMicroservice); MicroserviceInstance getSelfMicroserviceInstance(); @VisibleForTesting void setSelfMicroserviceInstance( MicroserviceInstance selfMicroserviceInstance); static ZeroConfigClient INSTANCE; }
@Test public void test_register_withCorrectData_RegisterShouldSucceed() { boolean returnedResult = target.register(); Assert.assertTrue(returnedResult); } @Test public void test_register_MulticastThrowException_RegisterShouldFail() throws IOException { doThrow(IOException.class).when(multicastSocket).send(anyObject()); boolean returnedResult = target.register(); Assert.assertFalse(returnedResult); }
QueryVarParamWriter extends AbstractUrlParamWriter { @Override public void write(URLPathStringBuilder builder, Map<String, Object> args) throws Exception { Object value = getParamValue(args); if (value == null) { return; } if (value.getClass().isArray()) { writeArray(builder, value); return; } if (Collection.class.isInstance(value)) { writeCollection(builder, value); return; } builder.appendQuery(param.getParamName(), encodeNotNullValue(value)); } QueryVarParamWriter(RestParam param); @Override void write(URLPathStringBuilder builder, Map<String, Object> args); }
@Test public void write() throws Exception { URLPathStringBuilder stringBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("q", "a"); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=a", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=a", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=a", stringBuilder.build()); } @Test public void writeNull() throws Exception { URLPathStringBuilder stringBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("test", null); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); } @Test public void writeList() throws Exception { List<String> queryList = Arrays.asList("ab", "cd", "ef"); Map<String, Object> parameters = new HashMap<>(); parameters.put("q", queryList); URLPathStringBuilder stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=ab%2Ccd%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=ef", stringBuilder.build()); parameters.put("q", Arrays.asList("a b", " ", "", "ef")); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b%2C+%2C%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b&q=+&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b&q=+&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); parameters.put("q", Collections.singletonList("")); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); parameters.put("q", new ArrayList<>()); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); parameters.put("q", Collections.singletonList(null)); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); parameters.put("q", Arrays.asList(null, "ab", null, "cd", null, null, "", null, "ef", null)); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=ab%2Ccd%2C%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=&q=ef", stringBuilder.build()); }
QueryVarParamWriter extends AbstractUrlParamWriter { private void writeArray(URLPathStringBuilder builder, Object value) throws Exception { if (shouldJoinParams()) { writeJoinedParams(builder, Arrays.asList(((Object[]) value))); return; } for (Object item : (Object[]) value) { writeItem(builder, item); } } QueryVarParamWriter(RestParam param); @Override void write(URLPathStringBuilder builder, Map<String, Object> args); }
@Test public void writeArray() throws Exception { URLPathStringBuilder stringBuilder = new URLPathStringBuilder(); Map<String, Object> parameters = new HashMap<>(); parameters.put("q", new String[] {"ab", "cd", "ef"}); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=ab%2Ccd%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); parameters.put("q", new String[] {"a b", " ", "", "ef"}); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b%2C+%2C%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b&q=+&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=a+b&q=+&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); parameters.put("q", new String[] {""}); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); parameters.put("q", new String[] {}); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); parameters.put("q", new String[] {null}); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("", stringBuilder.build()); parameters.put("q", new String[] {null, "ab", null, "cd", null, null, "", null, "ef", null}); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterCsv.write(stringBuilder, parameters); Assert.assertEquals("?q=ab%2Ccd%2C%2Cef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterMulti.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=&q=ef", stringBuilder.build()); stringBuilder = new URLPathStringBuilder(); queryVarParamWriterDefault.write(stringBuilder, parameters); Assert.assertEquals("?q=ab&q=cd&q=&q=ef", stringBuilder.build()); }
URLPathBuilder { public String createRequestPath(Map<String, Object> args) throws Exception { URLPathStringBuilder builder = new URLPathStringBuilder(); genPathString(builder, args); genQueryString(builder, args); return builder.build(); } URLPathBuilder(String rawPath, Map<String, RestParam> paramMap); String createRequestPath(Map<String, Object> args); String createPathString(Map<String, Object> args); }
@Test public void testMultiQuery() throws Exception { Map<String, RestParam> paramMap = new LinkedHashMap<>(); addParam("strArr", String[].class, QueryParameter::new, paramMap); addParam("intArr", int[].class, QueryParameter::new, paramMap); URLPathBuilder urlPathBuilder = new URLPathBuilder("/path", paramMap); Map<String, Object> parameters = new HashMap<>(); parameters.put("strArr", new Object[] {"a", "b", "c"}); parameters.put("intArr", new Object[] {1, 2, 3}); Assert.assertEquals("/path?strArr=a&strArr=b&strArr=c&intArr=1&intArr=2&intArr=3", urlPathBuilder.createRequestPath(parameters)); parameters.put("strArr", new Object[] {}); parameters.put("intArr", new Object[] {1, 2, 3}); Assert.assertEquals("/path?intArr=1&intArr=2&intArr=3", urlPathBuilder.createRequestPath(parameters)); parameters.put("strArr", new Object[] {"a", "b", "c"}); parameters.put("intArr", new Object[] {}); Assert.assertEquals("/path?strArr=a&strArr=b&strArr=c", urlPathBuilder.createRequestPath(parameters)); parameters.put("strArr", new Object[] {}); parameters.put("intArr", new Object[] {}); Assert.assertEquals("/path", urlPathBuilder.createRequestPath(parameters)); }
RestProducerInvocation extends AbstractRestInvocation { public void invoke(Transport transport, HttpServletRequestEx requestEx, HttpServletResponseEx responseEx, List<HttpServerFilter> httpServerFilters) { this.transport = transport; this.requestEx = requestEx; this.responseEx = responseEx; this.httpServerFilters = httpServerFilters; requestEx.setAttribute(RestConst.REST_REQUEST, requestEx); try { findRestOperation(); } catch (InvocationException e) { sendFailResponse(e); return; } scheduleInvocation(); } void invoke(Transport transport, HttpServletRequestEx requestEx, HttpServletResponseEx responseEx, List<HttpServerFilter> httpServerFilters); }
@Test public void invokeSendFail(@Mocked InvocationException expected) { restProducerInvocation = new MockUp<RestProducerInvocation>() { @Mock void sendFailResponse(Throwable throwable) { throwableOfSendFailResponse = throwable; } @Mock void findRestOperation() { throw expected; } @Mock void scheduleInvocation() { throw new IllegalStateException("must not invoke scheduleInvocation"); } }.getMockInstance(); restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters); Assert.assertSame(expected, throwableOfSendFailResponse); } @Test public void invokeNormal() { restProducerInvocation = new MockUp<RestProducerInvocation>() { @Mock void findRestOperation() { restProducerInvocation.restOperationMeta = restOperationMeta; } @Mock void scheduleInvocation() { scheduleInvocation = true; } }.getMockInstance(); requestEx = new AbstractHttpServletRequest() { }; restProducerInvocation.invoke(transport, requestEx, responseEx, httpServerFilters); Assert.assertTrue(scheduleInvocation); Assert.assertSame(requestEx, requestEx.getAttribute(RestConst.REST_REQUEST)); }
RestProducerInvocation extends AbstractRestInvocation { protected void findRestOperation() { MicroserviceMeta selfMicroserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); findRestOperation(selfMicroserviceMeta); } void invoke(Transport transport, HttpServletRequestEx requestEx, HttpServletResponseEx responseEx, List<HttpServerFilter> httpServerFilters); }
@Test public void findRestOperationNameFromRegistry() { Microservice microservice = new Microservice(); microservice.setServiceName("ms"); new Expectations(ServicePathManager.class) { { ServicePathManager.getServicePathManager(microserviceMeta); result = null; } }; restProducerInvocation = new RestProducerInvocation(); initRestProducerInvocation(); expectedException.expect(Exception.class); expectedException.expectMessage("[message=Not Found]"); restProducerInvocation.findRestOperation(); } @Test public void findRestOperationNormal(@Mocked ServicePathManager servicePathManager, @Mocked OperationLocator locator) { requestEx = new AbstractHttpServletRequest() { @Override public String getRequestURI() { return "/path"; } @Override public String getMethod() { return "GET"; } @Override public String getHeader(String name) { return "ms"; } }; Map<String, String> pathVars = new HashMap<>(); new Expectations(ServicePathManager.class) { { ServicePathManager.getServicePathManager(microserviceMeta); result = servicePathManager; servicePathManager.producerLocateOperation(anyString, anyString); result = locator; locator.getPathVarMap(); result = pathVars; locator.getOperation(); result = restOperationMeta; } }; restProducerInvocation = new RestProducerInvocation(); initRestProducerInvocation(); restProducerInvocation.findRestOperation(); Assert.assertSame(restOperationMeta, restProducerInvocation.restOperationMeta); Assert.assertSame(pathVars, requestEx.getAttribute(RestConst.PATH_PARAMETERS)); }
VertxRestInvocation extends RestProducerInvocation { @Override protected void createInvocation() { super.createInvocation(); RoutingContext routingContext = ((VertxServerRequestToHttpServletRequest) this.requestEx).getContext(); VertxHttpTransportContext transportContext = new VertxHttpTransportContext(routingContext, requestEx, responseEx, produceProcessor); invocation.setTransportContext(transportContext); routingContext.put(RestConst.REST_INVOCATION_CONTEXT, this.invocation); } }
@Test public void testCreateInvocation() { new MockUp<RestProducerInvocation>() { @Mock void createInvocation() { } }; VertxRestInvocation vertxRestInvocation = new VertxRestInvocation(); VertxServerRequestToHttpServletRequest requestEx = Mockito.mock(VertxServerRequestToHttpServletRequest.class); RoutingContext routingContext = Mockito.mock(RoutingContext.class); Invocation invocation = Mockito.mock(Invocation.class); Deencapsulation.setField( vertxRestInvocation, "requestEx", requestEx); Deencapsulation.setField( vertxRestInvocation, "invocation", invocation); Mockito.when(requestEx.getContext()).thenReturn(routingContext); Deencapsulation.invoke(vertxRestInvocation, "createInvocation"); Mockito.verify(routingContext, Mockito.times(1)).put(RestConst.REST_INVOCATION_CONTEXT, invocation); }
Utils { public static String findActualPath(String path, int pathIndex) { if (pathIndex <= 0) { return path; } int fromIndex = 0; int counter = pathIndex; char[] chars = path.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '/') { if (--counter < 0) { fromIndex = i; break; } } } return fromIndex > 0 ? path.substring(fromIndex) : ""; } private Utils(); static String findActualPath(String path, int pathIndex); }
@Test public void testUtisl() { Assert.assertEquals(Utils.findActualPath("/a/b/c", -1), "/a/b/c"); Assert.assertEquals(Utils.findActualPath("/a/b/c", 0), "/a/b/c"); Assert.assertEquals(Utils.findActualPath("/a/b/c", 1), "/b/c"); Assert.assertEquals(Utils.findActualPath("/a/b/c", 2), "/c"); Assert.assertEquals(Utils.findActualPath("/a/b/c", 3), ""); Assert.assertEquals(Utils.findActualPath("/a/b/c", 100), ""); }
DefaultEdgeDispatcher extends AbstractEdgeDispatcher { protected void onRequest(RoutingContext context) { Map<String, String> pathParams = context.pathParams(); String microserviceName = pathParams.get("param0"); String path = Utils.findActualPath(context.request().path(), prefixSegmentCount); EdgeInvocation edgeInvocation = createEdgeInvocation(); if (withVersion) { String pathVersion = pathParams.get("param1"); edgeInvocation.setVersionRule(versionMapper.getOrCreate(pathVersion).getVersionRule()); } edgeInvocation.init(microserviceName, context, path, httpServerFilters); edgeInvocation.edgeInvoke(); } @Override int getOrder(); @Override boolean enabled(); @Override void init(Router router); }
@Test @SuppressWarnings("unchecked") public void testOnRequest(@Mocked Router router, @Mocked Route route , @Mocked RoutingContext context , @Mocked HttpServerRequest requst , @Mocked EdgeInvocation invocation) { DefaultEdgeDispatcher dispatcher = new DefaultEdgeDispatcher(); Map<String, String> pathParams = new HashMap<>(); pathParams.put("param0", "testService"); pathParams.put("param1", "v1"); new Expectations() { { router.routeWithRegex("/api/([^\\\\/]+)/([^\\\\/]+)/(.*)"); result = route; route.handler((Handler<RoutingContext>) any); result = route; route.failureHandler((Handler<RoutingContext>) any); result = route; context.pathParams(); result = pathParams; context.request(); result = requst; requst.path(); result = "/api/testService/v1/hello"; invocation.setVersionRule("1.0.0.0-2.0.0.0"); invocation.init("testService", context, "/testService/v1/hello", Deencapsulation.getField(dispatcher, "httpServerFilters")); invocation.edgeInvoke(); } }; dispatcher.init(router); Assert.assertEquals(dispatcher.enabled(), false); Assert.assertEquals(Utils.findActualPath("/api/test", 1), "/test"); Assert.assertEquals(dispatcher.getOrder(), 20000); dispatcher.onRequest(context); }
AbstractEdgeDispatcher extends AbstractVertxHttpDispatcher { protected void onFailure(RoutingContext context) { LOGGER.error("edge server failed.", context.failure()); HttpServerResponse response = context.response(); if (response.closed() || response.ended()) { return; } if (context.failure() instanceof InvocationException) { InvocationException exception = (InvocationException) context.failure(); response.setStatusCode(exception.getStatusCode()); response.setStatusMessage(exception.getReasonPhrase()); if (null == exception.getErrorData()) { response.end(); return; } String responseBody; try { responseBody = RestObjectMapperFactory.getRestObjectMapper().writeValueAsString(exception.getErrorData()); response.putHeader("Content-Type", MediaType.APPLICATION_JSON); } catch (JsonProcessingException e) { responseBody = exception.getErrorData().toString(); response.putHeader("Content-Type", MediaType.TEXT_PLAIN); } response.end(responseBody); } else { response.setStatusCode(Status.BAD_GATEWAY.getStatusCode()); response.setStatusMessage(Status.BAD_GATEWAY.getReasonPhrase()); response.end(); } } }
@Test public void onFailure(@Mocked RoutingContext context) { Map<String, Object> map = new HashMap<>(); HttpServerResponse response = new MockUp<HttpServerResponse>() { @Mock HttpServerResponse setStatusCode(int statusCode) { map.put("code", statusCode); return null; } @Mock HttpServerResponse setStatusMessage(String statusMessage) { map.put("msg", statusMessage); return null; } }.getMockInstance(); new Expectations() { { context.failure(); returns(new RuntimeExceptionWithoutStackTrace("failed"), null); context.response(); result = response; } }; AbstractEdgeDispatcherForTest dispatcher = new AbstractEdgeDispatcherForTest(); dispatcher.onFailure(context); Assert.assertEquals(502, map.get("code")); Assert.assertEquals("Bad Gateway", map.get("msg")); new Expectations() { { context.failure(); returns(new InvocationException(401, "unauthorized", "unauthorized"), new InvocationException(401, "unauthorized", "unauthorized")); context.response(); result = response; } }; dispatcher = new AbstractEdgeDispatcherForTest(); dispatcher.onFailure(context); Assert.assertEquals(401, map.get("code")); Assert.assertEquals("unauthorized", map.get("msg")); }
EdgeBootListener implements BootListener { @Override public void onBootEvent(BootEvent event) { if (!EventType.BEFORE_PRODUCER_PROVIDER.equals(event.getEventType())) { return; } TransportClientConfig.setRestTransportClientCls(EdgeRestTransportClient.class); TransportConfig.setRestServerVerticle(EdgeRestServerVerticle.class); String defaultExecutor = DynamicPropertyFactory.getInstance() .getStringProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, null) .get(); if (defaultExecutor != null) { LOGGER.info("Edge service default executor is {}.", defaultExecutor); return; } Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource(); configuration.setProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, ExecutorManager.EXECUTOR_REACTIVE); LOGGER.info("Set ReactiveExecutor to be edge service default executor."); } @Override void onBootEvent(BootEvent event); }
@Test public void onBootEvent_ignore() { System.setProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, ExecutorManager.EXECUTOR_DEFAULT); bootEvent.setEventType(EventType.AFTER_CONSUMER_PROVIDER); listener.onBootEvent(bootEvent); Assert.assertEquals(ExecutorManager.EXECUTOR_DEFAULT, DynamicPropertyFactory.getInstance().getStringProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, null).get()); } @Test public void onBootEvent_accept_notChange() { System.setProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, ExecutorManager.EXECUTOR_DEFAULT); bootEvent.setEventType(EventType.BEFORE_PRODUCER_PROVIDER); listener.onBootEvent(bootEvent); Assert.assertEquals(ExecutorManager.EXECUTOR_DEFAULT, DynamicPropertyFactory.getInstance().getStringProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, null).get()); } @Test public void onBootEvent_change() { bootEvent.setEventType(EventType.BEFORE_PRODUCER_PROVIDER); listener.onBootEvent(bootEvent); Assert.assertEquals(ExecutorManager.EXECUTOR_REACTIVE, DynamicPropertyFactory.getInstance().getStringProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, null).get()); }
CompatiblePathVersionMapper { public VersionRule getOrCreate(String pathVersion) { return mapper.computeIfAbsent(pathVersion, pv -> { return createVersionRule(pathVersion); }); } VersionRule getOrCreate(String pathVersion); }
@Test public void getOrCreate() { VersionRule versionRule = mapper.getOrCreate("v1"); Assert.assertEquals("1.0.0.0-2.0.0.0", versionRule.getVersionRule()); } @Test public void createVersionRule_empty() { expectedException.expect(ServiceCombException.class); expectedException.expectMessage(Matchers.is("pathVersion \"\" is invalid, format must be v+number or V+number.")); mapper.getOrCreate(""); } @Test public void createVersionRule_invalidFormat() { expectedException.expect(ServiceCombException.class); expectedException.expectMessage(Matchers.is("pathVersion \"a1\" is invalid, format must be v+number or V+number.")); mapper.getOrCreate("a1"); } @Test public void createVersionRule_invalidNumber() { expectedException.expect(ServiceCombException.class); expectedException.expectMessage(Matchers.is("pathVersion \"va\" is invalid, format must be v+number or V+number.")); mapper.getOrCreate("va"); } @Test public void createVersionRule_tooSmall() { expectedException.expect(ServiceCombException.class); expectedException.expectMessage(Matchers.is("pathVersion \"v-1\" is invalid, version range is [0, 32767].")); mapper.getOrCreate("v-1"); } @Test public void createVersionRule_tooBig() { expectedException.expect(ServiceCombException.class); expectedException.expectMessage(Matchers.is("pathVersion \"v32768\" is invalid, version range is [0, 32767].")); mapper.getOrCreate("v32768"); } @Test public void createVersionRule_32767() { VersionRule versionRule = mapper.getOrCreate("v32767"); Assert.assertEquals("32767.0.0.0+", versionRule.getVersionRule()); }
ZeroConfigClient { public boolean unregister() { ServerMicroserviceInstance foundInstance = preUnregisterCheck(); if (foundInstance == null) { LOGGER.warn( "Failed to unregister as Microservice Instance doesn't exist in server side in Zero-Config mode"); return false; } try { LOGGER.info( "Start Multicast Microservice Instance Unregister Event in Zero-Config mode. Service ID: {}, Instance ID:{}", foundInstance.getServiceId(), foundInstance.getInstanceId()); Map<String, String> unregisterEventMap = new HashMap<>(); unregisterEventMap.put(EVENT, UNREGISTER_EVENT); unregisterEventMap.put(SERVICE_ID, foundInstance.getServiceId()); unregisterEventMap.put(INSTANCE_ID, foundInstance.getInstanceId()); byte[] unregisterEventBytes = unregisterEventMap.toString().getBytes(ENCODE); DatagramPacket unregisterEventDataPacket = new DatagramPacket(unregisterEventBytes, unregisterEventBytes.length, InetAddress.getByName(GROUP), PORT); this.multicastSocket.send(unregisterEventDataPacket); return true; } catch (IOException e) { LOGGER.error( "Failed to Multicast Microservice Instance Unregister Event in Zero-Config mode. Service ID: {}, Instance ID:{}", foundInstance.getServiceId(), foundInstance.getInstanceId(), e); return false; } } private ZeroConfigClient(ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); @VisibleForTesting ZeroConfigClient initZeroConfigClientWithMocked( ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); void init(); boolean register(); boolean unregister(); List<Microservice> getAllMicroservices(); Microservice getMicroservice(String microserviceId); String getSchema(String microserviceId, String schemaId); MicroserviceInstance findMicroserviceInstance(String serviceId, String instanceId); MicroserviceInstances findServiceInstances(String appId, String providerServiceName, String strVersionRule); Microservice getSelfMicroservice(); @VisibleForTesting void setSelfMicroservice( Microservice selfMicroservice); MicroserviceInstance getSelfMicroserviceInstance(); @VisibleForTesting void setSelfMicroserviceInstance( MicroserviceInstance selfMicroserviceInstance); static ZeroConfigClient INSTANCE; }
@Test public void test_unregister_withCorrectData_UnregisterShouldSucceed() { when(zeroConfigRegistryService.findServiceInstance(selfServiceId, selfInstanceId)) .thenReturn(prepareServerServiceInstance(true)); boolean returnedResult = target.unregister(); Assert.assertTrue(returnedResult); } @Test public void test_unregister_withWrongData_UnregisterShouldFail() { when(zeroConfigRegistryService.findServiceInstance(selfServiceId, selfInstanceId)) .thenReturn(null); boolean returnedResult = target.unregister(); Assert.assertFalse(returnedResult); } @Test public void test_unregister_MulticastThrowException_UnregisterShouldFail() throws IOException { when(zeroConfigRegistryService.findServiceInstance(selfServiceId, selfInstanceId)) .thenReturn(prepareServerServiceInstance(true)); doThrow(IOException.class).when(multicastSocket).send(anyObject()); boolean returnedResult = target.unregister(); Assert.assertFalse(returnedResult); }
InspectorBootListener implements BootListener { @Override public int getOrder() { return Short.MAX_VALUE; } @Override int getOrder(); @Override void onAfterTransport(BootEvent event); }
@Test public void getOrder() { Assert.assertEquals(Short.MAX_VALUE, new InspectorBootListener().getOrder()); }
InspectorImpl { @Path("/schemas") @GET public Collection<String> getSchemaIds() { return schemas.keySet(); } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void getSchemaIds() { Assert.assertThat(inspector.getSchemaIds(), Matchers.contains("schema1", "schema2")); }
InspectorImpl { @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) public Response downloadSchemas(@QueryParam("format") SchemaFormat format) { if (format == null) { format = SchemaFormat.SWAGGER; } ByteArrayOutputStream os = new ByteArrayOutputStream(); try (ZipOutputStream zos = new ZipOutputStream(os)) { for (Entry<String, String> entry : schemas.entrySet()) { zos.putNextEntry(new ZipEntry(entry.getKey() + format.getSuffix())); String content = entry.getValue(); if (SchemaFormat.HTML.equals(format)) { content = swaggerToHtml(content); } zos.write(content.getBytes(StandardCharsets.UTF_8)); zos.closeEntry(); } } catch (Throwable e) { String msg = "failed to create schemas zip file, format=" + format + "."; LOGGER.error(msg, e); return Response.failResp(new InvocationException(Status.INTERNAL_SERVER_ERROR, msg)); } Part part = new InputStreamPart(null, new ByteArrayInputStream(os.toByteArray())) .setSubmittedFileName( RegistrationManager.INSTANCE.getMicroservice().getServiceName() + format.getSuffix() + ".zip"); return Response.ok(part); } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void downloadSchemas_html(@Mocked Microservice microservice) throws IOException { new Expectations(RegistrationManager.INSTANCE) { { RegistrationManager.INSTANCE.getMicroservice(); result = microservice; microservice.getServiceName(); result = "ms"; } }; Response response = inspector.downloadSchemas(SchemaFormat.HTML); Part part = response.getResult(); Assert.assertEquals("ms.html.zip", part.getSubmittedFileName()); try (InputStream is = part.getInputStream()) { Map<String, String> unziped = unzip(is); Assert.assertEquals(schemas.size(), unziped.size()); Assert.assertTrue(unziped.get("schema1.html").endsWith("</html>")); Assert.assertTrue(unziped.get("schema2.html").endsWith("</html>")); } } @Test public void downloadSchemas_failed() { SchemaFormat format = SchemaFormat.SWAGGER; new Expectations(format) { { format.getSuffix(); result = new RuntimeExceptionWithoutStackTrace("zip failed."); } }; try (LogCollector logCollector = new LogCollector()) { Response response = inspector.downloadSchemas(format); Assert.assertEquals("failed to create schemas zip file, format=SWAGGER.", logCollector.getLastEvents().getMessage()); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR, invocationException.getStatus()); Assert.assertEquals("failed to create schemas zip file, format=SWAGGER.", ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode()); Assert.assertEquals(Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), response.getReasonPhrase()); } }
InspectorImpl { @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) public Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download) { String swaggerContent = schemas.get(schemaId); if (swaggerContent == null) { return Response.failResp(new InvocationException(Status.NOT_FOUND, Status.NOT_FOUND.getReasonPhrase())); } if (format == null) { format = SchemaFormat.SWAGGER; } byte[] bytes; if (SchemaFormat.HTML.equals(format)) { String html = swaggerToHtml(swaggerContent); bytes = html.getBytes(StandardCharsets.UTF_8); } else { bytes = swaggerContent.getBytes(StandardCharsets.UTF_8); } Part part = new InputStreamPart(null, new ByteArrayInputStream(bytes)) .setSubmittedFileName(schemaId + format.getSuffix()); Response response = Response.ok(part); if (!download) { response.getHeaders().addHeader(HttpHeaders.CONTENT_DISPOSITION, "inline"); } response.getHeaders().addHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML); return response; } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void getSchemaContentById_notExist() { Response response = inspector.getSchemaContentById("notExist", null, false); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.NOT_FOUND, invocationException.getStatus()); Assert.assertEquals(Status.NOT_FOUND.getReasonPhrase(), ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(404, response.getStatusCode()); Assert.assertEquals("Not Found", response.getReasonPhrase()); }
InspectorImpl { @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) public Response getStaticResource(@PathParam("path") String path) { return resourceHandler.handle(path); } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void getStaticResource_notExist() throws IOException { Response response = inspector.getStaticResource("notExist"); InvocationException invocationException = response.getResult(); Assert.assertEquals(Status.NOT_FOUND, invocationException.getStatus()); Assert.assertEquals(Status.NOT_FOUND.getReasonPhrase(), ((CommonExceptionData) invocationException.getErrorData()).getMessage()); Assert.assertEquals(404, response.getStatusCode()); Assert.assertEquals("Not Found", response.getReasonPhrase()); } @Test public void getStaticResource() throws IOException { Response response = inspector.getStaticResource("index.html"); Part part = response.getResult(); Assert.assertEquals("inline", response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION)); Assert.assertEquals(MediaType.TEXT_HTML, response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE)); try (InputStream is = part.getInputStream()) { Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("</html>")); } }
InspectorImpl { @Path("/dynamicProperties") @GET public List<DynamicPropertyView> dynamicProperties() { List<DynamicPropertyView> views = new ArrayList<>(); for (DynamicProperty property : ConfigUtil.getAllDynamicProperties().values()) { views.add(createDynamicPropertyView(property)); } views.sort(Comparator .comparing(DynamicPropertyView::getCallbackCount) .thenComparing(DynamicPropertyView::getChangedTime).reversed() .thenComparing(DynamicPropertyView::getKey)); return views; } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void dynamicProperties() { DynamicProperty.getInstance("zzz"); ArchaiusUtils.setProperty("zzz", "abc"); DynamicProperty.getInstance("yyy").addCallback(() -> { }); List<DynamicPropertyView> views = inspector.dynamicProperties(); Map<String, DynamicPropertyView> viewMap = views.stream() .collect(Collectors.toMap(DynamicPropertyView::getKey, Function.identity())); Assert.assertEquals(1, viewMap.get("yyy").getCallbackCount()); Assert.assertEquals(0, viewMap.get("zzz").getCallbackCount()); Assert.assertEquals(0, viewMap.get("servicecomb.inspector.enabled").getCallbackCount()); Assert.assertEquals(0, viewMap.get("servicecomb.inspector.swagger.html.asciidoctorCss").getCallbackCount()); int count = ConfigUtil.getAllDynamicProperties().size(); ConfigUtil.getAllDynamicProperties().remove("yyy"); ConfigUtil.getAllDynamicProperties().remove("zzz"); Assert.assertEquals(count - 2, ConfigUtil.getAllDynamicProperties().size()); }
InspectorImpl { @Path("/priorityProperties") @GET public List<PriorityPropertyView> priorityProperties() { List<PriorityPropertyView> views = new ArrayList<>(); priorityPropertyManager.getConfigObjectMap().values().stream() .flatMap(Collection::stream) .forEach(p -> views.add(createPriorityPropertyView(p))); priorityPropertyManager.getPriorityPropertySet().forEach(p -> views.add(createPriorityPropertyView(p))); return views; } InspectorImpl(SCBEngine scbEngine, InspectorConfig inspectorConfig, Map<String, String> schemas); SCBEngine getScbEngine(); InspectorConfig getInspectorConfig(); void setPriorityPropertyManager(PriorityPropertyManager priorityPropertyManager); @Path("/schemas") @GET Collection<String> getSchemaIds(); @Path("/download/schemas") @GET @ApiResponse(code = 200, message = "", response = File.class) Response downloadSchemas(@QueryParam("format") SchemaFormat format); @Path("/schemas/{schemaId}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getSchemaContentById(@PathParam("schemaId") String schemaId, @QueryParam("format") SchemaFormat format, @QueryParam("download") boolean download); @Path("/{path : .+}") @GET @ApiResponse(code = 200, message = "", response = File.class) Response getStaticResource(@PathParam("path") String path); @Path("/dynamicProperties") @GET List<DynamicPropertyView> dynamicProperties(); @Path("/priorityProperties") @GET List<PriorityPropertyView> priorityProperties(); }
@Test public void priorityProperties() { PriorityPropertyManager priorityPropertyManager = new PriorityPropertyManager(); inspector.setPriorityPropertyManager(priorityPropertyManager); PriorityProperty<?> priorityProperty = priorityPropertyManager .createPriorityProperty(int.class, 0, 0, "high", "low"); List<PriorityPropertyView> views = inspector.priorityProperties(); Assert.assertEquals(1, views.size()); Assert.assertThat( views.get(0).getDynamicProperties().stream().map(DynamicPropertyView::getKey).collect(Collectors.toList()), Matchers.contains("high", "low")); priorityPropertyManager.close(); inspector.setPriorityPropertyManager(null); }
Exceptions { public static InvocationException convert(@Nonnull Invocation invocation, Throwable throwable) { StatusType genericStatus = getGenericStatus(invocation); return convert(invocation, throwable, genericStatus); } private Exceptions(); static Throwable unwrapIncludeInvocationException(Throwable throwable); static T unwrap(Throwable throwable); static InvocationException create(StatusType status, Object errorData); static InvocationException create(StatusType status, String code, String msg); static InvocationException consumer(String code, String msg); static InvocationException consumer(String code, String msg, Throwable cause); static InvocationException genericConsumer(String msg); static InvocationException genericConsumer(String msg, Throwable cause); static InvocationException producer(String code, String msg); static InvocationException producer(String code, String msg, Throwable cause); static InvocationException genericProducer(String msg); static InvocationException genericProducer(String msg, Throwable cause); static StatusType getGenericStatus(@Nonnull Invocation invocation); static Response exceptionToResponse(@Nullable Invocation invocation, Throwable exception, StatusType genericStatus); static InvocationException convert(@Nonnull Invocation invocation, Throwable throwable); static InvocationException convert(@Nullable Invocation invocation, Throwable throwable, StatusType genericStatus); }
@Test void should_convert_unknown_client_exception_to_invocation_exception() { IllegalStateException exception = new IllegalStateException("msg"); InvocationException invocationException = Exceptions.convert(null, exception, BAD_REQUEST); assertThat(invocationException).hasCause(exception); assertThat(invocationException.getStatus()).isEqualTo(BAD_REQUEST); assertThat(invocationException.getErrorData()).isInstanceOf(CommonExceptionData.class); assertThat(Json.encode(invocationException.getErrorData())) .isEqualTo("{\"code\":\"SCB.00000000\",\"message\":\"msg\"}"); } @Test void should_convert_unknown_server_exception_to_invocation_exception() { IllegalStateException exception = new IllegalStateException("msg"); InvocationException invocationException = Exceptions.convert(null, exception, INTERNAL_SERVER_ERROR); assertThat(invocationException).hasCause(exception); assertThat(invocationException.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR); assertThat(invocationException.getErrorData()).isInstanceOf(CommonExceptionData.class); assertThat(Json.encode(invocationException.getErrorData())) .isEqualTo("{\"code\":\"SCB.50000000\",\"message\":\"msg\"}"); }
ConfigurationSpringInitializer extends PropertyPlaceholderConfigurer implements EnvironmentAware { @Override public void setEnvironment(Environment environment) { String environmentName = generateNameForEnvironment(environment); LOGGER.info("Environment received, will get configurations from [{}].", environmentName); Map<String, Object> extraConfig = getAllProperties(environment); ConfigUtil.addExtraConfig(EXTRA_CONFIG_SOURCE_PREFIX + environmentName, extraConfig); ConfigUtil.installDynamicConfig(); setUpSpringPropertySource(environment); } ConfigurationSpringInitializer(); @Override void setEnvironment(Environment environment); static final String EXTRA_CONFIG_SOURCE_PREFIX; }
@Test public void testSetEnvironment() { ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources = new MutablePropertySources(); Map<String, String> propertyMap = new HashMap<>(); final String map0Key0 = "map0-Key0"; final String map1Key0 = "map1-Key0"; final String map2Key0 = "map2-Key0"; final String map3Key0 = "map3-Key0"; propertyMap.put(map0Key0, "map0-Value0"); propertyMap.put(map1Key0, "map1-Value0"); propertyMap.put(map2Key0, "map2-Value0"); propertyMap.put(map3Key0, "map3-Value0"); CompositePropertySource compositePropertySource0 = new CompositePropertySource("compositePropertySource0"); propertySources.addFirst(compositePropertySource0); HashMap<String, Object> map0 = new HashMap<>(); map0.put(map0Key0, propertyMap.get(map0Key0)); MapPropertySource mapPropertySource0 = new MapPropertySource("mapPropertySource0", map0); compositePropertySource0.addFirstPropertySource(mapPropertySource0); CompositePropertySource compositePropertySource1 = new CompositePropertySource("compositePropertySource1"); compositePropertySource0.addPropertySource(compositePropertySource1); HashMap<String, Object> map1 = new HashMap<>(); map1.put(map1Key0, propertyMap.get(map1Key0)); MapPropertySource mapPropertySource1 = new MapPropertySource("mapPropertySource1", map1); compositePropertySource1.addPropertySource(mapPropertySource1); HashMap<String, Object> map2 = new HashMap<>(); map2.put(map2Key0, propertyMap.get(map2Key0)); MapPropertySource mapPropertySource2 = new MapPropertySource("mapPropertySource2", map2); compositePropertySource1.addPropertySource(mapPropertySource2); compositePropertySource1.addPropertySource(Mockito.mock(JndiPropertySource.class)); HashMap<String, Object> map3 = new HashMap<>(); map3.put(map3Key0, propertyMap.get(map3Key0)); MapPropertySource mapPropertySource3 = new MapPropertySource("mapPropertySource3", map3); compositePropertySource0.addPropertySource(mapPropertySource3); Mockito.when(environment.getPropertySources()).thenReturn(propertySources); Mockito.doAnswer((Answer<String>) invocation -> { Object[] args = invocation.getArguments(); String propertyName = (String) args[0]; if ("spring.config.name".equals(propertyName) || "spring.application.name".equals(propertyName)) { return null; } String value = propertyMap.get(propertyName); if (null == value) { fail("get unexpected property name: " + propertyName); } return value; }).when(environment).getProperty(anyString(), Matchers.eq(Object.class)); new ConfigurationSpringInitializer().setEnvironment(environment); Map<String, Map<String, Object>> extraLocalConfig = getExtraConfigMapFromConfigUtil(); assertFalse(extraLocalConfig.isEmpty()); Map<String, Object> extraProperties = extraLocalConfig .get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + environment.getClass().getName() + "@" + environment.hashCode()); assertNotNull(extraLocalConfig); for (Entry<String, String> entry : propertyMap.entrySet()) { assertEquals(entry.getValue(), extraProperties.get(entry.getKey())); } } @Test public void testSetEnvironmentOnEnvironmentName() { ConfigurableEnvironment environment0 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources0 = new MutablePropertySources(); Mockito.when(environment0.getPropertySources()).thenReturn(propertySources0); Map<String, Object> map0 = new HashMap<>(1); map0.put("spring.config.name", "application"); propertySources0.addFirst(new MapPropertySource("mapPropertySource0", map0)); Mockito.when(environment0.getProperty("spring.config.name", Object.class)).thenReturn("application"); Mockito.when(environment0.getProperty("spring.config.name")).thenReturn("application"); ConfigurableEnvironment environment1 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources1 = new MutablePropertySources(); Mockito.when(environment1.getPropertySources()).thenReturn(propertySources1); Map<String, Object> map1 = new HashMap<>(1); map1.put("spring.application.name", "bootstrap"); propertySources1.addFirst(new MapPropertySource("mapPropertySource1", map1)); Mockito.when(environment1.getProperty("spring.application.name", Object.class)).thenReturn("bootstrap"); Mockito.when(environment1.getProperty("spring.application.name")).thenReturn("bootstrap"); ConfigurableEnvironment environment2 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources2 = new MutablePropertySources(); Mockito.when(environment2.getPropertySources()).thenReturn(propertySources2); Map<String, Object> map2 = new HashMap<>(1); map2.put("key2", "value2"); propertySources2.addFirst(new MapPropertySource("mapPropertySource2", map2)); Mockito.when(environment2.getProperty("key2", Object.class)).thenReturn("value2"); Mockito.when(environment2.getProperty("key2")).thenReturn("value2"); ConfigurationSpringInitializer configurationSpringInitializer = new ConfigurationSpringInitializer(); configurationSpringInitializer.setEnvironment(environment0); configurationSpringInitializer.setEnvironment(environment1); configurationSpringInitializer.setEnvironment(environment2); Map<String, Map<String, Object>> extraConfig = getExtraConfigMapFromConfigUtil(); assertEquals(3, extraConfig.size()); Map<String, Object> extraProperties = extraConfig .get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + "application"); assertEquals(1, extraProperties.size()); assertEquals("application", extraProperties.get("spring.config.name")); extraProperties = extraConfig.get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + "bootstrap"); assertEquals(1, extraProperties.size()); assertEquals("bootstrap", extraProperties.get("spring.application.name")); extraProperties = extraConfig.get( ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + environment2.getClass().getName() + "@" + environment2.hashCode()); assertEquals(1, extraProperties.size()); assertEquals("value2", extraProperties.get("key2")); } @Test(expected = RuntimeException.class) public void shoud_throw_exception_when_given_ignoreResolveFailure_false() { StandardEnvironment environment = newStandardEnvironment(); ConfigurationSpringInitializer configurationSpringInitializer = new ConfigurationSpringInitializer(); configurationSpringInitializer.setEnvironment(environment); }
GroupExecutor implements Executor, Closeable { public void initConfig() { if (LOG_PRINTED.compareAndSet(false, true)) { LOGGER.info("thread pool rules:\n" + "1.use core threads.\n" + "2.if all core threads are busy, then create new thread.\n" + "3.if thread count reach the max limitation, then queue the request.\n" + "4.if queue is full, and threads count is max, then reject the request."); } groupCount = DynamicPropertyFactory.getInstance().getIntProperty(KEY_GROUP, 2).get(); coreThreads = DynamicPropertyFactory.getInstance().getIntProperty(KEY_CORE_THREADS, 25).get(); maxThreads = DynamicPropertyFactory.getInstance().getIntProperty(KEY_MAX_THREADS, -1).get(); if (maxThreads <= 0) { maxThreads = DynamicPropertyFactory.getInstance().getIntProperty(KEY_OLD_MAX_THREAD, -1).get(); if (maxThreads > 0) { LOGGER.warn("{} is deprecated, recommended to use {}.", KEY_OLD_MAX_THREAD, KEY_MAX_THREADS); } else { maxThreads = 100; } } if (coreThreads > maxThreads) { LOGGER.warn("coreThreads is bigger than maxThreads, change from {} to {}.", coreThreads, maxThreads); coreThreads = maxThreads; } maxIdleInSecond = DynamicPropertyFactory.getInstance().getIntProperty(KEY_MAX_IDLE_SECOND, 60).get(); maxQueueSize = DynamicPropertyFactory.getInstance().getIntProperty(KEY_MAX_QUEUE_SIZE, Integer.MAX_VALUE).get(); LOGGER.info( "executor name={}, group={}. per group settings, coreThreads={}, maxThreads={}, maxIdleInSecond={}, maxQueueSize={}.", groupName, groupCount, coreThreads, maxThreads, maxIdleInSecond, maxQueueSize); } GroupExecutor init(); GroupExecutor init(String groupName); void initConfig(); List<ExecutorService> getExecutorList(); @Override void execute(Runnable command); @Override void close(); static final String KEY_GROUP; static final String KEY_OLD_MAX_THREAD; static final String KEY_CORE_THREADS; static final String KEY_MAX_THREADS; static final String KEY_MAX_IDLE_SECOND; static final String KEY_MAX_QUEUE_SIZE; }
@Test public void groupCount() { groupExecutor.initConfig(); Assert.assertEquals(2, groupExecutor.groupCount); ArchaiusUtils.setProperty(GroupExecutor.KEY_GROUP, 4); groupExecutor.initConfig(); Assert.assertEquals(4, groupExecutor.groupCount); } @Test public void coreThreads() { groupExecutor.initConfig(); Assert.assertEquals(25, groupExecutor.coreThreads); ArchaiusUtils.setProperty(GroupExecutor.KEY_CORE_THREADS, 100); groupExecutor.initConfig(); Assert.assertEquals(100, groupExecutor.coreThreads); } @Test public void maxIdleInSecond() { groupExecutor.initConfig(); Assert.assertEquals(60, groupExecutor.maxIdleInSecond); ArchaiusUtils.setProperty(GroupExecutor.KEY_MAX_IDLE_SECOND, 100); groupExecutor.initConfig(); Assert.assertEquals(100, groupExecutor.maxIdleInSecond); } @Test public void maxQueueSize() { groupExecutor.initConfig(); Assert.assertEquals(Integer.MAX_VALUE, groupExecutor.maxQueueSize); ArchaiusUtils.setProperty(GroupExecutor.KEY_MAX_QUEUE_SIZE, 100); groupExecutor.initConfig(); Assert.assertEquals(100, groupExecutor.maxQueueSize); } @Test public void maxThreads() { groupExecutor.initConfig(); Assert.assertEquals(100, groupExecutor.maxThreads); LogCollector collector = new LogCollector(); ArchaiusUtils.setProperty(GroupExecutor.KEY_OLD_MAX_THREAD, 200); groupExecutor.initConfig(); Assert.assertEquals(200, groupExecutor.maxThreads); Assert.assertEquals( "servicecomb.executor.default.thread-per-group is deprecated, recommended to use servicecomb.executor.default.maxThreads-per-group.", collector.getEvents().get(collector.getEvents().size() - 2).getMessage()); collector.teardown(); ArchaiusUtils.setProperty(GroupExecutor.KEY_MAX_THREADS, 300); groupExecutor.initConfig(); Assert.assertEquals(300, groupExecutor.maxThreads); } @Test public void adjustCoreThreads() { ArchaiusUtils.setProperty(GroupExecutor.KEY_MAX_THREADS, 10); LogCollector collector = new LogCollector(); groupExecutor.initConfig(); Assert.assertEquals(10, groupExecutor.maxThreads); Assert.assertEquals( "coreThreads is bigger than maxThreads, change from 25 to 10.", collector.getEvents().get(collector.getEvents().size() - 2).getMessage()); collector.teardown(); }
ExecutorManager { public Executor findExecutor(OperationMeta operationMeta) { return findExecutor(operationMeta, null); } ExecutorManager(); void registerExecutor(String id, Executor executor); Executor findExecutor(OperationMeta operationMeta); Executor findExecutor(OperationMeta operationMeta, Executor defaultOperationExecutor); Executor findExecutorById(String id); static final String KEY_EXECUTORS_PREFIX; static final String KEY_EXECUTORS_DEFAULT; static final String EXECUTOR_GROUP_THREADPOOL; static final String EXECUTOR_REACTIVE; static final String EXECUTOR_DEFAULT; }
@Test public void findExecutor_oneParam(@Mocked Executor executor, @Mocked OperationMeta operationMeta) { new Expectations(BeanUtils.class) { { BeanUtils.getBean(ExecutorManager.EXECUTOR_DEFAULT); result = executor; } }; Assert.assertSame(executor, new ExecutorManager().findExecutor(operationMeta)); } @Test public void findExecutor_twoParam_opCfg_withoutOpDef(@Mocked Executor executor, @Mocked OperationMeta operationMeta) { String schemaQualifiedName = "schemaId.opId"; String opBeanId = "opBeanId"; ArchaiusUtils.setProperty(ExecutorManager.KEY_EXECUTORS_PREFIX + schemaQualifiedName, opBeanId); new Expectations(BeanUtils.class) { { operationMeta.getSchemaQualifiedName(); result = schemaQualifiedName; BeanUtils.getBean(opBeanId); result = executor; } }; Assert.assertSame(executor, new ExecutorManager().findExecutor(operationMeta, null)); } @Test public void findExecutor_twoParam_opCfg_withOpDef(@Mocked Executor executor, @Mocked Executor defExecutor, @Mocked OperationMeta operationMeta) { String schemaQualifiedName = "schemaId.opId"; String opBeanId = "opBeanId"; ArchaiusUtils.setProperty(ExecutorManager.KEY_EXECUTORS_PREFIX + schemaQualifiedName, opBeanId); new Expectations(BeanUtils.class) { { operationMeta.getSchemaQualifiedName(); result = schemaQualifiedName; BeanUtils.getBean(opBeanId); result = executor; } }; Assert.assertSame(executor, new ExecutorManager().findExecutor(operationMeta, defExecutor)); } @Test public void findExecutor_twoParam_schemaCfg_withOpDef(@Mocked OperationMeta operationMeta, @Mocked Executor defExecutor) { Assert.assertSame(defExecutor, new ExecutorManager().findExecutor(operationMeta, defExecutor)); } @Test public void findExecutor_twoParam_schemaCfg_withoutOpDef(@Mocked Executor executor, @Mocked OperationMeta operationMeta) { String schemaName = "schemaId"; String opBeanId = "opBeanId"; ArchaiusUtils.setProperty(ExecutorManager.KEY_EXECUTORS_PREFIX + schemaName, opBeanId); new Expectations(BeanUtils.class) { { operationMeta.getSchemaId(); result = schemaName; BeanUtils.getBean(opBeanId); result = executor; } }; Assert.assertSame(executor, new ExecutorManager().findExecutor(operationMeta, null)); } @Test public void findExecutor_twoParam_defaultCfg(@Mocked Executor executor, @Mocked SchemaMeta schemaMeta, @Mocked OperationMeta operationMeta) { String beanId = "beanId"; ArchaiusUtils.setProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, beanId); new Expectations(BeanUtils.class) { { BeanUtils.getBean(beanId); result = executor; } }; Assert.assertSame(executor, new ExecutorManager().findExecutor(operationMeta, null)); }
ZeroConfigClient { public Microservice getMicroservice(String microserviceId) { if (selfMicroservice.getServiceId().equals(microserviceId)) { return selfMicroservice; } else { return ClientUtil .convertToClientMicroservice(zeroConfigRegistryService.getMicroservice(microserviceId)); } } private ZeroConfigClient(ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); @VisibleForTesting ZeroConfigClient initZeroConfigClientWithMocked( ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); void init(); boolean register(); boolean unregister(); List<Microservice> getAllMicroservices(); Microservice getMicroservice(String microserviceId); String getSchema(String microserviceId, String schemaId); MicroserviceInstance findMicroserviceInstance(String serviceId, String instanceId); MicroserviceInstances findServiceInstances(String appId, String providerServiceName, String strVersionRule); Microservice getSelfMicroservice(); @VisibleForTesting void setSelfMicroservice( Microservice selfMicroservice); MicroserviceInstance getSelfMicroserviceInstance(); @VisibleForTesting void setSelfMicroserviceInstance( MicroserviceInstance selfMicroserviceInstance); static ZeroConfigClient INSTANCE; }
@Test public void test_getMicroservice_forOtherService_shouldCallZeroConfigRegistryService() { when(zeroConfigRegistryService.getMicroservice(otherServiceId)) .thenReturn(prepareServerServiceInstance(true)); Microservice returnedResult = target.getMicroservice(otherServiceId); Assert.assertEquals(otherServiceId, returnedResult.getServiceId()); verify(zeroConfigRegistryService, times(1)).getMicroservice(otherServiceId); }
AbstractTransport implements Transport { protected void setListenAddressWithoutSchema(String addressWithoutSchema) { setListenAddressWithoutSchema(addressWithoutSchema, null); } @Override Endpoint getPublishEndpoint(); @Override Endpoint getEndpoint(); @Override Object parseAddress(String address); static final String ENDPOINT_KEY; }
@Test(expected = IllegalArgumentException.class) public void testMyAbstractTransportException(@Mocked TransportManager manager) { MyAbstractTransport transport = new MyAbstractTransport(); transport.setListenAddressWithoutSchema(":127.0.0.1:9090"); }
TransportManager { protected Map<String, List<Transport>> groupByName() { Map<String, List<Transport>> groups = new HashMap<>(); for (Transport transport : transports) { List<Transport> list = groups.computeIfAbsent(transport.getName(), name -> new ArrayList<>()); list.add(transport); } return groups; } void clearTransportBeforeInit(); void addTransportBeforeInit(Transport transport); void addTransportsBeforeInit(List<Transport> transports); void init(SCBEngine scbEngine); Transport findTransport(String transportName); }
@Test public void testGroupByName(@Mocked Transport t1, @Mocked Transport t2_1, @Mocked Transport t2_2) { new Expectations() { { t1.getName(); result = "t1"; t2_1.getName(); result = "t2"; t2_2.getName(); result = "t2"; } }; TransportManager manager = new TransportManager(); manager.addTransportsBeforeInit(Arrays.asList(t1, t2_1, t2_2)); Map<String, List<Transport>> groups = manager.groupByName(); Assert.assertEquals(2, groups.size()); Assert.assertEquals(1, groups.get("t1").size()); Assert.assertEquals(t1, groups.get("t1").get(0)); Assert.assertEquals(2, groups.get("t2").size()); Assert.assertEquals(t2_1, groups.get("t2").get(0)); Assert.assertEquals(t2_2, groups.get("t2").get(1)); }
TransportManager { protected void checkTransportGroup(List<Transport> group) { Map<Integer, Transport> orderMap = new HashMap<>(); for (Transport transport : group) { Transport existTransport = orderMap.putIfAbsent(transport.getOrder(), transport); if (existTransport != null) { throw new ServiceCombException(String.format("%s and %s have the same order %d", existTransport.getClass().getName(), transport.getClass().getName(), transport.getOrder())); } } } void clearTransportBeforeInit(); void addTransportBeforeInit(Transport transport); void addTransportsBeforeInit(List<Transport> transports); void init(SCBEngine scbEngine); Transport findTransport(String transportName); }
@Test public void testCheckTransportGroupInvalid(@Mocked Transport t1, @Mocked Transport t2) { new Expectations() { { t1.getOrder(); result = 1; t2.getOrder(); result = 1; } }; TransportManager manager = new TransportManager(); List<Transport> group = Arrays.asList(t1, t2); try { manager.checkTransportGroup(group); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals( "org.apache.servicecomb.core.$Impl_Transport and org.apache.servicecomb.core.$Impl_Transport have the same order 1", e.getMessage()); } } @Test public void testCheckTransportGroupValid(@Mocked Transport t1, @Mocked Transport t2) { new Expectations() { { t1.getOrder(); result = 1; t2.getOrder(); result = 2; } }; TransportManager manager = new TransportManager(); List<Transport> group = Arrays.asList(t1, t2); try { manager.checkTransportGroup(group); } catch (ServiceCombException e) { Assert.fail("must not throw exception: " + e.getMessage()); } }
TransportManager { protected Transport chooseOneTransport(List<Transport> group) { group.sort(Comparator.comparingInt(Transport::getOrder)); for (Transport transport : group) { if (transport.canInit()) { LOGGER.info("choose {} for {}.", transport.getClass().getName(), transport.getName()); return transport; } } throw new ServiceCombException( String.format("all transport named %s refused to init.", group.get(0).getName())); } void clearTransportBeforeInit(); void addTransportBeforeInit(Transport transport); void addTransportsBeforeInit(List<Transport> transports); void init(SCBEngine scbEngine); Transport findTransport(String transportName); }
@Test public void testChooseOneTransportFirst(@Mocked Transport t1, @Mocked Transport t2) { new Expectations() { { t1.getOrder(); result = 1; t1.canInit(); result = true; t2.getOrder(); result = 2; } }; TransportManager manager = new TransportManager(); List<Transport> group = Arrays.asList(t1, t2); Assert.assertEquals(t1, manager.chooseOneTransport(group)); } @Test public void testChooseOneTransportSecond(@Mocked Transport t1, @Mocked Transport t2) { new Expectations() { { t1.getOrder(); result = Integer.MAX_VALUE; t1.canInit(); result = true; t2.getOrder(); result = -1000; t2.canInit(); result = false; } }; TransportManager manager = new TransportManager(); List<Transport> group = Arrays.asList(t1, t2); Assert.assertEquals(t1, manager.chooseOneTransport(group)); } @Test public void testChooseOneTransportNone(@Mocked Transport t1, @Mocked Transport t2) { new Expectations() { { t1.getName(); result = "t"; t1.getOrder(); result = 1; t1.canInit(); result = false; t2.getOrder(); result = 2; t2.canInit(); result = false; } }; TransportManager manager = new TransportManager(); List<Transport> group = Arrays.asList(t1, t2); try { manager.chooseOneTransport(group); Assert.fail("must throw exception"); } catch (ServiceCombException e) { Assert.assertEquals("all transport named t refused to init.", e.getMessage()); } }
FilterChainsManager { public List<Filter> createConsumerFilters(String microservice) { return createFilters(consumerChainsConfig, microservice); } @Autowired FilterChainsManager setTransportFiltersConfig(TransportFiltersConfig transportFiltersConfig); @Value("${servicecomb.filter-chains.enabled:false}") FilterChainsManager setEnabled(boolean enabled); FilterManager getFilterManager(); @Autowired FilterChainsManager setFilterManager(FilterManager filterManager); FilterChainsManager init(SCBEngine engine); boolean isEnabled(); FilterChainsManager addProviders(FilterProvider... providers); FilterChainsManager addProviders(Collection<FilterProvider> providers); FilterNode createConsumerFilterChain(String microservice); FilterNode createProducerFilterChain(String microservice); List<Filter> createConsumerFilters(String microservice); List<Filter> createProducerFilters(String microservice); String collectResolvedChains(); }
@Test public void should_allow_not_share_filter_instance() { default_chain("simple-load-balance"); FilterChainsManager filterChains = createFilterChains(); List<Filter> aFilters = filterChains.createConsumerFilters("a"); List<Filter> bFilters = filterChains.createConsumerFilters("b"); assertThat(aFilters.get(0)).isNotSameAs(bFilters.get(0)); } @Test public void should_allow_share_filter_instance() { default_chain("simple-retry"); FilterChainsManager filterChains = createFilterChains(); List<Filter> aFilters = filterChains.createConsumerFilters("a"); List<Filter> bFilters = filterChains.createConsumerFilters("b"); assertThat(aFilters).hasSameElementsAs(bFilters); } @Test public void should_allow_mix_share_and_not_share_filter_instance() { default_chain("simple-load-balance, simple-retry"); FilterChainsManager filterChains = createFilterChains(); List<Filter> aFilters = filterChains.createConsumerFilters("a"); List<Filter> bFilters = filterChains.createConsumerFilters("b"); assertThat(aFilters.get(0)).isNotSameAs(bFilters.get(0)); assertThat(aFilters.get(1)).isSameAs(bFilters.get(1)); } @Test public void microservice_scope_should_override_default_scope() { default_chain("simple-load-balance"); microservice_chain("a", "simple-retry"); FilterChainsManager filterChains = createFilterChains(); List<Filter> filters = filterChains.createConsumerFilters("a"); assertThat(filters.get(0)).isInstanceOf(SimpleRetryFilter.class); }
ZeroConfigClient { public String getSchema(String microserviceId, String schemaId) { LOGGER.info("Retrieve schema content for Microservice ID: {}, Schema ID: {}", microserviceId, schemaId); if (selfMicroservice.getServiceId().equals(microserviceId)) { return selfMicroservice.getSchemaMap().computeIfPresent(schemaId, (k, v) -> v); } else { return null; } } private ZeroConfigClient(ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); @VisibleForTesting ZeroConfigClient initZeroConfigClientWithMocked( ZeroConfigRegistryService zeroConfigRegistryService, MulticastSocket multicastSocket); void init(); boolean register(); boolean unregister(); List<Microservice> getAllMicroservices(); Microservice getMicroservice(String microserviceId); String getSchema(String microserviceId, String schemaId); MicroserviceInstance findMicroserviceInstance(String serviceId, String instanceId); MicroserviceInstances findServiceInstances(String appId, String providerServiceName, String strVersionRule); Microservice getSelfMicroservice(); @VisibleForTesting void setSelfMicroservice( Microservice selfMicroservice); MicroserviceInstance getSelfMicroserviceInstance(); @VisibleForTesting void setSelfMicroserviceInstance( MicroserviceInstance selfMicroserviceInstance); static ZeroConfigClient INSTANCE; }
@Test public void test_getSchema_forSelfMicroservice_shouldNotCallZeroConfigRegistryService_And_Succeed() { String returnedResult = target.getSchema(selfServiceId, schemaId1); Assert.assertEquals(schemaContent1, returnedResult); verifyZeroInteractions(zeroConfigRegistryService); } @Test public void test_getSchema_forOtherMicroservice_shouldReturnNull() { String returnedResult = target.getSchema(otherServiceId, schemaId1); Assert.assertNull(returnedResult); }
SimpleLoadBalanceFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { if (invocation.getEndpoint() != null) { return nextNode.onFilter(invocation); } invocation.setEndpoint(selectEndpoint(invocation)); return nextNode.onFilter(invocation); } SimpleLoadBalanceFilter(); @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); Endpoint selectEndpoint(Invocation invocation); }
@Test public void should_invoke_next_directly_when_invocation_already_has_endpoint() throws ExecutionException, InterruptedException { Response response = Response.ok("ok"); new Expectations() { { invocation.getEndpoint(); result = endpoint; nextNode.onFilter(invocation); result = CompletableFuture.completedFuture(response); } }; Response result = filter.onFilter(invocation, nextNode).get(); assertThat(result).isSameAs(response); new Verifications() { { discoveryContext.setInputParameters(invocation); times = 0; } }; }