method2testcases
stringlengths
118
6.63k
### Question: VcfGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public GeneticVariant getSnpVariantByPos(String seqName, int startPos) { Iterable<GeneticVariant> variants = getVariantsByPos(seqName, startPos); GeneticVariant snp = null; for (GeneticVariant variant : variants) { if (snp == null && variant.isSnp()) { snp = variant; } } return snp; } VcfGenotypeData(File bzipVcfFile, int cacheSize, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, int cacheSize, double minimumPosteriorProbabilityToCall); @Override Iterator<GeneticVariant> iterator(); @Override List<Alleles> getSampleVariants(final GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override Iterable<GeneticVariant> getVariantsByPos(final String seqName, final int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getVariantsByRange(final String seqName, final int rangeStart, final int rangeEnd); MappedGenotypeField getPreferredGenotypeField(); void setPreferredGenotypeField(String preferredGenotypeField); }### Answer: @Test public void testSnpVariants() { GeneticVariant snpGeneticVariant = genotypeData.getSnpVariantByPos("1", 3172273); assertNotNull(snpGeneticVariant); assertEquals(snpGeneticVariant.isSnp(), true); }
### Question: VcfGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public Iterable<GeneticVariant> getVariantsByPos(final String seqName, final int startPos) { return getVariantsByRange(seqName, startPos - 1, startPos); } VcfGenotypeData(File bzipVcfFile, int cacheSize, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, int cacheSize, double minimumPosteriorProbabilityToCall); @Override Iterator<GeneticVariant> iterator(); @Override List<Alleles> getSampleVariants(final GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override Iterable<GeneticVariant> getVariantsByPos(final String seqName, final int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getVariantsByRange(final String seqName, final int rangeStart, final int rangeEnd); MappedGenotypeField getPreferredGenotypeField(); void setPreferredGenotypeField(String preferredGenotypeField); }### Answer: @Test public void testGeneticVariantAnnotations() { List<GeneticVariant> variants = Lists.newArrayList(genotypeData.getVariantsByPos("1", 3171929)); assertNotNull(variants); assertEquals(variants.size(), 1); GeneticVariant variant = variants.get(0); assertNotNull(variant.getAnnotationValues()); assertEquals(variant.getAnnotationValues().size(), 9); Object annotationValue = variant.getAnnotationValues().get("NS"); assertNotNull(annotationValue); assertEquals(annotationValue, Integer.valueOf(1)); annotationValue = variant.getAnnotationValues().get("AF"); assertNotNull(annotationValue); assertTrue(annotationValue instanceof List); @SuppressWarnings("unchecked") List<Float> floats = (List<Float>) annotationValue; assertEquals(floats.size(), 1); assertEquals(floats.get(0).floatValue(), 1.0, 0.001); annotationValue = variant.getAnnotationValues().get("ANNOT"); assertNotNull(annotationValue); assertTrue(annotationValue instanceof List); @SuppressWarnings("unchecked") List<String> strings = (List<String>) annotationValue; assertEquals(strings.size(), 1); assertEquals(strings.get(0), "INT"); assertEquals(variant.getAnnotationValues().get("VCF_Filter"), "flt"); assertNull(variant.getAnnotationValues().get("VCF_Qual")); } @Test public void testStopPos() throws IOException, URISyntaxException { List<GeneticVariant> variants = Lists.newArrayList(genotypeData.getVariantsByPos("1", 565286)); assertNotNull(variants); assertEquals(variants.size(), 1); variants = Lists.newArrayList(genotypeData.getVariantsByPos("3", 7569)); assertNotNull(variants); assertEquals(variants.size(), 1); }
### Question: VcfGenotypeData extends AbstractRandomAccessGenotypeData implements SampleVariantsProvider { @Override public List<Boolean> getSamplePhasing(GeneticVariant variant) { VcfRecord vcfRecord = getVcfRecord(variant); final int nrSamples = vcfRecord.getNrSamples(); if (nrSamples == 0) { return Collections.emptyList(); } List<Boolean> phasing = new ArrayList<>(nrSamples); for (VcfSample vcfSample : vcfRecord.getSamples()) { List<Boolean> genotypePhasings = vcfSample.getPhasings(); if (genotypePhasings == null || genotypePhasings.isEmpty()) { phasing.add(Boolean.FALSE); } else if (genotypePhasings.size() == 1) { phasing.add(genotypePhasings.get(0)); } else if (genotypePhasings.contains(Boolean.FALSE)) { phasing.add(Boolean.FALSE); } else { phasing.add(Boolean.TRUE); } } return phasing; } VcfGenotypeData(File bzipVcfFile, int cacheSize, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, double minimumPosteriorProbabilityToCall); VcfGenotypeData(File bzipVcfFile, File tabixIndexFile, int cacheSize, double minimumPosteriorProbabilityToCall); @Override Iterator<GeneticVariant> iterator(); @Override List<Alleles> getSampleVariants(final GeneticVariant variant); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override List<Sequence> getSequences(); @Override List<Sample> getSamples(); @Override int cacheSize(); @Override List<Boolean> getSamplePhasing(GeneticVariant variant); @Override boolean arePhasedProbabilitiesPresent(GeneticVariant variant); @Override int getSampleVariantProviderUniqueId(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override byte[] getSampleCalledDosage(GeneticVariant variant); @Override float[] getSampleDosage(GeneticVariant variant); @Override void close(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override float[][] getSampleProbilities(GeneticVariant variant); @Override double[][] getSampleProbabilitiesComplex(GeneticVariant variant); @Override double[][][] getSampleProbabilitiesPhased(GeneticVariant variant); @Override FixedSizeIterable<GenotypeRecord> getSampleGenotypeRecords(GeneticVariant variant); @Override List<String> getSeqNames(); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override Iterable<GeneticVariant> getVariantsByPos(final String seqName, final int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getVariantsByRange(final String seqName, final int rangeStart, final int rangeEnd); MappedGenotypeField getPreferredGenotypeField(); void setPreferredGenotypeField(String preferredGenotypeField); }### Answer: @Test public void testGetSamplePhasing() { GeneticVariant variant = genotypeData.getVariantsByPos("1", 565286).iterator().next(); assertEquals(genotypeData.getSamplePhasing(variant), Arrays.asList(false)); }
### Question: VcfGenotypeRecord implements GenotypeRecord { public VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample) { if(vcfMeta == null) throw new IllegalArgumentException("vcfMeta is null"); if(vcfRecord == null) throw new IllegalArgumentException("vcfRecord is null"); if(vcfSample == null) throw new IllegalArgumentException("vcfSample is null"); this.vcfMeta = vcfMeta; this.vcfRecord = vcfRecord.createClone(); this.vcfSample = vcfSample.createClone(); } VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample); @Override Object getGenotypeRecordData(String recordId); @Override Alleles getSampleAlleles(); @Override float[] getSampleProbs(); @Override float getSampleDosage(); @Override boolean containsGenotypeRecord(String recordId); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class) public void VcfGenotypeRecord() { new VcfGenotypeRecord(null, null, null); }
### Question: VcfGenotypeRecord implements GenotypeRecord { @Override public Alleles getSampleAlleles() { List<Allele> alleles = vcfSample.getAlleles(); if(vcfSample.getAlleles() != null){ return Alleles.createAlleles(alleles); } else { return null; } } VcfGenotypeRecord(VcfMeta vcfMeta, VcfRecord vcfRecord, VcfSample vcfSample); @Override Object getGenotypeRecordData(String recordId); @Override Alleles getSampleAlleles(); @Override float[] getSampleProbs(); @Override float getSampleDosage(); @Override boolean containsGenotypeRecord(String recordId); }### Answer: @Test public void getSampleAlleles() { Map<String, String> propertiesGt = new HashMap<String, String>(); propertiesGt.put("ID", "GT"); propertiesGt.put("Number", "1"); propertiesGt.put("Type", "String"); propertiesGt.put("Description", "Genotype"); VcfMetaFormat vcfMetaFormatGt = new VcfMetaFormat(propertiesGt); VcfMeta vcfMeta = new VcfMeta(); vcfMeta.addFormatMeta(vcfMetaFormatGt); String[] recordTokens = new String[]{"x", "x", "x", "G", "A", "x", "x", "x", "GT:DP:EC:CONFS"}; VcfRecord vcfRecord = new VcfRecord(vcfMeta, recordTokens); String[] sampleTokens = new String[]{"1/0", "5", "5", "5.300,5.300,1.000"}; VcfSample vcfSample = new VcfSample(vcfRecord, sampleTokens ); VcfGenotypeRecord vcfGenotypeRecord = new VcfGenotypeRecord(vcfMeta, vcfRecord, vcfSample); List<Allele> alleles = vcfGenotypeRecord.getSampleAlleles().getAlleles(); assertEquals(alleles.get(0).getAlleleAsSnp(), 'A'); assertEquals(alleles.get(1).getAlleleAsSnp(), 'G'); }
### Question: Alleles implements Iterable<Allele>, Comparable<Alleles> { public List<Allele> getAlleles() { return alleles; } private Alleles(List<Allele> alleles); static Alleles createAlleles(List<Allele> alleleList); static Alleles createAlleles(Allele... allele); static Alleles createBasedOnString(List<String> stringAlleles); static Alleles createBasedOnString(String allele1, String allele2); static Alleles createBasedOnChars(char allele1, char allele2); static Alleles createBasedOnChars(char[] charAlleles); List<Allele> getAlleles(); List<String> getAllelesAsString(); int getAlleleCount(); boolean isSnp(); char[] getAllelesAsChars(); @Override String toString(); Alleles getComplement(); boolean sameAlleles(Alleles other); boolean isAtOrGcSnp(); @Override Iterator<Allele> iterator(); Allele get(int alleleIndex); boolean contains(Allele queryAllele); boolean containsAll(Alleles queryAlleles); @Override int compareTo(Alleles other); @Override int hashCode(); @Override boolean equals(Object obj); Alleles createCopyWithoutDuplicates(); static final Alleles BI_ALLELIC_MISSING; }### Answer: @Test public void getAlleles() { Alleles alleles = Alleles.createBasedOnString(Arrays.asList("A", "T")); assertNotNull(alleles.getAlleles()); assertEquals(alleles.getAlleles().size(), 2); assertEquals(alleles.getAlleles().get(0).getAlleleAsString(), "A"); assertEquals(alleles.getAllelesAsString().get(1), "T"); assertEquals(alleles.getAllelesAsChars()[0], 'A'); assertEquals(alleles.getAllelesAsChars()[1], 'T'); Alleles alleles2 = Alleles.createBasedOnChars('A', 'T'); assertEquals(alleles2, alleles); }
### Question: Alleles implements Iterable<Allele>, Comparable<Alleles> { public boolean sameAlleles(Alleles other) { if (this == other) { return true; } if (this.alleles.size() != other.alleles.size()) { return false; } return this.alleles.containsAll(other.alleles) && other.alleles.containsAll(this.alleles); } private Alleles(List<Allele> alleles); static Alleles createAlleles(List<Allele> alleleList); static Alleles createAlleles(Allele... allele); static Alleles createBasedOnString(List<String> stringAlleles); static Alleles createBasedOnString(String allele1, String allele2); static Alleles createBasedOnChars(char allele1, char allele2); static Alleles createBasedOnChars(char[] charAlleles); List<Allele> getAlleles(); List<String> getAllelesAsString(); int getAlleleCount(); boolean isSnp(); char[] getAllelesAsChars(); @Override String toString(); Alleles getComplement(); boolean sameAlleles(Alleles other); boolean isAtOrGcSnp(); @Override Iterator<Allele> iterator(); Allele get(int alleleIndex); boolean contains(Allele queryAllele); boolean containsAll(Alleles queryAlleles); @Override int compareTo(Alleles other); @Override int hashCode(); @Override boolean equals(Object obj); Alleles createCopyWithoutDuplicates(); static final Alleles BI_ALLELIC_MISSING; }### Answer: @Test public void sameAlleles() { Alleles variantAlleles = Alleles.createBasedOnChars('A', 'G'); Alleles variantAlleles2 = Alleles.createBasedOnChars('T', 'G'); Alleles variantAlleles3 = Alleles.createBasedOnChars('G', 'A'); Alleles variantAlleles4 = Alleles.createBasedOnChars(new char[] { 'A', 'G', 'T' }); Alleles variantAlleles5 = Alleles.createBasedOnChars(new char[] { 'A' }); Alleles variantAlleles6 = Alleles.createBasedOnChars('A', 'G'); assertEquals(variantAlleles.sameAlleles(variantAlleles2), false); assertEquals(variantAlleles.sameAlleles(variantAlleles3), true); assertEquals(variantAlleles.sameAlleles(variantAlleles4), false); assertEquals(variantAlleles.sameAlleles(variantAlleles5), false); assertEquals(variantAlleles.sameAlleles(variantAlleles6), true); }
### Question: Alleles implements Iterable<Allele>, Comparable<Alleles> { public boolean isAtOrGcSnp() { return isAtOrGcSnp; } private Alleles(List<Allele> alleles); static Alleles createAlleles(List<Allele> alleleList); static Alleles createAlleles(Allele... allele); static Alleles createBasedOnString(List<String> stringAlleles); static Alleles createBasedOnString(String allele1, String allele2); static Alleles createBasedOnChars(char allele1, char allele2); static Alleles createBasedOnChars(char[] charAlleles); List<Allele> getAlleles(); List<String> getAllelesAsString(); int getAlleleCount(); boolean isSnp(); char[] getAllelesAsChars(); @Override String toString(); Alleles getComplement(); boolean sameAlleles(Alleles other); boolean isAtOrGcSnp(); @Override Iterator<Allele> iterator(); Allele get(int alleleIndex); boolean contains(Allele queryAllele); boolean containsAll(Alleles queryAlleles); @Override int compareTo(Alleles other); @Override int hashCode(); @Override boolean equals(Object obj); Alleles createCopyWithoutDuplicates(); static final Alleles BI_ALLELIC_MISSING; }### Answer: @Test public void isAtOrGcSnp() { Alleles variantAlleles; variantAlleles = Alleles.createBasedOnChars('A', 'G'); assertEquals(variantAlleles.isAtOrGcSnp(), false); variantAlleles = Alleles.createBasedOnString(Arrays.asList("A", "G")); assertEquals(variantAlleles.isAtOrGcSnp(), false); variantAlleles = Alleles.createBasedOnString(Arrays.asList("G", "C")); assertEquals(variantAlleles.isAtOrGcSnp(), true); variantAlleles = Alleles.createBasedOnChars('A', 'T'); assertEquals(variantAlleles.isAtOrGcSnp(), true); variantAlleles = Alleles.createBasedOnString(Arrays.asList("G", "C", "GC")); assertEquals(variantAlleles.isAtOrGcSnp(), false); variantAlleles = Alleles.createBasedOnString(Arrays.asList("G", "C", "G")); assertEquals(variantAlleles.isAtOrGcSnp(), true); variantAlleles = Alleles.createBasedOnString(Arrays.asList("G", "C", "T")); assertEquals(variantAlleles.isAtOrGcSnp(), false); }
### Question: Alleles implements Iterable<Allele>, Comparable<Alleles> { public boolean contains(Allele queryAllele) { return (alleles.contains(queryAllele)); } private Alleles(List<Allele> alleles); static Alleles createAlleles(List<Allele> alleleList); static Alleles createAlleles(Allele... allele); static Alleles createBasedOnString(List<String> stringAlleles); static Alleles createBasedOnString(String allele1, String allele2); static Alleles createBasedOnChars(char allele1, char allele2); static Alleles createBasedOnChars(char[] charAlleles); List<Allele> getAlleles(); List<String> getAllelesAsString(); int getAlleleCount(); boolean isSnp(); char[] getAllelesAsChars(); @Override String toString(); Alleles getComplement(); boolean sameAlleles(Alleles other); boolean isAtOrGcSnp(); @Override Iterator<Allele> iterator(); Allele get(int alleleIndex); boolean contains(Allele queryAllele); boolean containsAll(Alleles queryAlleles); @Override int compareTo(Alleles other); @Override int hashCode(); @Override boolean equals(Object obj); Alleles createCopyWithoutDuplicates(); static final Alleles BI_ALLELIC_MISSING; }### Answer: @Test public void contains() { Alleles alleles = Alleles.createBasedOnString(Arrays.asList("A", "T")); assertEquals(alleles.contains(Allele.A), true); assertEquals(alleles.contains(Allele.T), true); assertEquals(alleles.contains(Allele.C), false); assertEquals(alleles.contains(Allele.create("AA")), false); }
### Question: ModifiableGenotypeDataInMemory extends AbstractRandomAccessGenotypeData implements ModifiableGenotypeData { @Override public Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants() { return ModifiableGeneticVariantIterator.createModifiableGeneticVariantIterable(sourceGenotypeData.iterator(), this, filteredOutVariants); } ModifiableGenotypeDataInMemory(RandomAccessGenotypeData sourceGenotypeData); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override List<Annotation> getVariantAnnotations(); @Override Annotation getVariantAnnotation(String annotationId); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override synchronized GeneticVariantId getUpdatedId(ModifiableGeneticVariant geneticVariant); @Override synchronized Allele getUpdatedRef(ModifiableGeneticVariant geneticVariant); @Override synchronized SampleVariantsProvider getUpdatedSampleVariantProvider(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateVariantId(ModifiableGeneticVariant geneticVariant, GeneticVariantId newGeneticVariantId); @Override synchronized void updateVariantPrimaryId(ModifiableGeneticVariant geneticVariant, String newPrimaryId); @Override synchronized void swapGeneticVariant(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateRefAllele(ModifiableGeneticVariant geneticVariant, Allele newRefAllele); @Override synchronized Alleles getUpdatedAlleles(ModifiableGeneticVariant geneticVariant); @Override Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName); @Override Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos); @Override ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos); @Override Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants(); @Override void excludeVariant(ModifiableGeneticVariant geneticVariant); @Override int getExcludedVariantCount(); @Override List<SampleAnnotation> getSampleAnnotations(); @Override Annotation getSampleAnnotation(String annotationId); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override boolean isSwapped(GeneticVariant geneticVariant); }### Answer: @Test public void getModifiableGeneticVariants() { Iterator<GeneticVariant> originalGeneticVariants = originalGenotypeData.iterator(); Iterator<ModifiableGeneticVariant> modifiableGeneticVariants = modifiableGenotypeData .getModifiableGeneticVariants().iterator(); assertEqualsVariantIterators(originalGeneticVariants, modifiableGeneticVariants); }
### Question: ModifiableGenotypeDataInMemory extends AbstractRandomAccessGenotypeData implements ModifiableGenotypeData { @Override public Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName) { Iterator<GeneticVariant> originalIterator = sourceGenotypeData.getSequenceGeneticVariants(seqName).iterator(); return ModifiableGeneticVariantIterator.createModifiableGeneticVariantIterable(originalIterator, this, filteredOutVariants); } ModifiableGenotypeDataInMemory(RandomAccessGenotypeData sourceGenotypeData); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override List<Annotation> getVariantAnnotations(); @Override Annotation getVariantAnnotation(String annotationId); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override synchronized GeneticVariantId getUpdatedId(ModifiableGeneticVariant geneticVariant); @Override synchronized Allele getUpdatedRef(ModifiableGeneticVariant geneticVariant); @Override synchronized SampleVariantsProvider getUpdatedSampleVariantProvider(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateVariantId(ModifiableGeneticVariant geneticVariant, GeneticVariantId newGeneticVariantId); @Override synchronized void updateVariantPrimaryId(ModifiableGeneticVariant geneticVariant, String newPrimaryId); @Override synchronized void swapGeneticVariant(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateRefAllele(ModifiableGeneticVariant geneticVariant, Allele newRefAllele); @Override synchronized Alleles getUpdatedAlleles(ModifiableGeneticVariant geneticVariant); @Override Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName); @Override Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos); @Override ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos); @Override Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants(); @Override void excludeVariant(ModifiableGeneticVariant geneticVariant); @Override int getExcludedVariantCount(); @Override List<SampleAnnotation> getSampleAnnotations(); @Override Annotation getSampleAnnotation(String annotationId); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override boolean isSwapped(GeneticVariant geneticVariant); }### Answer: @Test public void getModifiableSequenceGeneticVariants() { Iterator<GeneticVariant> originalGeneticVariants = originalGenotypeData.getSequenceGeneticVariants("22") .iterator(); Iterator<ModifiableGeneticVariant> modifiableGeneticVariants = modifiableGenotypeData .getModifiableSequenceGeneticVariants("22").iterator(); assertEqualsVariantIterators(originalGeneticVariants, modifiableGeneticVariants); }
### Question: ModifiableGenotypeDataInMemory extends AbstractRandomAccessGenotypeData implements ModifiableGenotypeData { @Override public ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos) { GeneticVariant originalVariant = sourceGenotypeData.getSnpVariantByPos(seqName, startPos); if (originalVariant == null) { return null; } ModifiableGeneticVariant modifiableVariant = new ModifiableGeneticVariant(originalVariant, this); if (filteredOutVariants.contains(modifiableVariant)) { return null; } else { return modifiableVariant; } } ModifiableGenotypeDataInMemory(RandomAccessGenotypeData sourceGenotypeData); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override List<Annotation> getVariantAnnotations(); @Override Annotation getVariantAnnotation(String annotationId); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override synchronized GeneticVariantId getUpdatedId(ModifiableGeneticVariant geneticVariant); @Override synchronized Allele getUpdatedRef(ModifiableGeneticVariant geneticVariant); @Override synchronized SampleVariantsProvider getUpdatedSampleVariantProvider(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateVariantId(ModifiableGeneticVariant geneticVariant, GeneticVariantId newGeneticVariantId); @Override synchronized void updateVariantPrimaryId(ModifiableGeneticVariant geneticVariant, String newPrimaryId); @Override synchronized void swapGeneticVariant(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateRefAllele(ModifiableGeneticVariant geneticVariant, Allele newRefAllele); @Override synchronized Alleles getUpdatedAlleles(ModifiableGeneticVariant geneticVariant); @Override Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName); @Override Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos); @Override ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos); @Override Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants(); @Override void excludeVariant(ModifiableGeneticVariant geneticVariant); @Override int getExcludedVariantCount(); @Override List<SampleAnnotation> getSampleAnnotations(); @Override Annotation getSampleAnnotation(String annotationId); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override boolean isSwapped(GeneticVariant geneticVariant); }### Answer: @Test public void getModifiableSnpVariantByPos() { GeneticVariant originalVariant = originalGenotypeData.getSnpVariantByPos("22", 14433624); ModifiableGeneticVariant modifiableGeneticVariant = modifiableGenotypeData.getModifiableSnpVariantByPos("22", 14433624); assertEquals(modifiableGeneticVariant.getSequenceName(), originalVariant.getSequenceName()); assertEquals(modifiableGeneticVariant.getStartPos(), originalVariant.getStartPos()); originalVariant = modifiableGenotypeData.getModifiableSnpVariantByPos("22", 1); assertNull(originalVariant); }
### Question: ModifiableGenotypeDataInMemory extends AbstractRandomAccessGenotypeData implements ModifiableGenotypeData { @Override public Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos) { Iterator<GeneticVariant> originalIterator = sourceGenotypeData.getVariantsByPos(seqName, startPos).iterator(); return ModifiableGeneticVariantIterator.createModifiableGeneticVariantIterable(originalIterator, this, filteredOutVariants); } ModifiableGenotypeDataInMemory(RandomAccessGenotypeData sourceGenotypeData); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override List<Annotation> getVariantAnnotations(); @Override Annotation getVariantAnnotation(String annotationId); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override synchronized GeneticVariantId getUpdatedId(ModifiableGeneticVariant geneticVariant); @Override synchronized Allele getUpdatedRef(ModifiableGeneticVariant geneticVariant); @Override synchronized SampleVariantsProvider getUpdatedSampleVariantProvider(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateVariantId(ModifiableGeneticVariant geneticVariant, GeneticVariantId newGeneticVariantId); @Override synchronized void updateVariantPrimaryId(ModifiableGeneticVariant geneticVariant, String newPrimaryId); @Override synchronized void swapGeneticVariant(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateRefAllele(ModifiableGeneticVariant geneticVariant, Allele newRefAllele); @Override synchronized Alleles getUpdatedAlleles(ModifiableGeneticVariant geneticVariant); @Override Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName); @Override Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos); @Override ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos); @Override Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants(); @Override void excludeVariant(ModifiableGeneticVariant geneticVariant); @Override int getExcludedVariantCount(); @Override List<SampleAnnotation> getSampleAnnotations(); @Override Annotation getSampleAnnotation(String annotationId); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override boolean isSwapped(GeneticVariant geneticVariant); }### Answer: @Test public void getModifiableVariantsByPos() { Iterator<GeneticVariant> originalGeneticVariants = originalGenotypeData.getVariantsByPos("22", 14433624) .iterator(); Iterator<ModifiableGeneticVariant> modifiableGeneticVariants = modifiableGenotypeData .getModifiableVariantsByPos("22", 14433624).iterator(); assertEqualsVariantIterators(originalGeneticVariants, modifiableGeneticVariants); }
### Question: ModifiableGenotypeDataInMemory extends AbstractRandomAccessGenotypeData implements ModifiableGenotypeData { @Override public List<Sample> getSamples() { return sourceGenotypeData.getSamples(); } ModifiableGenotypeDataInMemory(RandomAccessGenotypeData sourceGenotypeData); @Override List<String> getSeqNames(); @Override Iterable<Sequence> getSequences(); @Override Sequence getSequenceByName(String name); @Override Iterable<GeneticVariant> getVariantsByPos(String seqName, int startPos); @Override GeneticVariant getSnpVariantByPos(String seqName, int startPos); @Override Iterable<GeneticVariant> getSequenceGeneticVariants(String seqName); @Override List<Annotation> getVariantAnnotations(); @Override Annotation getVariantAnnotation(String annotationId); @Override List<Sample> getSamples(); @Override Iterator<GeneticVariant> iterator(); @Override synchronized GeneticVariantId getUpdatedId(ModifiableGeneticVariant geneticVariant); @Override synchronized Allele getUpdatedRef(ModifiableGeneticVariant geneticVariant); @Override synchronized SampleVariantsProvider getUpdatedSampleVariantProvider(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateVariantId(ModifiableGeneticVariant geneticVariant, GeneticVariantId newGeneticVariantId); @Override synchronized void updateVariantPrimaryId(ModifiableGeneticVariant geneticVariant, String newPrimaryId); @Override synchronized void swapGeneticVariant(ModifiableGeneticVariant geneticVariant); @Override synchronized void updateRefAllele(ModifiableGeneticVariant geneticVariant, Allele newRefAllele); @Override synchronized Alleles getUpdatedAlleles(ModifiableGeneticVariant geneticVariant); @Override Iterable<ModifiableGeneticVariant> getModifiableSequenceGeneticVariants(String seqName); @Override Iterable<ModifiableGeneticVariant> getModifiableVariantsByPos(String seqName, int startPos); @Override ModifiableGeneticVariant getModifiableSnpVariantByPos(String seqName, int startPos); @Override Iterable<ModifiableGeneticVariant> getModifiableGeneticVariants(); @Override void excludeVariant(ModifiableGeneticVariant geneticVariant); @Override int getExcludedVariantCount(); @Override List<SampleAnnotation> getSampleAnnotations(); @Override Annotation getSampleAnnotation(String annotationId); @Override Iterable<GeneticVariant> getVariantsByRange(String seqName, int rangeStart, int rangeEnd); @Override void close(); @Override Map<String, Annotation> getVariantAnnotationsMap(); @Override Map<String, SampleAnnotation> getSampleAnnotationsMap(); @Override boolean isOnlyContaingSaveProbabilityGenotypes(); @Override boolean isSwapped(GeneticVariant geneticVariant); }### Answer: @Test public void getSamples() { assertEquals(modifiableGenotypeData.getSamples(), originalGenotypeData.getSamples()); }
### Question: CertificateManager { public boolean hasNoCertificates() { return (certs == null || certs.length == 0); } CertificateManager(KeyStoreLoader loader); void setPasswordRequestListener(KeyStoreEntryPasswordRequestListener passwordRequestListener); void setKeyStoreRequestListener(KeyStoreRequestListener keyStoreRequestListener); Certificate[] getCerts(); boolean hasNoCertificates(); byte[] sign(Certificate cert, byte[] challenge); Signature extractSignature(Certificate cert); boolean verify(Certificate cert, byte[] original, byte[] signed); void load(); }### Answer: @Test public void testHasNoCertificates() { boolean hasNoCertificates = manager.hasNoCertificates(); assertFalse(hasNoCertificates); }
### Question: CertificateManager { public Certificate[] getCerts() { return certs; } CertificateManager(KeyStoreLoader loader); void setPasswordRequestListener(KeyStoreEntryPasswordRequestListener passwordRequestListener); void setKeyStoreRequestListener(KeyStoreRequestListener keyStoreRequestListener); Certificate[] getCerts(); boolean hasNoCertificates(); byte[] sign(Certificate cert, byte[] challenge); Signature extractSignature(Certificate cert); boolean verify(Certificate cert, byte[] original, byte[] signed); void load(); }### Answer: @Test public void testGetCerts_HasExpectedNumberOfCerts() { Certificate[] certs = manager.getCerts(); int numCerts = certs.length; assertThat(numCerts, equalTo(1)); }
### Question: CertificateManager { public byte[] sign(Certificate cert, byte[] challenge) throws SignatureImpossibleException { byte[] signedChallenge; try { PrivateKey pk = getPrivateKey(cert); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(pk); signature.update(challenge); signedChallenge = signature.sign(); } catch(Exception e) { throw new SignatureImpossibleException(e.getMessage()); } return signedChallenge; } CertificateManager(KeyStoreLoader loader); void setPasswordRequestListener(KeyStoreEntryPasswordRequestListener passwordRequestListener); void setKeyStoreRequestListener(KeyStoreRequestListener keyStoreRequestListener); Certificate[] getCerts(); boolean hasNoCertificates(); byte[] sign(Certificate cert, byte[] challenge); Signature extractSignature(Certificate cert); boolean verify(Certificate cert, byte[] original, byte[] signed); void load(); }### Answer: @Test public void testSign() throws Exception { Certificate cert = manager.getCerts()[0]; byte[] challenge = "Sign this!".getBytes(); byte[] signed = manager.sign(cert, challenge); Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(cert); verifier.update(challenge); assertTrue(verifier.verify(signed)); }
### Question: CertificateManagerProvider { public static synchronized CertificateManager provideCertificateManager() { if (manager != null) return manager; manager = new CertificateManagerProvider().createCertificateManager(); return manager; } private CertificateManagerProvider(); static synchronized CertificateManager provideCertificateManager(); static synchronized void dispose(); }### Answer: @Test public void testProvideCertificateManager_SameInstance() { CertificateManager mgr2 = CertificateManagerProvider.provideCertificateManager(); assertThat(manager, equalTo(mgr2)); }
### Question: RecommendTask { public void recommend(String taskName) { new MahoutRecommender().buildRecommend(taskName); } void recommend(String taskName); }### Answer: @Test public void recommend(){ new RecommendTask().recommend("mmsnsarticle"); }
### Question: MapreduceTask { public void startMapreduce(String taskName) { log.info("开始mapreduce程序"); AbstractMapReduce mapReduce = new BasicMapReduce(); mapReduce.startMapReduce(taskName); } void startMapreduce(String taskName); }### Answer: @Test public void startMapreduce(){ new MapreduceTask().startMapreduce("mmsnsarticle"); }
### Question: MahoutRecommender implements Recommender { @Override public long[] recommend(String taskName, int userID) { return recommend(taskName, null, null, null, userID); } @Override long[] recommend(String taskName, int userID); @Override long[] recommend(final String taskName, final Float threshold, final int userID); @Override long[] recommend(String taskName, String similarity, String neighborhood, Float threshold, int userID); void buildRecommend(String taskName); void evaluate(String taskName); void IRState(String taskName); }### Answer: @Test public void recommend() { long[] mmsnsarticles = recommender.recommend("mmsnsarticle", 10); System.out.println(StringUtils.join(mmsnsarticles, ',')); }
### Question: MahoutRecommender implements Recommender { public void evaluate(String taskName) { String itemmodelsPath = RecommendConfig.class.getResource("/").getPath() + "itemmodels.csv"; HadoopUtil.download(taskName, itemmodelsPath, false); RandomUtils.useTestSeed(); try { DataModel fileDataModel = new FileDataModel(new File(itemmodelsPath)); RecommenderEvaluator recommenderEvaluator = new RMSRecommenderEvaluator(); double evaluate = recommenderEvaluator.evaluate(new RecommenderBuilder() { @Override public org.apache.mahout.cf.taste.recommender.Recommender buildRecommender(final DataModel dataModel) throws TasteException { UserSimilarity userSimilarity = new PearsonCorrelationSimilarity(dataModel); UserNeighborhood userNeighborhood = new NearestNUserNeighborhood(2, userSimilarity, dataModel); return new GenericUserBasedRecommender(dataModel, userNeighborhood, userSimilarity); } }, new DataModelBuilder() { @Override public DataModel buildDataModel(final FastByIDMap<PreferenceArray> fastByIDMap) { for (Map.Entry<Long, PreferenceArray> entry : fastByIDMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } return new GenericDataModel(fastByIDMap); } }, fileDataModel, 0.6, 1.0); System.out.println("评估结果:" + evaluate); } catch (TasteException | IOException e) { e.printStackTrace(); } } @Override long[] recommend(String taskName, int userID); @Override long[] recommend(final String taskName, final Float threshold, final int userID); @Override long[] recommend(String taskName, String similarity, String neighborhood, Float threshold, int userID); void buildRecommend(String taskName); void evaluate(String taskName); void IRState(String taskName); }### Answer: @Test public void evaluate() { recommender.evaluate("mmsnsarticle"); }
### Question: MahoutRecommender implements Recommender { public void IRState(String taskName) { String itemmodelsPath = RecommendConfig.class.getResource("/").getPath() + "itemmodels.csv"; HadoopUtil.download(taskName, itemmodelsPath, false); try { DataModel fileDataModel = new FileDataModel(new File(itemmodelsPath)); RecommenderIRStatsEvaluator irStatsEvaluator = new GenericRecommenderIRStatsEvaluator(); IRStatistics irStatistics = irStatsEvaluator.evaluate(new RecommenderBuilder() { @Override public org.apache.mahout.cf.taste.recommender.Recommender buildRecommender(final DataModel dataModel) throws TasteException { UserSimilarity userSimilarity = new PearsonCorrelationSimilarity(dataModel); UserNeighborhood userNeighborhood = new NearestNUserNeighborhood(5, userSimilarity, dataModel); return new GenericUserBasedRecommender(dataModel, userNeighborhood, userSimilarity); } }, new DataModelBuilder() { @Override public DataModel buildDataModel(final FastByIDMap<PreferenceArray> fastByIDMap) { return new GenericDataModel(fastByIDMap); } }, fileDataModel, null, 5, GenericRecommenderIRStatsEvaluator.CHOOSE_THRESHOLD, 1.0); System.out.println("查准率:" + irStatistics.getPrecision()); System.out.println("查全率:" + irStatistics.getRecall()); } catch (TasteException | IOException e) { e.printStackTrace(); } } @Override long[] recommend(String taskName, int userID); @Override long[] recommend(final String taskName, final Float threshold, final int userID); @Override long[] recommend(String taskName, String similarity, String neighborhood, Float threshold, int userID); void buildRecommend(String taskName); void evaluate(String taskName); void IRState(String taskName); }### Answer: @Test public void IRState() { recommender.IRState("mmsnsarticle"); }
### Question: DesignatorToAccountIdentifierMapper { public Optional<String> map(final @Nonnull String accountDesignator) { final Set<String> accountAssignmentGroups = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentGroups(); if (accountAssignmentGroups.contains(accountDesignator)) return Optional.empty(); return mapToAccountAssignment(accountDesignator) .map(AccountAssignment::getAccountIdentifier); } DesignatorToAccountIdentifierMapper(final @Nonnull DataContextOfAction dataContextOfAction); DesignatorToAccountIdentifierMapper( final @Nonnull Set<ProductAccountAssignmentEntity> productAccountAssignments, final @Nonnull Set<CaseAccountAssignmentEntity> caseAccountAssignments, final @Nonnull List<AccountAssignment> oneTimeAccountAssignments); Optional<String> map(final @Nonnull String accountDesignator); String mapOrThrow(final @Nonnull String accountDesignator); Stream<GroupNeedingLedger> getGroupsNeedingLedgers(); Stream<AccountAssignment> getLedgersNeedingAccounts(); }### Answer: @Test public void map() { Assert.assertEquals(Optional.empty(), testSubject.map(AccountDesignators.CUSTOMER_LOAN_GROUP)); Assert.assertEquals(testCase.expectedMapCustomerLoanPrincipalResult, testSubject.map(AccountDesignators.CUSTOMER_LOAN_PRINCIPAL)); Assert.assertEquals(Optional.empty(), testSubject.map("this-account-designator-doesnt-exist")); }
### Question: DesignatorToAccountIdentifierMapper { Optional<AccountAssignment> mapToCaseAccountAssignment(final @Nonnull String accountDesignator) { return caseAccountAssignments.stream().map(CaseMapper::mapAccountAssignmentEntity) .filter(x -> x.getDesignator().equals(accountDesignator)) .findFirst(); } DesignatorToAccountIdentifierMapper(final @Nonnull DataContextOfAction dataContextOfAction); DesignatorToAccountIdentifierMapper( final @Nonnull Set<ProductAccountAssignmentEntity> productAccountAssignments, final @Nonnull Set<CaseAccountAssignmentEntity> caseAccountAssignments, final @Nonnull List<AccountAssignment> oneTimeAccountAssignments); Optional<String> map(final @Nonnull String accountDesignator); String mapOrThrow(final @Nonnull String accountDesignator); Stream<GroupNeedingLedger> getGroupsNeedingLedgers(); Stream<AccountAssignment> getLedgersNeedingAccounts(); }### Answer: @Test public void mapToCaseAccountAssignment() { final Optional<AccountAssignment> ret = testSubject.mapToCaseAccountAssignment(AccountDesignators.CUSTOMER_LOAN_GROUP); Assert.assertEquals(testCase.expectedCaseAccountAssignmentMappingForCustomerLoanGroup, ret); }
### Question: DesignatorToAccountIdentifierMapper { public Stream<AccountAssignment> getLedgersNeedingAccounts() { final Set<String> accountAssignmentGroups = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentGroups(); final Set<RequiredAccountAssignment> accountAssignmentsRequired = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentsRequired(); final Map<String, RequiredAccountAssignment> accountAssignmentsRequiredMap = accountAssignmentsRequired.stream().collect(Collectors.toMap(RequiredAccountAssignment::getAccountDesignator, x -> x)); final Map<String, String> accountAssignmentAlternativeAccountIdsMap = oneTimeAccountAssignments.stream() .filter(x -> x.getAlternativeAccountNumber() != null) .collect(Collectors.toMap(AccountAssignment::getDesignator, AccountAssignment::getAlternativeAccountNumber)); final Map<String, String> existingAccountsAssignmentsMap = oneTimeAccountAssignments.stream() .filter(x -> x.getAccountIdentifier() != null) .collect(Collectors.toMap(AccountAssignment::getDesignator, AccountAssignment::getAccountIdentifier)); final Map<String, Optional<String>> groupToLedgerMapping = accountAssignmentGroups.stream() .collect(Collectors.toMap( Function.identity(), group -> mapToCaseAccountAssignment(group).map(AccountAssignment::getAccountIdentifier))); final Stream<AccountAssignment> ledgerAccountAssignments = productAccountAssignmentsAsStream() .filter(x -> !x.getDesignator().equals(AccountDesignators.ENTRY)) .filter(x -> (x.getAccountIdentifier() == null) && (x.getLedgerIdentifier() != null)); return ledgerAccountAssignments .map(ledgerAccountAssignment -> { final AccountAssignment ret = new AccountAssignment(ledgerAccountAssignment); ret.setAlternativeAccountNumber(accountAssignmentAlternativeAccountIdsMap.get(ledgerAccountAssignment.getDesignator())); final String existingAccountSetting = existingAccountsAssignmentsMap.get(ledgerAccountAssignment.getDesignator()); if (existingAccountSetting != null) ret.setAccountIdentifier(existingAccountSetting); final Optional<String> accountAssignmentGroup = Optional.ofNullable(accountAssignmentsRequiredMap.get(ledgerAccountAssignment.getDesignator())).map(RequiredAccountAssignment::getGroup); final Optional<String> changedLedger = accountAssignmentGroup.flatMap(groupToLedgerMapping::get); changedLedger.ifPresent(ret::setLedgerIdentifier); return ret; }); } DesignatorToAccountIdentifierMapper(final @Nonnull DataContextOfAction dataContextOfAction); DesignatorToAccountIdentifierMapper( final @Nonnull Set<ProductAccountAssignmentEntity> productAccountAssignments, final @Nonnull Set<CaseAccountAssignmentEntity> caseAccountAssignments, final @Nonnull List<AccountAssignment> oneTimeAccountAssignments); Optional<String> map(final @Nonnull String accountDesignator); String mapOrThrow(final @Nonnull String accountDesignator); Stream<GroupNeedingLedger> getGroupsNeedingLedgers(); Stream<AccountAssignment> getLedgersNeedingAccounts(); }### Answer: @Test public void getLedgersNeedingAccounts() { final Set<AccountAssignment> ret = testSubject.getLedgersNeedingAccounts().collect(Collectors.toSet()); Assert.assertEquals(testCase.expectedLedgersNeedingAccounts, ret); }
### Question: DesignatorToAccountIdentifierMapper { public Stream<GroupNeedingLedger> getGroupsNeedingLedgers() { final Set<String> accountAssignmentGroups = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentGroups(); final Set<RequiredAccountAssignment> accountAssignmentsRequired = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentsRequired(); return accountAssignmentGroups.stream() .filter(groupName -> !mapToProductAccountAssignment(groupName).isPresent()) .map(groupName -> { final Stream<RequiredAccountAssignment> requiredAccountAssignmentsInThisGroup = accountAssignmentsRequired.stream().filter(x -> groupName.equals(x.getGroup())); final List<String> ledgersAssignedToThem = requiredAccountAssignmentsInThisGroup .map(requiredAccountAssignment -> mapToProductAccountAssignment(requiredAccountAssignment.getAccountDesignator())) .map(optionalAccountAssignment -> optionalAccountAssignment.map(AccountAssignment::getLedgerIdentifier)) .distinct() .filter(Optional::isPresent) .map(Optional::get) .limit(2) .collect(Collectors.toList()); if (ledgersAssignedToThem.size() == 1) { return new GroupNeedingLedger(groupName, ledgersAssignedToThem.get(0)); } else return null; }) .filter(Objects::nonNull); } DesignatorToAccountIdentifierMapper(final @Nonnull DataContextOfAction dataContextOfAction); DesignatorToAccountIdentifierMapper( final @Nonnull Set<ProductAccountAssignmentEntity> productAccountAssignments, final @Nonnull Set<CaseAccountAssignmentEntity> caseAccountAssignments, final @Nonnull List<AccountAssignment> oneTimeAccountAssignments); Optional<String> map(final @Nonnull String accountDesignator); String mapOrThrow(final @Nonnull String accountDesignator); Stream<GroupNeedingLedger> getGroupsNeedingLedgers(); Stream<AccountAssignment> getLedgersNeedingAccounts(); }### Answer: @Test public void getGroupsNeedingLedgers() { Set<DesignatorToAccountIdentifierMapper.GroupNeedingLedger> ret = testSubject.getGroupsNeedingLedgers().collect(Collectors.toSet()); ret.toString(); Assert.assertEquals(testCase.expectedGroupsNeedingLedgers, ret); }
### Question: ScheduledChargesService { Optional<ChargeRange> findChargeRange(final String productIdentifier, final ChargeDefinition chargeDefinition) { if ((chargeDefinition.getForSegmentSet() == null) || (chargeDefinition.getFromSegment() == null) || (chargeDefinition.getToSegment() == null)) return Optional.empty(); final List<BalanceSegmentEntity> segmentSet = balanceSegmentRepository.findByProductIdentifierAndSegmentSetIdentifier(productIdentifier, chargeDefinition.getForSegmentSet()) .sorted(Comparator.comparing(BalanceSegmentEntity::getLowerBound)) .collect(Collectors.toList()); final Map<String, Segment> segments = Stream.iterate(0, i -> i + 1).limit(segmentSet.size()) .map(i -> new Segment( segmentSet.get(i).getSegmentIdentifier(), segmentSet.get(i).getLowerBound(), Optional.ofNullable(i + 1 < segmentSet.size() ? segmentSet.get(i + 1).getLowerBound() : null) )) .collect(Collectors.toMap(x -> x.identifier, x -> x)); final Optional<Segment> fromSegment = Optional.ofNullable(segments.get(chargeDefinition.getFromSegment())); final Optional<Segment> toSegment = Optional.ofNullable(segments.get(chargeDefinition.getToSegment())); if (!fromSegment.isPresent() || !toSegment.isPresent()) return Optional.empty(); return Optional.of(new ChargeRange(fromSegment.get().getLowerBound(), toSegment.get().getUpperBound())); } @Autowired ScheduledChargesService( final ChargeDefinitionService chargeDefinitionService, final BalanceSegmentRepository balanceSegmentRepository); List<ScheduledCharge> getScheduledCharges( final String productIdentifier, final @Nonnull List<ScheduledAction> scheduledActions); }### Answer: @Test public void findChargeRange() throws Exception { final ChargeDefinitionService chargeDefinitionServiceMock = Mockito.mock(ChargeDefinitionService.class); final BalanceSegmentRepository balanceSegmentRepositoryMock = Mockito.mock(BalanceSegmentRepository.class); Mockito.doReturn(testCase.balanceSegmentEntities.stream()) .when(balanceSegmentRepositoryMock) .findByProductIdentifierAndSegmentSetIdentifier(PRODUCT_IDENTIFIER, SEGMENT_SET_IDENTIFIER); final ScheduledChargesService testSubject = new ScheduledChargesService(chargeDefinitionServiceMock, balanceSegmentRepositoryMock); final ChargeDefinition chargeDefinition = new ChargeDefinition(); chargeDefinition.setForSegmentSet(SEGMENT_SET_IDENTIFIER); chargeDefinition.setFromSegment(testCase.fromSegment); chargeDefinition.setToSegment(testCase.toSegment); final Optional<ChargeRange> result = testSubject.findChargeRange(PRODUCT_IDENTIFIER, chargeDefinition); Assert.assertEquals(testCase.expectedResult, result); }
### Question: ScheduledAction { boolean actionIsOnOrAfter(final LocalDate date) { return when.compareTo(date) >= 0; } ScheduledAction( @Nonnull final Action action, @Nonnull final LocalDate when, @Nonnull final Period actionPeriod, @Nonnull final Period repaymentPeriod); ScheduledAction( @Nonnull final Action action, @Nonnull final LocalDate when, @Nonnull final Period actionPeriod); ScheduledAction( @Nonnull final Action action, @Nonnull final LocalDate when); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable Period getActionPeriod(); Action getAction(); @Nullable Period getRepaymentPeriod(); LocalDate getWhen(); }### Answer: @Test public void actionIsOnOrBefore() { final LocalDate today = LocalDate.now(); final LocalDate tomorrow = today.plusDays(1); final LocalDate yesterday = today.minusDays(1); final ScheduledAction testSubject = new ScheduledAction(Action.APPLY_INTEREST, today); Assert.assertTrue(testSubject.actionIsOnOrAfter(today)); Assert.assertFalse(testSubject.actionIsOnOrAfter(tomorrow)); Assert.assertTrue(testSubject.actionIsOnOrAfter(yesterday)); }
### Question: ChargeRange { public boolean amountIsWithinRange(final BigDecimal amountProportionalTo) { return to.map(bigDecimal -> from.compareTo(amountProportionalTo) <= 0 && bigDecimal.compareTo(amountProportionalTo) > 0) .orElseGet(() -> from.compareTo(amountProportionalTo) <= 0); } ChargeRange( final BigDecimal from, @SuppressWarnings("OptionalUsedAsFieldOrParameterType") final Optional<BigDecimal> to); boolean amountIsWithinRange(final BigDecimal amountProportionalTo); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void amountIsWithinRange() throws Exception { final ChargeRange testSubject1 = new ChargeRange(BigDecimal.TEN, Optional.empty()); Assert.assertFalse(testSubject1.amountIsWithinRange(BigDecimal.ZERO)); Assert.assertFalse(testSubject1.amountIsWithinRange(BigDecimal.ONE)); Assert.assertTrue(testSubject1.amountIsWithinRange(BigDecimal.TEN)); Assert.assertTrue(testSubject1.amountIsWithinRange(BigDecimal.TEN.add(BigDecimal.ONE))); final ChargeRange testSubject2 = new ChargeRange(BigDecimal.ZERO, Optional.of(BigDecimal.TEN)); Assert.assertTrue(testSubject2.amountIsWithinRange(BigDecimal.ZERO)); Assert.assertTrue(testSubject2.amountIsWithinRange(BigDecimal.ONE)); Assert.assertFalse(testSubject2.amountIsWithinRange(BigDecimal.TEN)); Assert.assertFalse(testSubject2.amountIsWithinRange(BigDecimal.TEN.add(BigDecimal.ONE))); }
### Question: ScheduledActionHelpers { public static ScheduledAction getNextScheduledPayment(final @Nonnull LocalDate startOfTerm, final @Nonnull LocalDate fromDate, final @Nonnull LocalDate endOfTerm, final @Nonnull CaseParameters caseParameters) { final LocalDate effectiveEndOfTerm = fromDate.isAfter(endOfTerm) ? fromDate : endOfTerm; return getHypotheticalScheduledActionsForDisbursedLoan(startOfTerm, effectiveEndOfTerm, caseParameters) .filter(x -> x.getAction().equals(Action.ACCEPT_PAYMENT)) .filter(x -> x.actionIsOnOrAfter(fromDate)) .findFirst() .orElseGet(() -> new ScheduledAction(Action.ACCEPT_PAYMENT, fromDate)); } static boolean actionHasNoActionPeriod(final Action action); static List<ScheduledAction> getHypotheticalScheduledActions(final @Nonnull LocalDate startOfTerm, final @Nonnull CaseParameters caseParameters); static ScheduledAction getNextScheduledPayment(final @Nonnull LocalDate startOfTerm, final @Nonnull LocalDate fromDate, final @Nonnull LocalDate endOfTerm, final @Nonnull CaseParameters caseParameters); static LocalDate getRoughEndDate(final @Nonnull LocalDate startOfTerm, final @Nonnull CaseParameters caseParameters); static Stream<Period> generateRepaymentPeriods( final LocalDate startOfTerm, final LocalDate endOfTerm, final CaseParameters caseParameters); static Optional<Duration> getAccrualPeriodDurationForAction(final Action action); }### Answer: @Test public void getNextScheduledPayment() throws Exception { final LocalDate roughEndDate = ScheduledActionHelpers.getRoughEndDate(testCase.initialDisbursementDate, testCase.caseParameters); testCase.expectedResultContents.stream() .filter(x -> x.getAction() == Action.ACCEPT_PAYMENT) .forEach(expectedResultContents -> { final ScheduledAction nextScheduledPayment = ScheduledActionHelpers.getNextScheduledPayment( testCase.initialDisbursementDate, expectedResultContents.getWhen().minusDays(1), roughEndDate, testCase.caseParameters); Assert.assertEquals(expectedResultContents, nextScheduledPayment); }); final ScheduledAction afterAction = ScheduledActionHelpers.getNextScheduledPayment( testCase.initialDisbursementDate, roughEndDate.plusDays(1), roughEndDate, testCase.caseParameters); Assert.assertNotNull(afterAction.getActionPeriod()); Assert.assertTrue(afterAction.getActionPeriod().isLastPeriod()); }
### Question: ScheduledChargeComparator implements Comparator<ScheduledCharge> { @Override public int compare(ScheduledCharge o1, ScheduledCharge o2) { return compareScheduledCharges(o1, o2); } @Override int compare(ScheduledCharge o1, ScheduledCharge o2); }### Answer: @Test public void compare() { Assert.assertEquals(testCase.expected == 0, ScheduledChargeComparator.compareScheduledCharges(testCase.a, testCase.b) == 0); Assert.assertEquals(testCase.expected > 0, ScheduledChargeComparator.compareScheduledCharges(testCase.a, testCase.b) > 0); Assert.assertEquals(testCase.expected < 0, ScheduledChargeComparator.compareScheduledCharges(testCase.a, testCase.b) < 0); }
### Question: AccountingAdapter { public Optional<String> bookCharges( final Map<String, BigDecimal> balanceAdjustments, final DesignatorToAccountIdentifierMapper designatorToAccountIdentifierMapper, final String note, final String transactionDate, final String message, final String transactionType) { final JournalEntry journalEntry = getJournalEntry( balanceAdjustments, designatorToAccountIdentifierMapper, note, transactionDate, message, transactionType, UserContextHolder.checkedGetUser()); if (journalEntry.getCreditors().isEmpty() && journalEntry.getDebtors().isEmpty()) return Optional.empty(); while (true) { try { final String transactionUniqueifier = RandomStringUtils.random(26, true, true); journalEntry.setTransactionIdentifier(formulateTransactionIdentifier(message, transactionUniqueifier)); ledgerManager.createJournalEntry(journalEntry); return Optional.of(transactionUniqueifier); } catch (final JournalEntryAlreadyExistsException ignore) { } } } @Autowired AccountingAdapter(@SuppressWarnings("SpringJavaAutowiringInspection") final LedgerManager ledgerManager, final AccountingListener accountingListener, @Qualifier(ServiceConstants.LOGGER_NAME) final Logger logger); Optional<String> bookCharges( final Map<String, BigDecimal> balanceAdjustments, final DesignatorToAccountIdentifierMapper designatorToAccountIdentifierMapper, final String note, final String transactionDate, final String message, final String transactionType); Optional<LocalDateTime> getDateOfOldestEntryContainingMessage(final String accountIdentifier, final String message); BigDecimal sumMatchingEntriesSinceDate(final String accountIdentifier, final LocalDate startDate, final String message); Account getAccount(final String accountIdentifier); String createLedger( final String customerIdentifier, final String groupName, final String parentLedger); String createProductAccountForLedgerAssignment( final String productIdentifier, final String accountDesignator, final String ledgerIdentifier); String createOrFindCaseAccountForLedgerAssignment( final String customerIdentifier, final AccountAssignment ledgerAssignment, final BigDecimal currentBalance); static Set<String> accountAssignmentsRequiredButNotProvided( final Set<AccountAssignment> accountAssignments, final Stream<ChargeDefinition> chargeDefinitionEntities); static Set<String> getRequiredAccountDesignators(final Stream<ChargeDefinition> chargeDefinitionEntities); Set<String> accountAssignmentsMappedToNonexistentAccounts(final Set<AccountAssignment> accountAssignments); boolean accountAssignmentRepresentsRealAccount(final AccountAssignment accountAssignment); }### Answer: @Test public void journalEntryCreationFailsBecauseIdentifierAlreadyExistsShouldCauseRetry() { final LedgerManager ledgerManagerMock = Mockito.mock(LedgerManager.class); final AccountingAdapter testSubject = new AccountingAdapter(ledgerManagerMock, null, null); final Map<String, BigDecimal> balanceAdjustments = new HashMap<>(); balanceAdjustments.put("a", BigDecimal.ONE); balanceAdjustments.put("b", BigDecimal.ONE.negate()); final DesignatorToAccountIdentifierMapper designatorToAccountIdentifierMapper = Mockito.mock(DesignatorToAccountIdentifierMapper.class); Mockito.doReturn("a1").when(designatorToAccountIdentifierMapper).mapOrThrow("a"); Mockito.doReturn("b1").when(designatorToAccountIdentifierMapper).mapOrThrow("b"); Mockito.doThrow(JournalEntryAlreadyExistsException.class) .doThrow(JournalEntryAlreadyExistsException.class) .doNothing() .when(ledgerManagerMock).createJournalEntry(Matchers.anyObject()); UserContextHolder.setAccessToken("blah", "blah"); testSubject.bookCharges( balanceAdjustments, designatorToAccountIdentifierMapper, "", "", "x", ""); Mockito.verify(ledgerManagerMock, Mockito.atLeast(3)).createJournalEntry(Matchers.anyObject()); }
### Question: Period implements Comparable<Period> { public Duration getDuration() { long days = beginDate.until(endDate, ChronoUnit.DAYS); return ChronoUnit.DAYS.getDuration().multipliedBy(days); } Period(final LocalDate beginDate, final LocalDate endDateExclusive); Period(final LocalDate beginDate, final LocalDate endDateExclusive, final boolean lastPeriod); Period(final LocalDate beginDate, final int periodLength); Period(final int periodLength, final LocalDate endDate); LocalDate getBeginDate(); LocalDate getEndDate(); boolean isLastPeriod(); Duration getDuration(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(@Nonnull Period o); @Override String toString(); }### Answer: @Test public void getDuration() throws Exception { final Period testSubjectByDates = new Period(today, dayAfterTommorrow); Assert.assertEquals(2, testSubjectByDates.getDuration().toDays()); final Period testSubjectByDuration = new Period(today, 5); Assert.assertEquals(5, testSubjectByDuration.getDuration().toDays()); }
### Question: Period implements Comparable<Period> { boolean containsDate(final LocalDate date) { return this.getBeginDate().compareTo(date) <= 0 && this.getEndDate().compareTo(date) > 0; } Period(final LocalDate beginDate, final LocalDate endDateExclusive); Period(final LocalDate beginDate, final LocalDate endDateExclusive, final boolean lastPeriod); Period(final LocalDate beginDate, final int periodLength); Period(final int periodLength, final LocalDate endDate); LocalDate getBeginDate(); LocalDate getEndDate(); boolean isLastPeriod(); Duration getDuration(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(@Nonnull Period o); @Override String toString(); }### Answer: @Test public void containsDate() throws Exception { final Period testSubject = new Period(today, 1); Assert.assertTrue(testSubject.containsDate(today)); Assert.assertFalse(testSubject.containsDate(tommorrow)); Assert.assertFalse(testSubject.containsDate(yesterday)); Assert.assertFalse(testSubject.containsDate(dayAfterTommorrow)); }
### Question: Period implements Comparable<Period> { @Override public int compareTo(@Nonnull Period o) { int comparison = compareNullableDates(endDate, o.endDate); if (comparison != 0) return comparison; comparison = compareNullableDates(beginDate, o.beginDate); if (comparison != 0) return comparison; if (lastPeriod == o.lastPeriod) return 0; else if (lastPeriod) return -1; else return 1; } Period(final LocalDate beginDate, final LocalDate endDateExclusive); Period(final LocalDate beginDate, final LocalDate endDateExclusive, final boolean lastPeriod); Period(final LocalDate beginDate, final int periodLength); Period(final int periodLength, final LocalDate endDate); LocalDate getBeginDate(); LocalDate getEndDate(); boolean isLastPeriod(); Duration getDuration(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(@Nonnull Period o); @Override String toString(); }### Answer: @Test public void compareTo() throws Exception { final Period yesterdayPeriod = new Period(yesterday, today); final Period todayPeriod = new Period(today, tommorrow); final Period tommorrowPeriod = new Period(tommorrow, dayAfterTommorrow); Assert.assertTrue(yesterdayPeriod.compareTo(todayPeriod) < 0); Assert.assertTrue(todayPeriod.compareTo(todayPeriod) == 0); Assert.assertTrue(tommorrowPeriod.compareTo(todayPeriod) > 0); }
### Question: RateCollectors { public static Collector<BigDecimal, ?, BigDecimal> geometricMean(int significantDigits) { return Collector.of( () -> new GeometricMean(significantDigits), GeometricMean::accumulate, GeometricMean::combine, GeometricMean::finish); } private RateCollectors(); static Collector<BigDecimal, ?, BigDecimal> compound(int significantDigits); static Collector<BigDecimal, ?, BigDecimal> geometricMean(int significantDigits); }### Answer: @Test public void geometricMean() throws Exception { Assert.assertEquals(testCase.expectedGeometricMean, testCase.values.stream().collect(RateCollectors.geometricMean(testCase.significantDigits))); } @Test public void geometricMeanViaParalletStream() { Assert.assertEquals(testCase.expectedGeometricMean, testCase.values.parallelStream().collect(RateCollectors.geometricMean(testCase.significantDigits))); }
### Question: RateCollectors { public static Collector<BigDecimal, ?, BigDecimal> compound(int significantDigits) { return Collector.of( () -> new Compound(significantDigits), Compound::accumulate, Compound::combine, Compound::finish); } private RateCollectors(); static Collector<BigDecimal, ?, BigDecimal> compound(int significantDigits); static Collector<BigDecimal, ?, BigDecimal> geometricMean(int significantDigits); }### Answer: @Test public void compound() { Assert.assertEquals(testCase.expectedCompound, testCase.values.stream().collect(RateCollectors.compound(testCase.significantDigits))); } @Test public void compoundViaParalletStream() { Assert.assertEquals(testCase.expectedCompound, testCase.values.parallelStream().collect(RateCollectors.compound(testCase.significantDigits))); }
### Question: WriteOffPaymentBuilderService implements PaymentBuilderService { @Override public PaymentBuilder getPaymentBuilder( final @Nonnull DataContextOfAction dataContextOfAction, final @Nullable BigDecimal ignored, final LocalDate forDate, final RunningBalances runningBalances) { final CaseParametersEntity caseParameters = dataContextOfAction.getCaseParametersEntity(); final int minorCurrencyUnitDigits = dataContextOfAction.getProductEntity().getMinorCurrencyUnitDigits(); final Stream<ScheduledCharge> scheduledChargesForAccruals = chargeDefinitionService.getChargeDefinitionsMappedByAccrueAction(dataContextOfAction.getProductEntity().getIdentifier()) .values().stream().flatMap(Collection::stream) .map(x -> getReverseAccrualScheduledCharge(x, forDate)); final List<ScheduledCharge> scheduledChargesForAccrualsAndWriteOff = Stream.concat(scheduledChargesForAccruals, Stream.of(getScheduledChargeForWriteOff(forDate))) .collect(Collectors.toList()); final BigDecimal loanPaymentSize = dataContextOfAction.getCaseParametersEntity().getPaymentSize(); return CostComponentService.getCostComponentsForScheduledCharges( scheduledChargesForAccrualsAndWriteOff, caseParameters.getBalanceRangeMaximum(), runningBalances, loanPaymentSize, BigDecimal.ZERO, BigDecimal.ZERO, dataContextOfAction.getInterest(), minorCurrencyUnitDigits, true); } @Autowired WriteOffPaymentBuilderService( final ChargeDefinitionService chargeDefinitionService); @Override PaymentBuilder getPaymentBuilder( final @Nonnull DataContextOfAction dataContextOfAction, final @Nullable BigDecimal ignored, final LocalDate forDate, final RunningBalances runningBalances); }### Answer: @Test public void getPaymentBuilder() throws Exception { final PaymentBuilder paymentBuilder = PaymentBuilderServiceTestHarness.constructCallToPaymentBuilder( (scheduledChargesService) -> new WriteOffPaymentBuilderService(DefaultChargeDefinitionsMocker.getChargeDefinitionService(Collections.emptyList())), testCase); final Payment payment = paymentBuilder.buildPayment(Action.WRITE_OFF, Collections.emptySet(), testCase.forDate.toLocalDate()); Assert.assertNotNull(payment); final Map<String, CostComponent> mappedCostComponents = payment.getCostComponents().stream() .collect(Collectors.toMap(CostComponent::getChargeIdentifier, x -> x)); Assert.assertEquals( testCase.remainingPrincipal, mappedCostComponents.get(ChargeIdentifiers.WRITE_OFF_ID).getAmount()); }
### Question: TaskDefinitionService { public List<TaskDefinition> findAllEntities(final String productIdentifier) { return taskDefinitionRepository.findByProductId(productIdentifier) .map(TaskDefinitionMapper::map) .collect(Collectors.toList()); } @Autowired TaskDefinitionService( final TaskDefinitionRepository taskDefinitionRepository); List<TaskDefinition> findAllEntities(final String productIdentifier); Optional<TaskDefinition> findByIdentifier(final String productIdentifier, final String identifier); }### Answer: @Test public void findAllEntities() { findAllEntitiesHelper(false); findAllEntitiesHelper(true); }
### Question: ApplyInterestPaymentBuilderService implements PaymentBuilderService { @Override public PaymentBuilder getPaymentBuilder( final DataContextOfAction dataContextOfAction, final BigDecimal ignored, final LocalDate forDate, final RunningBalances runningBalances) { final CaseParametersEntity caseParameters = dataContextOfAction.getCaseParametersEntity(); final String productIdentifier = dataContextOfAction.getProductEntity().getIdentifier(); final int minorCurrencyUnitDigits = dataContextOfAction.getProductEntity().getMinorCurrencyUnitDigits(); final ScheduledAction interestAction = new ScheduledAction(Action.APPLY_INTEREST, forDate, new Period(1, forDate)); final List<ScheduledCharge> scheduledCharges = scheduledChargesService.getScheduledCharges( productIdentifier, Collections.singletonList(interestAction)); return CostComponentService.getCostComponentsForScheduledCharges( scheduledCharges, caseParameters.getBalanceRangeMaximum(), runningBalances, dataContextOfAction.getCaseParametersEntity().getPaymentSize(), BigDecimal.ZERO, BigDecimal.ZERO, dataContextOfAction.getInterest(), minorCurrencyUnitDigits, true); } @Autowired ApplyInterestPaymentBuilderService(final ScheduledChargesService scheduledChargesService); @Override PaymentBuilder getPaymentBuilder( final DataContextOfAction dataContextOfAction, final BigDecimal ignored, final LocalDate forDate, final RunningBalances runningBalances); }### Answer: @Test public void getPaymentBuilder() throws Exception { final PaymentBuilderServiceTestCase testCase = new PaymentBuilderServiceTestCase("simple case"); final PaymentBuilder paymentBuilder = PaymentBuilderServiceTestHarness.constructCallToPaymentBuilder( ApplyInterestPaymentBuilderService::new, testCase); final Payment payment = paymentBuilder.buildPayment(Action.APPLY_INTEREST, Collections.emptySet(), testCase.forDate.toLocalDate()); Assert.assertNotNull(payment); Assert.assertEquals(BigDecimal.valueOf(27, 2), paymentBuilder.getBalanceAdjustments().get(AccountDesignators.INTEREST_ACCRUAL)); }
### Question: PeriodChargeCalculator { static Map<Period, BigDecimal> getPeriodAccrualInterestRate( final BigDecimal interest, final List<ScheduledCharge> scheduledCharges, final int precision) { return scheduledCharges.stream() .filter(PeriodChargeCalculator::accruedInterestCharge) .collect(Collectors.groupingBy(scheduledCharge -> scheduledCharge.getScheduledAction().getRepaymentPeriod(), Collectors.mapping(x -> chargeAmountPerPeriod(x, interest, precision), Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))); } }### Answer: @Test public void getPeriodAccrualRatesTest() { final Map<Period, BigDecimal> periodRates = PeriodChargeCalculator.getPeriodAccrualInterestRate(testCase.interest, testCase.scheduledCharges, testCase.precision); Assert.assertEquals(testCase.expectedPeriodRates, periodRates); }
### Question: PaymentBuilder { static Set<String> expandAccountDesignators(final Set<String> accountDesignators) { final Set<RequiredAccountAssignment> accountAssignmentsRequired = IndividualLendingPatternFactory.individualLendingPattern().getAccountAssignmentsRequired(); final Map<String, List<RequiredAccountAssignment>> accountAssignmentsByGroup = accountAssignmentsRequired.stream() .filter(x -> x.getGroup() != null) .collect(Collectors.groupingBy(RequiredAccountAssignment::getGroup, Collectors.toList())); final Set<String> groupExpansions = accountDesignators.stream() .flatMap(accountDesignator -> { final List<RequiredAccountAssignment> group = accountAssignmentsByGroup.get(accountDesignator); if (group != null) return group.stream(); else return Stream.empty(); }) .map(RequiredAccountAssignment::getAccountDesignator) .collect(Collectors.toSet()); final Set<String> ret = new HashSet<>(accountDesignators); ret.addAll(groupExpansions); return ret; } PaymentBuilder(final RunningBalances prePaymentBalances, final boolean accrualAccounting); Payment buildPayment( final Action action, final Set<String> forAccountDesignators, final @Nullable LocalDate forDate); PlannedPayment accumulatePlannedPayment( final SimulatedRunningBalances balances, final @Nullable LocalDate forDate); Map<String, BigDecimal> getBalanceAdjustments(); BigDecimal getBalanceAdjustment(final String... accountDesignators); }### Answer: @Test public void expandAccountDesignators() { final Set<String> ret = PaymentBuilder.expandAccountDesignators(new HashSet<>(Arrays.asList(AccountDesignators.CUSTOMER_LOAN_GROUP, AccountDesignators.ENTRY))); final Set<String> expected = new HashSet<>(Arrays.asList( AccountDesignators.ENTRY, AccountDesignators.CUSTOMER_LOAN_GROUP, AccountDesignators.CUSTOMER_LOAN_PRINCIPAL, AccountDesignators.CUSTOMER_LOAN_FEES, AccountDesignators.CUSTOMER_LOAN_INTEREST)); Assert.assertEquals(expected, ret); }
### Question: CostComponentService { private static BigDecimal getAmountProportionalTo( final ScheduledCharge scheduledCharge, final BigDecimal maximumBalance, final RunningBalances runningBalances, final BigDecimal contractualRepayment, final BigDecimal requestedDisbursement, final BigDecimal requestedRepayment, final PaymentBuilder paymentBuilder) { final Optional<ChargeProportionalDesignator> optionalChargeProportionalTo = ChargeProportionalDesignator.fromString(scheduledCharge.getChargeDefinition().getProportionalTo()); return optionalChargeProportionalTo.map(chargeProportionalTo -> getAmountProportionalTo( scheduledCharge, chargeProportionalTo, maximumBalance, runningBalances, contractualRepayment, requestedDisbursement, requestedRepayment, paymentBuilder)) .orElse(BigDecimal.ZERO); } static PaymentBuilder getCostComponentsForScheduledCharges( final Collection<ScheduledCharge> scheduledCharges, final BigDecimal maximumBalance, final RunningBalances preChargeBalances, final BigDecimal contractualRepayment, final BigDecimal requestedDisbursement, final BigDecimal requestedRepayment, final BigDecimal percentPoints, final int minorCurrencyUnitDigits, final boolean accrualAccounting); static BigDecimal getLoanPaymentSize( final BigDecimal maximumBalanceSize, final BigDecimal disbursementSize, final BigDecimal interest, final int minorCurrencyUnitDigits, final List<ScheduledCharge> scheduledCharges); static LocalDate today(); }### Answer: @Test public void getAmountProportionalTo() { final SimulatedRunningBalances runningBalances = new SimulatedRunningBalances(); runningBalances.adjustBalance(AccountDesignators.CUSTOMER_LOAN_PRINCIPAL, testCase.runningBalance.negate()); final BigDecimal amount = CostComponentService.getAmountProportionalTo( null, testCase.chargeProportionalDesignator, testCase.maximumBalance, runningBalances, testCase.loanPaymentSize, testCase.loanPaymentSize, testCase.loanPaymentSize, new PaymentBuilder(runningBalances, false)); Assert.assertEquals(testCase.toString(), testCase.expectedAmount, amount); }
### Question: TaskDefinitionService { public Optional<TaskDefinition> findByIdentifier(final String productIdentifier, final String identifier) { return taskDefinitionRepository .findByProductIdAndTaskIdentifier(productIdentifier, identifier) .map(TaskDefinitionMapper::map); } @Autowired TaskDefinitionService( final TaskDefinitionRepository taskDefinitionRepository); List<TaskDefinition> findAllEntities(final String productIdentifier); Optional<TaskDefinition> findByIdentifier(final String productIdentifier, final String identifier); }### Answer: @Test public void findByIdentifier() { findByIdentifierTestHelper(true, true); findByIdentifierTestHelper(false, false); }
### Question: PatternService { public List<Pattern> findAllEntities() { return patternFactoryRegistry.getAllPatternFactories().stream() .map(PatternFactory::pattern).collect(Collectors.toList()); } @Autowired PatternService(final PatternFactoryRegistry patternFactoryRegistry); List<Pattern> findAllEntities(); Optional<Pattern> findByIdentifier(final String identifier); }### Answer: @Test public void findAllEntities() throws Exception { final PatternFactoryRegistry registryMock = Mockito.mock(PatternFactoryRegistry.class); final PatternFactory patternFactoryMock = Mockito.mock(PatternFactory.class); final Pattern patternMock = Mockito.mock(Pattern.class); Mockito.doReturn(Optional.of(patternFactoryMock)).when(registryMock).getPatternFactoryForPackage("org.apache.fineract.cn.individuallending.api.v1"); Mockito.doReturn(Collections.singleton(patternFactoryMock)).when(registryMock).getAllPatternFactories(); Mockito.doReturn(patternMock).when(patternFactoryMock).pattern(); Mockito.doReturn("org.apache.fineract.cn.individuallending.api.v1").when(patternMock).getParameterPackage(); final PatternService testSubject = new PatternService(registryMock); final List<Pattern> all = testSubject.findAllEntities(); Assert.assertTrue(all.stream().anyMatch(pattern -> pattern.getParameterPackage().equals("org.apache.fineract.cn.individuallending.api.v1"))); final Optional<Pattern> pattern = testSubject.findByIdentifier("org.apache.fineract.cn.individuallending.api.v1"); Assert.assertTrue(pattern.isPresent()); }
### Question: ChargeDefinitionCommandHandler { @SuppressWarnings("unused") @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_CHARGE_DEFINITION) public ChargeDefinitionEvent process(final CreateChargeDefinitionCommand command) { final ChargeDefinition chargeDefinition = command.getInstance(); final String productIdentifier = command.getProductIdentifier(); final ProductEntity productEntity = productRepository.findByIdentifier(productIdentifier) .orElseThrow(() -> ServiceException.badRequest("The given product identifier does not refer to a product {0}", productIdentifier)); final SegmentRange segmentRange = getSegmentRange(chargeDefinition, productIdentifier); final ChargeDefinitionEntity chargeDefinitionEntity = ChargeDefinitionMapper.map(productEntity, chargeDefinition, segmentRange.fromSegment, segmentRange.toSegment); chargeDefinitionRepository.save(chargeDefinitionEntity); return new ChargeDefinitionEvent( command.getProductIdentifier(), command.getInstance().getIdentifier()); } @Autowired ChargeDefinitionCommandHandler( final ProductRepository productRepository, final ChargeDefinitionRepository chargeDefinitionRepository, final BalanceSegmentRepository balanceSegmentRepository); @SuppressWarnings("unused") @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.POST_CHARGE_DEFINITION) ChargeDefinitionEvent process(final CreateChargeDefinitionCommand command); @SuppressWarnings("unused") @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.PUT_CHARGE_DEFINITION) ChargeDefinitionEvent process(final ChangeChargeDefinitionCommand command); @SuppressWarnings("unused") @Transactional @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.SELECTOR_NAME, selectorValue = EventConstants.DELETE_PRODUCT_CHARGE_DEFINITION) ChargeDefinitionEvent process(final DeleteProductChargeDefinitionCommand command); }### Answer: @Test public void processDeleteHandlesCaseOfMissingChargeCorrectly() throws Exception { final String productIdentifier = "bibbledybobbeldy"; final String chargeDefinitionIdentifier = "booboo"; final ChargeDefinitionRepository chargeDefinitionRepositoryMock = Mockito.mock(ChargeDefinitionRepository.class); Mockito.doReturn(Optional.empty()) .when(chargeDefinitionRepositoryMock) .findByProductIdAndChargeDefinitionIdentifier(productIdentifier, chargeDefinitionIdentifier); final BalanceSegmentRepository balanceSegmentRepository = Mockito.mock(BalanceSegmentRepository.class); final ChargeDefinitionCommandHandler testSubject = new ChargeDefinitionCommandHandler(null, chargeDefinitionRepositoryMock, balanceSegmentRepository); try { testSubject.process(new DeleteProductChargeDefinitionCommand(productIdentifier, chargeDefinitionIdentifier)); Assert.assertTrue(false); } catch (final ServiceException e) { Assert.assertTrue(e.getMessage().contains(productIdentifier)); Assert.assertTrue(e.getMessage().contains(chargeDefinitionIdentifier)); } }
### Question: ContactPointUtils { public static void process(final Cluster.Builder clusterBuilder, final String contactPoints) { final String[] splitContactPoints = contactPoints.split(","); for (final String contactPoint : splitContactPoints) { if (contactPoint.contains(":")) { final String[] address = contactPoint.split(":"); clusterBuilder.addContactPointsWithPorts( new InetSocketAddress(address[0].trim(), Integer.valueOf(address[1].trim()))); } else { try { clusterBuilder.addContactPoints(InetAddress.getByName(contactPoint.trim())); } catch (final UnknownHostException uhex) { throw new IllegalArgumentException("Host not found!", uhex); } } } } private ContactPointUtils(); static void process(final Cluster.Builder clusterBuilder, final String contactPoints); }### Answer: @Test public void shouldAddSimpleContactPoints() { final String contactPoints = "127.0.0.1,127.0.0.2,127.0.0.3"; final Cluster.Builder clusterBuilder = Cluster.builder(); ContactPointUtils.process(clusterBuilder, contactPoints); final List<InetSocketAddress> addedClusterPoints = clusterBuilder.getContactPoints(); Assert.assertTrue(addedClusterPoints.size() == 3); for (final InetSocketAddress address : addedClusterPoints) { Assert.assertTrue(contactPoints.contains(address.getAddress().getHostAddress())); } } @Test public void shouldAddComplexContactPoints() { final String contactPoints = "127.0.0.1:1234,127.0.0.2:2345,127.0.0.3:3456"; final Cluster.Builder clusterBuilder = Cluster.builder(); ContactPointUtils.process(clusterBuilder, contactPoints); final List<InetSocketAddress> addedClusterPoints = clusterBuilder.getContactPoints(); Assert.assertTrue(addedClusterPoints.size() == 3); final InetSocketAddress firstAddress = addedClusterPoints.get(0); Assert.assertEquals("127.0.0.1", firstAddress.getAddress().getHostAddress()); Assert.assertEquals(1234, firstAddress.getPort()); final InetSocketAddress secondAddress = addedClusterPoints.get(1); Assert.assertEquals("127.0.0.2", secondAddress.getAddress().getHostAddress()); Assert.assertEquals(2345, secondAddress.getPort()); final InetSocketAddress thirdAddress = addedClusterPoints.get(2); Assert.assertEquals("127.0.0.3", thirdAddress.getAddress().getHostAddress()); Assert.assertEquals(3456, thirdAddress.getPort()); }
### Question: IdentityServiceInitializer { List<PermittableEndpoint> getPermittables(final @Nonnull String applicationUri) { try { final Anubis anubis = this.applicationCallContextProvider.getApplication(Anubis.class, applicationUri); return anubis.getPermittableEndpoints(); } catch (final RuntimeException unexpected) { logger.error("Request for permittable endpoints to '{}' failed.", applicationUri, unexpected); return Collections.emptyList(); } } @Autowired IdentityServiceInitializer( final IdentityListener identityListener, final ApplicationCallContextProvider applicationCallContextProvider, final HashGenerator hashGenerator, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final SystemProperties systemProperties); IdentityServiceInitializationResult initializeIsis( final @Nonnull String tenantIdentifier, final @Nonnull String applicationName, final @Nonnull String identityManagerUri); List<EventExpectation> postApplicationPermittableGroups( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationUri); void postApplicationDetails( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationName, final @Nonnull String applicationUri, final @Nonnull ApplicationSignatureSet applicationSignatureSet); }### Answer: @Test public void getPermittablesAnubisCallFails() throws Exception { final IdentityListener identityListenerMock = Mockito.mock(IdentityListener.class); final ApplicationCallContextProvider applicationCallContextProviderMock = Mockito.mock(ApplicationCallContextProvider.class); final Logger loggerMock = Mockito.mock(Logger.class); final Anubis anubisMock = Mockito.mock(Anubis.class); when(applicationCallContextProviderMock.getApplication(Anubis.class, "blah")).thenReturn(anubisMock); when(anubisMock.getPermittableEndpoints()).thenThrow(IllegalStateException.class); final SystemProperties systemProperties = new SystemProperties(); final List<PermittableEndpoint> ret = new IdentityServiceInitializer(identityListenerMock, applicationCallContextProviderMock, null, loggerMock, systemProperties) .getPermittables("blah"); Assert.assertEquals(ret, Collections.emptyList()); verify(loggerMock).error(anyString(), anyString(), isA(IllegalStateException.class)); }
### Question: IdentityServiceInitializer { static Stream<PermittableGroup> getPermittableGroups(final @Nonnull List<PermittableEndpoint> permittables) { final Map<String, Set<PermittableEndpoint>> groupedPermittables = new HashMap<>(); permittables.forEach(x -> groupedPermittables.computeIfAbsent(x.getGroupId(), y -> new LinkedHashSet<>()).add(x)); return groupedPermittables.entrySet().stream() .map(entry -> new PermittableGroup(entry.getKey(), new ArrayList<PermittableEndpoint>(entry.getValue()))); } @Autowired IdentityServiceInitializer( final IdentityListener identityListener, final ApplicationCallContextProvider applicationCallContextProvider, final HashGenerator hashGenerator, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final SystemProperties systemProperties); IdentityServiceInitializationResult initializeIsis( final @Nonnull String tenantIdentifier, final @Nonnull String applicationName, final @Nonnull String identityManagerUri); List<EventExpectation> postApplicationPermittableGroups( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationUri); void postApplicationDetails( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationName, final @Nonnull String applicationUri, final @Nonnull ApplicationSignatureSet applicationSignatureSet); }### Answer: @Test public void getPermittableGroups() throws Exception { final List<PermittableEndpoint> permittableEndpoints = Arrays.asList(abcPost1, abcGet1, defGet1, abcPost2, abcGet2, defGet2, defGet3); final List<PermittableGroup> ret = IdentityServiceInitializer.getPermittableGroups(permittableEndpoints).collect(Collectors.toList()); Assert.assertEquals(ret, Arrays.asList(group1, group2, group3)); } @Test public void getPermittableGroupsOnEmptyList() throws Exception { final List<PermittableGroup> ret = IdentityServiceInitializer.getPermittableGroups(Collections.emptyList()).collect(Collectors.toList()); Assert.assertEquals(ret, Collections.emptyList()); }
### Question: PahoRxMqttCallback implements RxMqttCallback, MqttCallbackExtended { public static PahoRxMqttCallback create( Consumer<Throwable> onConnectionLost, BiConsumer<Boolean, String> onConnectComplete) { return create( onConnectionLost, onConnectComplete, token -> { }); } @Override void messageArrived(String topic, MqttMessage message); @Override void deliveryComplete(IMqttDeliveryToken token); static PahoRxMqttCallback create( Consumer<Throwable> onConnectionLost, BiConsumer<Boolean, String> onConnectComplete); static PahoRxMqttCallback create( Consumer<Throwable> onConnectionLost, BiConsumer<Boolean, String> onConnectComplete, Consumer<RxMqttToken> onDeliveryComplete); }### Answer: @Test public void whenConnectionLostOccurs() { PahoRxMqttCallback rxMqttCallback = spy(PahoRxMqttCallback.create(cause -> {}, (recon, uri) -> {}, t -> {})); PahoRxMqttException exception = new PahoRxMqttException( new MqttException(MqttException.REASON_CODE_CONNECTION_LOST)); ArgumentCaptor<Throwable> onConnectionLostCauseArgumentCaptor = ArgumentCaptor.forClass(Throwable.class); rxMqttCallback.connectionLost(exception); verify(rxMqttCallback).connectionLost(onConnectionLostCauseArgumentCaptor.capture()); assertThat(onConnectionLostCauseArgumentCaptor.getValue()).isNotNull(); assertThat(onConnectionLostCauseArgumentCaptor.getValue()).isInstanceOf(PahoRxMqttException.class); assertThat(onConnectionLostCauseArgumentCaptor.getValue()).hasCauseInstanceOf(MqttException.class); assertThat(onConnectionLostCauseArgumentCaptor.getValue()).isEqualTo(exception); } @Test public void whenConnectCompleteOccurs() { PahoRxMqttCallback rxMqttCallback = spy(PahoRxMqttCallback.create(cause -> {}, (r, u) -> {}, t -> {})); boolean reconnect = true; String brokerUri = "tcp: ArgumentCaptor<Boolean> onConnectCompleteReconnectArgumentCaptor = ArgumentCaptor.forClass(Boolean.class); ArgumentCaptor<String> onConnectCompleteServerUriArgumentCaptor = ArgumentCaptor.forClass(String.class); rxMqttCallback.connectComplete(reconnect, brokerUri); verify(rxMqttCallback).connectComplete( onConnectCompleteReconnectArgumentCaptor.capture(), onConnectCompleteServerUriArgumentCaptor.capture()); assertThat(onConnectCompleteReconnectArgumentCaptor.getValue()).isNotNull(); assertThat(onConnectCompleteReconnectArgumentCaptor.getValue()).isEqualTo(reconnect); assertThat(onConnectCompleteServerUriArgumentCaptor.getValue()).isNotNull(); assertThat(onConnectCompleteServerUriArgumentCaptor.getValue()).isEqualTo(brokerUri); }
### Question: PahoRxMqttClient implements RxMqttClient { public static Builder builder(String brokerUri) { return builder(brokerUri, MqttAsyncClient.generateClientId()); } private PahoRxMqttClient(final Builder builder); @Override Single<String> getClientId(); @Override Single<String> getServerUri(); @Override Single<Boolean> isConnected(); @Override Completable close(); @Override Single<RxMqttToken> connect(); @Override Single<RxMqttToken> disconnect(); @Override Completable disconnectForcibly(); @Override Single<RxMqttToken> publish(String topic, RxMqttMessage message); @Override Flowable<RxMqttMessage> on(String topic); @Override Flowable<RxMqttMessage> on(String topic, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on(String[] topics); @Override Flowable<RxMqttMessage> on(String[] topics, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on(String topic, RxMqttQoS qos); @Override Flowable<RxMqttMessage> on(String topic, RxMqttQoS qos, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on(String[] topics, RxMqttQoS[] qos); @Override Flowable<RxMqttMessage> on(String[] topics, RxMqttQoS[] qos, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on(String topic, BackpressureStrategy strategy); @Override Flowable<RxMqttMessage> on(String topic, BackpressureStrategy strategy, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on(String topic, RxMqttQoS qos, BackpressureStrategy strategy); @Override Flowable<RxMqttMessage> on(String topic, RxMqttQoS qos, BackpressureStrategy strategy, Consumer<RxMqttToken> doOnComplete); @Override Flowable<RxMqttMessage> on( String[] topics, RxMqttQoS[] rxMqttQos, BackpressureStrategy strategy); @Override Flowable<RxMqttMessage> on(String[] topics, RxMqttQoS[] qos, BackpressureStrategy strategy, Consumer<RxMqttToken> doOnComplete); @Override Single<RxMqttToken> off(String... topics); static Builder builder(String brokerUri); static Builder builder(String brokerUri, String clientId); static Builder builder( String brokerUri, String clientId, MqttClientPersistence persistence); static Builder builder(IMqttAsyncClient client); }### Answer: @Test(expected = NullPointerException.class) public void whenNullClientIsPassedThenThrowsAnError() { PahoRxMqttClient.builder((IMqttAsyncClient) null).build(); } @Test(expected = NullPointerException.class) public void whenNullBrokerUriIsPassedThenThrowsAnError() { PahoRxMqttClient.builder((String) null).build(); } @Test(expected = IllegalArgumentException.class) public void whenNullBrokerUriAndClientIdIsPassedThenThrowsAnError() { PahoRxMqttClient.builder(null, null).build(); } @Test(expected = IllegalArgumentException.class) public void whenNullBrokerUriAndClientIdAndMqttClientPersistenceIsPassedThenThrowsAnError() { PahoRxMqttClient.builder(null, null, null).build(); }
### Question: PahoRxMqttMessage implements RxMqttMessage { public static PahoRxMqttMessage create() { return create(new byte[0]); } PahoRxMqttMessage(byte[] payload); PahoRxMqttMessage(byte[] payload, RxMqttQoS qos); PahoRxMqttMessage(byte[] payload, RxMqttQoS qos, boolean retained); PahoRxMqttMessage(MqttMessage mqttMessage); @Override String getTopic(); @Override int getId(); @Override byte[] getPayload(); @Override RxMqttQoS getQoS(); @Override boolean isRetained(); @Override String toString(); static PahoRxMqttMessage create(); static PahoRxMqttMessage create(MqttMessage message); static PahoRxMqttMessage create(String payload); static PahoRxMqttMessage create(String payload, RxMqttQoS qos); static PahoRxMqttMessage create(String payload, RxMqttQoS qos, boolean retained); static PahoRxMqttMessage create(String payload, Charset charset); static PahoRxMqttMessage create(String payload, Charset charset, RxMqttQoS qos); static PahoRxMqttMessage create( String payload, Charset charset, RxMqttQoS qos, boolean retained); static PahoRxMqttMessage create(byte[] payload); static PahoRxMqttMessage create(byte[] payload, RxMqttQoS qos); static PahoRxMqttMessage create(byte[] payload, RxMqttQoS qos, boolean retained); }### Answer: @Test(expected = NullPointerException.class) public void whenANullMessageIsSuppliedThenAnExceptionIsThrown() { PahoRxMqttMessage.create((MqttMessage) null); } @Test(expected = NullPointerException.class) public void whenANullStringMessageIsSuppliedThenAnExceptionIsThrown() { PahoRxMqttMessage.create((String) null); } @Test(expected = NullPointerException.class) public void whenANullByteArrayMessageIsSuppliedThenAnExceptionIsThrown() { PahoRxMqttMessage.create((byte[]) null); }
### Question: PahoRxMqttToken implements RxMqttToken { @Override public RxMqttMessage getMessage() { return Optional.of(token) .filter(t -> IMqttDeliveryToken.class.isAssignableFrom(t.getClass())) .map(t -> { try { return IMqttDeliveryToken.class.cast(t).getMessage(); } catch (MqttException me) { throw new PahoRxMqttException(me, t); } }) .map(PahoRxMqttMessage::create) .orElse(null); } PahoRxMqttToken(IMqttToken token); @Override String getClientId(); @Override boolean isComplete(); @Override String[] getTopics(); @Override int getMessageId(); @Override int[] getGrantedQos(); @Override boolean getSessionPresent(); @Override RxMqttMessage getMessage(); @Override RxMqttException getException(); }### Answer: @Test public void whenAMqttDeliveryTokenIsSuppliedThenGetMessageFails() throws MqttException { IMqttDeliveryToken mqttToken = mock(IMqttDeliveryToken.class); assertThat(mqttToken).isNotNull(); doThrow(new MqttException(MqttException.REASON_CODE_UNEXPECTED_ERROR)).when(mqttToken).getMessage(); PahoRxMqttToken rxMqttToken = new PahoRxMqttToken(mqttToken); assertThat(rxMqttToken).isNotNull(); try { rxMqttToken.getMessage(); } catch (Exception e) { assertThat(e).isExactlyInstanceOf(PahoRxMqttException.class); assertThat(e).hasCauseExactlyInstanceOf(MqttException.class); } verify(mqttToken).getMessage(); }
### Question: TransactionConfig implements CertificateConfigurable<TransactionConfig> { public Optional<URI> getAssertionConsumerServiceUri(Optional<Integer> index) { for (AssertionConsumerService service : assertionConsumerServices) { boolean isDesiredEndpoint; if (index.isPresent() && service.getIndex().isPresent()) { isDesiredEndpoint = (service.getIndex().get().equals(index.get())); } else { isDesiredEndpoint = service.getDefault(); } if (isDesiredEndpoint) { return ofNullable(service.getUri()); } } return Optional.empty(); } @SuppressWarnings("unused") // needed to prevent guice injection protected TransactionConfig(); Optional<URI> getAssertionConsumerServiceUri(Optional<Integer> index); URI getServiceHomepage(); boolean isEnabled(); boolean isEnabledForSingleIdp(); String getEntityId(); @Override FederationEntityType getEntityType(); Certificate getEncryptionCertificate(); Optional<MatchingProcess> getMatchingProcess(); String getMatchingServiceEntityId(); List<LevelOfAssurance> getLevelsOfAssurance(); boolean getShouldHubSignResponseMessages(); boolean getShouldHubUseLegacySamlStandard(); Collection<Certificate> getSignatureVerificationCertificates(); Optional<List<UserAccountCreationAttribute>> getUserAccountCreationAttributes(); Optional<String> getSimpleId(); boolean isEidasEnabled(); Optional<List<String>> getEidasCountries(); URI getHeadlessStartpage(); Optional<URI> getSingleIdpStartPage(); boolean isUsingMatching(); boolean isEidasProxyNode(); boolean isSelfService(); CertificateOrigin getCertificateOrigin(); @Override TransactionConfig override(List<String> signatureVerificationCertificates, String encryptionCertificate, CertificateOrigin certificateOrigin); }### Answer: @Test public void getAssertionConsumerServiceUri_shouldReturnCorrectUriWhenIndexIsSpecified() { URI uri = URI.create("/expected-uri"); int index = 1; TransactionConfig systemUnderTests = aTransactionConfigData() .addAssertionConsumerService(anAssertionConsumerService().withIndex(0).build()) .addAssertionConsumerService(anAssertionConsumerService().withIndex(index).withUri(uri).build()) .build(); final Optional<URI> returnedUri = systemUnderTests.getAssertionConsumerServiceUri(Optional.of(index)); assertThat(returnedUri.isPresent()).isEqualTo(true); assertThat(returnedUri.get()).isEqualTo(uri); } @Test public void getAssertionConsumerServiceUri_shouldReturnAbsentWhenInvalidIndexIsSpecified() { TransactionConfig systemUnderTests = aTransactionConfigData() .addAssertionConsumerService(anAssertionConsumerService().withIndex(0).build()) .build(); final Optional<URI> returnedUri = systemUnderTests.getAssertionConsumerServiceUri(Optional.of(1)); assertThat(returnedUri.isPresent()).isEqualTo(false); } @Test public void getAssertionConsumerServiceUri_shouldReturnDefaultUriWhenNoIndexIsSpecified() { URI uri = URI.create("/some-uri"); TransactionConfig systemUnderTests = aTransactionConfigData() .addAssertionConsumerService(anAssertionConsumerService().isDefault(false).build()) .addAssertionConsumerService(anAssertionConsumerService().isDefault(true).withUri(uri).build()) .build(); final Optional<URI> returnedUri = systemUnderTests.getAssertionConsumerServiceUri(Optional.empty()); assertThat(returnedUri.isPresent()).isEqualTo(true); assertThat(returnedUri.get()).isEqualTo(uri); }
### Question: CertificateValidityChecker { public Optional<CertificateValidity> validate(Certificate certificate) { return certificate.getX509Certificate() .map(x509 -> getCertificateValidity(certificate, x509)); } private CertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, CertificateChainValidator certificateChainValidator); static CertificateValidityChecker createOCSPCheckingCertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, OCSPCertificateChainValidator ocspCertificateChainValidator); static CertificateValidityChecker createNonOCSPCheckingCertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, CertificateChainValidator certificateChainValidator); Set<InvalidCertificateDto> getInvalidCertificates(Collection<Certificate> certificates); Optional<CertificateValidity> validate(Certificate certificate); boolean isValid(Certificate certificate); }### Answer: @Test public void validateReturnsNoResultForLocalCertWithEmptyX509() { Certificate certificateWithoutX509 = new Certificate("entityId", FederationEntityType.RP, "", CertificateUse.SIGNING, CertificateOrigin.FEDERATION, true); Optional<CertificateValidity> result = certificateValidityChecker.validate(certificateWithoutX509); assertThat(result).isEmpty(); } @Test public void validateReturnsNoResultForSelfServiceCertWithEmptyX509() { Certificate certificateWithoutX509 = new Certificate("entityId", FederationEntityType.RP, "", CertificateUse.SIGNING, CertificateOrigin.SELFSERVICE, true); Optional<CertificateValidity> result = certificateValidityChecker.validate(certificateWithoutX509); assertThat(result).isEmpty(); }
### Question: CertificateValidityChecker { public boolean isValid(Certificate certificate) { return validate(certificate) .map(CertificateValidity::isValid) .orElse(false); } private CertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, CertificateChainValidator certificateChainValidator); static CertificateValidityChecker createOCSPCheckingCertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, OCSPCertificateChainValidator ocspCertificateChainValidator); static CertificateValidityChecker createNonOCSPCheckingCertificateValidityChecker(TrustStoreForCertificateProvider trustStoreForCertificateProvider, CertificateChainValidator certificateChainValidator); Set<InvalidCertificateDto> getInvalidCertificates(Collection<Certificate> certificates); Optional<CertificateValidity> validate(Certificate certificate); boolean isValid(Certificate certificate); }### Answer: @Test public void considersSelfServiceCertificateToBeValidWithoutCheckingTrustChain() { Boolean isCertificateValid = certificateValidityChecker.isValid(selfServiceCertificate); assertThat(isCertificateValid).isTrue(); verifyNoInteractions(certificateChainValidator); } @Test public void considersLocalCertificateWithEmptyX509ToBeInvalid() { Certificate certificateWithoutX509 = new Certificate("entityId", FederationEntityType.RP, "", CertificateUse.SIGNING, CertificateOrigin.FEDERATION, true); Boolean isCertificateValid = certificateValidityChecker.isValid(certificateWithoutX509); assertThat(isCertificateValid).isFalse(); } @Test public void considersSelfServiceCertificateWithEmptyX509ToBeInvalid() { Certificate certificateWithoutX509 = new Certificate("entityId", FederationEntityType.RP, "", CertificateUse.SIGNING, CertificateOrigin.SELFSERVICE, true); Boolean isCertificateValid = certificateValidityChecker.isValid(certificateWithoutX509); assertThat(isCertificateValid).isFalse(); }
### Question: IdentityProviderConfig implements EntityIdentifiable { public List<LevelOfAssurance> getSupportedLevelsOfAssurance() { return supportedLevelsOfAssurance; } @SuppressWarnings("unused") // needed to prevent guice injection protected IdentityProviderConfig(); @Override String getEntityId(); @Override String toString(); List<LevelOfAssurance> getSupportedLevelsOfAssurance(); boolean supportsLoa(LevelOfAssurance levelOfAssurance); String getSimpleId(); Boolean isEnabled(); @JsonProperty("temporarilyUnavailable") Boolean isTemporarilyUnavailable(); Boolean canReceiveRegistrationRequests(); Boolean canSendRegistrationResponses(Duration sessionDuration); @JsonProperty("authenticationEnabled") Boolean isAuthenticationEnabled(); Boolean isEnabledForSingleIdp(); String getProvideRegistrationUntil(); List<String> getOnboardingTransactionEntityIds(); boolean isOnboardingForTransactionEntityAtLoa(String transactionEntity, LevelOfAssurance levelOfAssurance); boolean isOnboardingAtAllLevels(); boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance); Boolean getUseExactComparisonType(); }### Answer: @Test public void should_defaultSupportedLevelsOfAssuranceToOnlyIncludeLOA2() { IdentityProviderConfig data = dataBuilder.build(); assertThat(data.getSupportedLevelsOfAssurance()).containsExactly(LevelOfAssurance.LEVEL_2); }
### Question: IdentityProviderConfig implements EntityIdentifiable { public Boolean canReceiveRegistrationRequests() { return Strings.isNullOrEmpty(provideRegistrationUntil) || provideRegistrationUntilDate().isAfterNow(); } @SuppressWarnings("unused") // needed to prevent guice injection protected IdentityProviderConfig(); @Override String getEntityId(); @Override String toString(); List<LevelOfAssurance> getSupportedLevelsOfAssurance(); boolean supportsLoa(LevelOfAssurance levelOfAssurance); String getSimpleId(); Boolean isEnabled(); @JsonProperty("temporarilyUnavailable") Boolean isTemporarilyUnavailable(); Boolean canReceiveRegistrationRequests(); Boolean canSendRegistrationResponses(Duration sessionDuration); @JsonProperty("authenticationEnabled") Boolean isAuthenticationEnabled(); Boolean isEnabledForSingleIdp(); String getProvideRegistrationUntil(); List<String> getOnboardingTransactionEntityIds(); boolean isOnboardingForTransactionEntityAtLoa(String transactionEntity, LevelOfAssurance levelOfAssurance); boolean isOnboardingAtAllLevels(); boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance); Boolean getUseExactComparisonType(); }### Answer: @Test(expected = java.lang.IllegalArgumentException.class) public void shouldThrowInvalidFormatException_whenProvideRegistrationUntilHasBeenSpecifiedButIsInvalid() { IdentityProviderConfig data = dataBuilder.build(); data.provideRegistrationUntil = "2020-09-09"; data.canReceiveRegistrationRequests(); }
### Question: IdentityProviderConfig implements EntityIdentifiable { @JsonProperty("authenticationEnabled") public Boolean isAuthenticationEnabled() { if (Strings.isNullOrEmpty(provideAuthenticationUntil)) { return true; } DateTime provideAuthenticationUntilDate = DateTime.parse(provideAuthenticationUntil, DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")); return provideAuthenticationUntilDate.isAfterNow(); } @SuppressWarnings("unused") // needed to prevent guice injection protected IdentityProviderConfig(); @Override String getEntityId(); @Override String toString(); List<LevelOfAssurance> getSupportedLevelsOfAssurance(); boolean supportsLoa(LevelOfAssurance levelOfAssurance); String getSimpleId(); Boolean isEnabled(); @JsonProperty("temporarilyUnavailable") Boolean isTemporarilyUnavailable(); Boolean canReceiveRegistrationRequests(); Boolean canSendRegistrationResponses(Duration sessionDuration); @JsonProperty("authenticationEnabled") Boolean isAuthenticationEnabled(); Boolean isEnabledForSingleIdp(); String getProvideRegistrationUntil(); List<String> getOnboardingTransactionEntityIds(); boolean isOnboardingForTransactionEntityAtLoa(String transactionEntity, LevelOfAssurance levelOfAssurance); boolean isOnboardingAtAllLevels(); boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance); Boolean getUseExactComparisonType(); }### Answer: @Test public void shouldReturnTrueForAuthenticationEnabled_whenProvideAuthenticationUntilHasNotBeenSpecified() { IdentityProviderConfig data = dataBuilder.build(); data.provideAuthenticationUntil = ""; assertThat(data.isAuthenticationEnabled()).isEqualTo(true); } @Test public void shouldReturnTrueForAuthenticationEnabled_whenProvideAuthenticationUntilDateHasNotExpired() { IdentityProviderConfig data = dataBuilder .withProvideAuthenticationUntil(futureDatetime) .build(); assertThat(data.isAuthenticationEnabled()).isEqualTo(true); } @Test public void shouldReturnFalseForAuthenticationEnabled_whenProvideAuthenticationUntilDateHasExpired() { IdentityProviderConfig data = dataBuilder .withProvideAuthenticationUntil(expiredDatetime) .build(); assertThat(data.isAuthenticationEnabled()).isEqualTo(false); } @Test(expected = java.lang.IllegalArgumentException.class) public void shouldThrowInvalidFormatException_whenProvideAuthenticationUntilHasBeenSpecifiedButIsInvalid() { IdentityProviderConfig data = dataBuilder.build(); data.provideAuthenticationUntil = "2020-09-09"; data.isAuthenticationEnabled(); }
### Question: IdentityProviderConfig implements EntityIdentifiable { public boolean isOnboardingAtAllLevels() { return supportedLevelsOfAssurance.stream().allMatch(this::isOnboardingAtLoa); } @SuppressWarnings("unused") // needed to prevent guice injection protected IdentityProviderConfig(); @Override String getEntityId(); @Override String toString(); List<LevelOfAssurance> getSupportedLevelsOfAssurance(); boolean supportsLoa(LevelOfAssurance levelOfAssurance); String getSimpleId(); Boolean isEnabled(); @JsonProperty("temporarilyUnavailable") Boolean isTemporarilyUnavailable(); Boolean canReceiveRegistrationRequests(); Boolean canSendRegistrationResponses(Duration sessionDuration); @JsonProperty("authenticationEnabled") Boolean isAuthenticationEnabled(); Boolean isEnabledForSingleIdp(); String getProvideRegistrationUntil(); List<String> getOnboardingTransactionEntityIds(); boolean isOnboardingForTransactionEntityAtLoa(String transactionEntity, LevelOfAssurance levelOfAssurance); boolean isOnboardingAtAllLevels(); boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance); Boolean getUseExactComparisonType(); }### Answer: @Test public void shouldCheckThatIsOnboardingAtAllLevels() { final IdentityProviderConfig dataOnboardingAtAllLevels = dataBuilder .withSupportedLevelsOfAssurance(Arrays.asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2)) .withOnboardingLevels(Arrays.asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2)) .build(); assertThat(dataOnboardingAtAllLevels.isOnboardingAtAllLevels()).isTrue(); final IdentityProviderConfig dataOnboardingAtOneLevelOnly = dataBuilder .withSupportedLevelsOfAssurance(Arrays.asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2)) .withOnboardingLevels(Collections.singletonList(LevelOfAssurance.LEVEL_1)) .build(); assertThat(dataOnboardingAtOneLevelOnly.isOnboardingAtAllLevels()).isFalse(); }
### Question: IdentityProviderConfig implements EntityIdentifiable { public boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance) { return onboardingLevelsOfAssurance.contains(levelOfAssurance); } @SuppressWarnings("unused") // needed to prevent guice injection protected IdentityProviderConfig(); @Override String getEntityId(); @Override String toString(); List<LevelOfAssurance> getSupportedLevelsOfAssurance(); boolean supportsLoa(LevelOfAssurance levelOfAssurance); String getSimpleId(); Boolean isEnabled(); @JsonProperty("temporarilyUnavailable") Boolean isTemporarilyUnavailable(); Boolean canReceiveRegistrationRequests(); Boolean canSendRegistrationResponses(Duration sessionDuration); @JsonProperty("authenticationEnabled") Boolean isAuthenticationEnabled(); Boolean isEnabledForSingleIdp(); String getProvideRegistrationUntil(); List<String> getOnboardingTransactionEntityIds(); boolean isOnboardingForTransactionEntityAtLoa(String transactionEntity, LevelOfAssurance levelOfAssurance); boolean isOnboardingAtAllLevels(); boolean isOnboardingAtLoa(LevelOfAssurance levelOfAssurance); Boolean getUseExactComparisonType(); }### Answer: @Test public void shouldCheckThatIsOnboardingAtLoa() { final IdentityProviderConfig data = dataBuilder .withSupportedLevelsOfAssurance(Arrays.asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_2)) .withOnboardingLevels(Collections.singletonList(LevelOfAssurance.LEVEL_1)) .build(); assertThat(data.isOnboardingAtLoa(LevelOfAssurance.LEVEL_1)).isTrue(); assertThat(data.isOnboardingAtLoa(LevelOfAssurance.LEVEL_2)).isFalse(); }
### Question: MatchingServiceHealthCheckResource { @GET public Response performMatchingServiceHealthCheck() { final AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); final Response.ResponseBuilder response = result.isHealthy() ? Response.ok() : Response.serverError(); response.entity(result); return response.build(); } @Inject MatchingServiceHealthCheckResource(MatchingServiceHealthCheckHandler matchingServiceHealthCheckHandler); @GET Response performMatchingServiceHealthCheck(); }### Answer: @Test public void performMatchingServiceHealthCheck_shouldReturn500WhenThereAreNoMSAResults() { AggregatedMatchingServicesHealthCheckResult result = new AggregatedMatchingServicesHealthCheckResult(); when(handler.handle()).thenReturn(result); final Response response = matchingServiceHealthCheckResource.performMatchingServiceHealthCheck(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } @Test public void performMatchingServiceHealthCheck_shouldReturn500WhenHealthCheckIsUnhealthy() { AggregatedMatchingServicesHealthCheckResult result = new AggregatedMatchingServicesHealthCheckResult(); result.addResult(unhealthy(aMatchingServiceHealthCheckDetails().build())); when(handler.handle()).thenReturn(result); final Response response = matchingServiceHealthCheckResource.performMatchingServiceHealthCheck(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } @Test public void performMatchingServiceHealthCheck_shouldReturnResultFromHandler() { final String failureDescription = "some-error-description"; AggregatedMatchingServicesHealthCheckResult result = new AggregatedMatchingServicesHealthCheckResult(); result.addResult(unhealthy(aMatchingServiceHealthCheckDetails().withDetails(failureDescription).build())); when(handler.handle()).thenReturn(result); final Response response = matchingServiceHealthCheckResource.performMatchingServiceHealthCheck(); AggregatedMatchingServicesHealthCheckResult returnedResult = (AggregatedMatchingServicesHealthCheckResult)response.getEntity(); assertThat(returnedResult).isEqualTo(result); }
### Question: MatchingServiceHealthCheckHandler { public AggregatedMatchingServicesHealthCheckResult handle() { return handle(false); } @Inject MatchingServiceHealthCheckHandler(final MatchingServiceConfigProxy matchingServiceConfigProxy, final MatchingServiceHealthChecker matchingServiceHealthChecker); AggregatedMatchingServicesHealthCheckResult handle(); AggregatedMatchingServicesHealthCheckResult forceCheckAllMSAs(); }### Answer: @Test public void handle_shouldReturnSuccessWhenMatchingServiceIsHealthy() throws Exception { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = MatchingServiceConfigEntityDataDtoBuilder.aMatchingServiceConfigEntityDataDto().build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(singletonList(matchingServiceConfigEntityDataDto)); when(matchingServiceHealthChecker.performHealthCheck(matchingServiceConfigEntityDataDto)) .thenReturn(MatchingServiceHealthCheckResult.healthy(MatchingServiceHealthCheckDetailsBuilder.aMatchingServiceHealthCheckDetails().build())); AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); assertThat(result.isHealthy()).isEqualTo(true); } @Test public void handle_shouldReturnSuccessWhenMatchingServiceIsNotHealthy() throws Exception { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = MatchingServiceConfigEntityDataDtoBuilder.aMatchingServiceConfigEntityDataDto().build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(singletonList(matchingServiceConfigEntityDataDto)); when(matchingServiceHealthChecker.performHealthCheck(matchingServiceConfigEntityDataDto)) .thenReturn(MatchingServiceHealthCheckResult.unhealthy(MatchingServiceHealthCheckDetailsBuilder.aMatchingServiceHealthCheckDetails().build())); AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); assertThat(result.isHealthy()).isEqualTo(false); } @Test public void handle_shouldCheckHealthOfAllMatchingServices() throws Exception { MatchingServiceConfigEntityDataDto firstMatchingService = aMatchingServiceConfigEntityDataDto().withUri(URI.create("/a-matching-service-uri-1")).withEntityId("1").build(); MatchingServiceConfigEntityDataDto secondMatchingService = aMatchingServiceConfigEntityDataDto().withUri(URI.create("/a-matching-service-uri-2")).withEntityId("2").build(); Collection<MatchingServiceConfigEntityDataDto> matchingServiceConfigEntityDatas = asList(firstMatchingService, secondMatchingService); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(matchingServiceConfigEntityDatas); when(matchingServiceHealthChecker.performHealthCheck(any(MatchingServiceConfigEntityDataDto.class))) .thenReturn(MatchingServiceHealthCheckResult.healthy(MatchingServiceHealthCheckDetailsBuilder.aMatchingServiceHealthCheckDetails().build())); AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); verify(matchingServiceHealthChecker).performHealthCheck(firstMatchingService); verify(matchingServiceHealthChecker).performHealthCheck(secondMatchingService); assertThat(result.getResults().size()).isEqualTo(2); } @Test public void handle_shouldNotExecuteHealthCheckForMatchingServiceWithHealthCheckDisabled() { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = aMatchingServiceConfigEntityDataDto().withHealthCheckDisabled().build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(singletonList(matchingServiceConfigEntityDataDto)); matchingServiceHealthCheckHandler.handle(); verify(matchingServiceHealthChecker, never()) .performHealthCheck(any(MatchingServiceConfigEntityDataDto.class)); }
### Question: SamlMessageSenderHandler { public SamlMessage generateAuthnResponseFromHub(SessionId sessionId, String principalIpAddressAsSeenByHub) { AuthnResponseFromHubContainerDto authnResponseFromHub = sessionProxy.getAuthnResponseFromHub(sessionId); Response samlResponse = responseTransformer.apply(authnResponseFromHub.getSamlResponse()); validateAndLogSamlResponseSignature(samlResponse); SamlMessage samlMessage = new SamlMessage( authnResponseFromHub.getSamlResponse(), SamlMessageType.SAML_RESPONSE, authnResponseFromHub.getRelayState(), authnResponseFromHub.getPostEndpoint().toString(), Optional.empty() ); externalCommunicationEventLogger.logResponseFromHub(samlResponse.getID(), sessionId, authnResponseFromHub.getPostEndpoint(), principalIpAddressAsSeenByHub); return samlMessage; } @Inject SamlMessageSenderHandler( StringToOpenSamlObjectTransformer<Response> responseTransformer, StringToOpenSamlObjectTransformer<AuthnRequest> authnRequestTransformer, SamlMessageSignatureValidator samlMessageSignatureValidator, ExternalCommunicationEventLogger externalCommunicationEventLogger, ProtectiveMonitoringLogger protectiveMonitoringLogger, SessionProxy sessionProxy); SamlMessage generateAuthnResponseFromHub(SessionId sessionId, String principalIpAddressAsSeenByHub); SamlMessage generateErrorResponseFromHub(final SessionId sessionId, String principalIpAddressAsSeenByHub); SamlMessage generateAuthnRequestFromHub(SessionId sessionId, String principalIpAddress); }### Answer: @Test public void generateAuthnResponseFromHub_shouldAddExternalCommunicationEvent() throws Exception { SessionId sessionId = SessionId.createNewSessionId(); String expectedSamlMessageId = UUID.randomUUID().toString(); Response openSamlResponse = setUpAuthnResponseFromHub(sessionId, expectedSamlMessageId); SamlMessage authnResponse = samlMessageSenderHandler.generateAuthnResponseFromHub(sessionId, principalIpAddressAsSeenByHub); assertThat(authnResponse.getSamlMessage()).isEqualTo(samlRequest); assertThat(authnResponse.getPostEndpoint()).isEqualTo(postEndPoint.toString()); assertThat(authnResponse.getRegistration()).isNotPresent(); assertThat(authnResponse.getRelayState().isPresent()).isTrue(); assertThat(authnResponse.getRelayState().get()).isEqualTo(relayState.get()); assertThat(authnResponse.getSamlMessageType()).isEqualTo(SamlMessageType.SAML_RESPONSE); verify(externalCommunicationEventLogger).logResponseFromHub(expectedSamlMessageId, sessionId, postEndPoint, principalIpAddressAsSeenByHub); verify(protectiveMonitoringLogger).logAuthnResponse(openSamlResponse, Direction.OUTBOUND, SignatureStatus.VALID_SIGNATURE); } @Test(expected = SamlTransformationErrorException.class) public void generateAuthResponseFromHub_shouldThrowSamlTransformationException() throws MarshallingException, SignatureException { SessionId sessionId = SessionId.createNewSessionId(); String expectedSamlMessageId = UUID.randomUUID().toString(); Response openSamlResponse = setUpAuthnResponseFromHub(sessionId, expectedSamlMessageId); when(samlMessageSignatureValidator.validate(openSamlResponse, SPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(SamlValidationResponse.anInvalidResponse(new SamlValidationSpecification("bad", true))); samlMessageSenderHandler.generateAuthnResponseFromHub(sessionId, principalIpAddressAsSeenByHub); }
### Question: MatchingServiceHealthCheckHandler { public AggregatedMatchingServicesHealthCheckResult forceCheckAllMSAs() { return handle(true); } @Inject MatchingServiceHealthCheckHandler(final MatchingServiceConfigProxy matchingServiceConfigProxy, final MatchingServiceHealthChecker matchingServiceHealthChecker); AggregatedMatchingServicesHealthCheckResult handle(); AggregatedMatchingServicesHealthCheckResult forceCheckAllMSAs(); }### Answer: @Test public void handle_shouldExecuteHealthCheckForMatchingServiceWithHealthCheckDisabledWhenForced() { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = aMatchingServiceConfigEntityDataDto().withHealthCheckDisabled().build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(singletonList(matchingServiceConfigEntityDataDto)); matchingServiceHealthCheckHandler.forceCheckAllMSAs(); verify(matchingServiceHealthChecker, times(1)) .performHealthCheck(any(MatchingServiceConfigEntityDataDto.class)); } @Test public void handle_shouldExecuteHealthCheckForMatchingServiceWithHealthCheckDisabledWhenForcedIfOneEnabledAndOneDisabled() { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDtoHCDisabled = aMatchingServiceConfigEntityDataDto().withHealthCheckDisabled().withEntityId("1").build(); MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDtoHCEnabled = aMatchingServiceConfigEntityDataDto().withHealthCheckEnabled().withEntityId("2").build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(asList(matchingServiceConfigEntityDataDtoHCDisabled, matchingServiceConfigEntityDataDtoHCEnabled)); matchingServiceHealthCheckHandler.forceCheckAllMSAs(); verify(matchingServiceHealthChecker, times(2)) .performHealthCheck(any(MatchingServiceConfigEntityDataDto.class)); } @Test public void handle_shouldRemoveDuplicatesFromMatchingServiceList() { MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = aMatchingServiceConfigEntityDataDto().withHealthCheckDisabled().withTransactionEntityId("1").build(); MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto2 = aMatchingServiceConfigEntityDataDto().withHealthCheckDisabled().withTransactionEntityId("2").build(); when(matchingServiceConfigProxy.getMatchingServices()).thenReturn(asList(matchingServiceConfigEntityDataDto,matchingServiceConfigEntityDataDto2)); matchingServiceHealthCheckHandler.forceCheckAllMSAs(); verify(matchingServiceHealthChecker, times(1)) .performHealthCheck(any(MatchingServiceConfigEntityDataDto.class)); }
### Question: SamlMessageSenderHandler { public SamlMessage generateErrorResponseFromHub(final SessionId sessionId, String principalIpAddressAsSeenByHub) { AuthnResponseFromHubContainerDto authnResponseFromHub = sessionProxy.getErrorResponseFromHub(sessionId); Response samlResponse = responseTransformer.apply(authnResponseFromHub.getSamlResponse()); validateAndLogSamlResponseSignature(samlResponse); SamlMessage samlMessage = new SamlMessage( authnResponseFromHub.getSamlResponse(), SamlMessageType.SAML_RESPONSE, authnResponseFromHub.getRelayState(), authnResponseFromHub.getPostEndpoint().toString(), Optional.empty() ); externalCommunicationEventLogger.logResponseFromHub(authnResponseFromHub.getResponseId(), sessionId, authnResponseFromHub.getPostEndpoint(), principalIpAddressAsSeenByHub); return samlMessage; } @Inject SamlMessageSenderHandler( StringToOpenSamlObjectTransformer<Response> responseTransformer, StringToOpenSamlObjectTransformer<AuthnRequest> authnRequestTransformer, SamlMessageSignatureValidator samlMessageSignatureValidator, ExternalCommunicationEventLogger externalCommunicationEventLogger, ProtectiveMonitoringLogger protectiveMonitoringLogger, SessionProxy sessionProxy); SamlMessage generateAuthnResponseFromHub(SessionId sessionId, String principalIpAddressAsSeenByHub); SamlMessage generateErrorResponseFromHub(final SessionId sessionId, String principalIpAddressAsSeenByHub); SamlMessage generateAuthnRequestFromHub(SessionId sessionId, String principalIpAddress); }### Answer: @Test public void generateErrorResponseFromHub_shouldAddExternalCommunicationEvent() throws MarshallingException, SignatureException { SessionId sessionId = SessionId.createNewSessionId(); String responseId = UUID.randomUUID().toString(); when(sessionProxy.getErrorResponseFromHub(sessionId)).thenReturn( new AuthnResponseFromHubContainerDto( samlRequest, postEndPoint, relayState, responseId ) ); Response samlResponse = setUpErrorResponseFromHub(sessionId, responseId); when(responseTransformer.apply(samlRequest)).thenReturn(samlResponse); SamlMessage samlMessage = samlMessageSenderHandler.generateErrorResponseFromHub(sessionId, principalIpAddressAsSeenByHub); assertThat(samlMessage.getSamlMessage()).isEqualTo(samlRequest); assertThat(samlMessage.getPostEndpoint()).isEqualTo(postEndPoint.toString()); assertThat(samlMessage.getRegistration()).isNotPresent(); assertThat(samlMessage.getSamlMessageType()).isEqualTo(SamlMessageType.SAML_RESPONSE); assertThat(samlMessage.getRelayState().isPresent()).isTrue(); assertThat(samlMessage.getRelayState()).isEqualTo(relayState); verify(externalCommunicationEventLogger).logResponseFromHub(responseId, sessionId, postEndPoint, principalIpAddressAsSeenByHub); } @Test(expected = SamlTransformationErrorException.class) public void generateErrorResponseFromHub_shouldThrowSamlTransformationException() throws MarshallingException, SignatureException { SessionId sessionId = SessionId.createNewSessionId(); String expectedSamlMessageId = UUID.randomUUID().toString(); Response openSamlResponse = setUpErrorResponseFromHub(sessionId, expectedSamlMessageId); when(samlMessageSignatureValidator.validate(openSamlResponse, SPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(SamlValidationResponse.anInvalidResponse(new SamlValidationSpecification("bad", true))); samlMessageSenderHandler.generateErrorResponseFromHub(sessionId, principalIpAddressAsSeenByHub); }
### Question: IdaJsonProcessingExceptionMapper implements ExceptionMapper<JsonProcessingException> { @Override public Response toResponse(JsonProcessingException exception) { if (exception instanceof JsonGenerationException) { LOG.error("Error generating JSON", exception); return Response.serverError().build(); } if (exception.getMessage().startsWith("No suitable constructor found")) { LOG.error("Unable to deserialize the specific type", exception); return Response.serverError().build(); } LOG.info(exception.getLocalizedMessage()); return Response .status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON_TYPE) .entity(createUnauditedErrorStatus(UUID.randomUUID(), ExceptionType.JSON_PARSING, exception.getOriginalMessage())) .build(); } @Override Response toResponse(JsonProcessingException exception); }### Answer: @Test public void toResponse_shouldReturnServerErrorWhenExceptionThrownGeneratingJson() { assertThat(mapper.toResponse(mock(JsonGenerationException.class)).getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } @Test public void toResponse_shouldReturnServerErrorWhenDeserialisationLacksAppropriateConstructor() { assertThat(mapper.toResponse(new JsonMappingException(null, "No suitable constructor found")).getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } @Test public void toResponse_shouldReturnBadRequestAndErrorStatusDtoWhenErrorDeemedToBeFromClient() { String clientErrorMessage = "This is a client error"; Response response = mapper.toResponse(new JsonMappingException(null, clientErrorMessage)); ErrorStatusDto errorStatus = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(errorStatus.isAudited()).isEqualTo(false); assertThat(errorStatus.getClientMessage()).isEqualTo(clientErrorMessage); assertThat(errorStatus.getExceptionType()).isEqualTo(ExceptionType.JSON_PARSING); }
### Question: SamlProxyDuplicateRequestExceptionMapper extends AbstractContextExceptionMapper<SamlDuplicateRequestIdException> { @Override protected Response handleException(SamlDuplicateRequestIdException exception) { UUID errorId = UUID.randomUUID(); eventSinkMessageSender.audit(exception, errorId, getSessionId().orElse(SessionId.NO_SESSION_CONTEXT_IN_ERROR)); levelLogger.log(ExceptionType.INVALID_SAML_DUPLICATE_REQUEST_ID.getLevel(), exception, errorId); return Response.status(BAD_REQUEST) .entity(ErrorStatusDto.createAuditedErrorStatus(errorId, INVALID_SAML_DUPLICATE_REQUEST_ID)) .build(); } @Inject SamlProxyDuplicateRequestExceptionMapper( Provider<HttpServletRequest> contextProvider, EventSinkMessageSender eventSinkMessageSender, LevelLoggerFactory<SamlProxyDuplicateRequestExceptionMapper> levelLoggerFactory); }### Answer: @Test public void shouldCreateAuditedErrorResponseForDuplicateRequestIdError() throws Exception { SamlDuplicateRequestIdException exception = new SamlDuplicateRequestIdException("error", new RuntimeException(), Level.DEBUG); SessionId sessionId = SessionId.createNewSessionId(); when(httpServletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn(sessionId.getSessionId()); Response response = exceptionMapper.handleException(exception); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML_DUPLICATE_REQUEST_ID); verify(eventSinkMessageSender).audit(eq(exception), any(UUID.class), eq(sessionId)); }
### Question: HealthCheckEventLogger { public void logException(ApplicationException exception, String message) { LOG.warn(message, exception); if (exception.isAudited() || !exception.requiresAuditing()) { return; } Map<EventDetailsKey, String> details = Map.of( downstream_uri, exception.getUri().orElse(URI.create("uri-not-present")).toASCIIString(), EventDetailsKey.message, exception.getMessage()); EventSinkHubEvent hubEvent = new EventSinkHubEvent(serviceInfo, NO_SESSION_CONTEXT_IN_ERROR, ERROR_EVENT, details); eventSinkProxy.logHubEvent(hubEvent); eventEmitter.record(hubEvent); } @Inject HealthCheckEventLogger(EventSinkProxy eventSinkProxy, EventEmitter eventEmitter, ServiceInfoConfiguration serviceInfo); void logException(ApplicationException exception, String message); }### Answer: @Test public void shouldLogToEventSinkIfTheExceptionIsUnaudited() { URI uri = URI.create("uri-geller"); ApplicationException unauditedException = ApplicationException.createUnauditedException(ExceptionType.INVALID_SAML, UUID.randomUUID(), uri); Map<EventDetailsKey, String> details = Map.of( downstream_uri, unauditedException.getUri().orElse(URI.create("uri-not-present")).toASCIIString(), message, unauditedException.getMessage()); EventSinkHubEvent event = new EventSinkHubEvent(serviceInfo, NO_SESSION_CONTEXT_IN_ERROR, ERROR_EVENT,details); eventLogger.logException(unauditedException, "test error message"); ArgumentCaptor<EventSinkHubEvent> eventSinkCaptor = ArgumentCaptor.forClass(EventSinkHubEvent.class); ArgumentCaptor<EventSinkHubEvent> eventEmitterCaptor = ArgumentCaptor.forClass(EventSinkHubEvent.class); verify(eventSinkProxy, times(1)).logHubEvent(eventSinkCaptor.capture()); verify(eventEmitter, times(1)).record(eventEmitterCaptor.capture()); assertThat(event).isEqualToComparingOnlyGivenFields(eventSinkCaptor.getValue(), "originatingService", "sessionId", "eventType", "details"); assertThat(event).isEqualToComparingOnlyGivenFields(eventEmitterCaptor.getValue(), "originatingService", "sessionId", "eventType", "details"); } @Test public void shouldNotLogToEventSinkIfTheExceptionIsAudited() { ApplicationException unauditedException = ApplicationException.createAuditedException(ExceptionType.INVALID_SAML, UUID.randomUUID()); eventLogger.logException(unauditedException, "test error message"); verify(eventSinkProxy, times(0)).logHubEvent(any()); } @Test public void shouldNotLogToEventSinkIfTheExceptionIsUnauditedButShouldNotBeaudited() { ApplicationException unauditedException = ApplicationException.createUnauditedException(ExceptionType.NETWORK_ERROR, UUID.randomUUID()); eventLogger.logException(unauditedException, "test error message"); verify(eventSinkProxy, times(0)).logHubEvent(any()); }
### Question: ExternalCommunicationEventLogger { public void logMatchingServiceRequest(String messageId, SessionId sessionId, URI targetUrl) { logExternalCommunicationEvent(messageId, sessionId, targetUrl, MATCHING_SERVICE_REQUEST, IncludeIpAddressState.WITH_RESOLVED_IP_ADDRESS); } @Inject ExternalCommunicationEventLogger(ServiceInfoConfiguration serviceInfo, EventSinkProxy eventSinkProxy, EventEmitter eventEmitter, IpAddressResolver ipAddressResolver); void logMatchingServiceRequest(String messageId, SessionId sessionId, URI targetUrl); void logIdpAuthnRequest(String messageId, SessionId sessionId, URI targetUrl, String principalIpAddressAsSeenByHub); void logResponseFromHub(String messageId, SessionId sessionId, URI endpointUrl, String principalIpAddressAsSeenByHub); }### Answer: @Test public void logMatchingServiceRequest_shouldPassHubEventToEventSinkProxyNew() { externalCommunicationEventLogger.logMatchingServiceRequest(MESSAGE_ID, SESSION_ID, ENDPOINT_URL); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, MATCHING_SERVICE_REQUEST, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), external_ip_address, ENDPOINT_IP_ADDRESS )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); } @Test public void logMatchingServiceRequest_shouldPassHubEventToEventSinkProxy() { externalCommunicationEventLogger.logMatchingServiceRequest(MESSAGE_ID, SESSION_ID, ENDPOINT_URL); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, MATCHING_SERVICE_REQUEST, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), external_ip_address, ENDPOINT_IP_ADDRESS )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); }
### Question: AbstractContextExceptionMapper implements ExceptionMapper<TException> { @Override public final Response toResponse(TException exception) { if (exception instanceof NotFoundException) { return Response.status(Response.Status.NOT_FOUND).build(); } else if (noSessionIdInQueryString() && inARequestWhereWeExpectContext()) { LOG.error(MessageFormat.format("No Session Id found for request to: {0}", context.get().getRequestURI()), exception); return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .entity(ErrorStatusDto.createUnauditedErrorStatus(UUID.randomUUID(), ExceptionType.UNKNOWN, exception.getMessage())) .build(); } return handleException(exception); } AbstractContextExceptionMapper(Provider<HttpServletRequest> context); @Override final Response toResponse(TException exception); }### Answer: @Test public void shouldReturnInternalServerErrorWhenThereIsNoSessionIdAndTheRequestUriIsNotAKnownNoContextPath() { when(servletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn(""); when(servletRequest.getParameter(Urls.SharedUrls.RELAY_STATE_PARAM)).thenReturn(""); String unknownUri = UUID.randomUUID().toString(); when(servletRequest.getRequestURI()).thenReturn(unknownUri); Response response = mapper.toResponse(new RuntimeException("We don't expect to see this message")); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(response.getEntity()).isInstanceOf(ErrorStatusDto.class); } @Test public void shouldReturnResponseStatusOfNotFoundWhenANotFoundExceptionIsThrown() { Response response = mapper.toResponse(new NotFoundException()); assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); }
### Question: ExternalCommunicationEventLogger { public void logIdpAuthnRequest(String messageId, SessionId sessionId, URI targetUrl, String principalIpAddressAsSeenByHub) { Map<EventDetailsKey, String> details = new HashMap<>(); details.put(principal_ip_address_as_seen_by_hub, principalIpAddressAsSeenByHub); logExternalCommunicationEvent(messageId, sessionId, targetUrl, AUTHN_REQUEST, IncludeIpAddressState.NO_RESOLVED_IP_ADDRESS, details); } @Inject ExternalCommunicationEventLogger(ServiceInfoConfiguration serviceInfo, EventSinkProxy eventSinkProxy, EventEmitter eventEmitter, IpAddressResolver ipAddressResolver); void logMatchingServiceRequest(String messageId, SessionId sessionId, URI targetUrl); void logIdpAuthnRequest(String messageId, SessionId sessionId, URI targetUrl, String principalIpAddressAsSeenByHub); void logResponseFromHub(String messageId, SessionId sessionId, URI endpointUrl, String principalIpAddressAsSeenByHub); }### Answer: @Test public void logAuthenticationRequest_shouldPassHubEventToEventSinkProxy() { externalCommunicationEventLogger.logIdpAuthnRequest(MESSAGE_ID, SESSION_ID, ENDPOINT_URL, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_HUB); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, AUTHN_REQUEST, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), principal_ip_address_as_seen_by_hub, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_HUB )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); } @Test public void logAuthenticationRequest_shouldPassHubEventToEventSinkProxy() { externalCommunicationEventLogger.logIdpAuthnRequest(MESSAGE_ID, SESSION_ID, ENDPOINT_URL, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_THE_HUB); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, AUTHN_REQUEST, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), principal_ip_address_as_seen_by_hub, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_THE_HUB )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); }
### Question: ExternalCommunicationEventLogger { public void logResponseFromHub(String messageId, SessionId sessionId, URI endpointUrl, String principalIpAddressAsSeenByHub) { Map<EventDetailsKey, String> details = new HashMap<>(); details.put(principal_ip_address_as_seen_by_hub, principalIpAddressAsSeenByHub); logExternalCommunicationEvent(messageId, sessionId, endpointUrl, RESPONSE_FROM_HUB, IncludeIpAddressState.NO_RESOLVED_IP_ADDRESS, details); } @Inject ExternalCommunicationEventLogger(ServiceInfoConfiguration serviceInfo, EventSinkProxy eventSinkProxy, EventEmitter eventEmitter, IpAddressResolver ipAddressResolver); void logMatchingServiceRequest(String messageId, SessionId sessionId, URI targetUrl); void logIdpAuthnRequest(String messageId, SessionId sessionId, URI targetUrl, String principalIpAddressAsSeenByHub); void logResponseFromHub(String messageId, SessionId sessionId, URI endpointUrl, String principalIpAddressAsSeenByHub); }### Answer: @Test public void logResponseFromHub_shouldPassHubEventToEventSinkProxy() { externalCommunicationEventLogger.logResponseFromHub(MESSAGE_ID, SESSION_ID, ENDPOINT_URL, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_HUB); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, RESPONSE_FROM_HUB, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), principal_ip_address_as_seen_by_hub, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_HUB )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); } @Test public void logResponseFromHub_shouldPassHubEventToEventSinkProxy() { externalCommunicationEventLogger.logResponseFromHub(MESSAGE_ID, SESSION_ID, ENDPOINT_URL, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_THE_HUB); final EventSinkHubEvent expectedEvent = new EventSinkHubEvent( SERVICE_INFO, SESSION_ID, EXTERNAL_COMMUNICATION_EVENT, Map.of( external_communication_type, RESPONSE_FROM_HUB, message_id, MESSAGE_ID, external_endpoint, ENDPOINT_URL.toString(), principal_ip_address_as_seen_by_hub, PRINCIPAL_IP_ADDRESS_AS_SEEN_BY_THE_HUB )); verify(eventSinkProxy).logHubEvent(argThat(new EventMatching(expectedEvent))); verify(eventEmitter).record(argThat(new EventMatching(expectedEvent))); }
### Question: SoapMessageManager { public Document wrapWithSoapEnvelope(Element element) { DocumentBuilder documentBuilder; try { documentBuilder = newDocumentBuilder(); } catch (ParserConfigurationException e) { LOG.error("*** ALERT: Failed to create a document builder when trying to construct the the soap message. ***", e); throw new RuntimeException(e); } Document document = documentBuilder.newDocument(); document.adoptNode(element); Element envelope = document.createElementNS("http: Element body = document.createElementNS("http: envelope.appendChild(body); body.appendChild(element); document.appendChild(envelope); return document; } Document wrapWithSoapEnvelope(Element element); Element unwrapSoapMessage(Document document); Element unwrapSoapMessage(Element soapElement); }### Answer: @Test public void wrapWithSoapEnvelope_shouldWrapElementInsideSoapMessageBody() throws Exception { Element element = getTestElement(); SoapMessageManager manager = new SoapMessageManager(); Document soapMessage = manager.wrapWithSoapEnvelope(element); assertThat(getAttributeQuery(soapMessage)).isNotNull(); }
### Question: AttributeQueryRequestClient { public Element sendQuery(Element matchingServiceRequest, String messageId, SessionId sessionId, URI matchingServiceUri) { LOG.info("Sending attribute query to {}", matchingServiceUri); totalQueries.labels(matchingServiceUri.toString()).inc(); Optional<Element> response = sendSingleQuery( matchingServiceRequest, messageId, sessionId, matchingServiceUri ); if (response.isPresent()) { successfulQueries.labels(matchingServiceUri.toString()).inc(); return response.get(); } throw new MatchingServiceException(format("Attribute query failed")); } @Inject AttributeQueryRequestClient( SoapRequestClient soapRequestClient, ExternalCommunicationEventLogger externalCommunicationEventLogger, MetricRegistry metricsRegistry); Element sendQuery(Element matchingServiceRequest, String messageId, SessionId sessionId, URI matchingServiceUri); }### Answer: @Test public void sendQuery_expectingSuccessWithStatusCode200() throws IOException, SAXException, ParserConfigurationException { Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); Response response = mock(Response.class); when(response.getStatus()).thenReturn(200); when(builder.post(any(Entity.class))).thenReturn(response); final Element element = attributeQueryRequestClientWithRealSoapRequestClient.sendQuery(matchingServiceRequest, SOME_MESSAGE_ID, SOME_SESSION_ID, matchingServiceUri); assertThat(element).isNotNull(); } @Test public void sendQuery_shouldSendAuditHubEvent() throws Exception { Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); when(mockSoapRequestClient.makeSoapRequest(eq(matchingServiceRequest), any(URI.class))) .thenReturn(mock(Element.class)); attributeQueryRequestClientWithMockSoapRequestClient.sendQuery(matchingServiceRequest, SOME_MESSAGE_ID, SOME_SESSION_ID, matchingServiceUri); verify(externalCommunicationEventLogger).logMatchingServiceRequest(SOME_MESSAGE_ID, SOME_SESSION_ID, matchingServiceUri); }
### Question: HealthCheckSoapRequestClient extends SoapRequestClient { public HealthCheckResponse makeSoapRequestForHealthCheck(Element requestElement, URI uri) { LOG.info(MessageFormat.format("Making SOAP request to: {0}", uri)); try { SoapResponse response = makePost(uri, requestElement); return new HealthCheckResponse(response.getBody()); } catch(ProcessingException e) { throw ApplicationException.createUnauditedException(ExceptionType.NETWORK_ERROR, UUID.randomUUID(), e); } catch (SOAPRequestError e) { throw ApplicationException.createUnauditedException(ExceptionType.REMOTE_SERVER_ERROR, UUID.randomUUID(), e); } } @Inject HealthCheckSoapRequestClient(SoapMessageManager soapMessageManager, @Named("HealthCheckClient") Client client); HealthCheckResponse makeSoapRequestForHealthCheck(Element requestElement, URI uri); }### Answer: @Test(expected = ApplicationException.class) public void makeSoapRequestForHealthCheck_shouldThrowWhenResponseNot200() throws URISyntaxException { when(response.getStatus()).thenReturn(502); URI matchingServiceUri = new URI("http: healthCheckSoapRequestClient.makeSoapRequestForHealthCheck(null, matchingServiceUri); } @Test public void makePost_shouldEnsureResponseInputStreamIsClosedWhenResponseCodeIsNot200() throws URISyntaxException { when(response.getStatus()).thenReturn(502); URI matchingServiceUri = new URI("http: try { healthCheckSoapRequestClient.makeSoapRequestForHealthCheck(null, matchingServiceUri); fail("Exception should have been thrown"); } catch (ApplicationException e) { verify(response).close(); } }
### Question: MatchingServiceHealthCheckClient { public MatchingServiceHealthCheckResponseDto sendHealthCheckRequest( final Element matchingServiceHealthCheckRequest, final URI matchingServiceUri) { final String scope = matchingServiceUri.toString().replace(':','_').replace('/', '_'); final Timer timer = metricsRegistry.timer(MetricRegistry.name(MatchingServiceHealthCheckClient.class, "sendHealthCheckRequest", scope)); final Timer.Context context = timer.time(); HealthCheckResponse healthCheckResponse; try { healthCheckResponse = client.makeSoapRequestForHealthCheck(matchingServiceHealthCheckRequest, matchingServiceUri); } catch(ApplicationException ex) { final String errorMessage = MessageFormat.format("Failed to complete matching service health check to {0}.", matchingServiceUri); LOG.warn(errorMessage, ex); return new MatchingServiceHealthCheckResponseDto(Optional.empty()); } finally { context.stop(); } return new MatchingServiceHealthCheckResponseDto( Optional.of(XmlUtils.writeToString(healthCheckResponse.getResponseElement()))); } @Inject MatchingServiceHealthCheckClient(HealthCheckSoapRequestClient soapRequestClient, MetricRegistry metricsRegistry); MatchingServiceHealthCheckResponseDto sendHealthCheckRequest( final Element matchingServiceHealthCheckRequest, final URI matchingServiceUri); }### Answer: @Test public void sendHealthCheckRequest_shouldReturnTrueIfResponseReceived() { HealthCheckResponse healthCheckResponse = aHealthCheckResponse() .withElement(healthCheckResponseElement) .build(); when(soapRequestClient.makeSoapRequestForHealthCheck(healthCheckRequest, healthCheckUri)).thenReturn(healthCheckResponse); final MatchingServiceHealthCheckResponseDto matchingServiceHealthCheckResponseDto = matchingServiceHealthCheckClient.sendHealthCheckRequest(healthCheckRequest, healthCheckUri); assertThat(matchingServiceHealthCheckResponseDto.getResponse()).isEqualTo(Optional.of(XmlUtils.writeToString(healthCheckResponseElement))); } @Test public void sendHealthCheckRequest_shouldReturnOptionalAbsentIfNoResponseReceived() { when(soapRequestClient.makeSoapRequestForHealthCheck(healthCheckRequest, healthCheckUri)).thenThrow(ApplicationException.createUnauditedException(ExceptionType.NETWORK_ERROR, UUID.randomUUID())); final MatchingServiceHealthCheckResponseDto matchingServiceHealthCheckResponseDto = matchingServiceHealthCheckClient.sendHealthCheckRequest(healthCheckRequest, healthCheckUri); assertThat(matchingServiceHealthCheckResponseDto.getResponse()).isEqualTo(Optional.empty()); }
### Question: SoapRequestClient { public Element makeSoapRequest(Element requestElement, URI uri) throws SOAPRequestError { return makePost(uri, requestElement).getBody(); } @Inject SoapRequestClient(SoapMessageManager soapMessageManager, @Named("SoapClient") Client client); Element makeSoapRequest(Element requestElement, URI uri); }### Answer: @Test public void makePost_shouldEnsureResponseInputStreamIsClosedWhenResponseCodeIsNot200() throws URISyntaxException { when(response.getStatus()).thenReturn(502); when(webResourceBuilder.post(any(Entity.class))).thenReturn(response); URI matchingServiceUri = new URI("http: try { soapRequestClient.makeSoapRequest(null, matchingServiceUri); fail("Exception should have been thrown"); } catch (SOAPRequestError e) { verify(response).close(); } } @Test public void makePost_checkUniformInterfaceExceptionIsThrownOnNon200StatusCode() throws IOException, SAXException, ParserConfigurationException, URISyntaxException { when(response.getStatus()).thenReturn(303); when(webResourceBuilder.post(any(Entity.class))).thenReturn(response); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http: try { soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); fail("Exception should have been thrown"); } catch (SOAPRequestError ignored) { } } @Test public void makePost_checkProcessingExceptionIsThrown() throws IOException, SAXException, ParserConfigurationException, URISyntaxException, SOAPRequestError { ProcessingException exception = mock(ProcessingException.class); when(webResourceBuilder.post(any(Entity.class))).thenThrow(exception); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http: try { soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); fail("Exception should have been thrown"); } catch (ProcessingException e) { assertThat(e).isEqualTo(exception); } } @Test public void makePost_checkSOAPRequestErrorIsThrownWhenNotValidXML() throws Exception { when(webResourceBuilder.post(any(Entity.class))).thenReturn(response); when(response.readEntity(Document.class)).thenThrow(new BadRequestException()); when(response.getStatus()).thenReturn(200); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http: try { soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); fail("Exception should have been thrown"); } catch (SOAPRequestError ignored) { } finally { verify(response).readEntity(Document.class); } } @Test public void makePost_aSuccessfulRequest() throws IOException, SAXException, ParserConfigurationException, URISyntaxException, SOAPRequestError { when(response.getStatus()).thenReturn(200); when(webResourceBuilder.post(any(Entity.class))).thenReturn(response); Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>"); URI matchingServiceUri = new URI("http: final Element element = soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri); assertThat(element).isEqualTo(soapElement); }
### Question: TimeoutEvaluator { public void hasAttributeQueryTimedOut(AttributeQueryContainerDto queryContainerDto) { DateTime timeout = queryContainerDto.getAttributeQueryClientTimeOut(); DateTime timeOfCheck = DateTime.now(); if(timeout.isBefore(timeOfCheck)){ Duration duration = new Duration(timeout, timeOfCheck); throw new AttributeQueryTimeoutException(MessageFormat.format("Attribute Query timed out by {0} seconds.", duration.getStandardSeconds())); } } void hasAttributeQueryTimedOut(AttributeQueryContainerDto queryContainerDto); }### Answer: @Test(expected = AttributeQueryTimeoutException.class) public void hasAttributeQueryTimedOut_shouldThrowExceptionIfRequestIsTimedOut() { DateTimeFreezer.freezeTime(); AttributeQueryContainerDto queryWithTimeoutInPast = anAttributeQueryContainerDto(anAttributeQuery().build()) .withAttributeQueryClientTimeout(DateTime.now().minusSeconds(20)) .build(); TimeoutEvaluator timeoutEvaluator = new TimeoutEvaluator(); timeoutEvaluator.hasAttributeQueryTimedOut(queryWithTimeoutInPast); } @Test public void hasAttributeQueryTimedOut_shouldDoNothingIfRequestIsNotTimedOut() { DateTimeFreezer.freezeTime(); AttributeQueryContainerDto queryWithTimeoutInFuture = anAttributeQueryContainerDto(anAttributeQuery().build()) .withAttributeQueryClientTimeout(DateTime.now().plusSeconds(20)) .build(); TimeoutEvaluator timeoutEvaluator = new TimeoutEvaluator(); timeoutEvaluator.hasAttributeQueryTimedOut(queryWithTimeoutInFuture); }
### Question: CountryMatchingServiceRequestGeneratorResource { @POST @Timed public Response generateAttributeQuery(final EidasAttributeQueryRequestDto dto) { return Response.ok().entity(service.generate(dto)).build(); } @Inject CountryMatchingServiceRequestGeneratorResource(CountryMatchingServiceRequestGeneratorService service); @POST @Timed Response generateAttributeQuery(final EidasAttributeQueryRequestDto dto); }### Answer: @Test public void generateAttributeQueryIsSuccessful() { resource.generateAttributeQuery(eidasAttributeQueryRequestDto); verify(service).generate(eidasAttributeQueryRequestDto); verifyNoMoreInteractions(service); }
### Question: ResponseAssertionsFromCountryValidator { public void validate(ValidatedResponse validatedResponse, Assertion validatedIdentityAssertion) { assertionValidator.validateEidas( validatedIdentityAssertion, validatedResponse.getInResponseTo(), expectedRecipientId ); if (validatedResponse.isSuccess()) { if (validatedIdentityAssertion.getAuthnStatements().size() > 1) { SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.multipleAuthnStatements(); throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel()); } authnStatementAssertionValidator.validate(validatedIdentityAssertion); eidasAttributeStatementAssertionValidator.validate(validatedResponse, validatedIdentityAssertion); authnResponseIssuerValidator.validate(validatedResponse, validatedIdentityAssertion); } } ResponseAssertionsFromCountryValidator( IdentityProviderAssertionValidator assertionValidator, EidasAttributeStatementAssertionValidator eidasAttributeStatementAssertionValidator, AuthnStatementAssertionValidator authnStatementAssertionValidator, EidasAuthnResponseIssuerValidator authnResponseIssuerValidator, String expectedRecipientId); void validate(ValidatedResponse validatedResponse, Assertion validatedIdentityAssertion); }### Answer: @Test(expected = SamlTransformationErrorException.class) public void shouldThrowIfMultipleAuthnStatements() { when(assertion.getAuthnStatements()).thenReturn(List.of(authnStatement, authnStatement)); validator.validate(validatedResponse, assertion); } @Test public void shouldValidateAssertion() { validator.validate(validatedResponse, assertion); verify(assertionValidator).validateEidas(assertion, validatedResponse.getInResponseTo(), EXPECTED_RECIPIENT_ID); verify(authnStatementAssertionValidator).validate(assertion); verify(eidasAttributeStatementAssertionValidator).validate(validatedResponse, assertion); } @Test public void shouldNotValidateAssertionContentsIfResponseIsFailure() { when(validatedResponse.isSuccess()).thenReturn(false); validator.validate(validatedResponse, assertion); verifyNoInteractions(authnStatementAssertionValidator, eidasAttributeStatementAssertionValidator); } @Test public void validateIssuer() { validator.validate(validatedResponse, assertion); verify(authnResponseIssuerValidator).validate(validatedResponse, assertion); verifyNoMoreInteractions(authnResponseIssuerValidator); }
### Question: ExceptionAuditor { public boolean auditException(ApplicationException exception, Optional<SessionId> sessionId) { boolean isAudited = exception.isAudited(); if (!isAudited && exception.requiresAuditing()) { EventDetails eventDetails = new EventDetails( downstream_uri, exception.getUri().orElse(URI.create("uri-not-present")).toASCIIString()); eventSinkMessageSender.audit( exception, exception.getErrorId(), sessionId.orElse(SessionId.NO_SESSION_CONTEXT_IN_ERROR), eventDetails); isAudited = true; } return isAudited; } @Inject ExceptionAuditor(EventSinkMessageSender eventSinkMessageSender); boolean auditException(ApplicationException exception, Optional<SessionId> sessionId); }### Answer: @Test public void shouldAuditUnauditedException() throws Exception { DateTime expectedTimestamp = DateTime.now(); DateTimeFreezer.freezeTime(expectedTimestamp); final UUID errorId = UUID.randomUUID(); ApplicationException exception = createUnauditedException( ExceptionType.DUPLICATE_SESSION, errorId, URI.create("/some-uri") ); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); ArgumentCaptor<EventDetails> argumentCaptor = ArgumentCaptor.forClass(EventDetails.class); verify(eventSinkMessageSender).audit(eq(exception), eq(errorId), eq(SESSION_ID), argumentCaptor.capture()); final EventDetails event = argumentCaptor.getValue(); assertThat(event.getKey()).isEqualTo(downstream_uri); assertThat(event.getValue()).isEqualTo(exception.getUri().get().toASCIIString()); } @Test public void shouldNotAuditAlreadyAuditedException() throws Exception { final UUID errorId = UUID.randomUUID(); ApplicationException exception = createAuditedException(ExceptionType.DUPLICATE_SESSION, errorId); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); verify(eventSinkMessageSender, never()).audit( any(Exception.class), any(UUID.class), any(SessionId.class), any(EventDetails.class) ); } @Test public void shouldNotAuditUnauditedExceptionIfItDoesNotRequireAuditing() { ApplicationException exception = createUnauditedExceptionThatShouldNotBeAudited(); exceptionAuditor.auditException(exception, Optional.of(SESSION_ID)); verify(eventSinkMessageSender, never()).audit(any(Exception.class), any(UUID.class), any(SessionId.class), any(EventDetails.class)); } @Test public void shouldAuditWithNoSessionContextIfSessionIdIsNotPresent() { final UUID errorId = UUID.randomUUID(); ApplicationException exception = createUnauditedException( ExceptionType.DUPLICATE_SESSION, errorId, URI.create("/some-uri") ); exceptionAuditor.auditException(exception, Optional.empty()); verify(eventSinkMessageSender).audit(eq(exception), eq(errorId), eq(SessionId.NO_SESSION_CONTEXT_IN_ERROR), any(EventDetails.class)); }
### Question: ResponseFromCountryValidator extends EncryptedResponseFromIdpValidator<CountryAuthenticationStatus.Status> { protected void validateAssertionPresence(Response response) { boolean responseWasSuccessful = response.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS); if (responseWasSuccessful && !response.getAssertions().isEmpty()) { SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.unencryptedAssertion(); throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel()); } if (responseWasSuccessful && response.getEncryptedAssertions().isEmpty()) { SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.missingSuccessUnEncryptedAssertions(); throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel()); } if (!responseWasSuccessful && !response.getEncryptedAssertions().isEmpty()) { SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.nonSuccessHasUnEncryptedAssertions(); throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel()); } if (responseWasSuccessful && response.getEncryptedAssertions().size() != 1) { SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.unexpectedNumberOfAssertions(1, response.getEncryptedAssertions().size()); throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel()); } } ResponseFromCountryValidator(SamlStatusToCountryAuthenticationStatusCodeMapper samlStatusToCountryAuthenticationStatusCodeMapper); }### Answer: @Test public void shouldThrowIfResponseIsSuccessfulAndHasUnencryptedAssertions() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Response has unencrypted assertion."); when(response.getAssertions()).thenReturn(List.of(assertion)); validator.validateAssertionPresence(response); } @Test public void shouldNotThrowIfResponseIsNotSuccessfulAndHasUnencryptedAssertions() { when(statusCode.getValue()).thenReturn(StatusCode.AUTHN_FAILED); validator.validateAssertionPresence(response); } @Test public void shouldThrowIfResponseIsSuccessfulButHasNoEncryptedAssertions() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Success response has no unencrypted assertions."); when(response.getEncryptedAssertions()).thenReturn(Collections.emptyList()); validator.validateAssertionPresence(response); } @Test public void shouldThrowIfResponseNotSuccessfulButHasEncryptedAssertions() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Non-success response has unencrypted assertions. Should contain no assertions."); when(statusCode.getValue()).thenReturn(StatusCode.AUTHN_FAILED); when(response.getEncryptedAssertions()).thenReturn(List.of(encryptedAssertion)); validator.validateAssertionPresence(response); } @Test public void shouldThrowIfResponseIsSuccessfulButHasMultipleEncryptedAssertions() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Response expected to contain 1 assertions. 2 assertion(s) found."); when(response.getEncryptedAssertions()).thenReturn(List.of(encryptedAssertion, encryptedAssertion)); validator.validateAssertionPresence(response); }
### Question: EidasAuthnResponseIssuerValidator { public void validate(ValidatedResponse validatedResponse, Assertion validatedIdentityAssertion) { if ( !Objects.equals(validatedResponse.getIssuer().getFormat(), validatedIdentityAssertion.getIssuer().getFormat()) ) { throw EidasProfileValidationSpecification.authnResponseAssertionIssuerFormatMismatch( validatedResponse.getIssuer().getFormat(), validatedIdentityAssertion.getIssuer().getFormat() ); } if ( !Objects.equals(validatedResponse.getIssuer().getValue(), validatedIdentityAssertion.getIssuer().getValue()) ) { throw EidasProfileValidationSpecification.authnResponseAssertionIssuerValueMismatch( validatedResponse.getIssuer().getValue(), validatedIdentityAssertion.getIssuer().getValue() ); } } void validate(ValidatedResponse validatedResponse, Assertion validatedIdentityAssertion); }### Answer: @Test public void validationSucceedsWhenIssuerMatches() { when(responseIssuer.getFormat()).thenReturn("issuerFormat"); when(assertionIssuer.getFormat()).thenReturn("issuerFormat"); when(responseIssuer.getValue()).thenReturn("issuerValue"); when(assertionIssuer.getValue()).thenReturn("issuerValue"); validator.validate(validatedResponse, assertion); } @Test public void validationFailsForDifferentIssuerFormats() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Authn Response issuer format [theResponseIssuerFormat] does not match the assertion issuer format [aDifferentAssertionIssuerFormat]"); when(responseIssuer.getFormat()).thenReturn("theResponseIssuerFormat"); when(assertionIssuer.getFormat()).thenReturn("aDifferentAssertionIssuerFormat"); validator.validate(validatedResponse, assertion); } @Test public void validationFailsForDifferentIssuerValues() { exception.expect(SamlTransformationErrorException.class); exception.expectMessage("Authn Response issuer [theResponseIssuerValue] does not match the assertion issuer [aDifferentAssertionIssuerValue]"); when(responseIssuer.getFormat()).thenReturn("issuerFormat"); when(assertionIssuer.getFormat()).thenReturn("issuerFormat"); when(responseIssuer.getValue()).thenReturn("theResponseIssuerValue"); when(assertionIssuer.getValue()).thenReturn("aDifferentAssertionIssuerValue"); validator.validate(validatedResponse, assertion); }
### Question: CountrySingleSignOnServiceHelper { public URI getSingleSignOn(String entityId) { MetadataResolver metadataResolver = metadataResolverRepository.getMetadataResolver(entityId) .orElseThrow(() -> ApplicationException.createUnauditedException(ExceptionType.METADATA_PROVIDER_EXCEPTION, UUID.randomUUID(), new RuntimeException(format("no metadata resolver for EU Member State: {0}", entityId))) ); EntityDescriptor idpEntityDescriptor; try { CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion(entityId)); idpEntityDescriptor = metadataResolver.resolveSingle(criteria); } catch (ResolverException e) { LOG.error(format("Exception when accessing metadata: {0}", e)); throw new RuntimeException(e); } if (idpEntityDescriptor != null) { final IDPSSODescriptor idpssoDescriptor = idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS); final List<SingleSignOnService> singleSignOnServices = idpssoDescriptor.getSingleSignOnServices(); if (singleSignOnServices.isEmpty()) { LOG.error(format("No singleSignOnServices present for IDP entityId: {0}", entityId)); } else { if (singleSignOnServices.size() > 1) { LOG.warn(format("More than one singleSignOnService present: {0} for {1}", singleSignOnServices.size(), entityId)); } return URI.create(singleSignOnServices.get(0).getLocation()); } } throw ApplicationException.createUnauditedException(ExceptionType.NOT_FOUND, UUID.randomUUID(), new RuntimeException(format("no entity descriptor for EU Member State: {0}", entityId))); } @Inject CountrySingleSignOnServiceHelper(EidasMetadataResolverRepository metadataResolverRepository); URI getSingleSignOn(String entityId); }### Answer: @Test public void getSingleSignOn() throws Exception { SingleSignOnServiceBuilder singleSignOnServiceBuilder = new SingleSignOnServiceBuilder(); SingleSignOnService singleSignOnService = singleSignOnServiceBuilder.buildObject(); singleSignOnService.setLocation("http: IDPSSODescriptorBuilder idpssoDescriptorBuilder = new IDPSSODescriptorBuilder(); IDPSSODescriptor idpssoDescriptor = idpssoDescriptorBuilder.buildObject(); idpssoDescriptor.getSingleSignOnServices().add(singleSignOnService); idpssoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); EntityDescriptorBuilder entityDescriptorBuilder = new EntityDescriptorBuilder(); EntityDescriptor entityDescriptor = entityDescriptorBuilder.buildObject(); entityDescriptor.setEntityID("an-entity-id"); entityDescriptor.getRoleDescriptors().add(idpssoDescriptor); EidasMetadataResolverRepository eidasMetadataResolverRepository = mock(EidasMetadataResolverRepository.class); MetadataResolver metadataResolver = mock(MetadataResolver.class); when(eidasMetadataResolverRepository.getMetadataResolver(any())).thenReturn(Optional.of(metadataResolver)); CountrySingleSignOnServiceHelper service = new CountrySingleSignOnServiceHelper(eidasMetadataResolverRepository); when(metadataResolver.resolveSingle(new CriteriaSet(new EntityIdCriterion(entityDescriptor.getEntityID())))).thenReturn(entityDescriptor); URI singleSignOnUri = service.getSingleSignOn(entityDescriptor.getEntityID()); assertThat(singleSignOnUri.toString()).isEqualTo(singleSignOnService.getLocation()); verify(metadataResolver).resolveSingle(any(CriteriaSet.class)); }
### Question: IdpSingleSignOnServiceHelper { public URI getSingleSignOn(String entityId) { EntityDescriptor idpEntityDescriptor; try { CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion(entityId)); idpEntityDescriptor = metadataProvider.resolveSingle(criteria); } catch (ResolverException e) { LOG.error(format("Exception when accessing metadata: {0}", e)); throw new RuntimeException(e); } if(idpEntityDescriptor!=null) { final IDPSSODescriptor idpssoDescriptor = idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS); final List<SingleSignOnService> singleSignOnServices = idpssoDescriptor.getSingleSignOnServices(); if (singleSignOnServices.isEmpty()) { LOG.error(format("No singleSignOnServices present for IDP entityId: {0}", entityId)); } else { if (singleSignOnServices.size() > 1) { LOG.warn(format("More than one singleSignOnService present: {0} for {1}", singleSignOnServices.size(), entityId)); } return URI.create(singleSignOnServices.get(0).getLocation()); } } throw ApplicationException.createUnauditedException(ExceptionType.NOT_FOUND, UUID.randomUUID(), new RuntimeException(format("no entity descriptor for IDP: {0}", entityId))); } @Inject IdpSingleSignOnServiceHelper(@Named("VerifyMetadataResolver") MetadataResolver metadataProvider); URI getSingleSignOn(String entityId); }### Answer: @Test public void shouldReturnSSOUriForIDP() { final URI singleSignOn = idpSingleSignOnServiceHelper.getSingleSignOn(idpEntityId); assertThat(singleSignOn).isEqualTo(idpSSOUri); } @Test public void shouldThrowExceptionIfIDPIsNotContainedInMetadata() { try { idpSingleSignOnServiceHelper.getSingleSignOn("thisIdpDoesNotExist"); fail("should have thrown exception"); } catch (ApplicationException e) { assertThat(e.getExceptionType()).isEqualTo(ExceptionType.NOT_FOUND); } } @Test(expected = RuntimeException.class) public void shouldThrowExceptionWhenMetadataProviderThrowsOne() throws ResolverException { MetadataResolver metadataResolver = mock(MetadataResolver.class); when(metadataResolver.resolveSingle(any(CriteriaSet.class))).thenThrow(new ResolverException()); idpSingleSignOnServiceHelper = new IdpSingleSignOnServiceHelper(metadataResolver); idpSingleSignOnServiceHelper.getSingleSignOn(idpEntityId); }
### Question: IdpAuthnRequestGeneratorService { public SamlRequestDto generateSaml(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto) { URI ssoUri = idpSingleSignOnServiceHelper.getSingleSignOn(idaAuthnRequestFromHubDto.getIdpEntityId()); IdaAuthnRequestFromHub idaAuthnRequestFromHub = idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(idaAuthnRequestFromHubDto, ssoUri, hubEntityId); String request = idaRequestStringTransformer.apply(idaAuthnRequestFromHub); return new SamlRequestDto(request, ssoUri); } @Inject IdpAuthnRequestGeneratorService(IdpSingleSignOnServiceHelper idpSingleSignOnServiceHelper, Function<IdaAuthnRequestFromHub, String> idaRequestStringTransformer, IdaAuthnRequestTranslator idaAuthnRequestTranslator, @Named("HubEntityId") String hubEntityId); SamlRequestDto generateSaml(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto); }### Answer: @Test public void get_sendAuthnRequest_shouldReturnDtoWithSamlRequestAndPostLocation(){ String idpEntityId = UUID.randomUUID().toString(); IdaAuthnRequestFromHubDto dto = new IdaAuthnRequestFromHubDto("1", null, Optional.of(false), null, idpEntityId, false); String samlRequest = "samlRequest"; URI ssoUri = UriBuilder.fromPath(UUID.randomUUID().toString()).build(); when(idaAuthnRequestFromHubStringTransformer.apply(ArgumentMatchers.any())).thenReturn(samlRequest); when(idpSingleSignOnServiceHelper.getSingleSignOn(idpEntityId)).thenReturn(ssoUri); when(idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(dto, ssoUri, HUB_ENTITY_ID)).thenReturn(null); final SamlRequestDto output = idpAuthnRequestGeneratorService.generateSaml(dto); assertThat(output.getSamlRequest()).isEqualTo(samlRequest); assertThat(output.getSsoUri()).isEqualTo(ssoUri); }
### Question: IdaAuthnRequestTranslator { public IdaAuthnRequestFromHub getIdaAuthnRequestFromHub(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto, URI ssoUri, String hubEntityId) { List<AuthnContext> levelsOfAssurance = idaAuthnRequestFromHubDto.getLevelsOfAssurance(); AuthnContextComparisonTypeEnumeration comparisonType; if (idaAuthnRequestFromHubDto.getUseExactComparisonType()) { comparisonType = EXACT; } else { comparisonType = MINIMUM; if (levelsOfAssurance.size() == 1) { levelsOfAssurance = Arrays.asList(levelsOfAssurance.get(0), levelsOfAssurance.get(0)); } } return createRequestToSendFromHub( idaAuthnRequestFromHubDto.getId(), levelsOfAssurance, idaAuthnRequestFromHubDto.getForceAuthentication(), idaAuthnRequestFromHubDto.getSessionExpiryTimestamp(), ssoUri, comparisonType, hubEntityId); } @Inject IdaAuthnRequestTranslator(); IdaAuthnRequestFromHub getIdaAuthnRequestFromHub(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto, URI ssoUri, String hubEntityId); }### Answer: @Test public void shouldUseExactComparisonTypeAndLevelsOfAssurance(){ IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto = aRequestDto(singletonList(AuthnContext.LEVEL_2), true); IdaAuthnRequestFromHub idaAuthnRequestFromHub = idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(idaAuthnRequestFromHubDto, URI.create("http: assertThat(idaAuthnRequestFromHub.getComparisonType()).isEqualTo(AuthnContextComparisonTypeEnumeration.EXACT); assertThat(idaAuthnRequestFromHub.getLevelsOfAssurance()).containsSequence(AuthnContext.LEVEL_2); } @Test public void shouldUseMinimumComparisonTypeAndDuplicateSingleLevelOfAssurance(){ IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto = aRequestDto(singletonList(AuthnContext.LEVEL_2), false); IdaAuthnRequestFromHub idaAuthnRequestFromHub = idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(idaAuthnRequestFromHubDto, URI.create("http: assertThat(idaAuthnRequestFromHub.getComparisonType()).isEqualTo(AuthnContextComparisonTypeEnumeration.MINIMUM); assertThat(idaAuthnRequestFromHub.getLevelsOfAssurance()).containsSequence(AuthnContext.LEVEL_2, AuthnContext.LEVEL_2); } @Test public void shouldUseMinimumComparisonTypeAndLevelsOfAssuranceAsIs(){ IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto = aRequestDto(asList(AuthnContext.LEVEL_1, AuthnContext.LEVEL_2), false); IdaAuthnRequestFromHub idaAuthnRequestFromHub = idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(idaAuthnRequestFromHubDto, URI.create("http: assertThat(idaAuthnRequestFromHub.getComparisonType()).isEqualTo(AuthnContextComparisonTypeEnumeration.MINIMUM); assertThat(idaAuthnRequestFromHub.getLevelsOfAssurance()).containsSequence(AuthnContext.LEVEL_1, AuthnContext.LEVEL_2); } @Test public void shouldUseMinimumComparisonTypeAndSendDuplicateLOAs(){ IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto = aRequestDto(singletonList(AuthnContext.LEVEL_2), false); IdaAuthnRequestFromHub idaAuthnRequestFromHub = idaAuthnRequestTranslator.getIdaAuthnRequestFromHub(idaAuthnRequestFromHubDto, URI.create("http: assertThat(idaAuthnRequestFromHub.getComparisonType()).isEqualTo(AuthnContextComparisonTypeEnumeration.MINIMUM); assertThat(idaAuthnRequestFromHub.getLevelsOfAssurance()).containsSequence(AuthnContext.LEVEL_2, AuthnContext.LEVEL_2); }
### Question: CountryMatchingServiceRequestGeneratorService { public AttributeQueryContainerDto generate(EidasAttributeQueryRequestDto dto) { HubEidasAttributeQueryRequest hubEidasAttributeQueryRequest = eidasAttributeQueryRequestBuilder.createHubAttributeQueryRequest(dto); return eidasAttributeQueryGenerator.newCreateAttributeQueryContainer( hubEidasAttributeQueryRequest, dto.getAttributeQueryUri(), dto.getMatchingServiceEntityId(), dto.getMatchingServiceRequestTimeOut(), dto.isOnboarding()); } @Inject CountryMatchingServiceRequestGeneratorService( HubEidasAttributeQueryRequestBuilder eidasAttributeQueryRequestBuilder, AttributeQueryGenerator<HubEidasAttributeQueryRequest> eidasAttributeQueryGenerator); AttributeQueryContainerDto generate(EidasAttributeQueryRequestDto dto); }### Answer: @Test public void shouldGenerateAttributeQueryContainerDto() { service.generate(EIDAS_ATTRIBUTE_QUERY_REQUEST_DTO); verify(eidasAttributeQueryRequestBuilder).createHubAttributeQueryRequest(EIDAS_ATTRIBUTE_QUERY_REQUEST_DTO); verify(eidasAttributeQueryGenerator).newCreateAttributeQueryContainer( HUB_EIDAS_ATTRIBUTE_QUERY_REQUEST, MSA_URI, MATCHING_SERVICE_ENTITY_ID, MATCHING_SERVICE_REQUEST_TIMEOUT, IS_ONBOARDING); }
### Question: RpAuthnResponseGeneratorService { public AuthnResponseFromHubContainerDto generate(ResponseFromHubDto responseFromHub) { try{ return createSuccessResponse(responseFromHub); } catch (Exception e) { throw new UnableToGenerateSamlException("Unable to generate RP authn response", e, Level.ERROR); } } @Inject RpAuthnResponseGeneratorService(OutboundResponseFromHubToResponseTransformerFactory outboundResponseFromHubToResponseTransformerFactory, @Named("HubEntityId") String hubEntityId, final AssignableEntityToEncryptForLocator entityToEncryptForLocator); AuthnResponseFromHubContainerDto generate(ResponseFromHubDto responseFromHub); AuthnResponseFromHubContainerDto generate(AuthnResponseFromCountryContainerDto responseFromHub); }### Answer: @Test public void generateShouldReturnAnAuthnResponseFromHubContainerDtoFromAuthnResponseFromCountryContainerDto() { OutboundAuthnResponseFromCountryContainerToStringFunction transformerMock = mock(OutboundAuthnResponseFromCountryContainerToStringFunction.class); when(outboundResponseFromHubToResponseTransformerFactory.getCountryTransformer()).thenReturn(transformerMock); when(transformerMock.apply(countryContainer)).thenReturn(TRANSFORMED_SAML_RESPONSE); AuthnResponseFromHubContainerDto hubContainer = generatorService.generate(countryContainer); assertThat(hubContainer.getSamlResponse()).isEqualTo(TRANSFORMED_SAML_RESPONSE); assertThat(hubContainer.getPostEndpoint()).isEqualTo(POST_ENDPOINT); assertThat(hubContainer.getRelayState().get()).isEqualTo(RELAY_STATE); assertThat(hubContainer.getResponseId()).isEqualTo(RESPONSE_ID); } @Test(expected = UnableToGenerateSamlException.class) public void generateWithAuthnResponseFromCountryContainerDtoShouldThrowUnableToGenerateSamlExceptionIfExceptionIsCaught() { when(outboundResponseFromHubToResponseTransformerFactory.getCountryTransformer()).thenThrow(NullPointerException.class); generatorService.generate(countryContainer); }
### Question: RpAuthnRequestTranslatorService { public TranslatedAuthnRequestDto translate(SamlRequestWithAuthnRequestInformationDto samlRequestWithAuthnRequestInformationDto) { AuthnRequest authnRequest = stringToAuthnRequestTransformer.apply(samlRequestWithAuthnRequestInformationDto.getSamlMessage()); MdcHelper.addContextToMdc(authnRequest.getID(), authnRequest.getIssuer().getValue()); AuthnRequestFromRelyingParty authnRequestFromRelyingParty = authnRequestToIdaRequestFromRelyingPartyTransformer.apply(authnRequest); if (authnRequestFromRelyingParty.getVerifyServiceProviderVersion().isPresent()) { LOG.info(String.format( "Issuer %s uses VSP version %s", authnRequestFromRelyingParty.getIssuer(), authnRequestFromRelyingParty.getVerifyServiceProviderVersion().get() )); } UnknownMethodAlgorithmLogger.probeAuthnRequestForMethodAlgorithm(authnRequestFromRelyingParty); return new TranslatedAuthnRequestDto( authnRequestFromRelyingParty.getId(), authnRequestFromRelyingParty.getIssuer(), authnRequestFromRelyingParty.getForceAuthentication(), authnRequestFromRelyingParty.getAssertionConsumerServiceUrl(), authnRequestFromRelyingParty.getAssertionConsumerServiceIndex()); } @Inject RpAuthnRequestTranslatorService( StringToOpenSamlObjectTransformer<AuthnRequest> stringToAuthnRequestTransformer, AuthnRequestToIdaRequestFromRelyingPartyTransformer authnRequestToIdaRequestFromRelyingPartyTransformer ); TranslatedAuthnRequestDto translate(SamlRequestWithAuthnRequestInformationDto samlRequestWithAuthnRequestInformationDto); }### Answer: @Test public void shouldTranslateSamlAuthnRequest() throws Exception { RpAuthnRequestTranslatorService service = new RpAuthnRequestTranslatorService(stringToAuthnRequestTransformer, samlAuthnRequestToAuthnRequestFromRelyingPartyTransformer); boolean forceAuthentication = true; String id = UUID.randomUUID().toString(); String issuer = UUID.randomUUID().toString(); URI assertionConsumerServiceUrl = URI.create("http: int assertionConsumerServiceIndex = 1; Signature signature = aSignature().withSignatureAlgorithm(SIGNATURE_ALGORITHM).build(); ((SignatureImpl) signature).setXMLSignature(BuilderHelper.createXMLSignature(SIGNATURE_ALGORITHM, new DigestSHA256())); SamlRequestWithAuthnRequestInformationDto samlRequestWithAuthnRequestInformationDto = SamlAuthnRequestDtoBuilder.aSamlAuthnRequest() .withId(id) .withIssuer(issuer) .withForceAuthentication(forceAuthentication) .withAssertionConsumerIndex(assertionConsumerServiceIndex) .withPublicCert(TEST_RP_PUBLIC_SIGNING_CERT) .withPrivateKey(TEST_RP_PRIVATE_SIGNING_KEY) .build(); AuthnRequest authnRequest = AuthnRequestBuilder.anAuthnRequest().build(); TranslatedAuthnRequestDto expected = TranslatedAuthnRequestDtoBuilder.aTranslatedAuthnRequest() .withId(id) .withIssuer(issuer) .withForceAuthentication(forceAuthentication) .withAssertionConsumerServiceUrl(assertionConsumerServiceUrl) .withAssertionConsumerServiceIndex(assertionConsumerServiceIndex) .build(); AuthnRequestFromRelyingParty intermediateBlah = anAuthnRequestFromRelyingParty() .withId(id) .withIssuer(issuer) .withForceAuthentication(forceAuthentication) .withAssertionConsumerServiceUrl(assertionConsumerServiceUrl) .withAssertionConsumerServiceIndex(assertionConsumerServiceIndex) .withSignature(signature) .build(); when(stringToAuthnRequestTransformer.apply(samlRequestWithAuthnRequestInformationDto.getSamlMessage())).thenReturn(authnRequest); when(samlAuthnRequestToAuthnRequestFromRelyingPartyTransformer.apply(authnRequest)).thenReturn(intermediateBlah); TranslatedAuthnRequestDto actual = service.translate(samlRequestWithAuthnRequestInformationDto); assertThat(actual).isEqualToComparingFieldByField(expected); }
### Question: CountryAuthnResponseTranslatorService { public InboundResponseFromCountry translate(SamlAuthnResponseTranslatorDto samlResponseDto) { Response response = unmarshall(samlResponseDto); ValidatedResponse validatedResponse = validateResponse(response); List<Assertion> assertions = assertionDecrypter.decryptAssertions(validatedResponse); Optional<Assertion> validatedIdentityAssertion = validateAssertion(validatedResponse, assertions); List<String> base64EncryptedSecretKeys; Optional<CountrySignedResponseContainer> countrySignedResponseContainer; if (areAssertionsUnsigned(assertions)) { base64EncryptedSecretKeys = assertionDecrypter.getReEncryptedKeys( validatedResponse, secretKeyEncrypter, samlResponseDto.getMatchingServiceEntityId() ); countrySignedResponseContainer = Optional.of( new CountrySignedResponseContainer( samlResponseDto.getSamlResponse(), base64EncryptedSecretKeys, response.getIssuer().getValue() ) ); } else { countrySignedResponseContainer = Optional.empty(); } return toModel(validatedResponse, validatedIdentityAssertion, samlResponseDto.getMatchingServiceEntityId(), countrySignedResponseContainer); } @Inject CountryAuthnResponseTranslatorService(StringToOpenSamlObjectTransformer<Response> stringToOpenSamlResponseTransformer, ResponseFromCountryValidator responseFromCountryValidator, ResponseAssertionsFromCountryValidator responseAssertionFromCountryValidator, DestinationValidator validateSamlResponseIssuedByIdpDestination, AssertionDecrypter assertionDecrypter, SecretKeyEncrypter secretKeyEncrypter, AssertionBlobEncrypter assertionBlobEncrypter, EidasValidatorFactory eidasValidatorFactory, PassthroughAssertionUnmarshaller passthroughAssertionUnmarshaller, CountryAuthenticationStatusUnmarshaller countryAuthenticationStatusUnmarshaller); InboundResponseFromCountry translate(SamlAuthnResponseTranslatorDto samlResponseDto); }### Answer: @Test public void shouldExtractAuthnStatementAssertionDetailsSignedAssertions() throws Exception { setupSigned(); InboundResponseFromCountry result = service.translate(samlAuthnResponseTranslatorDto); assertThat(result.getIssuer()).isEqualTo(responseIssuer); assertThat(result.getStatus().isPresent()).isTrue(); assertThat(result.getStatus().get()).isEqualTo(successStatus); assertThat(result.getStatusMessage()).isNotPresent(); assertThat(result.getLevelOfAssurance().isPresent()).isTrue(); assertThat(result.getLevelOfAssurance().get()).isEqualTo(LEVEL_2); assertThat(result.getPersistentId().isPresent()).isTrue(); assertThat(result.getPersistentId().get()).isEqualTo(persistentIdName); assertThat(result.getEncryptedIdentityAssertionBlob().isPresent()).isTrue(); assertThat(result.getEncryptedIdentityAssertionBlob().get()).isEqualTo(identityUnderlyingAssertionBlob); } @Test public void shouldExtractAuthnStatementAssertionDetailsUnsignedAssertions() throws Exception { setupUnsigned(); InboundResponseFromCountry result = service.translate(samlAuthnResponseTranslatorDto); assertThat(result.getCountrySignedResponseContainer().isPresent()).isTrue(); CountrySignedResponseContainer countrySignedResponseContainer = result.getCountrySignedResponseContainer().get(); assertThat(countrySignedResponseContainer.getBase64SamlResponse()).isEqualTo(samlResponse); assertThat(countrySignedResponseContainer.getCountryEntityId()).isEqualTo(responseIssuer); assertThat(countrySignedResponseContainer.getBase64encryptedKeys()).isEqualTo(List.of(reEncryptedKey)); }
### Question: CountryAuthnRequestGeneratorService { public SamlRequestDto generateSaml(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto) { URI ssoUri = idaAuthnRequestFromHubDto.getoverriddenSsoUrl() != null ? idaAuthnRequestFromHubDto.getoverriddenSsoUrl() : countrySingleSignOnServiceHelper.getSingleSignOn(idaAuthnRequestFromHubDto.getIdpEntityId()); EidasAuthnRequestFromHub eidasAuthnRequestFromHub = eidasAuthnRequestTranslator.getEidasAuthnRequestFromHub(idaAuthnRequestFromHubDto, ssoUri, hubEidasEntityId); String request = eidasRequestStringTransformer.apply(eidasAuthnRequestFromHub); return new SamlRequestDto(request, ssoUri); } @Inject CountryAuthnRequestGeneratorService(CountrySingleSignOnServiceHelper countrySingleSignOnServiceHelper, Function<EidasAuthnRequestFromHub, String> eidasRequestStringTransformer, EidasAuthnRequestTranslator eidasAuthnRequestTranslator, String hubEidasEntityId); SamlRequestDto generateSaml(IdaAuthnRequestFromHubDto idaAuthnRequestFromHubDto); }### Answer: @Test public void generateSamlRequest() { String theCountryEntityId = "theCountryEntityId"; IdaAuthnRequestFromHubDto dto = new IdaAuthnRequestFromHubDto("1", null, Optional.of(false), null, theCountryEntityId, false); URI ssoUri = UriBuilder.fromPath("/the-sso-uri").build(); String samlRequest = "samlRequest"; EidasAuthnRequestFromHub eidasAuthnRequestFromHub = new EidasAuthnRequestBuilder().buildFromHub(); when(eidasAuthnRequestFromHubStringTransformer.apply(any())).thenReturn(samlRequest); when(countrySingleSignOnServiceHelper.getSingleSignOn(theCountryEntityId)).thenReturn(ssoUri); when(eidasAuthnRequestTranslator.getEidasAuthnRequestFromHub(dto, ssoUri, HUB_ENTITY_ID)).thenReturn(eidasAuthnRequestFromHub); final SamlRequestDto output = service.generateSaml(dto); assertThat(output.getSamlRequest()).isEqualTo(samlRequest); assertThat(output.getSsoUri()).isEqualTo(ssoUri); verify(countrySingleSignOnServiceHelper).getSingleSignOn(theCountryEntityId); verify(eidasAuthnRequestFromHubStringTransformer).apply(any(EidasAuthnRequestFromHub.class)); verifyNoMoreInteractions(countrySingleSignOnServiceHelper, eidasAuthnRequestFromHubStringTransformer); } @Test public void generateSamlRequestWithOverriddenSsoUri() { String theCountryEntityId = "theCountryEntityId"; URI overriddenSsoURI = URI.create("http: IdaAuthnRequestFromHubDto dto = new IdaAuthnRequestFromHubDto("1", null, Optional.of(false), null, theCountryEntityId, false, overriddenSsoURI); String samlRequest = "samlRequest"; when(eidasAuthnRequestFromHubStringTransformer.apply(any())).thenReturn(samlRequest); final SamlRequestDto output = service.generateSaml(dto); assertThat(output.getSamlRequest()).isEqualTo(samlRequest); assertThat(output.getSsoUri()).isEqualTo(overriddenSsoURI); verifyNoMoreInteractions(countrySingleSignOnServiceHelper); }
### Question: SamlProxySamlTransformationErrorExceptionMapper extends AbstractContextExceptionMapper<SamlTransformationErrorException> { @Override protected Response handleException(SamlTransformationErrorException exception) { UUID errorId = UUID.randomUUID(); eventSinkMessageSender.audit(exception, errorId, getSessionId().orElse(SessionId.NO_SESSION_CONTEXT_IN_ERROR)); levelLogger.log(exception.getLogLevel(), exception, errorId); ErrorStatusDto auditedErrorStatus = ErrorStatusDto.createAuditedErrorStatus(errorId, getExceptionTypeForSamlException(exception)); return Response.status(Response.Status.BAD_REQUEST).entity(auditedErrorStatus).build(); } @Inject SamlProxySamlTransformationErrorExceptionMapper( Provider<HttpServletRequest> contextProvider, EventSinkMessageSender eventSinkMessageSender, LevelLoggerFactory<SamlProxySamlTransformationErrorExceptionMapper> levelLoggerFactory); }### Answer: @Test public void shouldLogToEventSinkWhenExceptionHasContextAndSessionId() throws Exception { TestSamlTransformationErrorException exception = new TestSamlTransformationErrorException("error", new RuntimeException(), Level.DEBUG); SessionId sessionId = SessionId.createNewSessionId(); when(httpServletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn(sessionId.getSessionId()); exceptionMapper.handleException(exception); verify(eventSinkMessageSender).audit(eq(exception), any(UUID.class), eq(sessionId)); } @Test public void shouldLogToEventSinkWhenExceptionHasContextAndNoSessionId() throws Exception { TestSamlTransformationErrorException exception = new TestSamlTransformationErrorException("error", new RuntimeException(), Level.DEBUG); exceptionMapper.handleException(exception); verify(eventSinkMessageSender).audit(eq(exception), any(UUID.class), eq(SessionId.NO_SESSION_CONTEXT_IN_ERROR)); } @Test public void shouldCreateAuditedErrorResponseForInvalidSaml() throws Exception { Response response = exceptionMapper.handleException(new TestSamlTransformationErrorException("error", new RuntimeException(), Level.DEBUG)); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML); } @Test public void shouldCreateAuditedErrorResponseForRequestTooOldError() throws Exception { Response response = exceptionMapper.handleException(new SamlRequestTooOldException("error", new RuntimeException(), Level.DEBUG)); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML_REQUEST_TOO_OLD); } @Test public void shouldLogExceptionAtCorrectLevel() throws Exception { Level logLevel = Level.DEBUG; TestSamlTransformationErrorException exception = new TestSamlTransformationErrorException("error", new RuntimeException(), logLevel); exceptionMapper.handleException(exception); verify(levelLogger).log(eq(logLevel), eq(exception), any(UUID.class)); }
### Question: IdpAssertionMetricsCollector { public void update(Assertion assertion) { String idpName = replaceNonAlphaNumericCharacters(assertion); String metricName = NOT_ON_OR_AFTER + idpName; Long maxNotOnOrAfter = findMaxNotOnOrAfter(assertion.getSubject().getSubjectConfirmations(), notOnOrAfterLatestMax.get(metricName)); notOnOrAfterLatestMax.put(metricName, maxNotOnOrAfter); updateMetricRegistry(metricName); } IdpAssertionMetricsCollector(MetricRegistry metricRegistry); void update(Assertion assertion); }### Answer: @Test public void shouldRegisterIdpNameFromAssertion() { MetricRegistry metricRegistry = new MetricRegistry(); IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry); Assertion anAssertion = anAssertion() .withIssuer(anIssuer().withIssuerId("testIdP").build()) .buildUnencrypted(); idpAssertionMetricsCollector.update(anAssertion); assertThat(metricRegistry.getGauges().keySet()).contains("notOnOrAfter.testIdP"); } @Test public void shouldNotRegisterIdpAlreadyExist() { MetricRegistry metricRegistry = mock(MetricRegistry.class); SortedMap<String, Gauge> gaugeMock= mock(SortedMap.class); when(gaugeMock.containsKey(any())).thenReturn(true); when(metricRegistry.getGauges()).thenReturn(gaugeMock); Assertion assertion = anAssertion() .withIssuer(anIssuer().withIssuerId("testIdP").build()) .buildUnencrypted(); IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry); idpAssertionMetricsCollector.update(assertion); verify(metricRegistry, times(0)).register(any(), any()); } @Test public void shouldCollectNotOnOrAfterValueFromAssertion() { DateTimeFreezer.freezeTime(); MetricRegistry metricRegistry = new MetricRegistry(); IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry); DateTime notOnOrAfter = DateTime.now().plusMinutes(15); Assertion anAssertion = anAssertion() .withIssuer(anIssuer().withIssuerId("testIdP").build()) .withSubject(aSubject().withSubjectConfirmation(aSubjectConfirmation() .withSubjectConfirmationData(aSubjectConfirmationData() .withNotOnOrAfter(notOnOrAfter) .build()) .build()) .build()) .buildUnencrypted(); idpAssertionMetricsCollector.update(anAssertion); Gauge actual = metricRegistry.getGauges().get("notOnOrAfter.testIdP"); assertThat(actual.getValue()).isEqualTo(15L); } @Test public void shouldGetMaxInNotOnOrAfterFromSubjectConfirmations() { DateTimeFreezer.freezeTime(); MetricRegistry metricRegistry = new MetricRegistry(); IdpAssertionMetricsCollector idpAssertionMetricsCollector = new IdpAssertionMetricsCollector(metricRegistry); DateTime notOnOrAfterSmaller = DateTime.now().plusMinutes(15); DateTime notOnOrAfterBigger = DateTime.now().plusMinutes(30); Assertion anAssertion = anAssertion() .withIssuer(anIssuer().withIssuerId("testIdP").build()) .withSubject(aSubject() .withSubjectConfirmation(aSubjectConfirmation() .withSubjectConfirmationData(aSubjectConfirmationData() .withNotOnOrAfter(notOnOrAfterSmaller) .build()) .build()) .withSubjectConfirmation(aSubjectConfirmation() .withSubjectConfirmationData(aSubjectConfirmationData() .withNotOnOrAfter(notOnOrAfterBigger) .build()) .build()) .build()) .buildUnencrypted(); idpAssertionMetricsCollector.update(anAssertion); Gauge actual = metricRegistry.getGauges().get("notOnOrAfter.testIdP"); assertThat(actual.getValue()).isEqualTo(30L); }
### Question: SplunkAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> { @Override public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, LayoutFactory<ILoggingEvent> layoutFactory, LevelFilterFactory<ILoggingEvent> levelFilterFactory, AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) { HttpEventCollectorLogbackAppender<ILoggingEvent> appender = new HttpEventCollectorLogbackAppender<>(); checkNotNull(context); appender.setUrl(url); appender.setToken(token); appender.setSource(source); appender.setSourcetype(sourceType); appender.setIndex(index); appender.setbatch_size_count(batchSizeCount.toString()); appender.setLayout(buildLayout(context, layoutFactory)); appender.addFilter(levelFilterFactory.build(threshold)); appender.setHttpProxyHost(System.getProperty("http.proxyHost")); appender.setHttpProxyPort(getProxyPortIntFromSystem()); appender.start(); return wrapAsync(appender, asyncAppenderFactory, context); } @Override Appender<ILoggingEvent> build(LoggerContext context, String applicationName, LayoutFactory<ILoggingEvent> layoutFactory, LevelFilterFactory<ILoggingEvent> levelFilterFactory, AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory); }### Answer: @Test public void buildReturnsAnAsyncAppender() throws Exception { SplunkAppenderFactory splunkAppenderFactory = mapper.readValue(jsonSplunkFactory.toString(), SplunkAppenderFactory.class); Appender<ILoggingEvent> appender = splunkAppenderFactory.build( new LoggerContext(), "appName", new DropwizardLayoutFactory(), new ThresholdLevelFilterFactory(), new AsyncLoggingEventAppenderFactory() ); assertThat(appender).isExactlyInstanceOf(AsyncAppender.class); }
### Question: NotOnOrAfterLogger { public static void logAssertionNotOnOrAfter(final Assertion assertion, String typeOfAssertion) { final String idp = assertion.getIssuer().getValue(); assertion.getSubject().getSubjectConfirmations() .forEach(subjectConfirmation -> { DateTime notOnOrAfter = subjectConfirmation.getSubjectConfirmationData().getNotOnOrAfter(); LOGGER.info(String.format("NotOnOrAfter in %s from %s is set to %s", typeOfAssertion, idp, notOnOrAfter.toString(dateTimeFormatter))); }); } static void logAssertionNotOnOrAfter(final Assertion assertion, String typeOfAssertion); }### Answer: @Test public void shouldLogNotOnOrAfterWithIdp() { DateTime notOnOrAfter = DateTime.now().withZone(DateTimeZone.UTC).plusHours(1); Assertion assertion = anAssertionWithNotOnOrAfter(notOnOrAfter); String typeOfAssertion = "assertionType"; NotOnOrAfterLogger.logAssertionNotOnOrAfter(assertion, typeOfAssertion); String expectedMessage = String.format("NotOnOrAfter in %s from %s is set to %s", typeOfAssertion, ISSUER_IDP, notOnOrAfter.toString(dateTimeFormatter)); verifyLog(mockAppender, captorLoggingEvent, expectedMessage); }
### Question: UnknownMethodAlgorithmLogger { public static void probeResponseForMethodAlgorithm(final InboundResponseFromIdp response) { if (response != null) { response.getSignature().ifPresent((signature) -> logMethodAlgorithm(Role.IDP, signature, Response.DEFAULT_ELEMENT_LOCAL_NAME) ); } } static void probeResponseForMethodAlgorithm(final InboundResponseFromIdp response); static void probeAssertionForMethodAlgorithm(final Assertion assertion, final String typeOfAssertion); static void probeAuthnRequestForMethodAlgorithm(final AuthnRequestFromRelyingParty authnRequest); static final String SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE; static final String SIGNATURE_ALGORITHM_MESSAGE; static final String DIGEST_ALGORITHM_MESSAGE; }### Answer: @Test public void shouldNotReportStrongAlgorithmsInIDPResponse() throws Exception { final InboundResponseFromIdp inboundResponseFromIdp = new InboundResponseFromIdp( ID, IN_RESPONSE_TO, ISSUER_IDP, ISSUE_INSTANT, NOT_ON_OR_AFTER, STATUS, signature, MATCHING_DATASET_ASSERTION, DESTINATION, AUTHN_STATEMENT_ASSERTION); UnknownMethodAlgorithmLogger.probeResponseForMethodAlgorithm(inboundResponseFromIdp); verify(mockAppender, times(0)).doAppend(captorLoggingEvent.capture()); } @Test public void shouldReportUnknownSignatureAlgorithmInIDPResponse() throws Exception { InboundResponseFromIdp inboundResponseFromIdp = new InboundResponseFromIdp( ID, IN_RESPONSE_TO, ISSUER_IDP, ISSUE_INSTANT, NOT_ON_OR_AFTER, STATUS, signatureWithUnknownSignatureAlgorithm, MATCHING_DATASET_ASSERTION, DESTINATION, AUTHN_STATEMENT_ASSERTION); UnknownMethodAlgorithmLogger.probeResponseForMethodAlgorithm(inboundResponseFromIdp); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_ALGORITHM_MESSAGE, IDP, SIGNATURE_RSA_SHA1_ID, Response.DEFAULT_ELEMENT_LOCAL_NAME)); } @Test public void shouldReportUnknownDigestAlgorithmInIDPResponse() throws Exception { InboundResponseFromIdp inboundResponseFromIdp = new InboundResponseFromIdp( ID, IN_RESPONSE_TO, ISSUER_IDP, ISSUE_INSTANT, NOT_ON_OR_AFTER, STATUS, signatureWithUnknownDigestAlgorithm, MATCHING_DATASET_ASSERTION, DESTINATION, AUTHN_STATEMENT_ASSERTION); UnknownMethodAlgorithmLogger.probeResponseForMethodAlgorithm(inboundResponseFromIdp); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.DIGEST_ALGORITHM_MESSAGE, IDP, DIGEST_SHA1_ID, Response.DEFAULT_ELEMENT_LOCAL_NAME)); } @Test public void shouldReportUnknownSignatureAndDigestAlgorithmsInIDPResponse() throws Exception { InboundResponseFromIdp inboundResponseFromIdp = new InboundResponseFromIdp( ID, IN_RESPONSE_TO, ISSUER_IDP, ISSUE_INSTANT, NOT_ON_OR_AFTER, STATUS, signatureWithUnknownSignatureAndDigestAlgorithms, MATCHING_DATASET_ASSERTION, DESTINATION, AUTHN_STATEMENT_ASSERTION); UnknownMethodAlgorithmLogger.probeResponseForMethodAlgorithm(inboundResponseFromIdp); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE, IDP, SIGNATURE_RSA_SHA1_ID, DIGEST_SHA1_ID, Response.DEFAULT_ELEMENT_LOCAL_NAME)); }
### Question: UnknownMethodAlgorithmLogger { public static void probeAssertionForMethodAlgorithm(final Assertion assertion, final String typeOfAssertion) { String prefixAssertion = typeOfAssertion + Assertion.DEFAULT_ELEMENT_LOCAL_NAME; if (assertion != null) { Signature signature = assertion.getSignature(); if (signature != null) { logMethodAlgorithm(Role.IDP, signature, prefixAssertion); } } } static void probeResponseForMethodAlgorithm(final InboundResponseFromIdp response); static void probeAssertionForMethodAlgorithm(final Assertion assertion, final String typeOfAssertion); static void probeAuthnRequestForMethodAlgorithm(final AuthnRequestFromRelyingParty authnRequest); static final String SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE; static final String SIGNATURE_ALGORITHM_MESSAGE; static final String DIGEST_ALGORITHM_MESSAGE; }### Answer: @Test public void shouldNotReportStrongAlgorithmsInIDPAssertion() throws Exception { Assertion authnStatementAssertion = anAssertion() .withIssuer(anIssuer().withIssuerId(ISSUER_IDP).build()) .buildUnencrypted(); UnknownMethodAlgorithmLogger.probeAssertionForMethodAlgorithm(authnStatementAssertion, AUTHN_STATEMENT); verify(mockAppender, times(0)).doAppend(captorLoggingEvent.capture()); } @Test public void shouldReportUnknownSignatureAlgorithmInIDPAssertion() throws Exception { Assertion authnStatementAssertion = anAssertion() .withIssuer(anIssuer().withIssuerId(ISSUER_IDP).build()) .withSignature(signatureWithUnknownSignatureAlgorithm.get()) .buildUnencrypted(); UnknownMethodAlgorithmLogger.probeAssertionForMethodAlgorithm(authnStatementAssertion, AUTHN_STATEMENT); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_ALGORITHM_MESSAGE, IDP, SIGNATURE_RSA_SHA1_ID, AUTHN_STATEMENT + Assertion.DEFAULT_ELEMENT_LOCAL_NAME)); } @Test public void shouldReportUnknownDigestAlgorithmInIDPAssertion() throws Exception { Assertion authnStatementAssertion = anAssertion() .withId(ID) .withIssuer(anIssuer().withIssuerId(ISSUER_IDP).build()) .withSignature(signatureWithUnknownDigestAlgorithm.get()) .buildUnencrypted(); UnknownMethodAlgorithmLogger.probeAssertionForMethodAlgorithm(authnStatementAssertion, AUTHN_STATEMENT); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.DIGEST_ALGORITHM_MESSAGE, IDP, DIGEST_SHA1_ID, AUTHN_STATEMENT + Assertion.DEFAULT_ELEMENT_LOCAL_NAME)); } @Test public void shouldReportUnknownSignatureAndDigestAlgorithmsInIDPAssertion() throws Exception { Assertion authnStatementAssertion = anAssertion() .withId(ID) .withIssuer(anIssuer().withIssuerId(ISSUER_IDP).build()) .withSignature(signatureWithUnknownSignatureAndDigestAlgorithms.get()) .buildUnencrypted(); UnknownMethodAlgorithmLogger.probeAssertionForMethodAlgorithm(authnStatementAssertion, AUTHN_STATEMENT); verifyLog(mockAppender, captorLoggingEvent, 1, String.format(UnknownMethodAlgorithmLogger.SIGNATURE_AND_DIGEST_ALGORITHMS_MESSAGE, IDP, SIGNATURE_RSA_SHA1_ID, DIGEST_SHA1_ID, AUTHN_STATEMENT + Assertion.DEFAULT_ELEMENT_LOCAL_NAME)); }