method2testcases
stringlengths 118
3.08k
|
---|
### 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:
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:
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:
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:
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:
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:
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:
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 { 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:
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:
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:
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:
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:
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:
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:
HubEncryptionKeyStore implements EncryptionKeyStore { @Override public PublicKey getEncryptionKeyForEntity(String entityId) { LOG.info("Retrieving encryption key for {} from config", entityId); try { return configServiceKeyStore.getEncryptionKeyForEntity(entityId); } catch (ApplicationException e) { if (e.getExceptionType().equals(ExceptionType.CLIENT_ERROR)) { throw new NoKeyConfiguredForEntityException(entityId); } throw new RuntimeException(e); } } @Inject HubEncryptionKeyStore(ConfigServiceKeyStore configServiceKeyStore); @Override PublicKey getEncryptionKeyForEntity(String entityId); }### Answer:
@Test public void shouldGetPublicKeyForAnEntityThatExists() throws Exception { String entityId = "entityId"; when(configServiceKeyStore.getEncryptionKeyForEntity(entityId)).thenReturn(publicKey); final PublicKey key = keyStore.getEncryptionKeyForEntity(entityId); assertThat(key).isEqualTo(publicKey); }
@Test(expected = NoKeyConfiguredForEntityException.class) public void shouldThrowExceptionIfNoPublicKeyForEntityId() throws Exception { String entityId = "non-existent-entity"; when(configServiceKeyStore.getEncryptionKeyForEntity(entityId)).thenThrow(ApplicationException.createUnauditedException(ExceptionType.CLIENT_ERROR, UUID.randomUUID())); keyStore.getEncryptionKeyForEntity(entityId); }
|
### Question:
SamlProxyExceptionMapper extends AbstractContextExceptionMapper<Exception> { @Override protected Response handleException(Exception exception) { UUID errorId = UUID.randomUUID(); levelLogger.log(ExceptionType.UNKNOWN.getLevel(), exception, errorId); return Response.serverError() .entity(ErrorStatusDto.createAuditedErrorStatus(errorId, ExceptionType.UNKNOWN)) .build(); } @Inject SamlProxyExceptionMapper(
Provider<HttpServletRequest> contextProvider,
LevelLoggerFactory<SamlProxyExceptionMapper> levelLoggerFactory); }### Answer:
@Test public void shouldCreateAuditedErrorResponse() throws Exception { Response response = exceptionMapper.handleException(new RuntimeException()); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); }
@Test public void shouldLogExceptionAtErrorLevel() throws Exception { RuntimeException exception = new RuntimeException(); exceptionMapper.handleException(exception); verify(levelLogger).log(eq(Level.ERROR), eq(exception), any(UUID.class)); }
|
### Question:
OutboundResponseFromHubToResponseTransformerFactory { public Function<AuthnResponseFromCountryContainerDto, String> getCountryTransformer() { return outboundAuthnResponseFromCountryContainerToStringFunction; } @Inject OutboundResponseFromHubToResponseTransformerFactory(SimpleProfileOutboundResponseFromHubToResponseTransformerProvider simpleProfileOutboundResponseFromHubToResponseTransformerProvider,
TransactionsConfigProxy transactionsConfigProxy,
OutboundSamlProfileResponseFromHubToStringFunctionSHA256 outboundSamlProfileResponseFromHubToStringFunctionSHA256,
OutboundLegacyResponseFromHubToStringFunctionSHA256 outboundLegacyResponseFromHubToStringFunctionSHA256,
OutboundAuthnResponseFromCountryContainerToStringFunction outboundAuthnResponseFromCountryContainerToStringFunction); Function<OutboundResponseFromHub, String> get(String authnRequestIssuerEntityId); Function<AuthnResponseFromCountryContainerDto, String> getCountryTransformer(); }### Answer:
@Test public void getCountryTransformerShouldReturnOutboundAuthnResponseFromCountryContainerToStringFunction() { Function<AuthnResponseFromCountryContainerDto, String> transformer = outboundResponseFromHubToResponseTransformerFactory.getCountryTransformer(); assertThat(transformer).isEqualTo(outboundAuthnResponseFromCountryContainerToStringFunction); }
|
### Question:
PolicyExceptionMapper implements ExceptionMapper<TException> { @Override public final Response toResponse(TException exception) { if (exception instanceof NotFoundException) { return Response.status(Response.Status.NOT_FOUND).build(); } else if (noSessionIdInQueryStringOrPathParam() && inARequestWhereWeExpectContext()) { LOG.error(MessageFormat.format("No Session Id found for request to: {0}", httpServletRequest.getRequestURI()), exception); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return handleException(exception); } PolicyExceptionMapper(); @Context void setUriInfo(UriInfo uriInfo); @Context void setHttpServletRequest(HttpServletRequest httpServletRequest); @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(""); when(uriInfo.getPathParameters()).thenReturn(new StringKeyIgnoreCaseMultivaluedMap<>()); 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()); }
@Test public void shouldReturnResponseStatusOfNotFoundWhenANotFoundExceptionIsThrown() { Response response = mapper.toResponse(new NotFoundException()); assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); }
|
### Question:
AuthnRequestFromTransactionHandler { public void restartJourney(final SessionId sessionId) { final RestartJourneyStateController stateController = (RestartJourneyStateController) sessionRepository.getStateController(sessionId, RestartJourneyState.class); stateController.transitionToSessionStartedState(); } @Inject AuthnRequestFromTransactionHandler(
SessionRepository sessionRepository,
HubEventLogger hubEventLogger,
PolicyConfiguration policyConfiguration,
TransactionsConfigProxy transactionsConfigProxy,
IdGenerator idGenerator); SessionId handleRequestFromTransaction(SamlResponseWithAuthnRequestInformationDto samlResponse, Optional<String> relayState, String ipAddress, URI assertionConsumerServiceUri, boolean transactionSupportsEidas); void tryAnotherIdp(final SessionId sessionId); void restartJourney(final SessionId sessionId); void selectIdpForGivenSessionId(SessionId sessionId, IdpSelected idpSelected); AuthnRequestFromHub getIdaAuthnRequestFromHub(SessionId sessionId); AuthnRequestSignInProcess getSignInProcessDto(SessionId sessionIdParameter); String getRequestIssuerId(SessionId sessionId); ResponseFromHub getResponseFromHub(SessionId sessionId); ResponseFromHub getErrorResponseFromHub(SessionId sessionId); AuthnResponseFromCountryContainerDto getAuthnResponseFromCountryContainerDto(SessionId sessionId); boolean isResponseFromCountryWithUnsignedAssertions(SessionId sessionId); }### Answer:
@Test public void restartsJourney() { when(sessionRepository.getStateController(SESSION_ID, RestartJourneyState.class)).thenReturn(restartJourneyStateController); authnRequestFromTransactionHandler.restartJourney(SESSION_ID); verify(restartJourneyStateController).transitionToSessionStartedState(); }
|
### Question:
EidasConnectorMetrics { public static void increment(String entityId, Direction direction, Status status) { try { String country = getCountryCode(Objects.requireNonNull(entityId)); CONNECTOR_COUNTER.labels( country.toLowerCase(), Objects.requireNonNull(direction.name()), Objects.requireNonNull(status.name())) .inc(); } catch (IllegalArgumentException | NullPointerException e) { LOG.warn("Could not set counter for entityId '{}', direction '{}', status '{}'", entityId, direction, status, e); } } static void increment(String entityId, Direction direction, Status status); }### Answer:
@Test public void testIncrementingCounterWithParameters() throws Exception { Counter counter = mock(Counter.class); Counter.Child counterChild = mock(Counter.Child.class); setFinalStatic(EidasConnectorMetrics.class.getDeclaredField("CONNECTOR_COUNTER"), counter); when(counter.labels(expectedCountryCode, direction != null ? direction.name() : null, status != null ? status.name() : null)).thenReturn(counterChild); EidasConnectorMetrics.increment(entityId, direction, status); if (incrementsCounter) { verify(counterChild).inc(); } else { verifyNoInteractions(counter, counterChild); } }
|
### Question:
CountriesService { public void setSelectedCountry(SessionId sessionId, String countryCode) { ensureTransactionSupportsEidas(sessionId); List<EidasCountryDto> supportedCountries = getCountries(sessionId); EidasCountryDto selectedCountry = supportedCountries.stream() .filter(country -> country.getSimpleId().equals(countryCode)) .findFirst() .orElseThrow(() -> new EidasCountryNotSupportedException(sessionId, countryCode)); EidasCountrySelectingStateController eidasCountrySelectingStateController = (EidasCountrySelectingStateController) sessionRepository.getStateController(sessionId, EidasCountrySelectingState.class); eidasCountrySelectingStateController.selectCountry(selectedCountry.getEntityId()); } @Inject CountriesService(SessionRepository sessionRepository, TransactionsConfigProxy configProxy); List<EidasCountryDto> getCountries(SessionId sessionId); void setSelectedCountry(SessionId sessionId, String countryCode); }### Answer:
@Test public void shouldSetSelectedCountry() { EidasCountrySelectedStateController mockEidasCountrySelectedStateController = mock(EidasCountrySelectedStateController.class); when(sessionRepository.getStateController(sessionId, EidasCountrySelectingState.class)).thenReturn(mockEidasCountrySelectedStateController); setSystemWideCountries(singletonList(COUNTRY_1)); service.setSelectedCountry(sessionId, COUNTRY_1.getSimpleId()); verify(mockEidasCountrySelectedStateController).selectCountry(COUNTRY_1.getEntityId()); }
@Test(expected = EidasCountryNotSupportedException.class) public void shouldReturnErrorWhenAnInvalidCountryIsSelected() { setSystemWideCountries(singletonList(COUNTRY_1)); service.setSelectedCountry(sessionId, "not-a-valid-country-code"); }
@Test(expected = EidasNotSupportedException.class) public void shouldReturnErrorWhenACountryIsSelectedWithTxnNotSupportingEidas() { when(sessionRepository.getTransactionSupportsEidas(sessionId)).thenReturn(false); service.setSelectedCountry(sessionId, "NL"); }
|
### Question:
Cycle3Service { public Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId) { AbstractAwaitingCycle3DataStateController controller = (AbstractAwaitingCycle3DataStateController) sessionRepository.getStateController(sessionId, AbstractAwaitingCycle3DataState.class); return controller.getCycle3AttributeRequestData(); } @Inject Cycle3Service(SessionRepository sessionRepository, AttributeQueryService attributeQueryService); void sendCycle3MatchingRequest(SessionId sessionId, Cycle3UserInput cycle3UserInput); void cancelCycle3DataInput(SessionId sessionId); Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId); }### Answer:
@Test public void shouldReturnCycle3AttributeRequestDataAfterReceivingCycle3AttributeRequestDataForVerifyFlow() { when(awaitingCycle3DataStateController.getCycle3AttributeRequestData()).thenReturn(ATTRIBUTE_REQUEST_DATA); Cycle3AttributeRequestData result = service.getCycle3AttributeRequestData(sessionId); assertThat(result).isEqualTo(ATTRIBUTE_REQUEST_DATA); }
@Test public void shouldReturnCycle3AttributeRequestDataAfterReceivingCycle3AttributeRequestDataForEidasFlow() { SessionId eidasSessionId = SessionIdBuilder.aSessionId().build(); when(sessionRepository.getStateController(eidasSessionId, AbstractAwaitingCycle3DataState.class)).thenReturn(eidasAwaitingCycle3DataStateController); when(eidasAwaitingCycle3DataStateController.getCycle3AttributeRequestData()).thenReturn(ATTRIBUTE_REQUEST_DATA); Cycle3AttributeRequestData result = service.getCycle3AttributeRequestData(eidasSessionId); assertThat(result).isEqualTo(ATTRIBUTE_REQUEST_DATA); }
|
### Question:
Cycle3Service { public void cancelCycle3DataInput(SessionId sessionId) { AbstractAwaitingCycle3DataStateController controller = (AbstractAwaitingCycle3DataStateController) sessionRepository.getStateController(sessionId, AbstractAwaitingCycle3DataState.class); controller.handleCancellation(); } @Inject Cycle3Service(SessionRepository sessionRepository, AttributeQueryService attributeQueryService); void sendCycle3MatchingRequest(SessionId sessionId, Cycle3UserInput cycle3UserInput); void cancelCycle3DataInput(SessionId sessionId); Cycle3AttributeRequestData getCycle3AttributeRequestData(SessionId sessionId); }### Answer:
@Test public void shouldProcessCancellationAfterReceivingCancelCycle3DataInputForEidasFlow() { SessionId eidasSessionId = SessionIdBuilder.aSessionId().build(); when(sessionRepository.getStateController(eidasSessionId, AbstractAwaitingCycle3DataState.class)).thenReturn(eidasAwaitingCycle3DataStateController); doNothing().when(eidasAwaitingCycle3DataStateController).handleCancellation(); service.cancelCycle3DataInput(eidasSessionId); verify(eidasAwaitingCycle3DataStateController).handleCancellation(); }
|
### Question:
SessionService { public SessionId getSessionIfItExists(SessionId sessionId) { if (sessionRepository.sessionExists(sessionId)) { return sessionId; } throw new SessionNotFoundException(sessionId); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test public void getSession_ReturnSessionIdWhenSessionExists() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); assertThat(service.getSessionIfItExists(sessionId)).isEqualTo(sessionId); }
@Test(expected = SessionNotFoundException.class) public void getSession_ThrowsExceptionWhenSessionDoesNotExists() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(false); assertThat(service.getSessionIfItExists(sessionId)).isEqualTo(sessionId); }
|
### Question:
SessionService { public Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId){ getSessionIfItExists(sessionId); return sessionRepository.getLevelOfAssuranceFromIdp(sessionId); } @Inject SessionService(SamlEngineProxy samlEngineProxy,
TransactionsConfigProxy configProxy,
AuthnRequestFromTransactionHandler authnRequestHandler,
SessionRepository sessionRepository); SessionId create(final SamlAuthnRequestContainerDto requestDto); SessionId getSessionIfItExists(SessionId sessionId); Optional<LevelOfAssurance> getLevelOfAssurance(SessionId sessionId); AuthnRequestFromHubContainerDto getIdpAuthnRequest(SessionId sessionId); AuthnResponseFromHubContainerDto getRpAuthnResponse(SessionId sessionId); AuthnResponseFromHubContainerDto getRpErrorResponse(SessionId sessionId); }### Answer:
@Test public void shouldGetLevelOfAssurance() { SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); final Optional<LevelOfAssurance> loa = Optional.of(LevelOfAssurance.LEVEL_1); when(sessionRepository.getLevelOfAssuranceFromIdp(sessionId)).thenReturn(loa); assertThat(service.getLevelOfAssurance(sessionId)).isEqualTo(loa); }
|
### Question:
MatchingServiceResponseService { public void handleFailure(SessionId sessionId) { getSessionIfItExists(sessionId); logRequesterErrorAndUpdateState(sessionId, "received failure notification from saml-soap-proxy"); } @Inject MatchingServiceResponseService(SamlEngineProxy samlEngineProxy,
SessionRepository sessionRepository,
HubEventLogger eventLogger); void handleFailure(SessionId sessionId); void handleSuccessResponse(SessionId sessionId, SamlResponseDto samlResponse); }### Answer:
@Test(expected = SessionNotFoundException.class) public void handle_shouldThrowExceptionIfSessionDoesNotExistInMSResponseFailureCase() { when(sessionRepository.sessionExists(sessionId)).thenReturn(false); matchingServiceResponseService.handleFailure(sessionId); }
@Test public void handle_shouldLogToEventSinkAndUpdateStateWhenHandlingError() { matchingServiceResponseService.handleFailure(sessionId); verify(waitingForMatchingServiceResponseStateController, times(1)).handleRequestFailure(); verify(eventLogger).logErrorEvent(format("received failure notification from saml-soap-proxy for session {0}", sessionId), sessionId); }
|
### Question:
LevelOfAssuranceValidator { public void validate(Optional<LevelOfAssurance> responseLevelOfAssurance, LevelOfAssurance requiredLevelOfAssurance) { if (!responseLevelOfAssurance.isPresent()) { throw noLevelOfAssurance(); } if (!responseLevelOfAssurance.get().equals(requiredLevelOfAssurance)) { throw wrongLevelOfAssurance(java.util.Optional.of(responseLevelOfAssurance.get()), singletonList(requiredLevelOfAssurance)); } } void validate(Optional<LevelOfAssurance> responseLevelOfAssurance, LevelOfAssurance requiredLevelOfAssurance); }### Answer:
@Test public void validate_shouldNotThrowExceptionIfLevelOfAssuranceFromMatchingServiceMatchesOneFromIdp() throws Exception { LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2; levelOfAssuranceValidator.validate(Optional.ofNullable(levelOfAssurance), levelOfAssurance); }
@Test public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotExist() throws Exception { LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2; try { levelOfAssuranceValidator.validate(Optional.empty(), levelOfAssurance); fail("fail"); } catch (StateProcessingValidationException e) { assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.noLevelOfAssurance().getMessage()); } }
@Test public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotMatchOneFromIdp() throws Exception { try { levelOfAssuranceValidator.validate(Optional.ofNullable(LevelOfAssurance.LEVEL_2), LevelOfAssurance.LEVEL_4); fail("fail"); } catch (StateProcessingValidationException e) { assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.wrongLevelOfAssurance(java.util.Optional.of(LevelOfAssurance.LEVEL_2), singletonList(LevelOfAssurance.LEVEL_4)).getMessage()); } }
|
### Question:
ProtectiveMonitoringLogFormatter { public String formatAuthnRequest(AuthnRequest authnRequest, Direction direction, SignatureStatus signatureStatus) { Issuer issuer = authnRequest.getIssuer(); String issuerId = issuer != null ? issuer.getValue() : ""; return String.format(AUTHN_REQUEST, authnRequest.getID(), direction, authnRequest.getDestination(), issuerId, signatureStatus.valid()); } String formatAuthnRequest(AuthnRequest authnRequest, Direction direction, SignatureStatus signatureStatus); String formatAuthnResponse(Response samlResponse, Direction direction, SignatureStatus signatureStatus); }### Answer:
@Test public void shouldFormatAuthnRequest() { AuthnRequest authnRequest = anAuthnRequest().withId("test-id").withDestination("veganistan").build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnRequest(authnRequest, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); String expectedLogMessage = "Protective Monitoring – Authn Request Event – {" + "requestId: test-id, " + "direction: INBOUND, " + "destination: veganistan, " + "issuerId: a-test-entity, " + "validSignature: true}"; assertThat(logString).isEqualTo(expectedLogMessage); }
@Test public void shouldFormatAuthnRequestWithoutIssuer() { AuthnRequest authnRequest = anAuthnRequest().withId("test-id").withDestination("veganistan").withIssuer(null).build(); String logString = new ProtectiveMonitoringLogFormatter().formatAuthnRequest(authnRequest, Direction.INBOUND, SignatureStatus.VALID_SIGNATURE); assertThat(logString).contains("issuerId: ,"); }
|
### Question:
RedisSessionStore implements SessionStore { @Override public void insert(SessionId sessionId, State value) { dataStore.setex(sessionId, recordTTL, value); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldInsertIntoRedisWithExpiry() { SessionId sessionId = aSessionId().build(); State state = getRandomState(); redisSessionStore.insert(sessionId, state); verify(redis).setex(sessionId, EXPIRY_TIME, state); }
|
### Question:
RedisSessionStore implements SessionStore { @Override public void replace(SessionId sessionId, State value) { Long ttl = dataStore.ttl(sessionId); dataStore.setex(sessionId, ttl, value); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldReplaceSessionInRedis() { SessionId sessionId = aSessionId().build(); State state = getRandomState(); redisSessionStore.replace(sessionId, state); verify(redis).setex(eq(sessionId), anyLong(), eq(state)); }
|
### Question:
RedisSessionStore implements SessionStore { @Override public boolean hasSession(SessionId sessionId) { return dataStore.exists(sessionId) > 0; } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldCheckIfSessionExists() { SessionId sessionId = aSessionId().build(); redisSessionStore.hasSession(sessionId); verify(redis).exists(sessionId); }
|
### Question:
RedisSessionStore implements SessionStore { @Override public State get(SessionId sessionId) { return dataStore.get(sessionId); } RedisSessionStore(RedisCommands<SessionId, State> dataStore, Long recordTTL); @Override void insert(SessionId sessionId, State value); @Override void replace(SessionId sessionId, State value); @Override boolean hasSession(SessionId sessionId); @Override State get(SessionId sessionId); }### Answer:
@Test public void shouldGetASessionFromRedis() { SessionId sessionId = aSessionId().build(); redisSessionStore.get(sessionId); verify(redis).get(sessionId); }
|
### Question:
ResponseProcessingDetails { public SessionId getSessionId() { return sessionId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getSessionId() { assertThat(responseProcessingDetails.getSessionId()).isEqualTo(SESSION_ID); }
|
### Question:
ResponseProcessingDetails { public ResponseProcessingStatus getResponseProcessingStatus() { return responseProcessingStatus; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getResponseProcessingStatus() { assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.GET_C3_DATA); }
|
### Question:
ResponseProcessingDetails { public String getTransactionEntityId() { return transactionEntityId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getTransactionEntityId() { assertThat(responseProcessingDetails.getTransactionEntityId()).isEqualTo(TRANSACTION_ENTITY_ID); }
|
### Question:
ResponseProcessingDetails { @Override public String toString() { final StringBuilder sb = new StringBuilder("ResponseProcessingDetails{"); sb.append("sessionId=").append(sessionId); sb.append(", responseProcessingStatus=").append(responseProcessingStatus); sb.append(", transactionEntityId='").append(transactionEntityId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private ResponseProcessingDetails(); ResponseProcessingDetails(
SessionId sessionId,
ResponseProcessingStatus responseProcessingStatus,
String transactionEntityId); SessionId getSessionId(); ResponseProcessingStatus getResponseProcessingStatus(); String getTransactionEntityId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("ResponseProcessingDetails{"); sb.append("sessionId=").append(responseProcessingDetails.getSessionId()); sb.append(", responseProcessingStatus=").append(responseProcessingDetails.getResponseProcessingStatus()); sb.append(", transactionEntityId='").append(responseProcessingDetails.getTransactionEntityId()).append('\''); sb.append('}'); assertThat(responseProcessingDetails.toString()).isEqualTo(sb.toString()); }
|
### Question:
ResponseFromHub { public String getAuthnRequestIssuerEntityId() { return authnRequestIssuerEntityId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAuthnRequestIssuerEntityId() { assertThat(responseFromHub.getAuthnRequestIssuerEntityId()).isEqualTo(AUTHN_REQUEST_ISSUER_ENTITY_ID); }
|
### Question:
ResponseFromHub { public String getResponseId() { return responseId; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getResponseId() { assertThat(responseFromHub.getResponseId()).isEqualTo(RESPONSE_ID); }
|
### Question:
ResponseFromHub { public String getInResponseTo() { return inResponseTo; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getInResponseTo() { assertThat(responseFromHub.getInResponseTo()).isEqualTo(IN_RESPONSE_TO); }
|
### Question:
ResponseFromHub { public List<String> getEncryptedAssertions() { return encryptedAssertions; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getEncryptedAssertions() { assertThat(responseFromHub.getEncryptedAssertions()).containsOnly(MATCHING_SERVICE_ASSERTION); }
|
### Question:
ResponseFromHub { public Optional<String> getRelayState() { return relayState; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getRelayState() { assertThat(responseFromHub.getRelayState()).isEqualTo(RELAY_STATE); }
|
### Question:
ResponseFromHub { public URI getAssertionConsumerServiceUri() { return assertionConsumerServiceUri; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAssertionConsumerServiceUri() { assertThat(responseFromHub.getAssertionConsumerServiceUri()).isEqualTo(ASSERTION_CONSUMER_SERVICE_URI); }
|
### Question:
ResponseFromHub { public TransactionIdaStatus getStatus() { return status; } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getStatus() { assertThat(responseFromHub.getStatus()).isEqualTo(TransactionIdaStatus.Success); }
|
### Question:
ResponseFromHub { @Override public String toString() { final StandardToStringStyle style = new StandardToStringStyle(); style.setUseIdentityHashCode(false); return ReflectionToStringBuilder.toString(this, style); } @SuppressWarnings("unused")//Needed by JAXB private ResponseFromHub(); ResponseFromHub(
String responseId,
String inResponseTo,
String authnRequestIssuerEntityId,
List<String> encryptedAssertions,
Optional<String> relayState,
URI assertionConsumerServiceUri,
TransactionIdaStatus status); String getAuthnRequestIssuerEntityId(); String getResponseId(); String getInResponseTo(); List<String> getEncryptedAssertions(); Optional<String> getRelayState(); URI getAssertionConsumerServiceUri(); TransactionIdaStatus getStatus(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("uk.gov.ida.hub.policy.domain.ResponseFromHub["); sb.append("authnRequestIssuerEntityId=").append(responseFromHub.getAuthnRequestIssuerEntityId()); sb.append(",responseId=").append(responseFromHub.getResponseId()); sb.append(",inResponseTo=").append(responseFromHub.getInResponseTo()); sb.append(",status=").append(responseFromHub.getStatus()); sb.append(",encryptedAssertions=").append(responseFromHub.getEncryptedAssertions()); sb.append(",relayState=").append(responseFromHub.getRelayState()); sb.append(",assertionConsumerServiceUri=").append(responseFromHub.getAssertionConsumerServiceUri()); sb.append(']'); assertThat(responseFromHub.toString()).isEqualTo(sb.toString()); }
|
### Question:
Cycle3Dataset implements Serializable { public Map<String, String> getAttributes() { return attributes; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAttributes() throws Exception { Cycle3Dataset cycle3Dataset = new Cycle3Dataset(map); assertThat(cycle3Dataset.getAttributes()).isEqualTo(map); }
|
### Question:
Cycle3Dataset implements Serializable { public static Cycle3Dataset createFromData(String attributeKey, String userInputData) { Map<String, String> attributes = new HashMap<>(); attributes.put(attributeKey, userInputData); return new Cycle3Dataset(attributes); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void createFromData() throws Exception { Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(DEFAULT_ATTRIBUTE, DEFAULT_ATTRIBUTE_VALUE); assertThat(cycle3Dataset.getAttributes()).isEqualTo(map); }
|
### Question:
Cycle3Dataset implements Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder("Cycle3Dataset{"); sb.append("attributes=").append(attributes); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3Dataset(); Cycle3Dataset(Map<String, String> attributes); Map<String, String> getAttributes(); static Cycle3Dataset createFromData(String attributeKey, String userInputData); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() throws Exception { final Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(DEFAULT_ATTRIBUTE, DEFAULT_ATTRIBUTE_VALUE); final StringBuilder sb = new StringBuilder("Cycle3Dataset{"); sb.append("attributes=").append(cycle3Dataset.getAttributes()); sb.append('}'); assertThat(cycle3Dataset.toString()).isEqualTo(sb.toString()); }
|
### Question:
EidasAuthnFailedErrorStateController extends AbstractAuthnFailedErrorStateController<EidasAuthnFailedErrorState> implements RestartJourneyStateController, EidasCountrySelectingStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); stateTransitionAction.transitionTo(sessionStartedState); } EidasAuthnFailedErrorStateController(
EidasAuthnFailedErrorState state,
ResponseFromHubFactory responseFromHubFactory,
StateTransitionAction stateTransitionAction,
HubEventLogger hubEventLogger); @Override void transitionToSessionStartedState(); @Override void selectCountry(final String countryEntityId); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(eidasAuthnFailedErrorState.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(REQUEST_ISSUER_ID); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isEqualTo(true); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isEqualTo(true); }
|
### Question:
SuccessfulMatchStateController extends AbstractSuccessfulMatchStateController<SuccessfulMatchState> { @Override public ResponseFromHub getPreparedResponse() { Collection<String> enabledIdentityProviders = identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing( state.getRequestIssuerEntityId(), state.isRegistering(), state.getLevelOfAssurance()); if (!enabledIdentityProviders.contains(state.getIdentityProviderEntityId())) { throw new IdpDisabledException(state.getIdentityProviderEntityId()); } return getResponse(); } SuccessfulMatchStateController(
final SuccessfulMatchState state,
final ResponseFromHubFactory responseFromHubFactory,
final IdentityProvidersConfigProxy identityProvidersConfigProxy); @Override ResponseFromHub getPreparedResponse(); }### Answer:
@Test(expected = IdpDisabledException.class) public void getPreparedResponse_shouldThrowWhenIdpIsDisabled() { when(identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing(any(String.class), anyBoolean(), any(LevelOfAssurance.class))) .thenReturn(emptyList()); controller.getPreparedResponse(); }
@Test public void getPreparedResponse_shouldReturnResponse() { final List<String> enabledIdentityProviders = singletonList(state.getIdentityProviderEntityId()); final ResponseFromHub expectedResponseFromHub = ResponseFromHubBuilder.aResponseFromHubDto().build(); when(identityProvidersConfigProxy.getEnabledIdentityProvidersForAuthenticationResponseProcessing(eq(state.getRequestIssuerEntityId()), anyBoolean(), any(LevelOfAssurance.class))) .thenReturn(enabledIdentityProviders); when(responseFromHubFactory.createSuccessResponseFromHub( state.getRequestId(), state.getMatchingServiceAssertion(), state.getRelayState(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri())) .thenReturn(expectedResponseFromHub); final ResponseFromHub result = controller.getPreparedResponse(); assertThat(result).isEqualTo(expectedResponseFromHub); }
|
### Question:
AuthnFailedErrorStateController extends AbstractAuthnFailedErrorStateController<AuthnFailedErrorState> implements IdpSelectingStateController { public void tryAnotherIdpResponse() { stateTransitionAction.transitionTo(createSessionStartedState()); } AuthnFailedErrorStateController(
AuthnFailedErrorState state,
ResponseFromHubFactory responseFromHubFactory,
StateTransitionAction stateTransitionAction,
TransactionsConfigProxy transactionsConfigProxy,
IdentityProvidersConfigProxy identityProvidersConfigProxy,
HubEventLogger hubEventLogger); FailureResponseDetails handleFailureResponse(); void tryAnotherIdpResponse(); @Override void handleIdpSelected(String idpEntityId, String principalIpAddress, boolean registering, LevelOfAssurance requestedLoa, String analyticsSessionId, String journeyType, String abTestVariant); @Override String getRequestIssuerId(); @Override AuthnRequestSignInProcess getSignInProcessDetails(); }### Answer:
@Test public void tryAnotherIdpResponse_shouldTransitionToSessionStartedState() { ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); SessionStartedState expectedState = aSessionStartedState(). withSessionId(aSessionId().with("sessionId").build()) .withForceAuthentication(true) .withTransactionSupportsEidas(true) .withSessionExpiryTimestamp(NOW) .withAssertionConsumerServiceUri(URI.create("/default-service-index")) .build(); controller.tryAnotherIdpResponse(); verify(stateTransitionAction).transitionTo(capturedState.capture()); assertThat(capturedState.getValue()).isInstanceOf(SessionStartedState.class); assertThat(capturedState.getValue()).isEqualToComparingFieldByField(expectedState); }
|
### Question:
EidasSuccessfulMatchStateController extends AbstractSuccessfulMatchStateController<EidasSuccessfulMatchState> { @Override public ResponseFromHub getPreparedResponse() { List<EidasCountryDto> enabledCountries = countriesService.getCountries(state.getSessionId()); if (enabledCountries.stream().noneMatch(country -> country.getEntityId().equals(state.getIdentityProviderEntityId()))) { throw new IdpDisabledException(state.getIdentityProviderEntityId()); } return getResponse(); } EidasSuccessfulMatchStateController(
EidasSuccessfulMatchState state,
ResponseFromHubFactory responseFromHubFactory,
CountriesService countriesService); @Override ResponseFromHub getPreparedResponse(); }### Answer:
@Test(expected = IdpDisabledException.class) public void getPreparedResponse_shouldThrowWhenCountryIsDisabled() { when(countriesService.getCountries(state.getSessionId())) .thenReturn(emptyList()); controller.getPreparedResponse(); }
@Test public void shouldReturnPreparedResponse() { List<EidasCountryDto> enabledIdentityProviders = singletonList(new EidasCountryDto("country-entity-id", "simple-id", true)); ResponseFromHub expectedResponseFromHub = ResponseFromHubBuilder.aResponseFromHubDto().build(); when(countriesService.getCountries(state.getSessionId())) .thenReturn(enabledIdentityProviders); when(responseFromHubFactory.createSuccessResponseFromHub( state.getRequestId(), state.getMatchingServiceAssertion(), state.getRelayState(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri())) .thenReturn(expectedResponseFromHub); ResponseFromHub result = controller.getPreparedResponse(); assertThat(result).isEqualTo(expectedResponseFromHub); }
|
### Question:
EidasUserAccountCreationFailedStateController extends AbstractUserAccountCreationFailedStateController<EidasUserAccountCreationFailedState> implements RestartJourneyStateController { @Override public void transitionToSessionStartedState() { final SessionStartedState sessionStartedState = createSessionStartedState(); hubEventLogger.logSessionMovedToStartStateEvent(sessionStartedState); stateTransitionAction.transitionTo(sessionStartedState); } EidasUserAccountCreationFailedStateController(
final EidasUserAccountCreationFailedState state,
final ResponseFromHubFactory responseFromHubFactory,
final StateTransitionAction stateTransitionAction,
HubEventLogger hubEventLogger); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldTransitionToSessionStartedStateAndLogEvent() { controller.transitionToSessionStartedState(); ArgumentCaptor<SessionStartedState> capturedState = ArgumentCaptor.forClass(SessionStartedState.class); verify(stateTransitionAction, times(1)).transitionTo(capturedState.capture()); verify(hubEventLogger, times(1)).logSessionMovedToStartStateEvent(capturedState.getValue()); assertThat(capturedState.getValue().getSessionId()).isEqualTo(eidasUserAccountCreationFailedState.getSessionId()); assertThat(capturedState.getValue().getRequestIssuerEntityId()).isEqualTo(REQUEST_ISSUER_ID); assertThat(capturedState.getValue().getTransactionSupportsEidas()).isEqualTo(true); assertThat(capturedState.getValue().getForceAuthentication().orElse(null)).isEqualTo(false); }
|
### Question:
ConfigServiceKeyStore { public List<PublicKey> getVerifyingKeysForEntity(String entityId) { Collection<CertificateDto> certificates = certificatesConfigProxy.getSignatureVerificationCertificates(entityId); List<PublicKey> publicKeys = new ArrayList<>(); for (CertificateDto keyFromConfig : certificates) { String base64EncodedCertificateValue = keyFromConfig.getCertificate(); final X509Certificate certificate = x509CertificateFactory.createCertificate(base64EncodedCertificateValue); trustStoreForCertificateProvider.getTrustStoreFor(keyFromConfig.getFederationEntityType()) .ifPresent(keyStore -> validate(certificate, keyStore)); publicKeys.add(certificate.getPublicKey()); } return publicKeys; } @Inject ConfigServiceKeyStore(
CertificatesConfigProxy certificatesConfigProxy,
CertificateChainValidator certificateChainValidator,
TrustStoreForCertificateProvider trustStoreForCertificateProvider,
X509CertificateFactory x509CertificateFactory); List<PublicKey> getVerifyingKeysForEntity(String entityId); PublicKey getEncryptionKeyForEntity(String entityId); }### Answer:
@Test public void getVerifyingKeysForEntity_shouldGetVerifyingKeysFromConfigCertificateProxy() { configServiceKeyStore.getVerifyingKeysForEntity(issuerId); verify(certificatesConfigProxy).getSignatureVerificationCertificates(issuerId); }
|
### Question:
EidasCountrySelectedStateController implements ErrorResponsePreparedStateController, EidasCountrySelectingStateController, AuthnRequestCapableController, RestartJourneyStateController { public String getMatchingServiceEntityId() { return transactionsConfigProxy.getMatchingServiceEntityId(state.getRequestIssuerEntityId()); } EidasCountrySelectedStateController(
final EidasCountrySelectedState state,
final HubEventLogger hubEventLogger,
final StateTransitionAction stateTransitionAction,
final PolicyConfiguration policyConfiguration,
final TransactionsConfigProxy transactionsConfigProxy,
final MatchingServiceConfigProxy matchingServiceConfigProxy,
final ResponseFromHubFactory responseFromHubFactory,
final AssertionRestrictionsFactory assertionRestrictionFactory); String getMatchingServiceEntityId(); String getRequestIssuerId(); boolean isMatchingJourney(); String getCountryEntityId(); AuthnRequestFromHub getRequestFromHub(); EidasAttributeQueryRequestDto getEidasAttributeQueryRequestDto(InboundResponseFromCountry translatedResponse); @Override ResponseFromHub getErrorResponse(); @Override void selectCountry(String countryEntityId); void handleMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleNonMatchingJourneySuccessResponseFromCountry(InboundResponseFromCountry translatedResponse,
String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); void handleAuthenticationFailedResponseFromCountry(String principalIpAddressAsSeenByHub,
String analyticsSessionId,
String journeyType); @Override void transitionToSessionStartedState(); }### Answer:
@Test public void shouldReturnMatchingServiceEntityIdWhenAsked() { controller.getMatchingServiceEntityId(); verify(transactionsConfigProxy).getMatchingServiceEntityId(state.getRequestIssuerEntityId()); }
|
### Question:
SamlProxyConfiguration extends Configuration implements RestfulClientConfiguration, TrustStoreConfiguration, ServiceNameConfiguration, PrometheusConfiguration { public Optional<CountryConfiguration> getCountryConfiguration() { return Optional.ofNullable(country); } protected SamlProxyConfiguration(); SamlConfiguration getSamlConfiguration(); Duration getMetadataValidDuration(); URI getFrontendExternalUri(); URI getPolicyUri(); MetadataResolverConfiguration getMetadataConfiguration(); @Override JerseyClientConfiguration getJerseyClientConfiguration(); URI getEventSinkUri(); URI getConfigUri(); Duration getCertificatesConfigCacheExpiry(); ServiceInfoConfiguration getServiceInfo(); @Override String getServiceName(); @Override ClientTrustStoreConfiguration getRpTrustStoreConfiguration(); @Override boolean getEnableRetryTimeOutConnections(); Optional<CountryConfiguration> getCountryConfiguration(); EventEmitterConfiguration getEventEmitterConfiguration(); boolean isEidasEnabled(); @Override boolean isPrometheusEnabled(); @Valid
@JsonProperty
public EventEmitterConfiguration eventEmitterConfiguration; }### Answer:
@Test public void shouldReturnCountryConfigOptionalIfCountryConfigNotNull() { SamlProxyConfiguration samlProxyConfiguration = new SamlProxyConfiguration(); CountryConfiguration countryConfiguration = new CountryConfiguration(null); samlProxyConfiguration.country = countryConfiguration; assertThat(samlProxyConfiguration.getCountryConfiguration()).isEqualTo(Optional.of(countryConfiguration)); }
@Test public void shouldReturnEmptyOptionalIfCountConfigNull() { SamlProxyConfiguration samlProxyConfiguration = new SamlProxyConfiguration(); assertThat(samlProxyConfiguration.getCountryConfiguration()).isEqualTo(Optional.empty()); }
|
### Question:
Cycle3AttributeRequestData { public String getAttributeName() { return attributeName; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getAttributeName() { assertThat(cycle3AttributeRequestData.getAttributeName()).isEqualTo(CYCLE_3_ATTRIBUTE_NAME); }
|
### Question:
Cycle3AttributeRequestData { public String getRequestIssuerId() { return requestIssuerId; } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getRequestIssuerId() { assertThat(cycle3AttributeRequestData.getRequestIssuerId()).isEqualTo(REQUEST_ISSUER_ENTITY_ID); }
|
### Question:
Cycle3AttributeRequestData { @Override public String toString() { final StringBuilder sb = new StringBuilder("Cycle3AttributeRequestData{"); sb.append("attributeName='").append(attributeName).append('\''); sb.append(", requestIssuerId='").append(requestIssuerId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private Cycle3AttributeRequestData(); Cycle3AttributeRequestData(
final String attributeName,
final String requestIssuerId); String getAttributeName(); String getRequestIssuerId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("Cycle3AttributeRequestData{"); sb.append("attributeName='").append(cycle3AttributeRequestData.getAttributeName()).append('\''); sb.append(", requestIssuerId='").append(cycle3AttributeRequestData.getRequestIssuerId()).append('\''); sb.append('}'); assertThat(cycle3AttributeRequestData.toString()).isEqualTo(sb.toString()); }
|
### Question:
SessionRepository { @Timed(name =Urls.SESSION_REPO_TIMED_GROUP) public Optional<LevelOfAssurance> getLevelOfAssuranceFromIdp(SessionId sessionId){ State currentState = getCurrentState(sessionId); if(currentState instanceof Cycle0And1MatchRequestSentState){ return Optional.of(((Cycle0And1MatchRequestSentState) currentState).getIdpLevelOfAssurance()); } if(currentState instanceof SuccessfulMatchState){ return Optional.of(((SuccessfulMatchState) currentState).getLevelOfAssurance()); } if(currentState instanceof AwaitingCycle3DataState){ return Optional.of(((AwaitingCycle3DataState) currentState).getLevelOfAssurance()); } if(currentState instanceof UserAccountCreatedState){ return Optional.of(((UserAccountCreatedState) currentState).getLevelOfAssurance()); } return Optional.empty(); } @Inject SessionRepository(
SessionStore dataStore,
StateControllerFactory controllerFactory); SessionId createSession(SessionStartedState startedState); @Timed(name = Urls.SESSION_REPO_TIMED_GROUP) StateController getStateController(
final SessionId sessionId,
final Class<T> expectedStateClass); @Timed(name = Urls.SESSION_REPO_TIMED_GROUP) boolean sessionExists(SessionId sessionId); @Timed(name =Urls.SESSION_REPO_TIMED_GROUP) Optional<LevelOfAssurance> getLevelOfAssuranceFromIdp(SessionId sessionId); boolean getTransactionSupportsEidas(SessionId sessionId); String getRequestIssuerEntityId(SessionId sessionId); boolean isSessionInState(SessionId sessionId, Class<? extends State> stateClass); void validateSessionExists(SessionId sessionId); }### Answer:
@Test public void getLevelOfAssuranceFromIdp(){ SessionStartedState state = aSessionStartedState().build(); SessionId sessionId = sessionRepository.createSession(state); assertThat(sessionRepository.getLevelOfAssuranceFromIdp(sessionId)).isEqualTo(Optional.empty()); }
|
### Question:
PersistentId implements Serializable { public String getNameId() { return nameId; } @SuppressWarnings("unused")//Needed by JAXB private PersistentId(); @JsonCreator PersistentId(@JsonProperty("nameId") String nameId); String getNameId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getNameId() { assertThat(persistentId.getNameId()).isEqualTo(NAME_ID); }
|
### Question:
PersistentId implements Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder("PersistentId{"); sb.append("nameId='").append(nameId).append('\''); sb.append('}'); return sb.toString(); } @SuppressWarnings("unused")//Needed by JAXB private PersistentId(); @JsonCreator PersistentId(@JsonProperty("nameId") String nameId); String getNameId(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() { final StringBuilder sb = new StringBuilder("PersistentId{"); sb.append("nameId='").append(NAME_ID).append('\''); sb.append('}'); assertThat(persistentId.toString()).isEqualTo(sb.toString()); }
|
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { public String getEncryptedIdentityAssertion() { return encryptedIdentityAssertion; } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void getEncryptedIdentityAssertion() throws Exception { assertThat(eidasAttributeQueryRequestDto.getEncryptedIdentityAssertion()).isEqualTo(ENCRYPTED_IDENTITY_ASSERTION); }
|
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { @Override public AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy) { return samlEngineProxy.generateEidasAttributeQuery(this); } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void sendToSamlEngine() throws Exception { when(samlEngineProxy.generateEidasAttributeQuery(eidasAttributeQueryRequestDto)).thenReturn(ATTRIBUTE_QUERY_CONTAINER_DTO); AttributeQueryContainerDto actual = eidasAttributeQueryRequestDto.sendToSamlEngine(samlEngineProxy); assertThat(actual).isEqualTo(ATTRIBUTE_QUERY_CONTAINER_DTO); }
|
### Question:
EidasAttributeQueryRequestDto extends AbstractAttributeQueryRequestDto { public Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer() { return countrySignedResponseContainer; } EidasAttributeQueryRequestDto(
final String requestId,
final String authnRequestIssuerEntityId,
final URI assertionConsumerServiceUri,
final DateTime assertionExpiry,
final String matchingServiceEntityId,
final URI attributeQueryUri,
final DateTime matchingServiceRequestTimeOut,
final boolean onboarding,
final LevelOfAssurance levelOfAssurance,
final PersistentId persistentId,
final Optional<Cycle3Dataset> cycle3Dataset,
final Optional<List<UserAccountCreationAttribute>> userAccountCreationAttributes,
final String encryptedIdentityAssertion,
final Optional<CountrySignedResponseContainer> countrySignedResponseContainer); String getEncryptedIdentityAssertion(); Optional<CountrySignedResponseContainer> getCountrySignedResponseContainer(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override AttributeQueryContainerDto sendToSamlEngine(SamlEngineProxy samlEngineProxy); }### Answer:
@Test public void getCountrySignedResponseContainer() { assertThat(eidasAttributeQueryRequestDto.getCountrySignedResponseContainer()).isEqualTo(COUNTRY_SIGNED_RESPONSE); }
|
### Question:
ManagedEntityConfigRepository implements ConfigRepository<T> { public Optional<T> get(String entityId) { return localConfigRepository.getData(entityId) .map(this::overrideWithRemote); } @Inject ManagedEntityConfigRepository(LocalConfigRepository<T> localConfigRepository, S3ConfigSource s3ConfigSource); Collection<T> getAll(); boolean has(String entityId); Optional<T> get(String entityId); Stream<T> stream(); }### Answer:
@Test public void getReturnsOptionalEmptyIfNoLocalConfigFound() { ManagedEntityConfigRepository<TransactionConfig> configRepo = new ManagedEntityConfigRepository<>(localConfigRepository, s3ConfigSource); Optional<TransactionConfig> result = configRepo.get(BAD_ENTITY_ID); assertThat(result).isNotPresent(); }
@Test public void getReturnsOptionalEmptyIfNoLocalConfigFoundButRemoteExists() { ManagedEntityConfigRepository<TransactionConfig> configRepo = new ManagedEntityConfigRepository<>(localConfigRepository, s3ConfigSource); Optional<TransactionConfig> result = configRepo.get(REMOTE_ONLY_ENTITY_ID); assertThat(result).isNotPresent(); }
|
### Question:
IdpIdaStatusMarshaller extends IdaStatusMarshaller<IdpIdaStatus> { @Override protected Optional<String> getStatusMessage(IdpIdaStatus originalStatus) { return originalStatus.getMessage(); } IdpIdaStatusMarshaller(OpenSamlXmlObjectFactory samlObjectFactory); }### Answer:
@Test public void transform_shouldTransformRequesterErrorWithMessage() throws Exception { String message = "Oh dear"; Status transformedStatus = marshaller.toSamlStatus(IdpIdaStatus.requesterError(Optional.of(message))); assertThat(transformedStatus.getStatusCode().getValue()).isEqualTo(StatusCode.REQUESTER); assertThat(transformedStatus.getStatusMessage().getMessage()).isEqualTo(message); }
|
### Question:
LevelsOfAssuranceConfigValidator { protected void validateAllIDPsSupportLOA1orLOA2(Set<IdentityProviderConfig> identityProviderConfig) { List<IdentityProviderConfig> badIDPConfigs = identityProviderConfig.stream() .filter(x -> x.getSupportedLevelsOfAssurance().isEmpty() || containsUnsupportedLOAs(x)) .collect(Collectors.toList()); if(!badIDPConfigs.isEmpty()) { throw ConfigValidationException.createIDPLevelsOfAssuranceUnsupportedException(badIDPConfigs); } } void validateLevelsOfAssurance(final Set<IdentityProviderConfig> identityProviderConfig,
final Set<TransactionConfig> transactionConfig); }### Answer:
@Test public void checkIDPConfigIsWithinVerifyPolicyLevelsOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1And2Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); }
@Test public void shouldAllowSingleLevelOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); }
@Test(expected = ConfigValidationException.class) public void checkValidationThrowsExceptionWhenIDPSupportsAnLOAThatIsOutsideVerifyPolicyLevelsOfAssurance() { Set<IdentityProviderConfig> identityProviderConfig = Set.of(loa1To3Idp); levelsOfAssuranceConfigValidator.validateAllIDPsSupportLOA1orLOA2(identityProviderConfig); }
|
### Question:
OutboundResponseFromHubToSamlResponseTransformer extends IdaResponseToSamlResponseTransformer<OutboundResponseFromHub> { @Override protected void transformAssertions(OutboundResponseFromHub originalResponse, Response transformedResponse) { originalResponse .getEncryptedAssertions().stream() .map(encryptedAssertionUnmarshaller::transform) .forEach(transformedResponse.getEncryptedAssertions()::add); } OutboundResponseFromHubToSamlResponseTransformer(
IdaStatusMarshaller<TransactionIdaStatus> statusMarshaller,
OpenSamlXmlObjectFactory openSamlXmlObjectFactory,
EncryptedAssertionUnmarshaller encryptedAssertionUnmarshaller); }### Answer:
@Test public void transformAssertions_shouldTransformMatchingServiceAssertions() throws Exception { PassthroughAssertion matchingServiceAssertion = aPassthroughAssertion().buildMatchingServiceAssertion(); Response transformedResponse = aResponse().withNoDefaultAssertion().build(); EncryptedAssertion transformedMatchingDatasetAssertion = anAssertion().build(); when(encryptedAssertionUnmarshaller.transform(matchingServiceAssertion.getUnderlyingAssertionBlob())).thenReturn(transformedMatchingDatasetAssertion); String encryptedMatchingServiceAssertion = matchingServiceAssertion.getUnderlyingAssertionBlob(); transformer.transformAssertions(anAuthnResponse().withEncryptedAssertions(Collections.singletonList(encryptedMatchingServiceAssertion)).buildOutboundResponseFromHub(), transformedResponse); assertThat(transformedResponse.getEncryptedAssertions().size()).isEqualTo(1); assertThat(transformedResponse.getEncryptedAssertions().get(0)).isEqualTo(transformedMatchingDatasetAssertion); }
|
### Question:
EncryptedAssertionUnmarshaller { public EncryptedAssertion transform(String assertionString) { EncryptedAssertion assertion = stringAssertionTransformer.apply(assertionString); assertion.detach(); return assertion; } EncryptedAssertionUnmarshaller(StringToOpenSamlObjectTransformer<EncryptedAssertion> stringAssertionTransformer); EncryptedAssertion transform(String assertionString); }### Answer:
@Test public void shouldCreateAEncryptedAssertionObjectFromAGivenString() throws Exception { EncryptedAssertionUnmarshaller encryptedAssertionUnmarshaller = new EncryptedAssertionUnmarshaller(stringToEncryptedAssertionTransformer); final EncryptedAssertion expected = new EncryptedAssertionBuilder().buildObject(); when(stringToEncryptedAssertionTransformer.apply(ENCRYPTED_ASSERTION_BLOB)).thenReturn(expected); final EncryptedAssertion encryptedAssertion = encryptedAssertionUnmarshaller.transform(ENCRYPTED_ASSERTION_BLOB); assertThat(encryptedAssertion).isEqualTo(expected); }
|
### Question:
AuthnRequestIssueInstantValidator { public boolean isValid(DateTime issueInstant) { final Duration authnRequestValidityDuration = samlAuthnRequestValidityDurationConfiguration.getAuthnRequestValidityDuration(); return !issueInstant.isBefore(DateTime.now().minus(authnRequestValidityDuration.toMilliseconds())); } @Inject AuthnRequestIssueInstantValidator(SamlAuthnRequestValidityDurationConfiguration samlAuthnRequestValidityDurationConfiguration); boolean isValid(DateTime issueInstant); }### Answer:
@Test public void validate_shouldReturnFalseIfIssueInstantMoreThan5MinutesAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS).minusSeconds(1); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(false); }
@Test public void validate_shouldReturnTrueIfIssueInstant5MinsAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(true); }
@Test public void validate_shouldReturnTrueIfIssueInstantLessThan5MinsAgo() { DateTimeFreezer.freezeTime(); DateTime issueInstant = DateTime.now().minusMinutes(AUTHN_REQUEST_VALIDITY_MINS).plusSeconds(1); boolean validity = authnRequestIssueInstantValidator.isValid(issueInstant); assertThat(validity).isEqualTo(true); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.