method2testcases
stringlengths 118
6.63k
|
---|
### Question:
MrpAlgorithmStrategyTS implements MrpAlgorithmStrategy { public Map<Long, BigDecimal> perform(final OperationProductComponentWithQuantityContainer productComponentWithQuantities, final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm, final String operationProductComponentModelName) { OperationProductComponentWithQuantityContainer allWithSameEntityType = productComponentWithQuantities .getAllWithSameEntityType(operationProductComponentModelName); Map<Long, BigDecimal> productWithQuantities = Maps.newHashMap(); for (Entry<OperationProductComponentHolder, BigDecimal> productComponentWithQuantity : allWithSameEntityType.asMap() .entrySet()) { OperationProductComponentHolder operationProductComponentHolder = productComponentWithQuantity.getKey(); if (nonComponents.contains(operationProductComponentHolder)) { Entity product = operationProductComponentHolder.getProduct(); Entity technologyOperationComponent = operationProductComponentHolder.getTechnologyOperationComponent(); if (technologyOperationComponent != null) { List<Entity> children = technologyOperationComponent.getHasManyField(CHILDREN).find() .add(SearchRestrictions.eq(TechnologyOperationComponentFieldsTS.IS_SUBCONTRACTING, true)).list() .getEntities(); boolean isSubcontracting = false; for (Entity child : children) { Entity operationProductOutComponent = child.getHasManyField(OPERATION_PRODUCT_OUT_COMPONENTS).find() .add(SearchRestrictions.belongsTo(PRODUCT, product)).setMaxResults(1).uniqueResult(); if (operationProductOutComponent != null) { isSubcontracting = true; } } if (!isSubcontracting) { continue; } } } productQuantitiesService.addProductQuantitiesToList(productComponentWithQuantity, productWithQuantities); } return productWithQuantities; } boolean isApplicableFor(final MrpAlgorithm mrpAlgorithm); Map<Long, BigDecimal> perform(final OperationProductComponentWithQuantityContainer productComponentWithQuantities,
final Set<OperationProductComponentHolder> nonComponents, final MrpAlgorithm mrpAlgorithm,
final String operationProductComponentModelName); }### Answer:
@Test public void shouldReturnMapWithoutProductFromSubcontractingOperation() throws Exception { Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(2, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); }
@Test public void shouldReturnMapWithProductFromOneSubcontractingOperations() throws Exception { when(operComp1.getBooleanField("isSubcontracting")).thenReturn(true); Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(3, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product2.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); }
@Test public void shouldReturnProductFromAllSubcontractingOperation() throws Exception { when(operComp1.getBooleanField("isSubcontracting")).thenReturn(true); when(operComp2.getBooleanField("isSubcontracting")).thenReturn(true); Map<Long, BigDecimal> productsMap = algorithmStrategyTS.perform(productComponentQuantities, nonComponents, MrpAlgorithm.COMPONENTS_AND_SUBCONTRACTORS_PRODUCTS, "productInComponent"); assertEquals(4, productsMap.size()); assertEquals(new BigDecimal(5), productsMap.get(product1.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product2.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product3.getId())); assertEquals(BigDecimal.ONE, productsMap.get(product4.getId())); } |
### Question:
OrderRealizationTimeServiceImpl implements OrderRealizationTimeService { @Override @Transactional public int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) { Entity technology = operationComponent.getBelongsToField(TECHNOLOGY); Map<Long, BigDecimal> operationRunsFromProductionQuantities = Maps.newHashMap(); OperationProductComponentWithQuantityContainer productComponentQuantities = productQuantitiesService .getProductComponentQuantities(technology, plannedQuantity, operationRunsFromProductionQuantities); return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsFromProductionQuantities, productionLine, false, productComponentQuantities); } @Override Object setDateToField(final Date date); @Override @Transactional int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override @Transactional int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine); @Override Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateMaxOperationTimeConsumptionsForWorkstations(final Entity entity,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine); @Override int evaluateSingleOperationTime(Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation); @Override int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent,
final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns,
final Entity productionLine, final boolean maxForWorkstation,
final OperationProductComponentWithQuantityContainer productComponentQuantities); @Override int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent,
final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz,
final boolean includeAdditionalTime); @Override BigDecimal getBigDecimalFromField(final Object value, final Locale locale); @Override int estimateOperationTimeConsumption(EntityTreeNode operationComponent, BigDecimal plannedQuantity,
Entity productionLine); }### Answer:
@Test public void shouldReturnCorrectOperationTimeWithShifts() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); int time = orderRealizationTimeServiceImpl.estimateOperationTimeConsumption(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(10, time); }
@Test public void shouldActuallyMakeTimeConsumptionLongerWithMoreWorkstationsDueAdditionalTpz() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); when(productionLinesService.getWorkstationTypesCount(opComp1, productionLine)).thenReturn(2); when(productionLinesService.getWorkstationTypesCount(opComp2, productionLine)).thenReturn(2); int time = orderRealizationTimeServiceImpl.estimateOperationTimeConsumption(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(14, time); } |
### Question:
OrderRealizationTimeServiceImpl implements OrderRealizationTimeService { @Override @Transactional public int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine) { Entity technology = operationComponent.getBelongsToField(TECHNOLOGY); Map<Long, BigDecimal> operationRunsFromProductionQuantities = Maps.newHashMap(); OperationProductComponentWithQuantityContainer productComponentQuantities = productQuantitiesService .getProductComponentQuantities(technology, plannedQuantity, operationRunsFromProductionQuantities); return evaluateOperationTime(operationComponent, includeTpz, includeAdditionalTime, operationRunsFromProductionQuantities, productionLine, true, productComponentQuantities); } @Override Object setDateToField(final Date date); @Override @Transactional int estimateOperationTimeConsumption(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override @Transactional int estimateMaxOperationTimeConsumptionForWorkstation(final EntityTreeNode operationComponent,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine); @Override Map<Entity, Integer> estimateOperationTimeConsumptions(final Entity entity, final BigDecimal plannedQuantity,
final boolean includeTpz, final boolean includeAdditionalTime, final Entity productionLine); @Override Map<Entity, Integer> estimateMaxOperationTimeConsumptionsForWorkstations(final Entity entity,
final BigDecimal plannedQuantity, final boolean includeTpz, final boolean includeAdditionalTime,
final Entity productionLine); @Override int evaluateSingleOperationTime(Entity operationComponent, final boolean includeTpz,
final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns, final Entity productionLine,
final boolean maxForWorkstation); @Override int evaluateSingleOperationTimeIncludedNextOperationAfterProducedQuantity(Entity operationComponent,
final boolean includeTpz, final boolean includeAdditionalTime, final Map<Long, BigDecimal> operationRuns,
final Entity productionLine, final boolean maxForWorkstation,
final OperationProductComponentWithQuantityContainer productComponentQuantities); @Override int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent,
final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz,
final boolean includeAdditionalTime); @Override BigDecimal getBigDecimalFromField(final Object value, final Locale locale); @Override int estimateOperationTimeConsumption(EntityTreeNode operationComponent, BigDecimal plannedQuantity,
Entity productionLine); }### Answer:
@Test public void shouldCalculateMaxTimeConsumptionPerWorkstationCorrectly() { boolean includeTpz = true; boolean includeAdditionalTime = true; BigDecimal plannedQuantity = new BigDecimal(1); when(productionLinesService.getWorkstationTypesCount(opComp1, productionLine)).thenReturn(2); when(productionLinesService.getWorkstationTypesCount(opComp2, productionLine)).thenReturn(2); int time = orderRealizationTimeServiceImpl.estimateMaxOperationTimeConsumptionForWorkstation(opComp1, plannedQuantity, includeTpz, includeAdditionalTime, productionLine); assertEquals(7, time); } |
### Question:
MultitransferListeners { public void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { fillUnitsInADL(view, PRODUCTS); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo,
final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state,
final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }### Answer:
@Test public void shouldFillUnitsInADL() { multitransferListeners.fillUnitsInADL(view, state, null); verify(unit).setFieldValue(L_UNIT); verify(formComponent).setEntity(productQuantity); } |
### Question:
MultitransferListeners { @Transactional public void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (!isMultitransferFormValid(view)) { return; } FormComponent multitransferForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent typeField = (FieldComponent) view.getComponentByReference(TYPE); FieldComponent timeField = (FieldComponent) view.getComponentByReference(TIME); FieldComponent locationFromField = (FieldComponent) view.getComponentByReference(LOCATION_FROM); FieldComponent locationToField = (FieldComponent) view.getComponentByReference(LOCATION_TO); FieldComponent staffField = (FieldComponent) view.getComponentByReference(STAFF); typeField.requestComponentUpdateState(); timeField.requestComponentUpdateState(); locationToField.requestComponentUpdateState(); locationFromField.requestComponentUpdateState(); staffField.requestComponentUpdateState(); String type = typeField.getFieldValue().toString(); Date time = DateUtils.parseDate(timeField.getFieldValue()); Entity locationFrom = materialFlowService.getLocationById((Long) locationFromField.getFieldValue()); Entity locationTo = materialFlowService.getLocationById((Long) locationToField.getFieldValue()); Entity staff = materialFlowService.getStaffById((Long) staffField.getFieldValue()); AwesomeDynamicListComponent adlc = (AwesomeDynamicListComponent) view.getComponentByReference(PRODUCTS); List<FormComponent> formComponents = adlc.getFormComponents(); for (FormComponent formComponent : formComponents) { Entity productQuantity = formComponent.getEntity(); BigDecimal quantity = productQuantity.getDecimalField(QUANTITY); Entity product = productQuantity.getBelongsToField(PRODUCT); if ((product != null) && (quantity != null)) { Entity transfer = createTransfer(type, time, locationFrom, locationTo, staff, product, quantity); if (!checkIfTransferIsValid(formComponent, transfer)) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return; } } } adlc.setFieldValue(null); multitransferForm.setEntity(multitransferForm.getEntity()); state.performEvent(view, "refresh", new String[0]); view.getComponentByReference(L_FORM).addMessage("materialFlowMultitransfers.multitransfer.generate.success", MessageType.SUCCESS); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo,
final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state,
final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }### Answer:
@Ignore @Test public void shouldCreateMultitransfer() { multitransferListeners.createMultitransfer(view, state, null); verify(form).addMessage("materialFlow.multitransfer.generate.success", MessageType.SUCCESS); } |
### Question:
MatchingChangeoverNormsDetailsHooks { public void setFieldsVisible(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); ComponentState matchingNorm = view.getComponentByReference("matchingNorm"); ComponentState matchingNormNotFound = view.getComponentByReference("matchingNormNotFound"); if (form.getEntityId() == null) { matchingNorm.setVisible(false); matchingNormNotFound.setVisible(true); } else { matchingNorm.setVisible(true); matchingNormNotFound.setVisible(false); } } void setFieldsVisible(final ViewDefinitionState view); void fillOrCleanFields(final ViewDefinitionState view); }### Answer:
@Test public void shouldntSetFieldsVisibleWhenNormsNotFound() { given(form.getEntityId()).willReturn(null); hooks.setFieldsVisible(view); verify(matchingNorm).setVisible(false); verify(matchingNormNotFound).setVisible(true); }
@Test public void shouldSetFieldsVisibleWhenNormsFound() { given(form.getEntityId()).willReturn(1L); hooks.setFieldsVisible(view); verify(matchingNorm).setVisible(true); verify(matchingNormNotFound).setVisible(false); } |
### Question:
MultitransferListeners { public void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args) { getFromTemplates(view); } @Transactional void createMultitransfer(final ViewDefinitionState view, final ComponentState state, final String[] args); boolean checkIfTransferIsValid(FormComponent formComponent, Entity transfer); boolean isMultitransferFormValid(final ViewDefinitionState view); Entity createTransfer(final String type, final Date time, final Entity locationFrom, final Entity locationTo,
final Entity staff, final Entity product, final BigDecimal quantity); void fillUnitsInADL(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void getFromTemplates(final ViewDefinitionState view, final ComponentState state, final String[] args); void getFromTemplates(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view, final ComponentState state,
final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void checkIfLocationToHasExternalNumber(final ViewDefinitionState view); void checkIfLocationFromHasExternalNumber(final ViewDefinitionState view); }### Answer:
@Ignore @Test public void shouldDownloadProductsFromTemplates() { given(template.getBelongsToField(PRODUCT)).willReturn(product); given( dataDefinitionService.get(MaterialFlowMultitransfersConstants.PLUGIN_IDENTIFIER, MaterialFlowMultitransfersConstants.MODEL_PRODUCT_QUANTITY)).willReturn(productQuantityDD); given(productQuantityDD.create()).willReturn(productQuantity); multitransferListeners.getFromTemplates(view, state, null); verify(productQuantity).setField(PRODUCT, product); verify(adlc).setFieldValue(Arrays.asList(productQuantity)); verify(form).addMessage("materialFlow.multitransfer.template.success", MessageType.SUCCESS); } |
### Question:
MultitransferViewHooks { public void makeFieldsRequired(final ViewDefinitionState view) { for (String componentRef : COMPONENTS) { FieldComponent component = (FieldComponent) view.getComponentByReference(componentRef); component.setRequired(true); component.requestComponentUpdateState(); } } void makeFieldsRequired(final ViewDefinitionState view); void disableDateField(final ViewDefinitionState view); }### Answer:
@Test public void shouldMakeTimeAndTypeFieldsRequired() { given(view.getComponentByReference(TIME)).willReturn(time); given(view.getComponentByReference(TYPE)).willReturn(type); multitransferViewHooks.makeFieldsRequired(view); verify(time).setRequired(true); verify(type).setRequired(true); } |
### Question:
MessagesUtil { public static String joinArgs(final String[] splittedArgs) { if (ArrayUtils.isEmpty(splittedArgs)) { return null; } return StringUtils.join(splittedArgs, ARGS_SEPARATOR); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }### Answer:
@Test public final void shouldReturnJoinedString() { final String[] splittedArgs = new String[] { "mes", "plugins", "states", "test" }; final String joinedString = MessagesUtil.joinArgs(splittedArgs); final String expectedString = splittedArgs[0] + ARGS_SEPARATOR + splittedArgs[1] + ARGS_SEPARATOR + splittedArgs[2] + ARGS_SEPARATOR + splittedArgs[3]; assertEquals(expectedString, joinedString); }
@Test public final void shouldReturnNullIfGivenSplittedStringIsNull() { final String joinedString = MessagesUtil.joinArgs(null); assertNull(joinedString); }
@Test public final void shouldReturnNullIfGivenSplittedStringIsEmpty() { final String joinedString = MessagesUtil.joinArgs(new String[] {}); assertNull(joinedString); } |
### Question:
MessagesUtil { public static String[] splitArgs(final String joinedArgs) { if (StringUtils.isBlank(joinedArgs)) { return ArrayUtils.EMPTY_STRING_ARRAY; } return joinedArgs.split(ARGS_SEPARATOR); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }### Answer:
@Test public final void shouldReturnSplittedString() { final String arg1 = "mes"; final String arg2 = "plugins"; final String arg3 = "states"; final String arg4 = "test"; final String joinedArgs = arg1 + ARGS_SEPARATOR + arg2 + ARGS_SEPARATOR + arg3 + ARGS_SEPARATOR + arg4; final String[] splittedString = MessagesUtil.splitArgs(joinedArgs); assertEquals(4, splittedString.length); assertEquals(arg1, splittedString[0]); assertEquals(arg2, splittedString[1]); assertEquals(arg3, splittedString[2]); assertEquals(arg4, splittedString[3]); }
@Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsNull() { final String[] splittedString = MessagesUtil.splitArgs(null); assertNotNull(splittedString); assertEquals(0, splittedString.length); }
@Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsEmpty() { final String[] splittedString = MessagesUtil.splitArgs(""); assertNotNull(splittedString); assertEquals(0, splittedString.length); }
@Test public final void shouldReturnEmptyArrayIfGivenJoinedStringIsBlank() { final String[] splittedString = MessagesUtil.splitArgs(" "); assertNotNull(splittedString); assertEquals(0, splittedString.length); } |
### Question:
MessagesUtil { public static boolean hasFailureMessages(final List<Entity> messages) { return hasMessagesOfType(messages, StateMessageType.FAILURE); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }### Answer:
@Test public final void shouldHasFailureMessagesReturnTrue() { List<Entity> messages = Lists.newArrayList(); messages.add(mockMessage(StateMessageType.FAILURE, "test")); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertTrue(result); }
@Test public final void shouldHasFailureMessagesReturnFalse() { List<Entity> messages = Lists.newArrayList(); messages.add(mockMessage(StateMessageType.SUCCESS, "test")); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertFalse(result); }
@Test public final void shouldHasFailureMessagesReturnFalseForEmptyMessages() { List<Entity> messages = Lists.newArrayList(); EntityList messagesEntityList = mockEntityList(messages); boolean result = MessagesUtil.hasFailureMessages(messagesEntityList); assertFalse(result); } |
### Question:
MessagesUtil { public static boolean isAutoClosed(final Entity message) { return message.getField(AUTO_CLOSE) == null || message.getBooleanField(AUTO_CLOSE); } private MessagesUtil(); static String joinArgs(final String[] splittedArgs); static String[] splitArgs(final String joinedArgs); static boolean hasFailureMessages(final List<Entity> messages); static boolean hasValidationErrorMessages(final List<Entity> messages); static boolean messageIsTypeOf(final Entity message, final StateMessageType typeLookingFor); static boolean hasCorrespondField(final Entity message); static MessageType convertViewMessageType(final StateMessageType type); static String getKey(final Entity message); static String[] getArgs(final Entity message); static String getCorrespondFieldName(final Entity message); static boolean isAutoClosed(final Entity message); static final String ARGS_SEPARATOR; }### Answer:
@Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsFalse() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(false); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(false); final boolean result = MessagesUtil.isAutoClosed(message); assertFalse(result); }
@Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsTrue() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(true); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(true); final boolean result = MessagesUtil.isAutoClosed(message); assertTrue(result); }
@Test public final void shouldIsAutoClosedReturnFalseIfFieldValueIsNull() { final Entity message = mock(Entity.class); given(message.getField(MessageFields.AUTO_CLOSE)).willReturn(null); given(message.getBooleanField(MessageFields.AUTO_CLOSE)).willReturn(false); final boolean result = MessagesUtil.isAutoClosed(message); assertTrue(result); } |
### Question:
StateChangeViewClientValidationUtil { public void addValidationErrorMessages(final ComponentState component, final StateChangeContext stateChangeContext) { addValidationErrorMessages(component, stateChangeContext.getOwner(), stateChangeContext); } void addValidationErrorMessages(final ComponentState component, final StateChangeContext stateChangeContext); void addValidationErrorMessages(final ComponentState component, final Entity entity,
final MessagesHolder messagesHolder); }### Answer:
@Test public final void shouldAddValidationErrorToEntityField() { final String existingFieldName = "existingField"; FieldDefinition existingField = mockFieldDefinition(existingFieldName); DataDefinition dataDefinition = mockDataDefinition(Lists.newArrayList(existingField)); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg(existingFieldName, false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity).addError(existingField, TRANSLATION_KEY); }
@Test public final void shouldAddValidationErrorToWholeEntityIfFieldDoesNotExist() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg("notExistingField", false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); }
@Test public final void shouldAddValidationErrorToWholeEntityIfFieldIsEmpty() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg("", false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); }
@Test public final void shouldAddValidationErrorToWholeEntityIfFieldIsNull() { DataDefinition dataDefinition = mockDataDefinition(Lists.<FieldDefinition> newArrayList()); given(entity.getDataDefinition()).willReturn(dataDefinition); given(formComponent.getEntity()).willReturn(entity); Entity message = mockValidationErrorMsg(null, false, TRANSLATION_KEY); given(messagesHolder.getAllMessages()).willReturn(Lists.newArrayList(message)); validationUtil.addValidationErrorMessages(formComponent, entity, messagesHolder); verify(entity, Mockito.never()).addError(Mockito.any(FieldDefinition.class), Mockito.eq(TRANSLATION_KEY)); verify(entity).addGlobalError(TRANSLATION_KEY, false); } |
### Question:
AbstractStateChangeDescriber implements StateChangeEntityDescriber { @Override public void checkFields() { DataDefinition dataDefinition = getDataDefinition(); List<String> fieldNames = Lists.newArrayList(getOwnerFieldName(), getSourceStateFieldName(), getTargetStateFieldName(), getStatusFieldName(), getMessagesFieldName(), getPhaseFieldName(), getDateTimeFieldName(), getShiftFieldName(), getWorkerFieldName()); Set<String> uniqueFieldNames = Sets.newHashSet(fieldNames); checkState(fieldNames.size() == uniqueFieldNames.size(), "Describer methods should return unique field names."); Set<String> existingFieldNames = dataDefinition.getFields().keySet(); checkState(existingFieldNames.containsAll(uniqueFieldNames), "DataDefinition for " + dataDefinition.getPluginIdentifier() + '.' + dataDefinition.getName() + " does not have all fields with name specified by this desciber."); } @Override String getSourceStateFieldName(); @Override String getTargetStateFieldName(); @Override String getStatusFieldName(); @Override String getMessagesFieldName(); @Override String getPhaseFieldName(); @Override String getDateTimeFieldName(); @Override String getShiftFieldName(); @Override String getWorkerFieldName(); @Override String getOwnerStateFieldName(); @Override String getOwnerStateChangesFieldName(); @Override void checkFields(); }### Answer:
@Test public final void shouldCheckFieldsPass() { try { testStateChangeDescriber.checkFields(); } catch (IllegalStateException e) { fail(); } }
@Test public final void shouldCheckFieldsThrowExceptionIfAtLeastOneFieldIsMissing() { dataDefFieldsSet.remove("sourceState"); try { testStateChangeDescriber.checkFields(); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } }
@Test public final void shouldCheckFieldsThrowExceptionIfAtLeastOneFieldNameIsNotUnique() { BrokenTestStateChangeDescriber brokenTestStateChangeDescriber = new BrokenTestStateChangeDescriber(); try { brokenTestStateChangeDescriber.checkFields(); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } } |
### Question:
MatchingChangeoverNormsDetailsHooks { public void fillOrCleanFields(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); if (form.getEntityId() == null) { listeners.clearField(view); listeners.changeStateEditButton(view, false); } else { Entity changeover = dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS).get(form.getEntityId()); listeners.fillField(view, changeover); listeners.changeStateEditButton(view, true); } } void setFieldsVisible(final ViewDefinitionState view); void fillOrCleanFields(final ViewDefinitionState view); }### Answer:
@Test public void shouldFillOrCleanFieldsNormsNotFound() { given(form.getEntityId()).willReturn(null); hooks.fillOrCleanFields(view); verify(listeners).clearField(view); verify(listeners).changeStateEditButton(view, false); }
@Test public void shouldFillOrCleanFieldsWhenNormsFound() { given(form.getEntityId()).willReturn(1L); given( dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS)).willReturn(changeoverDD); given(changeoverDD.get(1L)).willReturn(changeover); hooks.fillOrCleanFields(view); verify(listeners).fillField(view, changeover); verify(listeners).changeStateEditButton(view, true); } |
### Question:
Sha1Digest implements MessageDigest { public String calculate(final InputStream inputStream) throws IOException { logger.trace("Calculating message digest"); return DigestUtils.sha1Hex(inputStream); } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }### Answer:
@Test public void testCalculateInputStream() throws IOException { try (InputStream inputStream = getClass().getResourceAsStream("message.txt")) { Sha1Digest sha1Digest = new Sha1Digest(); String ret = sha1Digest.calculate(inputStream); assertEquals("The message digest do not match", MESSAGE_DIGEST, ret); } } |
### Question:
WorkerDataUtils { public static <T extends MaestroWorker> BinaryRateWriter writer(final File reportFolder, final T worker) throws IOException { assert worker != null : "Invalid worker type"; if (worker instanceof MaestroSenderWorker) { return new BinaryRateWriter(new File(reportFolder, "sender.dat"), FileHeader.WRITER_DEFAULT_SENDER); } if (worker instanceof MaestroReceiverWorker) { return new BinaryRateWriter(new File(reportFolder, "receiver.dat"), FileHeader.WRITER_DEFAULT_SENDER); } logger.error("Invalid worker class: {}", worker.getClass()); return null; } static BinaryRateWriter writer(final File reportFolder, final T worker); }### Answer:
@Test public void testCreate() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportDir = new File(path); try (BinaryRateWriter writer = WorkerDataUtils.writer(reportDir, new DummySender())) { assertNotNull("The writer should not be null", writer); assertEquals("The report path does not match", new File(reportDir, "sender.dat"), writer.reportFile()); } } |
### Question:
JmsOptions { public JmsOptions(final String url) { try { final URI uri = new URI(url); final URLQuery urlQuery = new URLQuery(uri); protocol = JMSProtocol.valueOf(urlQuery.getString("protocol", JMSProtocol.AMQP.name())); path = uri.getPath(); type = urlQuery.getString("type", "queue"); configuredLimitDestinations = urlQuery.getInteger("limitDestinations", 0); durable = urlQuery.getBoolean("durable", false); priority = urlQuery.getInteger("priority", 0); ttl = urlQuery.getLong("ttl", 0L); sessionMode = urlQuery.getInteger("sessionMode", Session.AUTO_ACKNOWLEDGE); batchAcknowledge = urlQuery.getInteger("batchAcknowledge", 0); connectionUrl = filterJMSURL(uri); } catch (Throwable t) { logger.warn("Something wrong happened while parsing arguments from url : {}", t.getMessage(), t); } } JmsOptions(final String url); JMSProtocol getProtocol(); long getTtl(); boolean isDurable(); int getSessionMode(); int getConfiguredLimitDestinations(); String getType(); int getPriority(); String getConnectionUrl(); String getPath(); int getBatchAcknowledge(); }### Answer:
@Test public void testJmsOptions() { final String url = "amqps: JmsOptions jmsOptions = new JmsOptions(url); assertFalse("Expected durable to be false", jmsOptions.isDurable()); assertEquals("The connection URL does not match the expected one", "amqps: jmsOptions.getConnectionUrl()); } |
### Question:
JMSClient implements Client { public static String setupLimitDestinations(final String destinationName, final int limitDestinations, final int clientNumber) { String ret = destinationName; if (limitDestinations >= 1) { logger.debug("Client requested a client-specific limit to the number of destinations: {}", limitDestinations); final int destinationId = clientNumber % limitDestinations; ret = destinationName + '.' + destinationId; logger.info("Requested destination name after using client-specific limit to the number of destinations: {}", ret); return ret; } else { if (limitDestinations < 0) { throw new IllegalArgumentException("Negative number of limit destinations is invalid"); } logger.info("Requested destination name: {}", destinationName); } return ret; } int getNumber(); void setNumber(int number); JmsOptions getOpts(); @Override void start(); static String setupLimitDestinations(final String destinationName, final int limitDestinations,
final int clientNumber); @Override void stop(); @Override void setUrl(String url); }### Answer:
@Test public void testLimitDestinations() { final String requestedDestName = "test.unit.queue"; for (int i = 0; i < 5; i++) { String destinationName = JMSClient.setupLimitDestinations("test.unit.queue", 5, i); assertEquals("The destination name does not match the expected one", requestedDestName + "." + i, destinationName); } }
@Test public void testDefaultLimitDestination() { final String requestedDestName = "test.unit.queue"; for (int i = 0; i < 5; i++) { String destinationName = JMSClient.setupLimitDestinations("test.unit.queue", 0, i); assertEquals("The destination name does not match the expected one", requestedDestName, destinationName); } } |
### Question:
StringUtils { public static String capitalize(final String string) { if (string != null && string.length() >= 2) { return string.substring(0, 1).toUpperCase() + string.substring(1); } else { return string; } } private StringUtils(); static String capitalize(final String string); }### Answer:
@Test public void testCapitalize() { assertEquals("Username", StringUtils.capitalize("username")); assertEquals("u", StringUtils.capitalize("u")); assertEquals("Uu", StringUtils.capitalize("uu")); assertEquals(null, StringUtils.capitalize(null)); assertEquals("", StringUtils.capitalize("")); } |
### Question:
BinaryRateWriter implements RateWriter { @Override public void close() { try { flush(); fileChannel.close(); } catch (IOException e) { Logger logger = LoggerFactory.getLogger(BinaryRateWriter.class); logger.error(e.getMessage(), e); } } BinaryRateWriter(final File reportFile, final FileHeader fileHeader); @Override File reportFile(); void write(int metadata, long count, long timestamp); void flush(); @Override void close(); }### Answer:
@Test public void testHeader() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "testHeader.dat"); try { BinaryRateWriter binaryRateWriter = new BinaryRateWriter(reportFile, FileHeader.WRITER_DEFAULT_SENDER); binaryRateWriter.close(); try (BinaryRateReader reader = new BinaryRateReader(reportFile)) { FileHeader fileHeader = reader.getHeader(); assertEquals(FileHeader.MAESTRO_FORMAT_NAME, fileHeader.getFormatName().trim()); assertEquals(FileHeader.CURRENT_FILE_VERSION, fileHeader.getFileVersion()); assertEquals(Constants.VERSION_NUMERIC, fileHeader.getMaestroVersion()); assertEquals(Role.SENDER, fileHeader.getRole()); } } finally { clean(reportFile); } } |
### Question:
BinaryRateWriter implements RateWriter { private void write() throws IOException { byteBuffer.flip(); while (byteBuffer.hasRemaining()) { fileChannel.write(byteBuffer); } byteBuffer.flip(); byteBuffer.clear(); } BinaryRateWriter(final File reportFile, final FileHeader fileHeader); @Override File reportFile(); void write(int metadata, long count, long timestamp); void flush(); @Override void close(); }### Answer:
@Test(expected = InvalidRecordException.class) public void testHeaderWriteRecordsNonSequential() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "testHeaderWriteRecordsNonSequential.dat"); try (BinaryRateWriter binaryRateWriter = new BinaryRateWriter(reportFile, FileHeader.WRITER_DEFAULT_SENDER)) { EpochMicroClock clock = EpochClocks.exclusiveMicro(); long total = TimeUnit.DAYS.toSeconds(1); long now = clock.microTime(); for (int i = 0; i < total; i++) { binaryRateWriter.write(0, i + 1, now); now -= TimeUnit.SECONDS.toMicros(1); } } finally { clean(reportFile); } } |
### Question:
BinaryRateUpdater implements AutoCloseable { public static void joinFile(final BinaryRateUpdater binaryRateUpdater, final File reportFile1) throws IOException { try (BinaryRateReader reader = new BinaryRateReader(reportFile1)) { if (!binaryRateUpdater.isOverlay()) { FileHeader header = binaryRateUpdater.getFileHeader(); if (header == null) { binaryRateUpdater.updateHeader(reader.getHeader()); } } RateEntry entry = reader.readRecord(); long index = 0; while (entry != null) { binaryRateUpdater.update(entry, index); entry = reader.readRecord(); index++; } } } BinaryRateUpdater(final File reportFile); BinaryRateUpdater(final File reportFile, boolean overlay); FileHeader getFileHeader(); void updateHeader(final FileHeader header); void update(RateEntry newer, long index); void flush(); @Override void close(); static void joinFile(final BinaryRateUpdater binaryRateUpdater, final File reportFile1); static BinaryRateUpdater get(Role role, File path); }### Answer:
@Test public void testJoinFile() throws IOException { String path = this.getClass().getResource(".").getPath(); File reportFile = new File(path, "sender.dat"); File baseFile = new File(path, "sender-0.dat"); FileUtils.copyFile(baseFile, reportFile); try (BinaryRateUpdater binaryRateUpdater = new BinaryRateUpdater(reportFile)) { File reportFile1 = new File(path, "sender-1.dat"); BinaryRateUpdater.joinFile(binaryRateUpdater, reportFile1); File reportFile2 = new File(path, "sender-2.dat"); BinaryRateUpdater.joinFile(binaryRateUpdater, reportFile2); try (BinaryRateReader reader = new BinaryRateReader(reportFile)) { FileHeader fileHeader = reader.getHeader(); assertEquals(FileHeader.MAESTRO_FORMAT_NAME, fileHeader.getFormatName().trim()); assertEquals(FileHeader.CURRENT_FILE_VERSION, fileHeader.getFileVersion()); assertEquals(138, fileHeader.getMaestroVersion()); assertEquals(Role.SENDER, fileHeader.getRole()); long count = 0; RateEntry entry = reader.readRecord(); while (entry != null) { count++; assertEquals("Unexpected value", entry.getCount(), count * 3); entry = reader.readRecord(); } long total = 86400; assertEquals("The number of records don't match", total, count); } } finally { clean(reportFile); } } |
### Question:
PropertyUtils { public static void loadProperties(final File testProperties, Map<String, Object> context) { if (testProperties.exists()) { Properties prop = new Properties(); try (FileInputStream in = new FileInputStream(testProperties)) { prop.load(in); prop.forEach((key, value) -> addToContext(context, key, value)); } catch (FileNotFoundException e) { logger.error("File not found error: {}", e.getMessage(), e); } catch (IOException e) { logger.error("Input/output error: {}", e.getMessage(), e); } } else { logger.debug("There are no properties file at {}", testProperties.getPath()); } } private PropertyUtils(); static void loadProperties(final File testProperties, Map<String, Object> context); }### Answer:
@Test public void testLoadProperties() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-query-params.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("amqp: assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); assertEquals("value1", context.get("param1")); assertEquals("value2", context.get("param2")); assertEquals("value3", context.get("param3")); }
@Test public void testNotFailOnNonExistentFile() { final Map<String, Object> context = new HashMap<>(); final File propertiesFile = new File("does not exist"); PropertyUtils.loadProperties(propertiesFile, context); }
@Test public void testLoadPropertiesSetEncrypted() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-query-params-encrypted-url.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("amqps: assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); assertEquals("value1", context.get("param1")); assertEquals("value2", context.get("param2")); assertEquals("value3", context.get("param3")); assertEquals("true", context.get("encrypted")); }
@Test public void testLoadPropertiesInvalidUrl() { final Map<String, Object> context = new HashMap<>(); final String path = this.getClass().getResource("test-with-invalid-url.properties").getPath(); final File propertiesFile = new File(path); PropertyUtils.loadProperties(propertiesFile, context); assertEquals("10", context.get("fcl")); assertEquals("testApi", context.get("apiName")); assertEquals("0.9", context.get("apiVersion")); assertEquals("30", context.get("limitDestinations")); assertEquals("100", context.get("duration")); assertEquals("256", context.get("messageSize")); assertEquals("3", context.get("parallelCount")); assertEquals("true", context.get("variableSize")); } |
### Question:
Sha1Digest implements MessageDigest { public boolean verify(String source) throws IOException { try (InputStream stream = new FileInputStream(source + "." + HASH_NAME)) { final String digest = IOUtils.toString(stream, Charset.defaultCharset()).trim(); return verify(source, digest); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }### Answer:
@Test public void testVerify() throws IOException { Sha1Digest sha1Digest = new Sha1Digest(); boolean ret = sha1Digest.verify(MESSAGE_FILE, MESSAGE_DIGEST); assertTrue("The message digest do not match", ret); } |
### Question:
DurationDrain extends DurationCount { @Override public boolean canContinue(TestProgress progress) { long count = progress.messageCount(); return !staleChecker.isStale(count); } DurationDrain(); @Override boolean canContinue(TestProgress progress); static final String DURATION_DRAIN_FORMAT; }### Answer:
@Test public void testCanContinue() { DurationDrain durationDrain = new DurationDrain(); assertEquals(-1, durationDrain.getNumericDuration()); DurationCountTest.DurationCountTestProgress progress = new DurationCountTest.DurationCountTestProgress(); for (int i = 0; i < 10; i++) { assertTrue(durationDrain.canContinue(progress)); progress.increment(); } for (int i = 0; i < 9; i++) { assertTrue("Cannot continue with current count of " + progress.messageCount(), durationDrain.canContinue(progress)); } assertFalse(durationDrain.canContinue(progress)); progress.increment(); assertTrue(durationDrain.canContinue(progress)); } |
### Question:
DurationTime implements TestDuration { @Override public boolean canContinue(final TestProgress snapshot) { final long currentDuration = snapshot.elapsedTime(outputTimeUnit); return currentDuration < expectedDuration; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }### Answer:
@Test(timeout = 15000) public void testCanContinue() throws DurationParseException { DurationTime durationTime = new DurationTime("5s"); DurationTimeProgress progress = new DurationTimeProgress(System.currentTimeMillis()); assertTrue(durationTime.canContinue(progress)); try { Thread.sleep(5000); } catch (InterruptedException e) { fail("Interrupted while waiting for the test to timeout"); } assertFalse(durationTime.canContinue(progress)); assertEquals("time", durationTime.durationTypeName()); assertEquals(5, durationTime.getNumericDuration()); assertEquals(durationTime.getCoolDownDuration(), durationTime.getWarmUpDuration()); } |
### Question:
DurationTime implements TestDuration { @Override public long getNumericDuration() { return expectedDuration; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }### Answer:
@Test public void testExpectedDuration() throws DurationParseException { assertEquals(5, new DurationTime("5s").getNumericDuration()); assertEquals(300, new DurationTime("5m").getNumericDuration()); assertEquals(3900, new DurationTime("1h5m").getNumericDuration()); } |
### Question:
DurationTime implements TestDuration { public String toString() { return timeSpec; } DurationTime(final String timeSpec); @Override boolean canContinue(final TestProgress snapshot); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); }### Answer:
@Test public void testToStringRetainFormat() throws DurationParseException { assertEquals("5s", new DurationTime("5s").toString()); assertEquals("5m", new DurationTime("5m").toString()); assertEquals("1h5m", new DurationTime("1h5m").toString()); } |
### Question:
DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } DurationCount(final String durationSpec); DurationCount(long count); @Override boolean canContinue(final TestProgress progress); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); static final long WARM_UP_COUNT; }### Answer:
@Test public void testCanContinue() { DurationCount durationCount = new DurationCount("10"); assertEquals(10L, durationCount.getNumericDuration()); DurationCountTestProgress progress = new DurationCountTestProgress(); for (int i = 0; i < durationCount.getNumericDuration(); i++) { assertTrue(durationCount.canContinue(progress)); progress.increment(); } assertFalse(durationCount.canContinue(progress)); progress.increment(); assertFalse(durationCount.canContinue(progress)); assertEquals("count", durationCount.durationTypeName()); assertEquals("10", durationCount.toString()); assertEquals(durationCount.getCoolDownDuration(), durationCount.getWarmUpDuration()); } |
### Question:
WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } private WorkerUtils(); static long getExchangeInterval(final long rate); static long waitNanoInterval(final long expectedFireTime, final long intervalInNanos); }### Answer:
@Test public void testRate() { assertEquals(0, WorkerUtils.getExchangeInterval(0)); assertEquals(20000, WorkerUtils.getExchangeInterval(50000)); } |
### Question:
Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); }### Answer:
@Test public void testSave() throws IOException { Sha1Digest sha1Digest = new Sha1Digest(); sha1Digest.save(MESSAGE_FILE); sha1Digest.verify(MESSAGE_FILE); } |
### Question:
URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); }### Answer:
@Test public void testURLPathRewrite() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); }
@Test public void testURLPathRewriteWithUser() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); }
@Test public void testURLPathRewriteWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); }
@Test public void testURLPathRewriteWithUserWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } |
### Question:
ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } private ContentStrategyFactory(); static ContentStrategy parse(final String sizeSpec); }### Answer:
@Test public void testParse() { assertTrue(ContentStrategyFactory.parse("100") instanceof FixedSizeContent); assertTrue(ContentStrategyFactory.parse("~100") instanceof VariableSizeContent); } |
### Question:
VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } VariableSizeContent(int size); VariableSizeContent(final String sizeSpec); int minSize(); int maxSize(); @Override ByteBuffer prepareContent(); }### Answer:
@Test public void testPrepareContent() { VariableSizeContent content = new VariableSizeContent(100); assertEquals(96, content.minSize()); assertEquals(105, content.maxSize()); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); final int position = buffer.position(); final int offset = buffer.arrayOffset() + position; assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.minSize() <= length); assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.maxSize() >= length); } } |
### Question:
FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } FixedSizeContent(int size); FixedSizeContent(final String sizeSpec); @Override ByteBuffer prepareContent(); }### Answer:
@Test public void testPepareContent() { FixedSizeContent content = new FixedSizeContent(100); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); assertEquals(100, length); } } |
### Question:
MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }### Answer:
@Test public void testVariable() { assertEquals("~1024", MessageSize.variable(1024)); } |
### Question:
WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); }### Answer:
@Test public void testCleanExitOnDefault() { WorkerStateInfo wsi = new WorkerStateInfo(); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); }
@Test public void testCleanExitOnStopped() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); }
@Test public void testCleanExitOnSuccess() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); }
@Test public void testFailedExitOnFailure() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); }
@Test public void testCleanExitOnStoppedRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); }
@Test public void testCleanExitOnSuccessRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); }
@Test public void testFailedExitOnFailureRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } |
### Question:
MessageSize { public static String fixed(long value) { return Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }### Answer:
@Test public void testFixed() { assertEquals("1024", MessageSize.fixed(1024)); } |
### Question:
MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }### Answer:
@Test public void isVariable() { assertTrue(MessageSize.isVariable("~1024")); assertFalse(MessageSize.isVariable("1024")); } |
### Question:
MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); }### Answer:
@Test public void toSizeFromSpec() { assertEquals(1024, MessageSize.toSizeFromSpec("~1024")); } |
### Question:
LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } private LangUtils(); static void closeQuietly(T object); }### Answer:
@Test public void closeQuietly() { LangUtils.closeQuietly(null); MockCloseeable mock = new MockCloseeable(); LangUtils.closeQuietly(mock); assertTrue(mock.closeCalled); } |
### Question:
URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); }### Answer:
@Test public void testQueryWithFalse() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertFalse(urlQuery.getBoolean("value1", true)); assertTrue(urlQuery.getBoolean("value2", false)); } |
### Question:
URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); }### Answer:
@Test public void testQueryWithLong() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertEquals(1234L, (long) urlQuery.getLong("value1", 0L)); } |
### Question:
ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }### Answer:
@Test public void testInsert() { Report report = new Report(); report.setTestHost("localhost"); report.setTestHostRole(HostTypes.SENDER_HOST_TYPE); report.setTestName("unit-test"); report.setTestNumber(1); report.setTestId(1); report.setLocation(this.getClass().getResource(".").getPath()); report.setTestResult(ResultStrings.SUCCESS); report.setTestScript("undefined"); report.setTestDate(Date.from(Instant.now())); dao.insert(report); } |
### Question:
ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }### Answer:
@Test public void testFetchAll() throws DataNotFoundException { List<Report> reports = dao.fetch(); assertTrue("The database should not be empty", reports.size() > 0); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); } |
### Question:
ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }### Answer:
@Test public void testFetchById() throws DataNotFoundException { List<Report> reports = dao.fetch(2, 1); assertTrue("There should be at least 3 records for the given ID", reports.size() >= 3); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); } |
### Question:
ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); }### Answer:
@Test public void testAggregationInfo() throws DataNotFoundException { List<ReportAggregationInfo> aggregationInfos = dao.aggregationInfo(); long expectedAggregatedCount = 2; assertEquals("Unexpected amount of aggregated records", expectedAggregatedCount, aggregationInfos.size()); } |
### Question:
InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); }### Answer:
@SuppressWarnings("unchecked") @Test public void parseReceivedMessage() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); Map<String, Object> fakeMap = buildTestMap(); List<Map<String, Object>> ret = converter.parseReceivedMessage(fakeMap); assertNotNull(ret); assertEquals(3, ret.size()); Map<String, Object> map1 = ret.get(0); assertNotNull(map1); assertEquals(2, map1.size()); assertEquals(map1.get("attribute1"), "value1.1"); assertEquals(map1.get("attribute2"), "value1.2"); Map<String, Object> map2 = ret.get(1); assertNotNull(map2); assertEquals(2, map2.size()); assertEquals(map2.get("attribute1"), "value2.1"); assertEquals(map2.get("attribute2"), "value2.2"); Map<String, Object> map3 = ret.get(2); assertNotNull(map3); assertEquals(2, map3.size()); assertEquals(map3.get("attribute1"), "value3.1"); assertEquals(map3.get("attribute2"), "value3.2"); }
@Test public void parseReceivedMessageEmptyMap() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(new HashMap<String, Object>()); assertNotNull(ret); assertEquals(0, ret.size()); }
@Test public void parseReceivedMessageInvalidAttributeNames() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildInvalidMap()); assertNotNull(ret); assertEquals(0, ret.size()); }
@Test public void parseReceivedMessageWithEmptyLists() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildMapWithEmptyLists()); assertNotNull(ret); assertEquals(0, ret.size()); } |
### Question:
WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } WPSInitializer(WPSExecutionManager executionManager,
DefaultProcessManager processManager, WPSStorageCleaner cleaner); void initialize(final GeoServer geoServer); }### Answer:
@Test public void testSingleSave() throws Exception { GeoServer gs = createMock(GeoServer.class); List<ConfigurationListener> listeners = new ArrayList(); gs.addListener(capture(listeners)); expectLastCall().atLeastOnce(); List<ProcessGroupInfo> procGroups = new ArrayList(); WPSInfo wps = createNiceMock(WPSInfo.class); expect(wps.getProcessGroups()).andReturn(procGroups).anyTimes(); replay(wps); expect(gs.getService(WPSInfo.class)).andReturn(wps).anyTimes(); gs.save(wps); expectLastCall().once(); replay(gs); initer.initialize(gs); assertEquals(1, listeners.size()); ConfigurationListener l = listeners.get(0); l.handleGlobalChange(null, null, null, null); l.handlePostGlobalChange(null); verify(gs); } |
### Question:
WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } WPSXStreamLoader(GeoServerResourceLoader resourceLoader); Class<WPSInfo> getServiceClass(); }### Answer:
@Test public void testCreateFromScratch() throws Exception { WPSXStreamLoader loader = new WPSXStreamLoader(new GeoServerResourceLoader()); WPSInfo wps = loader.createServiceFromScratch(null); assertNotNull(wps); assertEquals("WPS", wps.getName()); } |
### Question:
WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } String getExecutionId(Boolean synch); void setCurrentExecutionId(String executionId); void addResource(WPSResource resource); File getOutputFile(String executionId, String fileName); File getTemporaryFile(String extension); File getStoredResponseFile(String executionId); File getWpsOutputStorage(); void finished(Request request); void finished(String executionId); Request init(Request request); Operation operationDispatched(Request request, Operation operation); Object operationExecuted(Request request, Operation operation, Object result); Response responseDispatched(Request request, Operation operation, Object result,
Response response); Service serviceDispatched(Request request, Service service); void onApplicationEvent(ApplicationEvent event); }### Answer:
@Test public void testAddResourceNoExecutionId() throws Exception { File f = File.createTempFile("dummy", "dummy", new File("target")); resourceMgr.addResource(new WPSFileResource(f)); } |
### Question:
PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping("") Flux<Post> all(); @PostMapping("") Mono<Post> create(@RequestBody Post post); @GetMapping("/{id}") Mono<Post> get(@PathVariable("id") String id); @PutMapping("/{id}") Mono<Post> update(@PathVariable("id") String id, @RequestBody Post post); @DeleteMapping("/{id}") Mono<Void> delete(@PathVariable("id") String id); }### Answer:
@Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } |
### Question:
PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); }### Answer:
@Test public void getPostById() throws Exception { this.rest .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.rest .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); }
@Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); }
@Test public void getPostById() throws Exception { this.client .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.client .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); }
@Test public void getAllPostsWillBeOk() throws Exception { this.rest .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } |
### Question:
PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } PostRepository(); }### Answer:
@Test public void testGetAllPosts() { StepVerifier.create(posts.findAll()) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post one"))) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post two"))) .expectComplete() .verify(); } |
### Question:
VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } @Override void init(FilterConfig cfg); @Override void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); @Override void destroy(); static final String VERSION; }### Answer:
@Test public void shoudlComplainIfNotInAServletEnviroment() throws Exception { exception.expect(ServletException.class); ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); vRaptor.doFilter(request, response, null); }
@Test public void shouldDeferToContainerIfStaticFile() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); handler.setRequestingStaticFile(true); vRaptor.doFilter(request, response, chain); assertThat(handler.isDeferProcessingToContainerCalled(), is(true)); }
@Test public void shouldBypassWebsocketRequests() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); vRaptor.doFilter(request, response, chain); verify(request).getHeader("Upgrade"); verify(chain).doFilter(request, response); verifyNoMoreInteractions(request, response); } |
### Question:
DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); }### Answer:
@Test public void registerParametersWithMultipleRegexes() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = new DefaultParametersControl("/test/{hash1:[a-z0-9]{16}}{id}{hash2:[a-z0-9]{16}}/", Collections.singletonMap("id", "\\d+"), converters, evaluator,encodingHandler); control.fillIntoRequest("/test/0123456789abcdef1234fedcba9876543210/", request); verify(request).setParameter("hash1", new String[] {"0123456789abcdef"}); verify(request).setParameter("id", new String[] {"1234"}); verify(request).setParameter("hash2", new String[] {"fedcba9876543210"}); }
@Test public void registerExtraParametersFromAcessedUrlWithGreedyParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile*}"); control.fillIntoRequest("/clients/my/path/to/file", request); verify(request).setParameter("pathToFile", new String[] {"my/path/to/file"}); }
@Test public void registerExtraParametersFromAcessedUrlWithGreedyAndDottedParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{path.to.file*}"); control.fillIntoRequest("/clients/my/path/to/file", request); verify(request).setParameter("path.to.file", new String[] {"my/path/to/file"}); }
@Test public void shouldDecodeUriParameters() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{name}"); control.fillIntoRequest("/clients/Joao+Leno", request); verify(request).setParameter("name", "Joao Leno"); control.fillIntoRequest("/clients/Paulo%20Macartinei", request); verify(request).setParameter("name", "Paulo Macartinei"); }
@Test public void registerExtraParametersFromAcessedUrl() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{dog.id}"); control.fillIntoRequest("/clients/45", request); verify(request).setParameter("dog.id", new String[] {"45"}); }
@Test public void registerParametersWithAsterisks() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{my.path*}"); control.fillIntoRequest("/clients/one/path", request); verify(request).setParameter("my.path", new String[] {"one/path"}); }
@Test public void registerParametersWithRegexes() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{hexa:[0-9A-Z]+}"); control.fillIntoRequest("/clients/FAF323", request); verify(request).setParameter("hexa", new String[] {"FAF323"}); } |
### Question:
DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); }### Answer:
@Test public void if_formatIsSpecifiedReturnIt() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); }
@Test public void if_formatIsSpecifiedReturnItEvenIfAcceptsHtml() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); when(request.getHeader("Accept")).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); }
@Test public void if_formatNotSpecifiedShouldReturnRequestAcceptFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/xml"); when(acceptHeaderToFormat.getFormat("application/xml")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); verify(request).getHeader("Accept"); }
@Test public void if_formatNotSpecifiedAndNoAcceptsHaveFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/SOMETHING_I_DONT_HAVE"); String format = resolver.getAcceptFormat(); assertNull(format); verify(request).getHeader("Accept"); }
@Test public void ifAcceptHeaderIsNullShouldReturnDefault() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn(null); when(acceptHeaderToFormat.getFormat(null)).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("html")); } |
### Question:
JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); }### Answer:
@Test public void shouldProxifyInterfaces() { TheInterface proxy = proxifier.proxify(TheInterface.class, new MethodInvocation<TheInterface>() { @Override public Object intercept(TheInterface proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); }
@Test public void shouldProxifyConcreteClassesWithDefaultConstructors() { TheClass proxy = proxifier.proxify(TheClass.class, new MethodInvocation<TheClass>() { @Override public Object intercept(TheClass proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); }
@Test public void shouldNotProxifyJavaLangObjectMethods() throws Exception { Object proxy = proxifier.proxify(JavassistProxifierTest.class, new MethodInvocation<Object>() { @Override public Object intercept(Object proxy, Method method, Object[] args, SuperMethod superMethod) { fail("should not call this Method interceptor"); return null; } }); new Mirror().on(proxy).invoke().method("finalize").withoutArgs(); }
@Test public void shouldThrowProxyInvocationExceptionIfAnErrorOccurs() { C proxy = proxifier.proxify(C.class, new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return superMethod.invoke(proxy, args); } }); try { proxy.doThrow(); fail("Should throw exception"); } catch (ProxyInvocationException e) { } }
@Test public void shouldNotProxifyBridges() throws Exception { B proxy = proxifier.proxify(B.class, new MethodInvocation<B>() { @Override public Object intercept(B proxy, Method method, Object[] args, SuperMethod superMethod) { if (method.isBridge()) { fail("Method " + method + " is a bridge"); } return null; } }); Method[] methods = proxy.getClass().getMethods(); for (Method m : methods) { if (m.getName().equals("getT")) { m.invoke(proxy, ""); } } }
@Test public void shouldConsiderSuperclassWhenProxifiyngProxy() throws Exception { MethodInvocation<C> handler = new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return null; } }; C firstProxy = proxifier.proxify(C.class, handler); C secondProxy = proxifier.proxify(firstProxy.getClass(), handler); assertEquals(firstProxy.getClass(), secondProxy.getClass()); } |
### Question:
DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); }### Answer:
@Test public void worksAsRegexWhenUsingParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{dog.id}"); assertThat(control.matches("/clients/15"), is(equalTo(true))); }
@Test public void worksWithBasicRegexEvaluation() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients.*"); assertThat(control.matches("/clientsWhatever"), is(equalTo(true))); }
@Test public void shouldMatchPatternLazily() throws Exception { DefaultParametersControl wrong = getDefaultParameterControlForUrl("/clients/{client.id}/"); DefaultParametersControl right = getDefaultParameterControlForUrl("/clients/{client.id}/subtask/"); String uri = "/clients/3/subtask/"; assertThat(wrong.matches(uri), is(false)); assertThat(right.matches(uri), is(true)); }
@Test public void shouldMatchMoreThanOneVariable() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{client.id}/subtask/{task.id}/"); assertThat(control.matches("/clients/3/subtask/5/"), is(true)); }
@Test public void shouldBeGreedyWhenIPutAnAsteriskOnExpression() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile*}"); assertThat(control.matches("/clients/my/path/to/file/"), is(true)); }
@Test public void whenNoParameterPatternsAreGivenShouldMatchAnything() throws Exception { ParametersControl control = new DefaultParametersControl("/any/{aParameter}/what", Collections.<String,String>emptyMap(), converters, evaluator,encodingHandler); assertTrue(control.matches("/any/ICanPutAnythingInHere/what")); }
@Test public void whenParameterPatternsAreGivenShouldMatchAccordingToGivenPatterns() throws Exception { ParametersControl control = new DefaultParametersControl("/any/{aParameter}/what", Collections.singletonMap("aParameter", "aaa\\d{3}bbb"), converters, evaluator,encodingHandler); assertFalse(control.matches("/any/ICantPutAnythingInHere/what")); assertFalse(control.matches("/any/aaa12bbb/what")); assertTrue(control.matches("/any/aaa123bbb/what")); } |
### Question:
CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); }### Answer:
@Test public void shoulIdentifyCDIProxies() { assertTrue(isCDIProxy(proxiable.getClass())); assertFalse(isCDIProxy(nonProxiable.getClass())); } |
### Question:
CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); }### Answer:
@Test public void shouldReturnTheBeanIfItsNotCDIProxy() { NonProxiableBean bean = unproxifyIfPossible(nonProxiable); assertThat(bean, equalTo(nonProxiable)); } |
### Question:
UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } protected UploadedFileConverter(); @Inject UploadedFileConverter(HttpServletRequest request); @Override UploadedFile convert(String value, Class<? extends UploadedFile> type); }### Answer:
@Test public void testIfUploadedFileIsConverted() { when(request.getAttribute("myfile")).thenReturn(file); UploadedFileConverter converter = new UploadedFileConverter(request); UploadedFile uploadedFile = converter.convert("myfile", UploadedFile.class); assertEquals(file, uploadedFile); } |
### Question:
CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } void upload(@Observes ControllerFound event, MutableRequest request,
MultipartConfig config, Validator validator); }### Answer:
@Test public void shouldNotAcceptFormURLEncoded() { MultipartConfig config = spy(new DefaultMultipartConfig()); when(request.getContentType()).thenReturn("application/x-www-form-urlencoded"); when(request.getMethod()).thenReturn("POST"); observer.upload(event, request, config, validator); verifyZeroInteractions(config); } |
### Question:
RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); }### Answer:
@Test public void shouldHandle404() throws Exception { when(translator.translate(webRequest)).thenThrow(new ControllerNotFoundException()); observer.handle(requestStarted); verify(notFoundHandler).couldntFind(chain, webRequest, webResponse); verify(interceptorStack, never()).start(); }
@Test public void shouldHandle405() throws Exception { EnumSet<HttpMethod> allowedMethods = EnumSet.of(HttpMethod.GET); when(translator.translate(webRequest)).thenThrow(new MethodNotAllowedException(allowedMethods, POST.toString())); observer.handle(requestStarted); verify(methodNotAllowedHandler).deny(webRequest, webResponse, allowedMethods); verify(interceptorStack, never()).start(); }
@Test public void shouldHandle400() throws Exception { InvalidInputException invalidInputException = new InvalidInputException(""); when(translator.translate(webRequest)).thenThrow(invalidInputException); observer.handle(requestStarted); verify(interceptorStack, never()).start(); verify(invalidInputHandler).deny(invalidInputException); }
@Test public void shouldUseControllerMethodFoundWithNextInterceptor() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(interceptorStack).start(); }
@Test public void shouldFireTheControllerWasFound() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(controllerFoundEvent).fire(any(ControllerFound.class)); }
@Test public void shouldFireTheRequestSuceeded() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(requestSucceededEvent).fire(any(RequestSucceded.class)); } |
### Question:
OutjectResult { public void outject(@Observes MethodExecuted event, Result result, MethodInfo methodInfo) { Type returnType = event.getMethodReturnType(); if (!returnType.equals(Void.TYPE)) { String name = extractor.nameFor(returnType); Object value = methodInfo.getResult(); logger.debug("outjecting {}={}", name, value); result.include(name, value); } } protected OutjectResult(); @Inject OutjectResult(TypeNameExtractor extractor); void outject(@Observes MethodExecuted event, Result result, MethodInfo methodInfo); }### Answer:
@Test public void shouldOutjectWithASimpleTypeName() throws NoSuchMethodException { Method method = MyComponent.class.getMethod("returnsAString"); when(controllerMethod.getMethod()).thenReturn(method); when(methodInfo.getResult()).thenReturn("myString"); when(extractor.nameFor(String.class)).thenReturn("string"); outjectResult.outject(new MethodExecuted(controllerMethod, methodInfo), result, methodInfo); verify(result).include("string", "myString"); }
@Test public void shouldOutjectACollectionAsAList() throws NoSuchMethodException { Method method = MyComponent.class.getMethod("returnsStrings"); when(controllerMethod.getMethod()).thenReturn(method); when(methodInfo.getResult()).thenReturn("myString"); when(extractor.nameFor(method.getGenericReturnType())).thenReturn("stringList"); outjectResult.outject(new MethodExecuted(controllerMethod, methodInfo), result, methodInfo); verify(result).include("stringList", "myString"); } |
### Question:
ForwardToDefaultView { public void forward(@Observes RequestSucceded event) { if (result.used() || event.getResponse().isCommitted()) { logger.debug("Request already dispatched and commited somewhere else, not forwarding."); return; } logger.debug("forwarding to the dafault page for this logic"); result.use(Results.page()).defaultView(); } protected ForwardToDefaultView(); @Inject ForwardToDefaultView(Result result); void forward(@Observes RequestSucceded event); }### Answer:
@Test public void doesNothingIfResultWasAlreadyUsed() { when(result.used()).thenReturn(true); interceptor.forward(new RequestSucceded(request, response)); verify(result, never()).use(PageResult.class); }
@Test public void doesNothingIfResponseIsCommited() { when(response.isCommitted()).thenReturn(true); interceptor.forward(new RequestSucceded(request, response)); verify(result, never()).use(PageResult.class); }
@Test public void shouldForwardToViewWhenResultWasNotUsed() { when(result.used()).thenReturn(false); when(result.use(PageResult.class)).thenReturn(new MockedPage()); interceptor.forward(new RequestSucceded(request, response)); verify(result).use(PageResult.class); } |
### Question:
DownloadObserver { public void download(@Observes MethodExecuted event, Result result) throws IOException { Object methodResult = event.getMethodInfo().getResult(); Download download = resolveDownload(methodResult); if (download != null && !result.used()) { logger.debug("Sending a file to the client"); result.use(DownloadView.class).of(download); } } void download(@Observes MethodExecuted event, Result result); Download resolveDownload(Object result); }### Answer:
@Test public void whenResultIsADownloadShouldUseIt() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); Download download = mock(Download.class); when(methodInfo.getResult()).thenReturn(download); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(download).write(response); }
@Test public void whenResultIsAnInputStreamShouldCreateAInputStreamDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("asByte")); byte[] bytes = "abc".getBytes(); when(methodInfo.getResult()).thenReturn(new ByteArrayInputStream(bytes)); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith(bytes))), eq(0), eq(3)); }
@Test public void whenResultIsAnInputStreamShouldCreateAByteArrayDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("asByte")); byte[] bytes = "abc".getBytes(); when(methodInfo.getResult()).thenReturn(bytes); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith(bytes))), eq(0), eq(3)); }
@Test public void whenResultIsAFileShouldCreateAFileDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("file")); File tmp = tmpdir.newFile(); Files.write(tmp.toPath(), "abc".getBytes()); when(methodInfo.getResult()).thenReturn(tmp); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith("abc".getBytes()))), eq(0), eq(3)); tmp.delete(); }
@Test public void whenResultIsNullShouldDoNothing() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); when(result.used()).thenReturn(true); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verifyZeroInteractions(response); }
@Test public void whenResultWasUsedShouldDoNothing() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); when(methodInfo.getResult()).thenReturn(null); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verifyZeroInteractions(response); } |
### Question:
DownloadObserver { public Download resolveDownload(Object result) throws IOException { if (result instanceof InputStream) { return new InputStreamDownload((InputStream) result, null, null); } if (result instanceof byte[]) { return new ByteArrayDownload((byte[]) result, null, null); } if (result instanceof File) { return new FileDownload((File) result, null, null); } if (result instanceof Download) { return (Download) result; } return null; } void download(@Observes MethodExecuted event, Result result); Download resolveDownload(Object result); }### Answer:
@Test public void shouldNotAcceptStringReturn() throws Exception { assertNull("String is not a Download", downloadObserver.resolveDownload("")); }
@Test public void shouldAcceptFile() throws Exception { File file = tmpdir.newFile(); assertThat(downloadObserver.resolveDownload(file), instanceOf(FileDownload.class)); }
@Test public void shouldAcceptInput() throws Exception { InputStream inputStream = mock(InputStream.class); assertThat(downloadObserver.resolveDownload(inputStream), instanceOf(InputStreamDownload.class)); }
@Test public void shouldAcceptDownload() throws Exception { Download download = mock(Download.class); assertEquals(downloadObserver.resolveDownload(download), download); }
@Test public void shouldAcceptByte() throws Exception { assertThat(downloadObserver.resolveDownload(new byte[]{}), instanceOf(ByteArrayDownload.class)); } |
### Question:
ByteArrayDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { download.write(response); } ByteArrayDownload(byte[] buff, String contentType, String fileName); ByteArrayDownload(byte[] buff, String contentType, String fileName, boolean doDownload); @Override void write(HttpServletResponse response); }### Answer:
@Test public void shouldFlushWholeStreamToHttpResponse() throws IOException { ByteArrayDownload fd = new ByteArrayDownload(bytes, "type", "x.txt"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { ByteArrayDownload fd = new ByteArrayDownload(bytes, "type", "x.txt"); fd.write(response); verify(response, times(1)).setHeader("Content-type", "type"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(bytes).withFileName("file.txt") .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(bytes.length)); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); } |
### Question:
InputStreamDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { writeDetails(response); OutputStream out = response.getOutputStream(); ByteStreams.copy(stream, out); stream.close(); } InputStreamDownload(InputStream input, String contentType, String fileName); InputStreamDownload(InputStream input, String contentType, String fileName, boolean doDownload, long size); @Override void write(HttpServletResponse response); }### Answer:
@Test public void shouldFlushWholeStreamToHttpResponse() throws IOException { InputStreamDownload fd = new InputStreamDownload(inputStream, "type", "x.txt"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { InputStreamDownload fd = new InputStreamDownload(inputStream, "type", "x.txt"); fd.write(response); verify(response).setHeader("Content-type", "type"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(inputStream).withFileName("file.txt") .withSize(bytes.length) .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(bytes.length)); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); }
@Test public void inputStreamNeedBeClosed() throws Exception { InputStream streamMocked = spy(inputStream); InputStreamDownload fd = new InputStreamDownload(streamMocked, "type", "x.txt"); fd.write(response); verify(streamMocked,times(1)).close(); } |
### Question:
FileDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { try (InputStream stream = new FileInputStream(file)) { Download download = new InputStreamDownload(stream, contentType, fileName, doDownload, file.length()); download.write(response); } } FileDownload(File file, String contentType, String fileName); FileDownload(File file, String contentType); FileDownload(File file, String contentType, String fileName, boolean doDownload); @Override void write(HttpServletResponse response); }### Answer:
@Test public void shouldFlushWholeFileToHttpResponse() throws IOException { FileDownload fd = new FileDownload(file, "type"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { FileDownload fd = new FileDownload(file, "type", "x.txt", false); fd.write(response); verify(response, times(1)).setHeader("Content-type", "type"); verify(response, times(1)).setHeader("Content-disposition", "inline; filename=x.txt"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void builderShouldUseNameArgument() throws Exception { Download fd = DownloadBuilder.of(file).withFileName("file.txt") .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(file.length())); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); }
@Test public void builderShouldUseFileNameWhenNameNotPresent() throws Exception { Download fd = DownloadBuilder.of(file).withContentType("text/plain").build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(file.length())); verify(response).setHeader("Content-disposition", "inline; filename=" + file.getName()); } |
### Question:
ZipDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { response.setHeader("Content-disposition", "attachment; filename=" + filename); response.setHeader("Content-type", "application/zip"); CheckedOutputStream stream = new CheckedOutputStream(response.getOutputStream(), new CRC32()); try (ZipOutputStream zip = new ZipOutputStream(stream)) { for (Path file : files) { zip.putNextEntry(new ZipEntry(file.getFileName().toString())); copy(file, zip); zip.closeEntry(); } } } ZipDownload(String filename, Iterable<Path> files); ZipDownload(String filename, Path... files); @Override void write(HttpServletResponse response); }### Answer:
@Test public void builderShouldThrowsExceptionIfFileDoesntExists() throws Exception { thrown.expect(NoSuchFileException.class); Download download = new ZipDownload("file.zip", Paths.get("/path/that/doesnt/exists/picture.jpg")); download.write(response); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { Download fd = new ZipDownload("download.zip", inpuFile0, inpuFile1); fd.write(response); verify(response, times(1)).setHeader("Content-type", "application/zip"); verify(response, times(1)).setHeader("Content-disposition", "attachment; filename=download.zip"); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(asList(inpuFile0, inpuFile1)) .withFileName("download.zip") .downloadable().build(); fd.write(response); verify(response).setHeader("Content-disposition", "attachment; filename=download.zip"); } |
### Question:
EnvironmentPropertyProducer { @Produces @Property public String get(InjectionPoint ip) { Annotated annotated = ip.getAnnotated(); Property property = annotated.getAnnotation(Property.class); String key = property.value(); if (isNullOrEmpty(key)) { key = ip.getMember().getName(); } String defaultValue = property.defaultValue(); if(!isNullOrEmpty(defaultValue)){ return environment.get(key, defaultValue); } return environment.get(key); } protected EnvironmentPropertyProducer(); @Inject EnvironmentPropertyProducer(Environment environment); @Produces @Property String get(InjectionPoint ip); }### Answer:
@Test public void shouldNotResolveUnexistentKeys() throws Exception { exception.expect(NoSuchElementException.class); nonExistent.get(); } |
### Question:
DefaultEnvironment implements Environment { @Override public URL getResource(String name) { URL resource = getClass().getResource("/" + getEnvironmentType().getName() + name); if (resource != null) { LOG.debug("Loading resource {} from environment {}", name, getEnvironmentType().getName()); return resource; } return getClass().getResource(name); } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; }### Answer:
@Test public void shouldUseEnvironmentBasedFileIfFoundUnderEnvironmentFolder() throws IOException { DefaultEnvironment env = buildEnvironment(EnvironmentType.DEVELOPMENT); URL resource = env.getResource("/rules.txt"); assertThat(resource, notNullValue()); assertThat(resource, is(getClass().getResource("/development/rules.txt"))); }
@Test public void shouldUseRootBasedFileIfNotFoundUnderEnvironmentFolder() throws IOException { DefaultEnvironment env = buildEnvironment(EnvironmentType.PRODUCTION); URL resource = env.getResource("/rules.txt"); assertThat(resource, notNullValue()); assertThat(resource, is(getClass().getResource("/rules.txt"))); } |
### Question:
DefaultEnvironment implements Environment { @Override public String get(String key) { if (!has(key)) { throw new NoSuchElementException(String.format("Key %s not found in environment %s", key, getName())); } String systemProperty = System.getProperty(key); if (!isNullOrEmpty(systemProperty)) { return systemProperty; } else { return properties.getProperty(key); } } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; }### Answer:
@Test public void shouldLoadConfigurationInDefaultFileEnvironment() throws IOException { when(context.getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY)).thenReturn("production"); DefaultEnvironment env = buildEnvironment(context); assertThat(env.get("env_name"), is("production")); assertThat(env.get("only_in_default_file"), is("only_in_default_file")); }
@Test public void shouldThrowExceptionIfKeyDoesNotExist() throws Exception { exception.expect(NoSuchElementException.class); DefaultEnvironment env = buildEnvironment(context); env.get("key_that_doesnt_exist"); }
@Test public void shouldGetValueWhenIsPresent() throws Exception { DefaultEnvironment env = buildEnvironment(context); String value = env.get("env_name", "fallback"); assertThat(value, is("development")); }
@Test public void shouldGetDefaultValueWhenIsntPresent() throws Exception { DefaultEnvironment env = buildEnvironment(context); String value = env.get("inexistent", "fallback"); assertThat(value, is("fallback")); } |
### Question:
DefaultEnvironment implements Environment { @Override public boolean supports(String feature) { if (has(feature)) { return Boolean.parseBoolean(get(feature).trim()); } return false; } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; }### Answer:
@Test public void shouldUseFalseWhenFeatureIsNotPresent() throws IOException { DefaultEnvironment env = buildEnvironment(context); assertThat(env.supports("feature_that_doesnt_exists"), is(false)); }
@Test public void shouldTrimValueWhenEvaluatingSupports() throws Exception { DefaultEnvironment env = buildEnvironment(context); assertThat(env.supports("untrimmed_boolean"), is(true)); } |
### Question:
DefaultEnvironment implements Environment { @Override public String getName() { return getEnvironmentType().getName(); } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; }### Answer:
@Test public void shouldUseContextInitParameterWhenSystemPropertiesIsntPresent() { when(context.getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY)).thenReturn("acceptance"); DefaultEnvironment env = buildEnvironment(context); assertThat(env.getName(), is("acceptance")); }
@Test public void shouldUseSystemPropertiesWhenSysenvIsntPresent() { System.getProperties().setProperty(DefaultEnvironment.ENVIRONMENT_PROPERTY, "acceptance"); DefaultEnvironment env = buildEnvironment(context); verify(context, never()).getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY); assertThat(env.getName(), is("acceptance")); System.getProperties().remove(DefaultEnvironment.ENVIRONMENT_PROPERTY); } |
### Question:
DefaultRepresentationResult implements RepresentationResult { @Override public <T> Serializer from(T object) { return from(object, null); } protected DefaultRepresentationResult(); @Inject DefaultRepresentationResult(FormatResolver formatResolver, Result result, @Any Instance<Serialization> serializations); @Override Serializer from(T object); @Override Serializer from(T object, String alias); }### Answer:
@Test public void whenThereIsNoFormatGivenShouldForwardToDefaultPage() { when(formatResolver.getAcceptFormat()).thenReturn(null); Serializer serializer = representation.from(new Object()); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notAcceptable(); }
@Test public void shouldSend404IfNothingIsRendered() { when(formatResolver.getAcceptFormat()).thenReturn(null); Serializer serializer = representation.from(null); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notFound(); }
@Test public void whenThereIsNoFormatGivenShouldForwardToDefaultPageWithAlias() { when(formatResolver.getAcceptFormat()).thenReturn(null); Object object = new Object(); Serializer serializer = representation.from(object, "Alias!"); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notAcceptable(); }
@Test public void whenThereIsAFormatGivenShouldUseCorrectSerializer() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(true); Object object = new Object(); representation.from(object); verify(serialization).from(object); }
@Test public void whenThereIsAFormatGivenShouldUseCorrectSerializerWithAlias() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(true); Object object = new Object(); representation.from(object, "Alias!"); verify(serialization).from(object, "Alias!"); }
@Test public void whenSerializationDontAcceptsFormatItShouldntBeUsed() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(false); Object object = new Object(); representation.from(object); verify(serialization, never()).from(object); } |
### Question:
DeserializesHandler { @SuppressWarnings("unchecked") public void handle(@Observes @DeserializesQualifier BeanClass beanClass) { Class<?> originalType = beanClass.getType(); checkArgument(Deserializer.class.isAssignableFrom(originalType), "%s must implement Deserializer", beanClass); deserializers.register((Class<? extends Deserializer>) originalType); } protected DeserializesHandler(); @Inject DeserializesHandler(Deserializers deserializers); @SuppressWarnings("unchecked") void handle(@Observes @DeserializesQualifier BeanClass beanClass); }### Answer:
@Test public void shouldThrowExceptionWhenTypeIsNotADeserializer() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("must implement Deserializer")); handler.handle(new DefaultBeanClass(NotADeserializer.class)); }
@Test public void shouldRegisterTypesOnDeserializers() throws Exception { handler.handle(new DefaultBeanClass(MyDeserializer.class)); verify(deserializers).register(MyDeserializer.class); } |
### Question:
DefaultDeserializers implements Deserializers { @Override public Deserializer deserializerFor(String contentType, Container container) { if (deserializers.containsKey(contentType)) { return container.instanceFor(deserializers.get(contentType)); } return subpathDeserializerFor(contentType, container); } @Override Deserializer deserializerFor(String contentType, Container container); @Override void register(Class<? extends Deserializer> type); }### Answer:
@Test public void shouldThrowExceptionWhenThereIsNoDeserializerRegisteredForGivenContentType() throws Exception { assertNull(deserializers.deserializerFor("bogus content type", container)); } |
### Question:
DefaultDeserializers implements Deserializers { @Override public void register(Class<? extends Deserializer> type) { Deserializes deserializes = type.getAnnotation(Deserializes.class); checkArgument(deserializes != null, "You must annotate your deserializers with @Deserializes"); for (String contentType : deserializes.value()) { deserializers.put(contentType, type); } } @Override Deserializer deserializerFor(String contentType, Container container); @Override void register(Class<? extends Deserializer> type); }### Answer:
@Test public void allDeserializersMustBeAnnotatedWithDeserializes() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("You must annotate your deserializers with @Deserializes"); deserializers.register(NotAnnotatedDeserializer.class); } |
### Question:
HTMLSerialization implements Serialization { @Override public <T> Serializer from(T object, String alias) { result.include(alias, object); result.use(page()).defaultView(); return new IgnoringSerializer(); } protected HTMLSerialization(); @Inject HTMLSerialization(Result result, TypeNameExtractor extractor); @Override boolean accepts(String format); @Override Serializer from(T object, String alias); @Override Serializer from(T object); }### Answer:
@Test public void shouldForwardToDefaultViewWithoutAlias() throws Exception { serialization.from(new Object()); verify(pageResult).defaultView(); }
@Test public void shouldForwardToDefaultViewWithAlias() throws Exception { serialization.from(new Object(), "Abc"); verify(pageResult).defaultView(); }
@Test public void shouldIncludeOnResultWithoutAlias() throws Exception { Object object = new Object(); when(extractor.nameFor(Object.class)).thenReturn("obj"); serialization.from(object); verify(result).include("obj", object); }
@Test public void shouldIncludeOnResultWithAlias() throws Exception { Object object = new Object(); serialization.from(object, "Abc"); verify(result).include("Abc", object); }
@Test public void shouldReturnAnIgnoringSerializerWithoutAlias() throws Exception { Serializer serializer = serialization.from(new Object()); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); }
@Test public void shouldReturnAnIgnoringSerializerWithAlias() throws Exception { Serializer serializer = serialization.from(new Object(), "Abc"); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); } |
### Question:
FlashInterceptor implements Interceptor { @Override public boolean accepts(ControllerMethod method) { return true; } protected FlashInterceptor(); @Inject FlashInterceptor(HttpSession session, Result result, MutableResponse response); @Override boolean accepts(ControllerMethod method); @Override void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance); }### Answer:
@Test public void shouldAcceptAlways() { assertTrue(interceptor.accepts(null)); } |
### Question:
FlashInterceptor implements Interceptor { @Override public void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance) throws InterceptionException { Map<String, Object> parameters = (Map<String, Object>) session.getAttribute(FLASH_INCLUDED_PARAMETERS); if (parameters != null) { parameters = new HashMap<>(parameters); session.removeAttribute(FLASH_INCLUDED_PARAMETERS); for (Entry<String, Object> parameter : parameters.entrySet()) { result.include(parameter.getKey(), parameter.getValue()); } } response.addRedirectListener(new RedirectListener() { @Override public void beforeRedirect() { Map<String, Object> included = result.included(); if (!included.isEmpty()) { try { session.setAttribute(FLASH_INCLUDED_PARAMETERS, new HashMap<>(included)); } catch (IllegalStateException e) { LOGGER.warn("HTTP Session was invalidated. It is not possible to include " + "Result parameters on Flash Scope", e); } } } }); stack.next(method, controllerInstance); } protected FlashInterceptor(); @Inject FlashInterceptor(HttpSession session, Result result, MutableResponse response); @Override boolean accepts(ControllerMethod method); @Override void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance); }### Answer:
@Test public void shouldDoNothingWhenThereIsNoFlashParameters() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); verifyZeroInteractions(result); }
@Test public void shouldAddAllFlashParametersToResult() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(singletonMap("Abc", 1002)); interceptor.intercept(stack, null, null); verify(result).include("Abc", 1002); }
@Test public void shouldRemoveFlashIncludedParameters() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(singletonMap("Abc", 1002)); interceptor.intercept(stack, null, null); verify(session).removeAttribute(FLASH_INCLUDED_PARAMETERS); }
@Test public void shouldIncludeFlashParametersWhenARedirectHappens() throws Exception { Map<String, Object> parameters = Collections.<String, Object>singletonMap("Abc", 1002); when(result.included()).thenReturn(parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); verify(session).setAttribute(FLASH_INCLUDED_PARAMETERS, parameters); }
@Test public void shouldNotIncludeFlashParametersWhenThereIsNoIncludedParameter() throws Exception { Map<String, Object> parameters = Collections.emptyMap(); when(result.included()).thenReturn(parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); verify(session, never()).setAttribute(anyString(), anyObject()); }
@Test public void shouldNotCrashWhenSessionIsInvalid() throws Exception { Map<String, Object> parameters = Collections.<String, Object>singletonMap("Abc", 1002); when(result.included()).thenReturn(parameters); doThrow(new IllegalStateException()).when(session).setAttribute(FLASH_INCLUDED_PARAMETERS, parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); } |
### Question:
CustomAndInternalAcceptsValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method accepts = invoker.findMethod(methods, Accepts.class, originalType); List<Annotation> constraints = getCustomAcceptsAnnotations(originalType); checkState(accepts == null || constraints.isEmpty(), "Interceptor %s must declare internal accepts or custom, not both.", originalType); } protected CustomAndInternalAcceptsValidationRule(); @Inject CustomAndInternalAcceptsValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); }### Answer:
@Test public void mustNotUseInternalAcceptsAndCustomAccepts(){ exception.expect(IllegalStateException.class); exception.expectMessage("Interceptor class " + InternalAndCustomAcceptsInterceptor.class.getName() + " must declare internal accepts or custom, not both"); Class<?> type = InternalAndCustomAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); }
@Test public void shouldValidateIfConstainsOnlyInternalAccepts(){ Class<?> type = InternalAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); }
@Test public void shouldValidateIfConstainsOnlyCustomAccepts(){ Class<?> type = CustomAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); } |
### Question:
NoInterceptMethodsValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { boolean hasAfterMethod = hasAnnotatedMethod(AfterCall.class, originalType, methods); boolean hasAroundMethod = hasAnnotatedMethod(AroundCall.class, originalType, methods); boolean hasBeforeMethod = hasAnnotatedMethod(BeforeCall.class, originalType, methods); if (!hasAfterMethod && !hasAroundMethod && !hasBeforeMethod) { throw new InterceptionException(format("Interceptor %s must " + "declare at least one method whith @AfterCall, @AroundCall " + "or @BeforeCall annotation", originalType.getCanonicalName())); } } protected NoInterceptMethodsValidationRule(); @Inject NoInterceptMethodsValidationRule(StepInvoker stepInvoker); @Override void validate(Class<?> originalType, List<Method> methods); }### Answer:
@Test public void shoulThrowExceptionIfInterceptorDontHaveAnyCallableMethod() { exception.expect(InterceptionException.class); exception.expectMessage("Interceptor " + SimpleInterceptor.class.getCanonicalName() +" must declare at least one method whith @AfterCall, @AroundCall or @BeforeCall annotation"); Class<?> type = SimpleInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); new NoInterceptMethodsValidationRule(stepInvoker).validate(type, allMethods); }
@Test public void shoulWorksFineIfInterceptorHaveAtLeastOneCallableMethod() { Class<?> type = SimpleInterceptorWithCallableMethod.class; List<Method> allMethods = stepInvoker.findAllMethods(type); new NoInterceptMethodsValidationRule(stepInvoker).validate(type, allMethods); } |
### Question:
CustomAcceptsVerifier { @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean isValid(Object interceptor, ControllerMethod controllerMethod, ControllerInstance controllerInstance, List<Annotation> constraints) { for (Annotation annotation : constraints) { AcceptsConstraint constraint = annotation.annotationType().getAnnotation(AcceptsConstraint.class); Class<? extends AcceptsValidator<?>> validatorClass = constraint.value(); AcceptsValidator validator = container.instanceFor(validatorClass); validator.initialize(annotation); if (!validator.validate(controllerMethod, controllerInstance)) { return false; } } return true; } protected CustomAcceptsVerifier(); @Inject CustomAcceptsVerifier(Container container); @SuppressWarnings({ "rawtypes", "unchecked" }) boolean isValid(Object interceptor, ControllerMethod controllerMethod,
ControllerInstance controllerInstance, List<Annotation> constraints); static List<Annotation> getCustomAcceptsAnnotations(Class<?> clazz); }### Answer:
@Test public void shouldValidateWithOne() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); assertTrue(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); }
@Test public void shouldValidateWithTwoOrMore() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor,packagesAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); assertTrue(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); }
@Test public void shouldEndProcessIfOneIsInvalid() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor,packagesAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); when(withAnnotationAcceptor.validate(controllerMethod, controllerInstance)).thenReturn(false); verify(packagesAcceptor, never()).validate(controllerMethod, controllerInstance); assertFalse(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); } |
### Question:
DefaultTypeNameExtractor implements TypeNameExtractor { @Override public String nameFor(Type generic) { if (generic instanceof ParameterizedType) { return nameFor((ParameterizedType) generic); } if (generic instanceof WildcardType) { return nameFor((WildcardType) generic); } if (generic instanceof TypeVariable<?>) { return nameFor((TypeVariable<?>) generic); } return nameFor((Class<?>) generic); } @Override String nameFor(Type generic); }### Answer:
@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercased() throws NoSuchMethodException { Assert.assertEquals("urlClassLoader",extractor.nameFor(URLClassLoader.class)); Assert.assertEquals("bigDecimal",extractor.nameFor(BigDecimal.class)); Assert.assertEquals("string",extractor.nameFor(String.class)); Assert.assertEquals("aClass",extractor.nameFor(AClass.class)); Assert.assertEquals("url",extractor.nameFor(URL.class)); }
@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercasedForListsAndArrays() throws NoSuchMethodException, SecurityException, NoSuchFieldException { Assert.assertEquals("stringList",extractor.nameFor(getField("strings"))); Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigs"))); Assert.assertEquals("hashSet",extractor.nameFor(getField("bigsOld"))); Assert.assertEquals("class",extractor.nameFor(getField("clazz"))); Assert.assertEquals("aClassList",extractor.nameFor(AClass[].class)); Assert.assertEquals("urlClassLoaderList",extractor.nameFor(getField("urls"))); }
@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercasedForListsAndArraysForBoundedGenericElements() throws NoSuchMethodException, SecurityException, NoSuchFieldException { Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigsLimited"))); Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigsLimited2"))); Assert.assertEquals("objectList",extractor.nameFor(getField("objects"))); }
@Test public void shouldDiscoverGenericTypeParametersWhenThereIsInheritance() throws Exception { Assert.assertEquals("t",extractor.nameFor(XController.class.getMethod("edit").getGenericReturnType())); Assert.assertEquals("tList",extractor.nameFor(XController.class.getMethod("list").getGenericReturnType())); } |
### Question:
AcceptsNeedReturnBooleanValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method accepts = invoker.findMethod(methods, Accepts.class, originalType); if (accepts != null && !isBooleanReturn(accepts.getReturnType())) { throw new InterceptionException(format("@%s method must return boolean", Accepts.class.getSimpleName())); } } protected AcceptsNeedReturnBooleanValidationRule(); @Inject AcceptsNeedReturnBooleanValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); }### Answer:
@Test public void shouldVerifyIfAcceptsMethodReturnsVoid() { exception.expect(InterceptionException.class); exception.expectMessage("@Accepts method must return boolean"); Class<VoidAcceptsInterceptor> type = VoidAcceptsInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); validationRule.validate(type, allMethods); }
@Test public void shouldVerifyIfAcceptsMethodReturnsNonBooleanType() { exception.expect(InterceptionException.class); exception.expectMessage("@Accepts method must return boolean"); Class<NonBooleanAcceptsInterceptor> type = NonBooleanAcceptsInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); validationRule.validate(type, allMethods); } |
### Question:
StepInvoker { public Method findMethod(List<Method> interceptorMethods, Class<? extends Annotation> step, Class<?> interceptorClass) { FluentIterable<Method> possibleMethods = FluentIterable.from(interceptorMethods).filter(hasStepAnnotation(step)); if (possibleMethods.size() > 1 && possibleMethods.allMatch(not(notSameClass(interceptorClass)))) { throw new IllegalStateException(String.format("%s - You should not have more than one @%s annotated method", interceptorClass.getCanonicalName(), step.getSimpleName())); } return possibleMethods.first().orNull(); } protected StepInvoker(); @Inject StepInvoker(ReflectionProvider reflectionProvider); Object tryToInvoke(Object interceptor, Method stepMethod, Object... params); List<Method> findAllMethods(Class<?> interceptorClass); Method findMethod(List<Method> interceptorMethods, Class<? extends Annotation> step, Class<?> interceptorClass); }### Answer:
@Test public void shouldNotReadInheritedMethods() throws Exception { Class<?> interceptorClass = InterceptorWithInheritance.class; Method method = findMethod(interceptorClass, BeforeCall.class); assertEquals(method, interceptorClass.getDeclaredMethod("begin")); }
@Test public void shouldThrowsExceptionWhenInterceptorHasMoreThanOneAnnotatedMethod() { exception.expect(IllegalStateException.class); exception.expectMessage(InterceptorWithMoreThanOneBeforeCallMethod.class.getName() + " - You should not have more than one @BeforeCall annotated method"); Class<?> interceptorClass = InterceptorWithMoreThanOneBeforeCallMethod.class; findMethod(interceptorClass, BeforeCall.class); }
@Test public void shouldFindFirstMethodAnnotatedWithInterceptorStep(){ ExampleOfSimpleStackInterceptor proxy = spy(new ExampleOfSimpleStackInterceptor()); findMethod(proxy.getClass(), BeforeCall.class); }
@Test public void shouldFindMethodFromWeldStyleInterceptor() throws SecurityException, NoSuchMethodException{ Class<?> interceptorClass = WeldProxy$$$StyleInterceptor.class; assertNotNull(findMethod(interceptorClass, AroundCall.class)); } |
### Question:
NoStackParamValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method aroundCall = invoker.findMethod(methods, AroundCall.class, originalType); Method afterCall = invoker.findMethod(methods, AfterCall.class, originalType); Method beforeCall = invoker.findMethod(methods, BeforeCall.class, originalType); Method accepts = invoker.findMethod(methods, Accepts.class, originalType); String interceptorStack = InterceptorStack.class.getName(); String simpleInterceptorStack = SimpleInterceptorStack.class.getName(); checkState(aroundCall == null || containsStack(aroundCall), "@AroundCall method must receive %s or %s", interceptorStack, simpleInterceptorStack); checkState(!containsStack(beforeCall) && !containsStack(afterCall) && !containsStack(accepts), "Non @AroundCall method must not receive %s or %s", interceptorStack, simpleInterceptorStack); } protected NoStackParamValidationRule(); @Inject NoStackParamValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); }### Answer:
@Test public void mustReceiveStackAsParameterForAroundCall() { exception.expect(IllegalStateException.class); exception.expectMessage("@AroundCall method must receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = AroundInterceptorWithoutSimpleStackParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); }
@Test public void mustNotReceiveStackAsParameterForAcceptsCall() { exception.expect(IllegalStateException.class); exception.expectMessage("Non @AroundCall method must not receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = AcceptsInterceptorWithStackAsParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); }
@Test public void mustNotReceiveStackAsParameterForBeforeAfterCall() { exception.expect(IllegalStateException.class); exception.expectMessage("Non @AroundCall method must not receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = BeforeAfterInterceptorWithStackAsParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); } |
### Question:
DefaultTypeFinder implements TypeFinder { @Override public Map<String, Class<?>> getParameterTypes(Method method, String[] parameterPaths) { Map<String,Class<?>> types = new HashMap<>(); Parameter[] parametersFor = provider.parametersFor(method); for (String path : parameterPaths) { for (Parameter parameter: parametersFor) { if (path.startsWith(parameter.getName() + ".") || path.equals(parameter.getName())) { String[] items = path.split("\\."); Class<?> type = parameter.getType(); for (int j = 1; j < items.length; j++) { String item = items[j]; try { type = reflectionProvider.getMethod(type, "get" + capitalize(item)).getReturnType(); } catch (Exception e) { throw new IllegalArgumentException("Parameters paths are invalid: " + Arrays.toString(parameterPaths) + " for method " + method, e); } } types.put(path, type); } } } return types; } protected DefaultTypeFinder(); @Inject DefaultTypeFinder(ParameterNameProvider provider, ReflectionProvider reflectionProvider); @Override Map<String, Class<?>> getParameterTypes(Method method, String[] parameterPaths); }### Answer:
@Test public void shouldGetTypesCorrectly() throws Exception { final Method method = new Mirror().on(AController.class).reflect().method("aMethod").withArgs(Bean.class, String.class); DefaultTypeFinder finder = new DefaultTypeFinder(provider, new DefaultReflectionProvider()); Map<String, Class<?>> types = finder.getParameterTypes(method, new String[] {"bean.bean2.id", "path"}); assertEquals(Integer.class, types.get("bean.bean2.id")); assertEquals(String.class, types.get("path")); }
@Test public void shouldGetTypesCorrectlyOnInheritance() throws Exception { final Method method = new Mirror().on(AController.class).reflect().method("otherMethod").withArgs(BeanExtended.class); DefaultTypeFinder finder = new DefaultTypeFinder(provider, new DefaultReflectionProvider()); Map<String, Class<?>> types = finder.getParameterTypes(method, new String[] {"extended.id"}); assertEquals(Integer.class, types.get("extended.id")); } |
### Question:
DefaultControllerInstance implements ControllerInstance { @Override public BeanClass getBeanClass(){ Class<?> controllerClass = extractRawTypeIfPossible(controller.getClass()); return new DefaultBeanClass(controllerClass); } DefaultControllerInstance(Object instance); @Override Object getController(); @Override BeanClass getBeanClass(); }### Answer:
@Test public void shouldUnwrapCDIProxyFromControllerType() { ControllerInstance controllerInstance = controllerInstance(); assertTrue(CDIProxies.isCDIProxy(controller.getClass())); BeanClass beanClass = controllerInstance.getBeanClass(); assertFalse(CDIProxies.isCDIProxy(beanClass.getType())); } |
### Question:
DefaultMethodNotAllowedHandler implements MethodNotAllowedHandler { @Override public void deny(MutableRequest request, MutableResponse response, Set<HttpMethod> allowedMethods) { response.addHeader("Allow", Joiner.on(", ").join(allowedMethods)); try { if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } catch (IOException e) { throw new InterceptionException(e); } } @Override void deny(MutableRequest request, MutableResponse response, Set<HttpMethod> allowedMethods); }### Answer:
@Test public void shouldAddAllowHeader() throws Exception { this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response).addHeader("Allow", "GET, POST"); }
@Test public void shouldSendErrorMethodNotAllowed() throws Exception { this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); }
@Test public void shouldNotSendMethodNotAllowedIfTheRequestMethodIsOptions() throws Exception { when(request.getMethod()).thenReturn("OPTIONS"); this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response, never()).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); }
@Test public void shouldThrowInterceptionExceptionIfAnIOExceptionOccurs() throws Exception { exception.expect(InterceptionException.class); doThrow(new IOException()).when(response).sendError(anyInt()); this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); } |
### Question:
DefaultLogicResult implements LogicResult { @Override public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted()) { logger.debug("Response already commited, not forwarding."); return null; } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); } protected DefaultLogicResult(); @Inject DefaultLogicResult(Proxifier proxifier, Router router, MutableRequest request, HttpServletResponse response,
Container container, PathResolver resolver, TypeNameExtractor extractor, FlashScope flash, MethodInfo methodInfo); @Override T forwardTo(final Class<T> type); @Override T redirectTo(final Class<T> type); }### Answer:
@Test public void shouldIncludeReturnValueOnForward() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(extractor.nameFor(String.class)).thenReturn("string"); logicResult.forwardTo(MyComponent.class).returnsValue(); verify(dispatcher).forward(request, response); verify(request).setAttribute("string", "A value"); }
@Test public void shouldExecuteTheLogicAndRedirectToItsViewOnForward() throws Exception { final MyComponent component = givenDispatcherWillBeReturnedWhenRequested(); assertThat(component.calls, is(0)); logicResult.forwardTo(MyComponent.class).base(); assertThat(component.calls, is(1)); verify(dispatcher).forward(request, response); }
@Test public void shouldForwardToMethodsDefaultViewWhenResponseIsNotCommited() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(false); logicResult.forwardTo(MyComponent.class).base(); verify(dispatcher).forward(request, response); }
@Test public void shouldNotForwardToMethodsDefaultViewWhenResponseIsCommited() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(true); logicResult.forwardTo(MyComponent.class).base(); verify(dispatcher, never()).forward(request, response); }
@Test public void shouldNotWrapValidationExceptionWhenForwarding() throws Exception { exception.expect(ValidationException.class); givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(true); logicResult.forwardTo(MyComponent.class).throwsValidationException(); }
@Test public void shouldForwardToTheRightDefaultValue() throws Exception { Result result = mock(Result.class); PageResult pageResult = new DefaultPageResult(request, response, methodInfo, resolver, proxifier); when(result.use(PageResult.class)).thenReturn(pageResult); when(container.instanceFor(TheComponent.class)).thenReturn(new TheComponent(result)); when(resolver.pathFor(argThat(sameMethodAs(TheComponent.class.getDeclaredMethod("method"))))).thenReturn("controlled!"); when(request.getRequestDispatcher(anyString())).thenThrow(new AssertionError("should have called with the right method!")); doReturn(dispatcher).when(request).getRequestDispatcher("controlled!"); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(MyComponent.class, MyComponent.class.getDeclaredMethod("base"))); logicResult.forwardTo(TheComponent.class).method(); } |
### Question:
FixedMethodStrategy implements Route { @Override public ControllerMethod controllerMethod(MutableRequest request, String uri) { parameters.fillIntoRequest(uri, request); return this.controllerMethod; } FixedMethodStrategy(String originalUri, ControllerMethod method, Set<HttpMethod> methods,
ParametersControl control, int priority, Parameter[] parameterNames); @Override boolean canHandle(Class<?> type, Method method); @Override ControllerMethod controllerMethod(MutableRequest request, String uri); @Override EnumSet<HttpMethod> allowedMethods(); @Override boolean canHandle(String uri); @Override String urlFor(Class<?> type, Method m, Object... params); @Override int getPriority(); @Override String getOriginalUri(); @Override ControllerMethod getControllerMethod(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void canTranslate() { FixedMethodStrategy strategy = new FixedMethodStrategy("abc", list, methods(HttpMethod.POST), control, 0, new Parameter[0]); when(control.matches("/clients/add")).thenReturn(true); ControllerMethod match = strategy.controllerMethod(request, "/clients/add"); assertThat(match, is(VRaptorMatchers.controllerMethod(method("list")))); verify(control, only()).fillIntoRequest("/clients/add", request); } |
### Question:
DefaultLogicResult implements LogicResult { @Override public <T> T redirectTo(final Class<T> type) { logger.debug("redirecting to class {}", type.getSimpleName()); return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { checkArgument(acceptsHttpGet(method), "Your logic method must accept HTTP GET method if you want to redirect to it"); try { String url = router.urlFor(type, method, args); String path = request.getContextPath() + url; includeParametersInFlash(type, method, args); logger.debug("redirecting to {}", path); response.sendRedirect(path); return null; } catch (IOException e) { throw new ProxyInvocationException(e); } } }); } protected DefaultLogicResult(); @Inject DefaultLogicResult(Proxifier proxifier, Router router, MutableRequest request, HttpServletResponse response,
Container container, PathResolver resolver, TypeNameExtractor extractor, FlashScope flash, MethodInfo methodInfo); @Override T forwardTo(final Class<T> type); @Override T redirectTo(final Class<T> type); }### Answer:
@Test public void shouldPutParametersOnFlashScopeOnRedirect() throws Exception { logicResult.redirectTo(MyComponent.class).withParameter("a"); verify(flash).includeParameters(any(ControllerMethod.class), eq(new Object[] {"a"})); }
@Test public void shouldNotPutParametersOnFlashScopeOnRedirectIfThereAreNoParameters() throws Exception { logicResult.redirectTo(MyComponent.class).base(); verify(flash, never()).includeParameters(any(ControllerMethod.class), any(Object[].class)); }
@Test public void clientRedirectingWillRedirectToTranslatedUrl() throws NoSuchMethodException, IOException { final String url = "custom_url"; when(request.getContextPath()).thenReturn("/context"); when(router.urlFor(MyComponent.class, MyComponent.class.getDeclaredMethod("base"))).thenReturn(url); logicResult.redirectTo(MyComponent.class).base(); verify(response).sendRedirect("/context" + url); }
@Test public void canRedirectWhenLogicMethodIsNotAnnotatedWithHttpMethods() throws Exception { logicResult.redirectTo(MyComponent.class).base(); verify(response).sendRedirect(any(String.class)); }
@Test public void canRedirectWhenLogicMethodIsAnnotatedWithHttpGetMethod() throws Exception { logicResult.redirectTo(MyComponent.class).annotatedWithGet(); verify(response).sendRedirect(any(String.class)); }
@Test public void cannotRedirectWhenLogicMethodIsAnnotatedWithAnyHttpMethodButGet() throws Exception { try { logicResult.redirectTo(MyComponent.class).annotated(); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { verify(response, never()).sendRedirect(any(String.class)); } } |
### Question:
DefaultAcceptHeaderToFormat implements AcceptHeaderToFormat { @Override public String getFormat(final String acceptHeader) { if (acceptHeader == null || acceptHeader.trim().equals("")) { return DEFAULT_FORMAT; } if (acceptHeader.contains(DEFAULT_FORMAT)) { return DEFAULT_FORMAT; } return acceptToFormatCache.fetch(acceptHeader, new Supplier<String>() { @Override public String get() { return chooseMimeType(acceptHeader); } }); } protected DefaultAcceptHeaderToFormat(); @Inject DefaultAcceptHeaderToFormat(@LRU CacheStore<String, String> acceptToFormatCache); @Override String getFormat(final String acceptHeader); }### Answer:
@Test public void shouldComplainIfThereIsNothingRegistered() { Assert.assertEquals("unknown", mimeTypeToFormat.getFormat("unknown")); }
@Test public void shouldReturnHtmlWhenRequestingAnyContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("*/*")); }
@Test public void shouldReturnHtmlWhenAcceptsIsBlankContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("")); }
@Test public void shouldReturnHtmlWhenRequestingUnknownAsFirstAndAnyContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("unknow, */*")); }
@Test public void testHtml() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("text/html")); }
@Test public void testJson() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json")); }
@Test public void testJsonWithQualifier() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json; q=0.4")); }
@Test public void testNull() { Assert.assertEquals("html", mimeTypeToFormat.getFormat(null)); }
@Test public void testJsonInAComplexAcceptHeader() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json, text/javascript, */*")); }
@Test public void testPrecendenceInAComplexAcceptHeaderHtmlShouldPrevailWhenTied() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("application/json, text/html, */*")); }
@Test public void testPrecendenceInABizzarreMSIE8AcceptHeader() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, */*")); }
@Test public void testPrecendenceInABizzarreMSIE8AcceptHeaderWithHtml() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, text/html, */*")); }
@Test public void testPrecendenceInAComplexAcceptHeaderHtmlShouldPrevailWhenTied2() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("text/html, application/json, */*")); }
@Test public void testJsonInAComplexAcceptHeaderWithParameters() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json; q=0.7, application/xml; q=0.1, */*")); }
@Test public void testXMLInAComplexAcceptHeaderWithParametersNotOrdered() { Assert.assertEquals("xml", mimeTypeToFormat.getFormat("application/json; q=0.1, application/xml; q=0.7, */*")); } |
### Question:
DefaultStatus implements Status { @Override public void header(String key, String value) { response.addHeader(key, value); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetHeader() throws Exception { status.header("Content-type", "application/xml"); verify(response).addHeader("Content-type", "application/xml"); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.