method2testcases
stringlengths 118
3.08k
|
---|
### Question:
OrderValidatorsMO { public boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order) { boolean isValid = true; Entity masterOrder = order.getBelongsToField(MASTER_ORDER); if (masterOrder == null) { return isValid; } if (!checkIfBelongToFieldIsTheSame(order, masterOrder, COMPANY)) { Entity company = masterOrder.getBelongsToField(COMPANY); order.addError(orderDD.getField(COMPANY), "masterOrders.order.masterOrder.company.fieldIsNotTheSame", createInfoAboutEntity(company, "company")); isValid = false; } if (!checkIfDeadlineIsCorrect(order, masterOrder)) { Date deadline = (Date) masterOrder.getField(DEADLINE); order.addError( orderDD.getField(DEADLINE), "masterOrders.order.masterOrder.deadline.fieldIsNotTheSame", deadline == null ? translationService.translate("masterOrders.order.masterOrder.deadline.hasNotDeadline", Locale.getDefault()) : DateUtils.toDateTimeString(deadline)); isValid = false; } return isValid; } boolean checkOrderNumber(final DataDefinition orderDD, final Entity order); boolean checkCompanyAndDeadline(final DataDefinition orderDD, final Entity order); boolean checkProductAndTechnology(final DataDefinition orderDD, final Entity order); }### Answer:
@Test public final void shouldCheckCompanyAndDeadlineReturnTrueWhenMasterOrderIsNotSpecified() { given(order.getBelongsToField(OrderFieldsMO.MASTER_ORDER)).willReturn(null); boolean result = orderValidatorsMO.checkCompanyAndDeadline(orderDD, order); Assert.assertTrue(result); } |
### 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:
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 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:
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:
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:
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:
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:
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:
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:
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 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:
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:
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:
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:
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:
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:
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"); } |
### Question:
DefaultStatus implements Status { @Override public void created() { response.setStatus(HttpServletResponse.SC_CREATED); result.use(Results.nothing()); } 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 shouldSetCreatedStatus() throws Exception { status.created(); verify(response).setStatus(201); }
@Test public void shouldSetCreatedStatusAndLocationWithAppPath() throws Exception { when(config.getApplicationPath()).thenReturn("http: status.created("/newResource"); verify(response).setStatus(201); verify(response).addHeader("Location", "http: } |
### Question:
DefaultStatus implements Status { @Override public void ok() { response.setStatus(HttpServletResponse.SC_OK); result.use(Results.nothing()); } 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 shouldSetOkStatus() throws Exception { status.ok(); verify(response).setStatus(200); } |
### Question:
DefaultStatus implements Status { @Override public void accepted(){ response.setStatus(HttpServletResponse.SC_ACCEPTED ); result.use(Results.nothing()); } 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 shouldSetAcceptedStatus() throws Exception { status.accepted(); verify(response).setStatus(202); } |
### Question:
DefaultStatus implements Status { @Override public void notImplemented() { response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); } 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 shouldSetNotImplementedStatus() throws Exception { status.notImplemented(); verify(response).setStatus(501); } |
### Question:
DefaultStatus implements Status { @Override public void internalServerError() { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } 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 shouldSetInternalServerErrorStatus() throws Exception { status.internalServerError(); verify(response).setStatus(500); } |
### Question:
DefaultPageResult implements PageResult { @Override public void redirectTo(String url) { logger.debug("redirection to {}", url); try { if (url.startsWith("/")) { response.sendRedirect(request.getContextPath() + url); } else { response.sendRedirect(url); } } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldRedirectIncludingContext() throws Exception { when(request.getContextPath()).thenReturn("/context"); view.redirectTo("/any/url"); verify(response).sendRedirect("/context/any/url"); }
@Test public void shouldNotIncludeContextPathIfURIIsAbsolute() throws Exception { view.redirectTo("http: verify(request, never()).getContextPath(); verify(response, only()).sendRedirect("http: }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileRedirect() throws Exception { exception.expect(ResultException.class); doThrow(new IOException()).when(response).sendRedirect(anyString()); view.redirectTo("/any/url"); } |
### Question:
VRaptorRequest extends HttpServletRequestWrapper implements MutableRequest { @Override public String getParameter(String name) { if (extraParameters.containsKey(name)) { return extraParameters.get(name)[0]; } return super.getParameter(name); } VRaptorRequest(HttpServletRequest request); @Override String getParameter(String name); @Override Enumeration<String> getParameterNames(); @Override String[] getParameterValues(String name); @Override Map<String, String[]> getParameterMap(); @Override void setParameter(String key, String... value); @Override String getRequestedUri(); static String getRelativeRequestURI(HttpServletRequest request); @Override String toString(); }### Answer:
@Test public void searchesOnTheFallbackRequest() { assertThat(vraptor.getParameter("name"), is(equalTo("guilherme"))); }
@Test public void returnsNullIfNotFound() { assertThat(vraptor.getParameter("minimum"), is(nullValue())); } |
### Question:
DefaultPageResult implements PageResult { @Override public void forwardTo(String url) { logger.debug("forwarding to {}", url); try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException | IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldForwardToGivenURI() throws Exception { when(request.getRequestDispatcher("/any/url")).thenReturn(dispatcher); view.forwardTo("/any/url"); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); } |
### Question:
DefaultPageResult implements PageResult { @Override public void defaultView() { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("forwarding to {}", to); try { request.getRequestDispatcher(to).forward(request, response); } catch (ServletException e) { throw new ApplicationLogicException(to + " raised an exception", e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldAllowCustomPathResolverWhileForwardingView() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.defaultView(); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowApplicationLogicExceptionIfServletExceptionOccursWhileForwardingView() throws Exception { exception.expect(ApplicationLogicException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.defaultView(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwardingView() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.defaultView(); } |
### Question:
DefaultPageResult implements PageResult { @Override public void include() { try { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("including {}", to); request.getRequestDispatcher(to).include(request, response); } catch (ServletException e) { throw new ResultException(e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldAllowCustomPathResolverWhileIncluding() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.include(); verify(dispatcher, only()).include(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).include(request, response); view.include(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).include(request, response); view.include(); } |
### Question:
DefaultPageResult implements PageResult { @Override public <T> T of(final Class<T> controllerType) { return proxifier.proxify(controllerType, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { request.getRequestDispatcher( resolver.pathFor(DefaultControllerMethod.instanceFor(controllerType, method))).forward( request, response); return null; } catch (Exception e) { throw new ProxyInvocationException(e); } } }); } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shoudNotExecuteLogicWhenUsingResultOf() { when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); try { view.of(SimpleController.class).notAllowedMethod(); } catch (UnsupportedOperationException e) { fail("Method should not be executed"); } }
@Test public void shoudThrowProxyInvocationExceptionIfAndExceptionOccursWhenUsingResultOf() { exception.expect(ProxyInvocationException.class); doThrow(new NullPointerException()).when(request).getRequestDispatcher(anyString()); view.of(SimpleController.class).notAllowedMethod(); } |
### Question:
DefaultPathResolver implements PathResolver { @Override public String pathFor(ControllerMethod method) { logger.debug("Resolving path for {}", method); String format = resolver.getAcceptFormat(); String suffix = ""; if (format != null && !format.equals("html")) { suffix = "." + format; } String name = method.getController().getType().getSimpleName(); String folderName = extractControllerFromName(name); String path = getPrefix() + folderName + "/" + method.getMethod().getName() + suffix + "." + getExtension(); logger.debug("Returning path {} for {}", path, method); return path; } protected DefaultPathResolver(); @Inject DefaultPathResolver(FormatResolver resolver); @Override String pathFor(ControllerMethod method); }### Answer:
@Test public void shouldUseResourceTypeAndMethodNameToResolveJsp(){ when(formatResolver.getAcceptFormat()).thenReturn(null); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); }
@Test public void shouldUseTheFormatIfSupplied() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("json"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.json.jsp")); }
@Test public void shouldIgnoreHtmlFormat() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("html"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); } |
### Question:
DefaultHttpResult implements HttpResult { @Override public void sendError(int statusCode) { try { response.sendError(statusCode); } catch (IOException e) { throw new ResultException("Error while setting status code", e); } } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldSendError() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); verify(response).sendError(SC_INTERNAL_SERVER_ERROR); }
@Test public void shouldThrowsResultExceptionIfAnIOExceptionWhenSendError() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt()); } }
@Test public void shouldSendErrorWithMessage() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); verify(response).sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenSendErrorWithMessage() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt(), anyString()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt(), anyString()); } } |
### Question:
DefaultHttpResult implements HttpResult { @Override public void setStatusCode(int statusCode) { response.setStatus(statusCode); } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldSetStatusCode() throws Exception { httpResult.setStatusCode(SC_INTERNAL_SERVER_ERROR); verify(response).setStatus(SC_INTERNAL_SERVER_ERROR); } |
### Question:
DefaultHttpResult implements HttpResult { @Override public HttpResult body(String body) { try { response.getWriter().print(body); } catch (IOException e) { throw new ResultException("Couldn't write to response body", e); } return this; } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldWriteStringBody() throws Exception { PrintWriter writer = mock(PrintWriter.class); when(response.getWriter()).thenReturn(writer); httpResult.body("The text"); verify(writer).print(anyString()); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteStringBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); try { httpResult.body("The text"); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteInputStreamBody() throws Exception { doThrow(new IOException()).when(response).getOutputStream(); InputStream in = new ByteArrayInputStream("the text".getBytes()); try { httpResult.body(in); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteReaderBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); Reader reader = new StringReader("the text"); try { httpResult.body(reader); fail("should throw ResultException"); } catch (ResultException e) { } } |
### Question:
InterceptorStereotypeHandler { public void handle(@Observes @InterceptsQualifier BeanClass beanClass) { Class<?> originalType = beanClass.getType(); interceptorValidator.validate(originalType); logger.debug("Found interceptor for {}", originalType); registry.register(originalType); } protected InterceptorStereotypeHandler(); @Inject InterceptorStereotypeHandler(InterceptorRegistry registry, InterceptorValidator validator); void handle(@Observes @InterceptsQualifier BeanClass beanClass); }### Answer:
@Test public void shouldRegisterInterceptorsOnRegistry() throws Exception { handler.handle(new DefaultBeanClass(InterceptorA.class)); verify(interceptorRegistry, times(1)).register(InterceptorA.class); } |
### Question:
DefaultResult extends AbstractResult { @Override public <T extends View> T use(Class<T> view) { messages.assertAbsenceOfErrors(); responseCommitted = true; return container.instanceFor(view); } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); }### Answer:
@Test public void shouldUseContainerForNewView() { final MyView expectedView = new MyView(); when(container.instanceFor(MyView.class)).thenReturn(expectedView); MyView view = result.use(MyView.class); assertThat(view, is(expectedView)); }
@Test public void shouldCallAssertAbsenceOfErrorsMethodFromMessages() throws Exception { result.use(Results.json()); verify(messages).assertAbsenceOfErrors(); } |
### Question:
DefaultResult extends AbstractResult { @Override public Result include(String key, Object value) { logger.debug("including attribute {}: {}", key, value); includedAttributes.put(key, value); request.setAttribute(key, value); return this; } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); }### Answer:
@Test public void shouldSetRequestAttribute() { result.include("my_key", "my_value"); verify(request).setAttribute("my_key", "my_value"); }
@Test public void shouldIncludeExtractedNameWhenSimplyIncluding() throws Exception { Account account = new Account(); when(extractor.nameFor(Account.class)).thenReturn("account"); result.include(account); verify(request).setAttribute("account", account); }
@Test public void shouldNotIncludeTheAttributeWhenTheValueIsNull() throws Exception { result.include(null); verify(request, never()).setAttribute(anyString(), anyObject()); } |
### Question:
InterceptorStackHandlersCache { public LinkedList<InterceptorHandler> getInterceptorHandlers() { return new LinkedList<>(interceptorHandlers); } protected InterceptorStackHandlersCache(); @Inject InterceptorStackHandlersCache(InterceptorRegistry registry, InterceptorHandlerFactory handlerFactory); void init(); LinkedList<InterceptorHandler> getInterceptorHandlers(); }### Answer:
@Test public void shouldReturnHandlersListInTheSameOrderThatRegistry() { LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); assertEquals(FirstInterceptor.class, extractInterceptor(handlers.get(0))); assertEquals(SecondInterceptor.class, extractInterceptor(handlers.get(1))); }
@Test public void cacheShouldBeImmutable() { cache.getInterceptorHandlers().remove(0); assertEquals(2, cache.getInterceptorHandlers().size()); } |
### Question:
DefaultInterceptorStack implements InterceptorStack { @Override public void start() { ControllerMethod method = controllerMethod.get(); interceptorsReadyEvent.fire(new InterceptorsReady(method)); LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); internalStack.addFirst(handlers.iterator()); this.next(method, controllerInstance.get().getController()); internalStack.poll(); } protected DefaultInterceptorStack(); @Inject DefaultInterceptorStack(InterceptorStackHandlersCache cache, Instance<ControllerMethod>
controllerMethod, Instance<ControllerInstance> controllerInstance, Event<InterceptorsExecuted> event,
Event<InterceptorsReady> stackStartingEvent); @Override void next(ControllerMethod method, Object controllerInstance); @Override void start(); }### Answer:
@Test public void firesStartEventOnStart() throws Exception { stack.start(); verify(interceptorsReadyEvent).fire(any(InterceptorsReady.class)); }
@Test public void executesTheFirstHandler() throws Exception { stack.start(); verify(handler).execute(stack, controllerMethod, controller); }
@Test public void doesntFireEndOfStackIfTheInterceptorsDontContinueTheStack() throws Exception { stack.start(); verify(interceptorsExecutedEvent, never()).fire(any(InterceptorsExecuted.class)); }
@Test public void firesEndOfStackIfAllInterceptorsWereExecuted() throws Exception { doAnswer(callNext()).when(handler).execute(stack, controllerMethod, controller); stack.start(); verify(interceptorsExecutedEvent).fire(any(InterceptorsExecuted.class)); } |
### Question:
ExceptionRecorder implements MethodInvocation<T> { public void replay(Result result) { Object current = result; for (ExceptionRecorderParameter p : parameters) { current = reflectionProvider.invoke(current, p.getMethod(), p.getArgs()); } } ExceptionRecorder(Proxifier proxifier, ReflectionProvider reflectionProvider); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod); void replay(Result result); }### Answer:
@Test public void withRootException() { mapper.record(Exception.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new Exception()).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); }
@Test public void withNestedException() { mapper.record(IllegalStateException.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new RuntimeException(new IllegalStateException())).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); } |
### Question:
DefaultConverters implements Converters { @SuppressWarnings("unchecked") @Override public <T> Converter<T> to(Class<T> clazz) { Class<? extends Converter<?>> converterType = findConverterTypeFromCache(clazz); checkState(!converterType.equals(NullConverter.class), "Unable to find converter for %s", clazz.getName()); logger.debug("found converter {} to {}", converterType.getName(), clazz.getName()); return (Converter<T>) container.instanceFor(converterType); } protected DefaultConverters(); @Inject DefaultConverters(Container container, @LRU CacheStore<Class<?>, Class<? extends Converter<?>>> cache); @Override void register(Class<? extends Converter<?>> converterClass); @SuppressWarnings("unchecked") @Override Converter<T> to(Class<T> clazz); @Override boolean existsFor(Class<?> type); @Override boolean existsTwoWayFor(Class<?> type); @Override TwoWayConverter<?> twoWayConverterFor(Class<?> type); }### Answer:
@Test public void complainsIfNoConverterFound() { exception.expect(IllegalStateException.class); exception.expectMessage("Unable to find converter for " + getClass().getName()); converters.to(DefaultConvertersTest.class); } |
### Question:
DefaultInterceptorHandlerFactory implements InterceptorHandlerFactory { @Override public InterceptorHandler handlerFor(final Class<?> type) { return cachedHandlers.fetch(type, new Supplier<InterceptorHandler>() { @Override public InterceptorHandler get() { if(type.isAnnotationPresent(Intercepts.class) && !Interceptor.class.isAssignableFrom(type)){ return new AspectStyleInterceptorHandler(type, stepInvoker, container, customAcceptsExecutor, acceptsExecutor, interceptorExecutor); } return new ToInstantiateInterceptorHandler(container, type, executeMethodExceptionHandler); } }); } protected DefaultInterceptorHandlerFactory(); @Inject DefaultInterceptorHandlerFactory(Container container, StepInvoker stepInvoker,
CacheStore<Class<?>, InterceptorHandler> cachedHandlers, InterceptorAcceptsExecutor acceptsExecutor,
CustomAcceptsExecutor customAcceptsExecutor, InterceptorExecutor interceptorExecutor,
ExecuteMethodExceptionHandler executeMethodExceptionHandler); @Override InterceptorHandler handlerFor(final Class<?> type); }### Answer:
@Test public void handlerForRegularInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(RegularInterceptor.class), is(instanceOf(ToInstantiateInterceptorHandler.class))); }
@Test public void handlerForAspectStyleInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(instanceOf(AspectStyleInterceptorHandler.class))); }
@Test public void aspectStyleHandlersShouldBeCached() throws Exception { InterceptorHandler handler = factory.handlerFor(AspectStyleInterceptor.class); assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(sameInstance(handler))); } |
### Question:
ReplicatorOutjector implements Outjector { @Override public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { result.include(vparameter.getName(), vparameter.getValue()); } } protected ReplicatorOutjector(); @Inject ReplicatorOutjector(Result result, MethodInfo method); @Override void outjectRequestMap(); }### Answer:
@Test public void shouldReplicateMethodParametersToNextRequest() throws Exception { methodInfo.setParameter(0, 1); methodInfo.setParameter(1, 2.0); methodInfo.setParameter(2, 3l); outjector.outjectRequestMap(); verify(result).include("first", 1); verify(result).include("second", 2.0); verify(result).include("third", 3l); } |
Subsets and Splits