method2testcases
stringlengths 118
3.08k
|
---|
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { @Override public void setConfiguration(org.jpos.core.Configuration cfg) { this.cfg = cfg; } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testSetConfiguration() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); Configuration cfg = new SimpleConfiguration(new Properties()); bSHLogListener.setConfiguration(cfg); assertSame(cfg, bSHLogListener.cfg, "bSHLogListener.cfg"); } |
### Question:
BSHAction implements ActionListener, UIAware { public void actionPerformed (ActionEvent ev) { String bshSource = ev.getActionCommand(); try { Interpreter bsh = new Interpreter (); bsh.source (bshSource); } catch (Exception e) { e.printStackTrace(); } } BSHAction(); void setUI(UI ui, Element e); void actionPerformed(ActionEvent ev); public UI ui; }### Answer:
@Disabled("test fails - needs a real action file") @Test public void testActionPerformed() throws Throwable { new BSHAction().actionPerformed(new ActionEvent("testString", 100, "testBSHActionParam3", 100L, 1000)); assertTrue(true, "Test completed without Exception"); }
@Test public void testActionPerformedThrowsNullPointerException() throws Throwable { try { new BSHAction().actionPerformed(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"java.awt.event.ActionEvent.getActionCommand()\" because \"ev\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
IFB_AMOUNT extends ISOFieldPackager { public byte[] pack (ISOComponent c) throws ISOException { String s = (String) c.getValue(); String amount = ISOUtil.zeropad(s.substring(1), getLength()-1); byte[] b = new byte[1 + (getLength() >> 1)]; b[0] = (byte) s.charAt(0); interpreter.interpret(amount, b, 1); return b; } IFB_AMOUNT(); IFB_AMOUNT(int len, String description, boolean pad); void setPad(boolean pad); byte[] pack(ISOComponent c); int unpack(ISOComponent c, byte[] b, int offset); int getMaxPackedLength(); }### Answer:
@Test public void testPack() throws Exception { ISOField field = new ISOField(12, "D123"); IFB_AMOUNT packager = new IFB_AMOUNT(6, "Should be D00123", true); TestUtils.assertEquals(new byte[]{68, 0x00, 0x01, 0x23}, packager.pack(field)); }
@Test public void testPackOddDigits() throws Exception { ISOField field = new ISOField(12, "D123"); IFB_AMOUNT packager = new IFB_AMOUNT(5, "Should be D0123", true); TestUtils.assertEquals(new byte[]{68, 0x01, 0x23}, packager.pack(field)); } |
### Question:
IFB_AMOUNT extends ISOFieldPackager { public int unpack (ISOComponent c, byte[] b, int offset) throws ISOException { String d = new String(b, offset, 1) + interpreter.uninterpret(b, offset + 1, getLength() - 1); c.setValue(d); return 1 + (getLength() >> 1); } IFB_AMOUNT(); IFB_AMOUNT(int len, String description, boolean pad); void setPad(boolean pad); byte[] pack(ISOComponent c); int unpack(ISOComponent c, byte[] b, int offset); int getMaxPackedLength(); }### Answer:
@Test public void testUnpack() throws Exception { byte[] raw = new byte[]{68, 0x00, 0x01, 0x23}; IFB_AMOUNT packager = new IFB_AMOUNT(6, "Should be D00123", true); ISOField field = new ISOField(12); packager.unpack(field, raw, 0); assertEquals("D00123", (String) field.getValue()); } |
### Question:
EbcdicBinaryInterpreter implements BinaryInterpreter { public void interpret(byte[] data, byte[] b, int offset) { ISOUtil.asciiToEbcdic(data, b, offset); } void interpret(byte[] data, byte[] b, int offset); byte[] uninterpret(byte[] rawData, int offset, int length); int getPackedLength(int nDataUnits); static final EbcdicBinaryInterpreter INSTANCE; }### Answer:
@Test public void interpret() { byte[] result = new byte[binaryData.length]; interpreter.interpret(binaryData, result, 0); assertThat(result, is(EBCDICDATA)); } |
### Question:
EbcdicBinaryInterpreter implements BinaryInterpreter { public byte[] uninterpret(byte[] rawData, int offset, int length) { return ISOUtil.ebcdicToAsciiBytes(rawData, offset, length); } void interpret(byte[] data, byte[] b, int offset); byte[] uninterpret(byte[] rawData, int offset, int length); int getPackedLength(int nDataUnits); static final EbcdicBinaryInterpreter INSTANCE; }### Answer:
@Test public void uninterpret() { int offset = 0; int length = EBCDICDATA.length; byte[] result = interpreter.uninterpret(EBCDICDATA, offset, length); assertThat(result, is(binaryData)); } |
### Question:
SpaceAdaptor extends QBeanSupport implements SpaceAdaptorMBean { protected void stopService () throws Exception { getServer().getMBeanServer().unregisterMBean (objectName); } SpaceAdaptor(); synchronized void setSpaceName(String spaceName); String getSpaceName(); Set getKeys(); }### Answer:
@Test public void testStopServiceThrowsNullPointerException() throws Throwable { SpaceAdaptor spaceAdaptor = new SpaceAdaptor(); try { spaceAdaptor.stopService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.q2.Q2.getMBeanServer()\" because the return value of \"org.jpos.q2.qbean.SpaceAdaptor.getServer()\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
KafkaWorkItemHandler extends AbstractLogOrThrowWorkItemHandler implements Cacheable { @Override public void close() { if (producer != null) { producer.flush(); producer.close(); } } KafkaWorkItemHandler(Producer producer); KafkaWorkItemHandler(String bootstrapServers,
String clientId,
String keySerializerClass,
String valueSerializerClass,
ClassLoader classLoader); KafkaWorkItemHandler(String bootstrapServers,
String clientId,
String keySerializerClass,
String valueSerializerClass); void executeWorkItem(WorkItem workItem,
WorkItemManager manager); void abortWorkItem(WorkItem workItem,
WorkItemManager manager); @Override void close(); }### Answer:
@Test public void testExceptionHandlingWhenClosed() throws Exception{ buildKafkaWIH(true); mockProducerString.close(); assertExceptionAfterExecuteWorkItem(workItem); } |
### Question:
ExecWorkItemHandler extends AbstractLogOrThrowWorkItemHandler { public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String command = (String) workItem.getParameter("Command"); List<String> arguments = (List<String>) workItem.getParameter("Arguments"); Map<String, Object> results = new HashMap<>(); CommandLine commandLine = CommandLine.parse(command); if (arguments != null && arguments.size() > 0) { commandLine.addArguments(arguments.toArray(new String[0]), true); } parsedCommandStr = commandLine.toString(); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(commandLine); results.put(RESULT, outputStream.toString()); outputStream.close(); manager.completeWorkItem(workItem.getId(), results); } catch (Throwable t) { handleException(t); } } void executeWorkItem(WorkItem workItem,
WorkItemManager manager); void abortWorkItem(WorkItem workItem,
WorkItemManager manager); String getParsedCommandStr(); static final String RESULT; }### Answer:
@Test public void testExecCommandInvalidParam() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); ExecWorkItemHandler handler = new ExecWorkItemHandler(); handler.setLogThrownException(true); handler.executeWorkItem(workItem, manager); assertNotNull(manager.getResults()); assertEquals(0, manager.getResults().size()); } |
### Question:
DiffInfo { public static DiffInfo fromFile(String path) { try { return new DiffInfo(Files.newBufferedReader(Paths.get(path))); } catch (IOException exc) { throw new RuntimeException("Could not open file: " + path, exc); } } DiffInfo(BufferedReader reader); boolean contains(String path); static DiffInfo fromFile(String path); }### Answer:
@Test void testFromFileWithANotExistingFile() { assertThrows(RuntimeException.class, () -> { DiffInfo.fromFile("notExistingPath"); }); } |
### Question:
DiffMutationFilterFactory implements MutationInterceptorFactory { @Override public MutationInterceptor createInterceptor(InterceptorParameters params) { Optional<String> path = params.getString(fileParameter); return new DiffMutationFilter(DiffInfo.fromFile(path.orElse(defaultPath))); } @Override MutationInterceptor createInterceptor(InterceptorParameters params); @Override Feature provides(); @Override String description(); }### Answer:
@Test void testInterceptorType() { DiffMutationFilterFactory diffMutationFilterFactory = new DiffMutationFilterFactory(); MutationInterceptor diffMutationFilter = diffMutationFilterFactory .createInterceptor(makeFor("file", "LICENSE")); assertEquals(InterceptorType.FILTER, diffMutationFilter.type()); } |
### Question:
TextAttributeConverter implements AttributeConverter<String, String> { @Override public String convertToEntityAttribute(String text) { return text; } @Override String convertToDatabaseColumn(String text); @Override String convertToEntityAttribute(String text); }### Answer:
@Test void testConvertToEntityAttribute() { Assertions.assertEquals("test", textAttributeConverter.convertToEntityAttribute("test")); } |
### Question:
HooksPhaseGetter { public List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context) { if (syncFlowableStep instanceof BeforeStepHookPhaseProvider) { return ((BeforeStepHookPhaseProvider) syncFlowableStep).getHookPhasesBeforeStep(context); } return Collections.singletonList(HookPhase.NONE); } List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context); List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context); }### Answer:
@Test void testGetHookPhasesBeforeStop() { List<HookPhase> hookPhases = List.of(HookPhase.BEFORE_STOP); StopAppStep beforeStepHookPhaseProvider = Mockito.mock(StopAppStep.class); Mockito.when(beforeStepHookPhaseProvider.getHookPhasesBeforeStep(context)) .thenReturn(hookPhases); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesBeforeStop(beforeStepHookPhaseProvider, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(hookPhases, hookPhasesBeforeStop); }
@Test void testGetHookPhasesBeforeStopNonHooksClass() { SyncFlowableStep syncFlowableStep = Mockito.mock(SyncFlowableStep.class); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesBeforeStop(syncFlowableStep, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(HookPhase.NONE, hookPhasesBeforeStop.get(0)); } |
### Question:
HooksPhaseGetter { public List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context) { if (syncFlowableStep instanceof AfterStepHookPhaseProvider) { return ((AfterStepHookPhaseProvider) syncFlowableStep).getHookPhasesAfterStep(context); } return Collections.singletonList(HookPhase.NONE); } List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context); List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context); }### Answer:
@Test void testGetHookPhasesAfterStop() { List<HookPhase> hookPhases = List.of(HookPhase.AFTER_STOP); StopAppStep afterStepHookPhaseProvider = Mockito.mock(StopAppStep.class); Mockito.when(afterStepHookPhaseProvider.getHookPhasesAfterStep(context)) .thenReturn(hookPhases); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesAfterStop(afterStepHookPhaseProvider, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(hookPhases, hookPhasesBeforeStop); }
@Test void testGetHookPhasesAfterStopNonHooksClass() { SyncFlowableStep syncFlowableStep = Mockito.mock(SyncFlowableStep.class); List<HookPhase> hookPhasesAfterStop = hooksPhaseGetter.getHookPhasesAfterStop(syncFlowableStep, context); Assertions.assertEquals(1, hookPhasesAfterStop.size()); Assertions.assertEquals(HookPhase.NONE, hookPhasesAfterStop.get(0)); } |
### Question:
EnvironmentServicesFinder { public CfService findService(String name) { if (StringUtils.isEmpty(name)) { return null; } return CollectionUtils.firstElement(env.findServicesByName(name)); } EnvironmentServicesFinder(); EnvironmentServicesFinder(CfJdbcEnv env); CfJdbcService findJdbcService(String name); CfService findService(String name); }### Answer:
@Test void testFindServiceWithNullOrEmptyServiceName() { Assertions.assertNull(environmentServicesFinder.findService(null)); Assertions.assertNull(environmentServicesFinder.findService("")); }
@Test void testFindService() { CfService expectedService = Mockito.mock(CfService.class); Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(List.of(expectedService)); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertEquals(expectedService, service); }
@Test void testFindServiceWithMultipleMatches() { CfService expectedService1 = Mockito.mock(CfService.class); CfService expectedService2 = Mockito.mock(CfService.class); Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(List.of(expectedService1, expectedService2)); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertEquals(expectedService1, service); }
@Test void testFindServiceWithZeroMatches() { Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(Collections.emptyList()); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertNull(service); } |
### Question:
HooksExecutor { public List<Hook> executeAfterStepHooks(StepPhase currentStepPhase) { if (!hooksCalculator.isInPostExecuteStepPhase(currentStepPhase)) { return Collections.emptyList(); } return executeHooks(currentStepPhase); } HooksExecutor(HooksCalculator hooksCalculator, Module moduleToDeploy); List<Hook> executeBeforeStepHooks(StepPhase currentStepPhase); List<Hook> executeAfterStepHooks(StepPhase currentStepPhase); }### Answer:
@Test void executeAfterStepHooksWhenPhaseIsNotAfter() { Module moduleToDeploy = createModule("test-module"); Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.DEPLOY); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeAfterStepHooks(StepPhase.EXECUTE); Assertions.assertTrue(hooksForExecution.isEmpty()); }
@Test void executeAfterStepHooks() { Module moduleToDeploy = createModule("test-module"); Mockito.when(hooksCalculator.isInPostExecuteStepPhase(StepPhase.DONE)) .thenReturn(true); List<Hook> expectedHooksForExecution = List.of(createHook("test-hook", Collections.emptyList())); Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.DEPLOY); Mockito.when(hooksCalculator.calculateHooksForExecution(moduleToDeploy, StepPhase.DONE)) .thenReturn(expectedHooksForExecution); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeAfterStepHooks(StepPhase.DONE); Assertions.assertEquals(expectedHooksForExecution, hooksForExecution); } |
### Question:
ProcessHelper { public Operation.State computeProcessState(String processId) { if (isInAbortedState(processId)) { return State.ABORTED; } if (isInErrorState(processId)) { return State.ERROR; } if (isInReceiveTask(processId)) { return State.ACTION_REQUIRED; } if (isInRunningState(processId)) { return State.RUNNING; } return State.FINISHED; } @Inject ProcessHelper(FlowableFacade flowableFacade, HistoricOperationEventService historicOperationEventService); Operation.State computeProcessState(String processId); List<HistoricOperationEvent> getHistoricOperationEventByProcessId(String processId); }### Answer:
@Test void testIsProcessAtReceiveTask() { Mockito.when(flowableFacade.isProcessInstanceAtReceiveTask(PROCESS_ID)) .thenReturn(true); Assertions.assertEquals(State.ACTION_REQUIRED, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessInErrorState() { Mockito.when(flowableFacade.hasDeadLetterJobs(PROCESS_ID)) .thenReturn(true); Assertions.assertEquals(State.ERROR, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessAbortedWhenThereIsAbortedProcess() { Mockito.when(historicOperationEventQuery.list()) .thenReturn(List.of(ImmutableHistoricOperationEvent.builder() .type(HistoricOperationEvent.EventType.ABORTED) .processId(PROCESS_ID) .build())); Assertions.assertEquals(State.ABORTED, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessAbortedWhenThereIsNotAbortedProcess() { mockHistoricEventsWithTypes(HistoricOperationEvent.EventType.FINISHED); Assertions.assertEquals(State.FINISHED, processHelper.computeProcessState(PROCESS_ID)); } |
### Question:
ModuleDeterminer { public Module determineModuleToDeploy() { Module moduleToDeploy = getContext().getVariable(Variables.MODULE_TO_DEPLOY); return moduleToDeploy != null ? moduleToDeploy : determineModule(); } Module determineModuleToDeploy(); abstract MtaMetadataParser getMtaMetadataParser(); abstract ProcessContext getContext(); }### Answer:
@Test void testDetermineModuleToDeployModuleIsSet() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); context.setVariable(Variables.MODULE_TO_DEPLOY, createModule("test-module")); Module module = moduleDeterminer.determineModuleToDeploy(); Assertions.assertEquals("test-module", module.getName()); }
@Test void testDetermineModuleIfModuleIsNotSetAnywhere() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); Assertions.assertNull(moduleDeterminer.determineModuleToDeploy()); }
@Test void testDetermineModuleIfModuleIsNotSet() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); DeploymentDescriptor completeDeploymentDescriptor = createDeploymentDescriptor(); Module moduleToDeploy = createModule("some-module-name"); completeDeploymentDescriptor.setModules(List.of(moduleToDeploy)); context.setVariable(Variables.COMPLETE_DEPLOYMENT_DESCRIPTOR, completeDeploymentDescriptor); context.setVariable(Variables.APP_TO_PROCESS, createApplication("app-to-process", "some-module-name", null)); context.setVariable(Variables.MTA_MAJOR_SCHEMA_VERSION, 3); Module module = moduleDeterminer.determineModuleToDeploy(); Assertions.assertEquals("some-module-name", module.getName()); } |
### Question:
ProcessConflictPreventer { public synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId) { LOGGER.info(format(Messages.ACQUIRING_LOCK, processId, mtaId)); validateNoConflictingOperationsExist(mtaId, namespace, spaceId); Operation currentOperation = getOperationByProcessId(processId); ImmutableOperation.Builder currentOperationWithAcquiredLock = ImmutableOperation.builder() .from(currentOperation) .mtaId(mtaId) .hasAcquiredLock(true); if (StringUtils.isNotEmpty(namespace)) { currentOperationWithAcquiredLock.namespace(namespace); } operationService.update(currentOperation, currentOperationWithAcquiredLock.build()); LOGGER.info(format(Messages.ACQUIRED_LOCK, processId, StepsUtil.getQualifiedMtaId(mtaId, namespace))); } ProcessConflictPreventer(OperationService operationService); synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId); void releaseLock(String processInstanceId, Operation.State state); }### Answer:
@Test void testAcquireLock() { SLException exception = assertThrows(SLException.class, this::tryToAcquireLock); assertEquals("Conflicting process \"test-process-id\" found for MTA \"test-mta-id\"", exception.getMessage()); }
@Test void testAcquireLockWithNoConflictingOperations() { assertDoesNotThrow(() -> processConflictPreventerMock.acquireLock(testMtaId, null, testSpaceId, testProcessId)); } |
### Question:
ProcessConflictPreventer { public void releaseLock(String processInstanceId, Operation.State state) { Operation operation = getOperationByProcessId(processInstanceId); LOGGER.info(MessageFormat.format(Messages.PROCESS_0_RELEASING_LOCK_FOR_MTA_1_IN_SPACE_2, operation.getProcessId(), operation.getMtaId(), operation.getSpaceId())); operation = ImmutableOperation.builder() .from(operation) .hasAcquiredLock(false) .state(state) .endedAt(ZonedDateTime.now()) .build(); operationService.update(operation, operation); LOGGER.debug(MessageFormat.format(Messages.PROCESS_0_RELEASED_LOCK, operation.getProcessId())); } ProcessConflictPreventer(OperationService operationService); synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId); void releaseLock(String processInstanceId, Operation.State state); }### Answer:
@Test void testReleaseLock() { Operation.State abortedState = Operation.State.ABORTED; processConflictPreventerMock.releaseLock(testProcessId, abortedState); ArgumentCaptor<Operation> argumentCaptor = ArgumentCaptor.forClass(Operation.class); verify(operationServiceMock).update(argumentCaptor.capture(), argThat(this::assertOperationAbort)); assertEquals(testProcessId, argumentCaptor.getValue() .getProcessId()); } |
### Question:
ArchiveMerger { public Path createArchiveFromParts(List<FileEntry> archiveParts) { List<FileEntry> sortedArchiveParts = sort(archiveParts); String archiveName = getArchiveName(sortedArchiveParts.get(0)); try (FilePartsMerger filePartsMerger = new FilePartsMerger(archiveName)) { mergeArchiveParts(sortedArchiveParts, filePartsMerger); return filePartsMerger.getMergedFilePath(); } } ArchiveMerger(FileService fileService, StepLogger stepLogger, DelegateExecution execution); Path createArchiveFromParts(List<FileEntry> archiveParts); }### Answer:
@Test void testCreateArchiveFromPartsFileStorageExceptionThrown() throws FileStorageException { Mockito.doThrow(FileStorageException.class) .when(fileService) .consumeFileContent(any(), any(), any()); Assertions.assertThrows(SLException.class, () -> archiveMerger.createArchiveFromParts(createFileEntriesFromFile(FILE_ENTRIES))); }
@Test void testCreateArchiveFromParts() { List<FileEntry> fileEntries = createFileEntriesFromFile(FILE_ENTRIES); Path archiveFromParts = archiveMerger.createArchiveFromParts(fileEntries); Assertions.assertTrue(archiveFromParts.toString() .endsWith(getArchiveName(fileEntries.get(0)))); }
@Test void testWithArchiveNameWithoutParts() throws FileStorageException { List<FileEntry> fileEntryWithoutParts = createFileEntriesFromFile(FILE_ENTRY_WITHOUT_PARTS); archiveMerger.createArchiveFromParts(fileEntryWithoutParts); Mockito.verify(fileService) .consumeFileContent(any(), any(), any()); } |
### Question:
ArchiveMerger { List<FileEntry> sort(List<FileEntry> archiveParts) { return archiveParts.stream() .sorted(Comparator.comparingInt(this::getArchivePartIndex)) .collect(Collectors.toList()); } ArchiveMerger(FileService fileService, StepLogger stepLogger, DelegateExecution execution); Path createArchiveFromParts(List<FileEntry> archiveParts); }### Answer:
@Test void testSortFileEntries() { List<FileEntry> randomSortedFileEntries = createFileEntriesFromFile(RANDOM_SORTED_ENTRIES); List<FileEntry> expectedFileEntries = createFileEntriesFromFile(EXPECTED_FILE_ENTRIES); List<FileEntry> sortedFileEntries = archiveMerger.sort(randomSortedFileEntries); Assertions.assertIterableEquals(getFileEntriesNames(expectedFileEntries), getFileEntriesNames(sortedFileEntries)); }
@Test void testSortFileEntriesWithInvalidNames() { List<FileEntry> invalidFileEntries = createFileEntriesFromFile(FILE_ENTRIES_WITH_INVALID_NAMES); Assertions.assertThrows(SLException.class, () -> archiveMerger.sort(invalidFileEntries)); }
@Test void testSortFileEntriesWithNamesWhichContainPartButDoNotContainIndexes() { List<FileEntry> invalidFileEntries = createFileEntriesFromFile(FILE_ENTRIES_WITHOUT_INDEXES); Assertions.assertThrows(SLException.class, () -> archiveMerger.sort(invalidFileEntries)); } |
### Question:
ApplicationArchiveReader { public String calculateApplicationDigest(ApplicationArchiveContext applicationArchiveContext) { try { iterateApplicationArchive(applicationArchiveContext); return applicationArchiveContext.getApplicationDigestCalculator() .getDigest(); } catch (IOException e) { throw new SLException(e, Messages.ERROR_RETRIEVING_MTA_MODULE_CONTENT, applicationArchiveContext.getModuleFileName()); } } String calculateApplicationDigest(ApplicationArchiveContext applicationArchiveContext); ZipEntry getFirstZipEntry(ApplicationArchiveContext applicationArchiveContext); ZipEntry getNextEntryByName(String name, ApplicationArchiveContext applicationArchiveContext); }### Answer:
@Test void testBadAbsolutePathRead() { String mtar = SAMPLE_MTAR_WITH_JAR_ENTRY_ABSOLUTE_PATH; String fileName = "/web/"; String expectedException = MessageFormat.format(FileUtils.PATH_SHOULD_NOT_BE_ABSOLUTE, "/web/"); long maxFileUploadSize = MAX_UPLOAD_FILE_SIZE; ApplicationArchiveContext applicationArchiveContext = getApplicationArchiveContext(mtar, fileName, maxFileUploadSize); ApplicationArchiveReader reader = getApplicationArchiveReaderForAbsolutePath(); Exception exception = Assertions.assertThrows(Exception.class, () -> reader.calculateApplicationDigest(applicationArchiveContext)); assertEquals(expectedException, exception.getMessage()); } |
### Question:
OperationsHelper { public String getProcessDefinitionKey(Operation operation) { return metadataMapper.getDiagramId(operation.getProcessType()); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testGetProcessDefinitionKey() { Operation mockedOperation = createMockedOperation(PROCESS_ID, ProcessType.DEPLOY, Operation.State.RUNNING); Mockito.when(metadataMapper.getDiagramId(ProcessType.DEPLOY)) .thenReturn(Constants.DEPLOY_SERVICE_ID); String processDefinitionKey = operationsHelper.getProcessDefinitionKey(mockedOperation); Assertions.assertEquals(Constants.DEPLOY_SERVICE_ID, processDefinitionKey); } |
### Question:
OperationsHelper { public Operation addState(Operation operation) { if (operation.getState() != null) { return operation; } Operation.State state = computeState(operation); if (operation.hasAcquiredLock() && (state.equals(Operation.State.ABORTED) || state.equals(Operation.State.FINISHED))) { operation = ImmutableOperation.builder() .from(operation) .hasAcquiredLock(false) .state(state) .build(); operationService.update(operation, operation); } return ImmutableOperation.copyOf(operation) .withState(state); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testAddStateWhenOperationHasState() { Operation mockedOperation = createMockedOperation(PROCESS_ID, ProcessType.DEPLOY, Operation.State.RUNNING); Operation operation = operationsHelper.addState(mockedOperation); Assertions.assertEquals(Operation.State.RUNNING, operation.getState()); } |
### Question:
ApplicationStager { public boolean isApplicationStagedCorrectly(CloudApplication app) { List<CloudBuild> buildsForApplication = client.getBuildsForApplication(app.getMetadata() .getGuid()); if (containsNullMetadata(buildsForApplication)) { return false; } CloudBuild build = getLastBuild(buildsForApplication); if (build == null) { logger.debug(Messages.NO_BUILD_FOUND_FOR_APPLICATION, app.getName()); return false; } if (isBuildStagedCorrectly(build)) { return true; } logMessages(app, build); return false; } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testIsApplicationStagedCorrectlyMetadataIsNull() { CloudApplication app = createApplication(); Mockito.when(client.getBuildsForApplication(any(UUID.class))) .thenReturn(List.of(Mockito.mock(CloudBuild.class))); Assertions.assertFalse(applicationStager.isApplicationStagedCorrectly(app)); }
@Test void testIsApplicationStagedCorrectlyNoLastBuild() { CloudApplication app = createApplication(); Mockito.when(client.getBuildsForApplication(any(UUID.class))) .thenReturn(Collections.emptyList()); Assertions.assertFalse(applicationStager.isApplicationStagedCorrectly(app)); } |
### Question:
ApplicationStager { public StepPhase stageApp(CloudApplication app) { CloudPackage cloudPackage = context.getVariable(Variables.CLOUD_PACKAGE); if (cloudPackage == null) { return StepPhase.DONE; } logger.info(Messages.STAGING_APP, app.getName()); return createBuild(cloudPackage.getGuid()); } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testStageAppIfThereIsNoCloudPacakge() { context.setVariable(Variables.CLOUD_PACKAGE, null); assertEquals(StepPhase.DONE, applicationStager.stageApp(null)); } |
### Question:
ApplicationStager { public StagingState getStagingState() { UUID buildGuid = context.getVariable(Variables.BUILD_GUID); if (buildGuid == null) { return ImmutableStagingState.builder() .state(PackageState.STAGED) .build(); } CloudBuild build = getBuild(buildGuid); return getStagingState(build); } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testIfBuildGuidDoesNotExist() { StagingState stagingState = applicationStager.getStagingState(); assertEquals(PackageState.STAGED, stagingState.getState()); assertNull(stagingState.getError()); } |
### Question:
JarSignatureOperations { public List<X509Certificate> readCertificates(String certificatesFilename) { try (InputStream certificatesInputStream = getClass().getResourceAsStream(certificatesFilename)) { CertificateFactory certificateFactory = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE_X_509); return (List<X509Certificate>) certificateFactory.generateCertificates(certificatesInputStream); } catch (CertificateException | IOException e) { throw new SLException(e, e.getMessage()); } } void checkCertificates(URL url, List<X509Certificate> certificates, String certificateCN); List<X509Certificate> readCertificates(String certificatesFilename); }### Answer:
@Test void testGetCertificatesCheckWhetherSymantecExists() { List<X509Certificate> providedCertificates = mtaCertificateChecker.readCertificates(Constants.SYMANTEC_CERTIFICATE_FILE); Assertions.assertEquals(1, providedCertificates.size()); Assertions.assertEquals(SYMANTEC_SUBJECT_DN, providedCertificates.get(0) .getSubjectDN() .toString()); Assertions.assertEquals(SYMANTEC_ISSUER_DN, providedCertificates.get(0) .getIssuerDN() .toString()); }
@Test void testGetCertificatesWithNullInputStream() { SLException exception = Assertions.assertThrows(SLException.class, () -> mtaCertificateChecker.readCertificates("non-existing-certificate.crt")); Assertions.assertEquals("Missing input stream", exception.getMessage()); } |
### Question:
ProcessTypeToOperationMetadataMapper { public String getDiagramId(ProcessType processType) { return getOperationMetadata(processType).getDiagramId(); } OperationMetadata getOperationMetadata(ProcessType processType); String getDiagramId(ProcessType processType); }### Answer:
@Test void testGetDiagramDeployProcessType() { Assertions.assertEquals(Constants.DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.DEPLOY)); }
@Test void testGetDiagramBlueGreenDeployProcessType() { Assertions.assertEquals(Constants.BLUE_GREEN_DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.BLUE_GREEN_DEPLOY)); }
@Test void testGetDiagramUndeployProcessType() { Assertions.assertEquals(Constants.UNDEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.UNDEPLOY)); }
@Test void testGetDiagramCtsDeployProcessType() { Assertions.assertEquals(Constants.CTS_DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.CTS_DEPLOY)); } |
### Question:
VersionRuleParameterConverter implements ParameterConverter { @Override public Object convert(Object value) { String versionRule = String.valueOf(value); validate(versionRule); return versionRule; } @Override Object convert(Object value); }### Answer:
@Test void testConvertWithInvalidValueType() { assertThrows(SLException.class, () -> new VersionRuleParameterConverter().convert(false)); }
@Test void testConvertWithInvalidValue() { assertThrows(SLException.class, () -> new VersionRuleParameterConverter().convert("foo")); }
@Test void testConvert() { String versionRule = (String) new VersionRuleParameterConverter().convert("ALL"); assertEquals("ALL", versionRule); } |
### Question:
StartTimeoutParameterConverter extends IntegerParameterConverter { @Override public Integer convert(Object value) { int startTimeout = super.convert(value); if (startTimeout < 0) { throw new SLException(Messages.ERROR_PARAMETER_1_MUST_NOT_BE_NEGATIVE, startTimeout, Variables.START_TIMEOUT.getName()); } return startTimeout; } @Override Integer convert(Object value); }### Answer:
@Test void testConvertWithInvalidValueType() { assertThrows(SLException.class, () -> new StartTimeoutParameterConverter().convert(false)); }
@Test void testConvertWithInvalidValue() { assertThrows(SLException.class, () -> new StartTimeoutParameterConverter().convert(-1000)); }
@Test void testConvert() { int startTimeout = (int) new StartTimeoutParameterConverter().convert("1000"); assertEquals(1000, startTimeout); } |
### Question:
RestartAppStep extends TimeoutAsyncFlowableStepWithHooks implements BeforeStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Collections.singletonList(HookPhase.BEFORE_START), context); } @Override StepPhase executePollingStep(ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetHookPhasesBeforeStep() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_START), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_LIVE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesBeforeStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
UpdateServiceMetadataStep extends ServiceStep { private MethodExecution<String> updateServiceMetadata(CloudControllerClient controllerClient, CloudServiceInstanceExtended service) { getStepLogger().debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0, service.getName(), service.getResourceName()); updateServiceMetadata(service, controllerClient); getStepLogger().debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0_DONE, service.getName()); return new MethodExecution<>(null, MethodExecution.ExecutionState.FINISHED); } }### Answer:
@Test void testUpdateServiceMetadata() { CloudServiceInstanceExtended serviceToProcess = buildServiceToProcess(); prepareServiceToProcess(serviceToProcess); prepareClient(serviceToProcess); step.execute(execution); verify(client).updateServiceInstanceMetadata(serviceToProcess.getMetadata() .getGuid(), serviceToProcess.getV3Metadata()); } |
### Question:
UpdateServiceMetadataExecution implements AsyncExecution { @Override public AsyncExecutionState execute(ProcessContext context) { CloudServiceInstanceExtended serviceInstance = context.getVariable(Variables.SERVICE_TO_PROCESS); context.getStepLogger() .debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0, serviceInstance.getName()); updateMetadata(context.getControllerClient(), serviceInstance); context.getStepLogger() .debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0_DONE, serviceInstance.getName()); return AsyncExecutionState.FINISHED; } @Override AsyncExecutionState execute(ProcessContext context); @Override String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testExecute() { Metadata v3Metadata = Metadata.builder() .annotation("a", "b") .annotation("c", "d") .build(); CloudServiceInstanceExtended serviceInstanceToCreate = ImmutableCloudServiceInstanceExtended.builder() .name(SERVICE_INSTANCE_NAME) .plan(SERVICE_INSTANCE_PLAN) .label(SERVICE_INSTANCE_LABEL) .v3Metadata(v3Metadata) .build(); Mockito.when(procesContext.getVariable(Variables.SERVICE_TO_PROCESS)) .thenReturn(serviceInstanceToCreate); CloudMetadata metadata = ImmutableCloudMetadata.builder() .guid(UUID.randomUUID()) .createdAt(new Date()) .updatedAt(new Date()) .build(); CloudServiceInstance serviceInstance = ImmutableCloudServiceInstance.builder() .name(SERVICE_INSTANCE_NAME) .plan(SERVICE_INSTANCE_PLAN) .label(SERVICE_INSTANCE_LABEL) .metadata(metadata) .build(); Mockito.when(controllerClient.getServiceInstance(serviceInstance.getName())) .thenReturn(serviceInstance); AsyncExecution asyncExecution = new UpdateServiceMetadataExecution(); asyncExecution.execute(procesContext); Mockito.verify(controllerClient) .updateServiceInstanceMetadata(metadata.getGuid(), v3Metadata); } |
### Question:
ProcessStepHelper { protected void postExecuteStep(ProcessContext context, StepPhase state) { logDebug(MessageFormat.format(Messages.STEP_FINISHED, context.getExecution() .getCurrentFlowElement() .getName())); getProcessLogsPersister().persistLogs(context.getVariable(Variables.CORRELATION_ID), context.getVariable(Variables.TASK_ID)); context.setVariable(Variables.STEP_EXECUTION, state.toString()); } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testPostExecutionStep() { Mockito.when(context.getVariable(Variables.TASK_ID)) .thenReturn(TASK_GUID); FlowElement flowElement = Mockito.mock(SubProcess.class); Mockito.when(execution.getCurrentFlowElement()) .thenReturn(flowElement); processStepHelper.postExecuteStep(context, StepPhase.DONE); Mockito.verify(processLogsPersister) .persistLogs(CORRELATION_GUID, TASK_GUID); Mockito.verify(context) .setVariable(Variables.STEP_EXECUTION, StepPhase.DONE.toString()); } |
### Question:
ProcessStepHelper { protected void logExceptionAndStoreProgressMessage(ProcessContext context, Throwable t) { logException(context, t); storeExceptionInProgressMessageService(context, t); } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testLogExceptionAndStoreExceptionContentError() { prepareProgressMessagesService(); processStepHelper.logExceptionAndStoreProgressMessage(context, new ContentException("content exception")); Mockito.verify(context) .setVariable(Variables.ERROR_TYPE, ErrorType.CONTENT_ERROR); Mockito.verify(progressMessageService) .add(any()); }
@Test void testLogExceptionAndStoreExceptionUnknownError() { prepareProgressMessagesService(); processStepHelper.logExceptionAndStoreProgressMessage(context, new RuntimeException("runtime exception")); Mockito.verify(context) .setVariable(Variables.ERROR_TYPE, ErrorType.UNKNOWN_ERROR); Mockito.verify(progressMessageService) .add(any()); } |
### Question:
ProcessStepHelper { public void failStepIfProcessIsAborted(ProcessContext context) { String correlationId = context.getVariable(Variables.CORRELATION_ID); List<HistoricOperationEvent> historicOperationEvents = getProcessHelper().getHistoricOperationEventByProcessId(correlationId); if (isProcessAborted(historicOperationEvents)) { throw new SLException(Messages.PROCESS_WAS_ABORTED); } } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testFailStepPhaseAbortIsInvoked() { prepareHistoricOperationsEventGetter(HistoricOperationEvent.EventType.STARTED, HistoricOperationEvent.EventType.FINISHED, HistoricOperationEvent.EventType.ABORT_EXECUTED); Exception exception = Assertions.assertThrows(SLException.class, () -> processStepHelper.failStepIfProcessIsAborted(context)); Assertions.assertEquals(Messages.PROCESS_WAS_ABORTED, exception.getMessage()); }
@Test void testFailedStepPhaseAbortIsNotInvoked() { prepareHistoricOperationsEventGetter(HistoricOperationEvent.EventType.STARTED, HistoricOperationEvent.EventType.FINISHED); Assertions.assertDoesNotThrow(() -> processStepHelper.failStepIfProcessIsAborted(context)); } |
### Question:
ProcessGitSourceStep extends SyncFlowableStep { protected String getGitUri(ProcessContext context) { String gitUriParam = StepsUtil.getGitRepoUri(context); try { return new URL(gitUriParam).toString(); } catch (MalformedURLException e) { throw new ContentException(e, Messages.GIT_URI_IS_NOT_SPECIFIED); } } static final String META_INF_PATH; }### Answer:
@Test void getGitUriTest() throws SLException { String gitUri = "https: context.setVariable(Variables.GIT_URI, gitUri); assertEquals(gitUri, step.getGitUri(context)); } |
### Question:
ProcessGitSourceStep extends SyncFlowableStep { protected String extractRepoName(String gitUri, String processId) { if (!gitUri.endsWith(PATH_SEPARATOR + org.eclipse.jgit.lib.Constants.DOT_GIT)) { return gitUri.substring(gitUri.lastIndexOf(PATH_SEPARATOR) + 1) + processId; } String repoLocation = gitUri.substring(0, gitUri.lastIndexOf(PATH_SEPARATOR + org.eclipse.jgit.lib.Constants.DOT_GIT)); return repoLocation.substring(repoLocation.lastIndexOf(PATH_SEPARATOR) + 1) + processId; } static final String META_INF_PATH; }### Answer:
@Test void testExtractRepoName() { String somerepoName = step.extractRepoName("https: assertEquals("somerepo" + PROCESS_INSTANCE_ID, somerepoName); String otherrepoName = step.extractRepoName("https: assertEquals("otherrepo" + PROCESS_INSTANCE_ID, otherrepoName); } |
### Question:
TextAttributeConverter implements AttributeConverter<String, String> { @Override public String convertToDatabaseColumn(String text) { if (text != null) { return StringUtils.abbreviate(text, MAX_STRING_LENGTH); } return ""; } @Override String convertToDatabaseColumn(String text); @Override String convertToEntityAttribute(String text); }### Answer:
@Test void testConvertToDatabaseColumnWhenInputIsNotNull() { Assertions.assertEquals("test", textAttributeConverter.convertToDatabaseColumn("test")); }
@Test void testConvertToDatabaseColumnWhenInputIsNull() { Assertions.assertEquals("", textAttributeConverter.convertToDatabaseColumn(null)); }
@Test void testConvertToDatabaseColumnWhenInputIsLongerThan4000chars() { String expectedString = getLongStringInput().substring(0, 3997) .concat("..."); Assertions.assertEquals(expectedString, textAttributeConverter.convertToDatabaseColumn(getLongStringInput())); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return MessageFormat.format(Messages.ERROR_STAGING_APP_0, context.getVariable(Variables.APP_TO_PROCESS) .getName()); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetErrorMessage() { String applicationName = "another-app"; mockApplication(applicationName); Assertions.assertEquals(MessageFormat.format(Messages.ERROR_STAGING_APP_0, applicationName), step.getStepErrorMessage(context)); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override protected List<AsyncExecution> getAsyncStepExecutions(ProcessContext context) { return Collections.singletonList(new PollStageAppStatusExecution(recentLogsRetriever, new ApplicationStager(context))); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testAsyncExecutionStatus() { List<AsyncExecution> asyncStepExecutions = step.getAsyncStepExecutions(context); Assertions.assertEquals(1, asyncStepExecutions.size()); Assertions.assertTrue(asyncStepExecutions.get(0) instanceof PollStageAppStatusExecution); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override public Integer getTimeout(ProcessContext context) { return context.getVariable(Variables.START_TIMEOUT); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetTimeoutDefaultValue() { Assertions.assertEquals(Variables.START_TIMEOUT.getDefaultValue(), step.getTimeout(context)); }
@Test void testGetTimeoutCustomValue() { int timeout = 10; context.setVariable(Variables.START_TIMEOUT, timeout); Assertions.assertEquals(timeout, step.getTimeout(context)); } |
### Question:
DeleteIdleRoutesStep extends SyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return Messages.ERROR_DELETING_IDLE_ROUTES; } }### Answer:
@Test void testErrorMessage() { Assertions.assertEquals(Messages.ERROR_DELETING_IDLE_ROUTES, step.getStepErrorMessage(context)); } |
### Question:
PollExecuteAppStatusExecution implements AsyncExecution { @Override public AsyncExecutionState execute(ProcessContext context) { List<ApplicationStateAction> actions = context.getVariable(Variables.APP_STATE_ACTIONS_TO_EXECUTE); if (!actions.contains(ApplicationStateAction.EXECUTE)) { return AsyncExecutionState.FINISHED; } CloudApplication app = getNextApp(context); CloudControllerClient client = context.getControllerClient(); ApplicationAttributes appAttributes = ApplicationAttributes.fromApplication(app); AppExecutionDetailedStatus status = getAppExecutionStatus(context, client, appAttributes, app); ProcessLoggerProvider processLoggerProvider = context.getStepLogger() .getProcessLoggerProvider(); StepsUtil.saveAppLogs(context, client, recentLogsRetriever, app, LOGGER, processLoggerProvider); return checkAppExecutionStatus(context, client, app, appAttributes, status); } PollExecuteAppStatusExecution(RecentLogsRetriever recentLogsRetriever); @Override AsyncExecutionState execute(ProcessContext context); String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testStepWithoutExecuteAction() { context.setVariable(Variables.APP_STATE_ACTIONS_TO_EXECUTE, Collections.emptyList()); AsyncExecutionState resultState = step.execute(context); assertEquals(AsyncExecutionState.FINISHED, resultState); } |
### Question:
DeleteApplicationRoutesStep extends UndeployAppStep implements BeforeStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.BEFORE_UNMAP_ROUTES, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES), context); } @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseBefore() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_UNMAP_ROUTES, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_UNMAP_ROUTES_LIVE, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_UNMAP_ROUTES_LIVE, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES); List<HookPhase> hookPhasesBeforeStep = ((BeforeStepHookPhaseProvider) step).getHookPhasesBeforeStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); } |
### Question:
StepsUtil { public static String determineCurrentUser(VariableScope scope) { String user = VariableHandling.get(scope, Variables.USER); if (user == null) { throw new SLException(Messages.CANT_DETERMINE_CURRENT_USER); } return user; } protected StepsUtil(); static String determineCurrentUser(VariableScope scope); static CloudHandlerFactory getHandlerFactory(VariableScope scope); static String getQualifiedMtaId(String mtaId, String namespace); static CloudServiceBroker getServiceBrokersToCreateForModule(VariableScope scope, String moduleName); static List<String> getCreatedOrUpdatedServiceBrokerNames(ProcessContext context); static String getLoggerPrefix(Logger logger); static void incrementVariable(VariableScope scope, String name); static void setExecutedHooksForModule(VariableScope scope, String moduleName, Map<String, List<String>> moduleHooks); static Map<String, List<String>> getExecutedHooksForModule(VariableScope scope, String moduleName); static Integer getInteger(VariableScope scope, String name); static Integer getInteger(VariableScope scope, String name, Integer defaultValue); static T getObject(VariableScope scope, String name); @SuppressWarnings("unchecked") static T getObject(VariableScope scope, String name, T defaultValue); static T getFromJsonBinary(VariableScope scope, String name, Class<T> classOfT); static T getFromJsonBinary(VariableScope scope, String name, TypeReference<T> type); static T getFromJsonBinary(VariableScope scope, String name, TypeReference<T> type, T defaultValue); static void setAsJsonBinary(VariableScope scope, String name, Object value); static final String DEPLOY_ID_PREFIX; }### Answer:
@Test void testDetermineCurrentUserWithSetUser() { VariableHandling.set(execution, Variables.USER, EXAMPLE_USER); String determinedUser = StepsUtil.determineCurrentUser(execution); assertEquals(EXAMPLE_USER, determinedUser); }
@Test void testDetermineCurrentUserError() { Assertions.assertThrows(SLException.class, () -> StepsUtil.determineCurrentUser(execution)); } |
### Question:
PrepareToUndeployStep extends SyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return Messages.ERROR_DETECTING_COMPONENTS_TO_UNDEPLOY; } }### Answer:
@Test void testErrorMessage() { Assertions.assertEquals(Messages.ERROR_DETECTING_COMPONENTS_TO_UNDEPLOY, step.getStepErrorMessage(context)); } |
### Question:
JdbcUtil { public static void rollback(Connection connection) throws SQLException { if (connection == null) { return; } if (!connection.getAutoCommit()) { connection.rollback(); } } private JdbcUtil(); static void closeQuietly(ResultSet resultSet); static void closeQuietly(Statement statement); static void closeQuietly(Connection connection); static void logSQLException(SQLException exception); static void commit(Connection connection); static void rollback(Connection connection); }### Answer:
@Test void rollback() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(false); JdbcUtil.rollback(connection); Mockito.verify(connection) .rollback(); }
@Test void rollbackWithNull() throws SQLException { JdbcUtil.rollback(null); }
@Test void rollbackWithAutoCommit() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(true); JdbcUtil.rollback(connection); Mockito.verify(connection, Mockito.never()) .rollback(); } |
### Question:
CollectSystemParametersStep extends SyncFlowableStep { private String getDefaultDomain(CloudControllerClient client, ProcessContext context) { try { return client.getDefaultDomain() .getName(); } catch (CloudOperationException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { context.setVariable(Variables.MISSING_DEFAULT_DOMAIN, true); return DEFAULT_DOMAIN_PLACEHOLDER; } throw e; } } }### Answer:
@Test void testDefaultDomainNotFoundException() { prepareDescriptor("system-parameters/mtad.yaml"); prepareClient(); when(client.getDefaultDomain()).thenThrow(new CloudOperationException(HttpStatus.NOT_FOUND)); step.execute(execution); assertTrue(context.getVariable(Variables.MISSING_DEFAULT_DOMAIN)); DeploymentDescriptor descriptor = context.getVariable(Variables.DEPLOYMENT_DESCRIPTOR_WITH_SYSTEM_PARAMETERS); assertEquals(DEFAULT_DOMAIN_PLACEHOLDER, descriptor.getParameters() .get(SupportedParameters.DEFAULT_DOMAIN)); }
@Test void testDefaultDomainException() { when(client.getDefaultDomain()).thenThrow(new CloudOperationException(HttpStatus.GATEWAY_TIMEOUT)); assertThrows(SLException.class, () -> step.execute(execution)); } |
### Question:
PollStageAppStatusExecution implements AsyncExecution { @Override public String getPollingErrorMessage(ProcessContext context) { CloudApplication application = context.getVariable(Variables.APP_TO_PROCESS); return MessageFormat.format(Messages.ERROR_STAGING_APP_0, application.getName()); } PollStageAppStatusExecution(RecentLogsRetriever recentLogsRetriever, ApplicationStager applicationStager); @Override AsyncExecutionState execute(ProcessContext context); @Override String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testPollingErrorMessage() { context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("anatz")); String pollingErrorMessage = step.getPollingErrorMessage(context); Assertions.assertEquals("Error staging application \"anatz\"", pollingErrorMessage); } |
### Question:
DeleteApplicationStep extends UndeployAppStep { private void deleteApplication(CloudControllerClient client, String applicationName) { getStepLogger().info(Messages.DELETING_APP, applicationName); client.deleteApplication(applicationName); getStepLogger().debug(Messages.APP_DELETED, applicationName); } }### Answer:
@Test void testApplicationNotFoundExceptionThrown() { Mockito.doThrow(new CloudOperationException(HttpStatus.NOT_FOUND)) .when(client) .deleteApplication(anyString()); context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("test-app")); step.execute(execution); assertStepFinishedSuccessfully(); }
@Test void testBadGatewayExceptionThrown() { Mockito.doThrow(new CloudOperationException(HttpStatus.BAD_GATEWAY)) .when(client) .deleteApplication(anyString()); context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("test-app")); Assertions.assertThrows(SLException.class, () -> step.execute(execution)); } |
### Question:
StopApplicationUndeploymentStep extends UndeployAppStep implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.BEFORE_STOP, HookPhase.APPLICATION_BEFORE_STOP_LIVE), context); } @Override StepPhase undeployApplication(CloudControllerClient client, CloudApplication cloudApplicationToUndeploy,
ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseBefore() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_STOP, HookPhase.APPLICATION_BEFORE_STOP_LIVE), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = ((StopApplicationUndeploymentStep) step).getHookPhasesBeforeStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
StopApplicationUndeploymentStep extends UndeployAppStep implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesAfterStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.AFTER_STOP, HookPhase.APPLICATION_AFTER_STOP_LIVE), context); } @Override StepPhase undeployApplication(CloudControllerClient client, CloudApplication cloudApplicationToUndeploy,
ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseAfter() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.AFTER_STOP, HookPhase.APPLICATION_AFTER_STOP_LIVE), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = ((StopApplicationUndeploymentStep) step).getHookPhasesAfterStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
RetryProcessAdditionalAction implements AdditionalProcessAction { @Override public void executeAdditionalProcessAction(String processInstanceId) { List<String> failedActivityIds = findFailedActivityIds(processInstanceId); for (String failedActivityId : failedActivityIds) { progressMessageService.createQuery() .processId(processInstanceId) .taskId(failedActivityId) .type(ProgressMessageType.ERROR) .delete(); } } @Inject RetryProcessAdditionalAction(FlowableFacade flowableFacade, ProgressMessageService progressMessageService); @Override void executeAdditionalProcessAction(String processInstanceId); @Override Action getApplicableAction(); }### Answer:
@Test void testExecuteAdditionalAction() { retryProcessAdditionalAction.executeAdditionalProcessAction(PROCESS_GUID); Mockito.verify(progressMessageQuery, times(2)) .delete(); } |
### Question:
FlowableFacade { public void shutdownJobExecutor() { LOGGER.info(Messages.SHUTTING_DOWN_FLOWABLE_JOB_EXECUTOR); AsyncExecutor asyncExecutor = processEngine.getProcessEngineConfiguration() .getAsyncExecutor(); asyncExecutor.shutdown(); } @Inject FlowableFacade(ProcessEngine processEngine); ProcessInstance startProcess(String processDefinitionKey, Map<String, Object> variables); String getProcessInstanceId(String executionId); String getCurrentTaskId(String executionId); ProcessInstance getProcessInstance(String processId); boolean hasDeadLetterJobs(String processId); List<String> getHistoricSubProcessIds(String correlationId); HistoricProcessInstance getHistoricProcessById(String processInstanceId); HistoricVariableInstance getHistoricVariableInstance(String processInstanceId, String variableName); List<String> getActiveHistoricSubProcessIds(String correlationId); void executeJob(String processInstanceId); void trigger(String executionId, Map<String, Object> variables); void deleteProcessInstance(String processInstanceId, String deleteReason); boolean isProcessInstanceAtReceiveTask(String processInstanceId); List<Execution> findExecutionsAtReceiveTask(String processInstanceId); List<Execution> getActiveProcessExecutions(String processInstanceId); void suspendProcessInstance(String processInstanceId); void shutdownJobExecutor(); boolean isJobExecutorActive(); ProcessEngine getProcessEngine(); List<ProcessInstance> findAllRunningProcessInstanceStartedBefore(Date startedBefore); }### Answer:
@Test void testAsyncExecutorMethodsAreCalled() { flowableFacade.shutdownJobExecutor(); Mockito.verify(mockedAsyncExecutor, Mockito.times(1)) .shutdown(); } |
### Question:
SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction { @Override public void executeAdditionalProcessAction(String processInstanceId) { flowableFacade.getActiveProcessExecutions(processInstanceId) .stream() .map(this::toExecutionEntityImpl) .filter(executionEntityImpl -> executionEntityImpl.getDeadLetterJobCount() > 0) .map(ExecutionEntityImpl::getProcessInstanceId) .forEach(this::setRetryPhaseForProcess); } @Inject SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade); @Override void executeAdditionalProcessAction(String processInstanceId); @Override Action getApplicableAction(); }### Answer:
@Test void testExecuteAdditionalProcessAction() { setRetryPhaseAdditionalProcessAction.executeAdditionalProcessAction(PROCESS_GUID); Mockito.verify(runtimeService) .setVariable(EXECUTION_WITH_DEADLETTER_JOBS_PROCESS_ID, Variables.STEP_PHASE.getName(), StepPhase.RETRY.name()); Mockito.verify(runtimeService, never()) .setVariable(EXECUTION_WITHOUT_DEADLETTER_JOBS_PROCESS_ID, Variables.STEP_PHASE.getName(), StepPhase.RETRY.name()); } |
### Question:
TaggingRequestFilterFunction implements ExchangeFilterFunction { @Override public Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction nextFilter) { HttpHeaders headers = clientRequest.headers(); setHeader(headers, TAG_HEADER_NAME, headerValue); if (orgHeaderValue != null && spaceHeaderValue != null) { setHeader(headers, TAG_HEADER_ORG_NAME, orgHeaderValue); setHeader(headers, TAG_HEADER_SPACE_NAME, spaceHeaderValue); } return nextFilter.exchange(clientRequest); } TaggingRequestFilterFunction(String deployServiceVersion); TaggingRequestFilterFunction(String deployServiceVersion, String org, String space); @Override Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction nextFilter); static final String TAG_HEADER_SPACE_NAME; static final String TAG_HEADER_ORG_NAME; static final String TAG_HEADER_NAME; }### Answer:
@Test void testInjectOnlyDeployServiceVersion() throws IOException { TaggingRequestFilterFunction testedFilterFunction = new TaggingRequestFilterFunction(TEST_VERSION_VALUE); testedFilterFunction.filter(clientRequest, nextFilter); assertEquals("MTA deploy-service v1.58.0", actualHeaders.getFirst(TaggingRequestFilterFunction.TAG_HEADER_NAME)); assertFalse(actualHeaders.containsKey(TaggingRequestFilterFunction.TAG_HEADER_ORG_NAME)); assertFalse(actualHeaders.containsKey(TaggingRequestFilterFunction.TAG_HEADER_SPACE_NAME)); }
@Test void testInjectOrgAndSpaceValues() throws IOException { TaggingRequestFilterFunction testedFilterFunction = new TaggingRequestFilterFunction(TEST_VERSION_VALUE, TEST_ORG_VALUE, TEST_SPACE_VALUE); testedFilterFunction.filter(clientRequest, nextFilter); assertEquals("MTA deploy-service v1.58.0", actualHeaders.getFirst(TaggingRequestFilterFunction.TAG_HEADER_NAME)); assertEquals(TEST_ORG_VALUE, actualHeaders.getFirst(TaggingRequestFilterFunction.TAG_HEADER_ORG_NAME)); assertEquals(TEST_SPACE_VALUE, actualHeaders.getFirst(TaggingRequestFilterFunction.TAG_HEADER_SPACE_NAME)); } |
### Question:
Environment { public Map<String, String> getAllVariables() { return environmentVariablesAccessor.getAllVariables(); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetAllVariables() { Map<String, String> variables = new HashMap<>(); variables.put("foo", "bar"); variables.put("baz", "qux"); Mockito.when(environmentVariablesAccessor.getAllVariables()) .thenReturn(variables); assertEquals(variables, environment.getAllVariables()); } |
### Question:
Environment { public String getString(String name) { return getString(name, null); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetString() { Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn("cd"); assertEquals("cd", environment.getString("ab")); }
@Test void testGetStringWhenVariableIsMissing() { assertNull(environment.getString("ab")); }
@Test void testGetStringWithDefault() { assertEquals("cd", environment.getString("ab", "cd")); } |
### Question:
JdbcUtil { public static void commit(Connection connection) throws SQLException { if (!connection.getAutoCommit()) { connection.commit(); } } private JdbcUtil(); static void closeQuietly(ResultSet resultSet); static void closeQuietly(Statement statement); static void closeQuietly(Connection connection); static void logSQLException(SQLException exception); static void commit(Connection connection); static void rollback(Connection connection); }### Answer:
@Test void commit() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(false); JdbcUtil.commit(connection); Mockito.verify(connection) .commit(); }
@Test void commitWithAutoCommit() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(true); JdbcUtil.commit(connection); Mockito.verify(connection, Mockito.never()) .commit(); } |
### Question:
Environment { public Long getLong(String name) { return getLong(name, null); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetLong() { Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn("12"); assertEquals(12, (long) environment.getLong("ab")); }
@Test void testGetLongWhenVariableIsMissing() { assertNull(environment.getLong("ab")); }
@Test void testGetLongWithDefault() { assertEquals(12, (long) environment.getLong("ab", 12L)); } |
### Question:
Environment { public Integer getInteger(String name) { return getInteger(name, null); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetInteger() { Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn("12"); assertEquals(12, (long) environment.getInteger("ab")); }
@Test void testGetIntegerWhenVariableIsMissing() { assertNull(environment.getInteger("ab")); }
@Test void testGetIntegerWithDefault() { assertEquals(12, (int) environment.getInteger("ab", 12)); } |
### Question:
Environment { public Boolean getBoolean(String name) { return getBoolean(name, null); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetBoolean() { Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn("false"); assertEquals(false, environment.getBoolean("ab")); }
@Test void testGetBooleanWhenVariableIsMissing() { assertNull(environment.getBoolean("ab")); }
@Test void testGetBooleanWithDefault() { assertEquals(false, environment.getBoolean("ab", false)); } |
### Question:
Environment { public Integer getPositiveInteger(String name, Integer defaultValue) { Integer value = getInteger(name, defaultValue); if (value == null || value <= 0) { value = Integer.MAX_VALUE; } return value; } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetPositiveIntegerWithNull() { assertEquals(Integer.MAX_VALUE, (int) environment.getPositiveInteger("ab", null)); } |
### Question:
Environment { public Integer getNegativeInteger(String name, Integer defaultValue) { Integer value = getInteger(name, defaultValue); if (value == null || value >= 0) { value = Integer.MIN_VALUE; } return value; } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testGetNegativeIntegerWithNull() { assertEquals(Integer.MIN_VALUE, (int) environment.getNegativeInteger("ab", null)); } |
### Question:
Environment { public <T> T getVariable(String name, Function<String, T> mappingFunction) { return getVariable(name, mappingFunction, null); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void tetGetVariable() { UUID expectedUuid = UUID.fromString("c9fbfbfd-8d54-4cba-958f-25a3f7a14ca7"); Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn(expectedUuid.toString()); assertEquals(expectedUuid, environment.getVariable("ab", UUID::fromString)); } |
### Question:
Environment { public boolean hasVariable(String name) { return !StringUtils.isEmpty(getString(name)); } Environment(); Environment(EnvironmentVariablesAccessor environmentVariablesAccessor); Map<String, String> getAllVariables(); Long getLong(String name); String getString(String name); Integer getInteger(String name); Boolean getBoolean(String name); Long getLong(String name, Long defaultValue); String getString(String name, String defaultValue); Integer getInteger(String name, Integer defaultValue); Boolean getBoolean(String name, Boolean defaultValue); Integer getPositiveInteger(String name, Integer defaultValue); Integer getNegativeInteger(String name, Integer defaultValue); T getVariable(String name, Function<String, T> mappingFunction); T getVariable(String name, Function<String, T> mappingFunction, T defaultValue); boolean hasVariable(String name); }### Answer:
@Test void testHasVariable() { Mockito.when(environmentVariablesAccessor.getVariable("ab")) .thenReturn("0"); assertTrue(environment.hasVariable("ab")); }
@Test void testHasVariableWhenVariableIsMissing() { assertFalse(environment.hasVariable("ab")); } |
### Question:
ProcessLoggerProvider { public ProcessLogger getLogger(DelegateExecution execution) { return getLogger(execution, DEFAULT_LOG_NAME); } ProcessLogger getLogger(DelegateExecution execution); ProcessLogger getLogger(DelegateExecution execution, String logName); ProcessLogger getLogger(DelegateExecution execution, String logName, PatternLayout layout); List<ProcessLogger> getExistingLoggers(String processId, String activityId); void remove(ProcessLogger processLogger); }### Answer:
@Test void testGetLogger() { prepareContext(); processLogger = processLoggerProvider.getLogger(execution); assertEquals(CORRELATION_ID, processLogger.getProcessId()); assertEquals(TASK_ID, processLogger.getActivityId()); assertEquals(SPACE_ID, processLogger.spaceId); }
@Test void testGetNullProcessLogger() { processLogger = processLoggerProvider.getLogger(execution); assertTrue(processLogger instanceof NullProcessLogger, MessageFormat.format("Expected NullProcessLogger but was {0}", processLogger.getClass() .getSimpleName())); } |
### Question:
SafeExecutor { public <E extends Exception> void execute(FailableRunnable<E> runnable) { try { runnable.run(); } catch (Exception e) { exceptionHandler.accept(e); } } SafeExecutor(); SafeExecutor(Consumer<Exception> exceptionHandler); void execute(FailableRunnable<E> runnable); }### Answer:
@Test void testWithoutExceptions() { SafeExecutor safeExecutor = new SafeExecutor(exceptionHandler); safeExecutor.execute(() -> { }); Mockito.verifyNoInteractions(exceptionHandler); }
@Test void testWithException() { SafeExecutor safeExecutor = new SafeExecutor(exceptionHandler); Exception e = new Exception(); safeExecutor.execute(() -> { throw e; }); Mockito.verify(exceptionHandler) .accept(e); }
@Test void testWithDefaultExceptionHandler() { SafeExecutor safeExecutor = new SafeExecutor(); Exception e = new Exception(); Assertions.assertDoesNotThrow(() -> safeExecutor.execute(() -> { throw e; })); } |
### Question:
UriUtil { public static CloudRoute findRoute(List<CloudRoute> routes, String uri) { return routes.stream() .filter(route -> routeMatchesUri(route, uri)) .findAny() .orElseThrow(() -> new NotFoundException(Messages.ROUTE_NOT_FOUND, uri)); } private UriUtil(); static String stripScheme(String uri); static CloudRoute findRoute(List<CloudRoute> routes, String uri); static boolean routeMatchesUri(CloudRoute route, String uri); static final String DEFAULT_SCHEME_SEPARATOR; static final char DEFAULT_PATH_SEPARATOR; static final char DEFAULT_HOST_DOMAIN_SEPARATOR; static final int STANDARD_HTTP_PORT; static final int STANDARD_HTTPS_PORT; static final String HTTP_PROTOCOL; static final String HTTPS_PROTOCOL; }### Answer:
@Test void testFindRouteWithHostBasedUriWithPort() { List<CloudRoute> routes = List.of(route); Assertions.assertThrows(NotFoundException.class, () -> UriUtil.findRoute(routes, HOST_BASED_URI_WITH_PORT)); }
@Test void testFindRouteWithHostBasedUriWithoutPort() { List<CloudRoute> routes = List.of(route); CloudRoute actualResult = UriUtil.findRoute(routes, HOST_BASED_URI_WITHOUT_PORT); Assertions.assertEquals(route, actualResult); }
@Test void testFindRouteWithPortBasedUri() { List<CloudRoute> routes = List.of(route); Assertions.assertThrows(NotFoundException.class, () -> UriUtil.findRoute(routes, PORT_BASED_URI)); } |
### Question:
UriUtil { public static boolean routeMatchesUri(CloudRoute route, String uri) { ApplicationURI appUriFromRoute = new ApplicationURI(route); ApplicationURI appUriFromString = new ApplicationURI(uri); return appUriFromRoute.equals(appUriFromString); } private UriUtil(); static String stripScheme(String uri); static CloudRoute findRoute(List<CloudRoute> routes, String uri); static boolean routeMatchesUri(CloudRoute route, String uri); static final String DEFAULT_SCHEME_SEPARATOR; static final char DEFAULT_PATH_SEPARATOR; static final char DEFAULT_HOST_DOMAIN_SEPARATOR; static final int STANDARD_HTTP_PORT; static final int STANDARD_HTTPS_PORT; static final String HTTP_PROTOCOL; static final String HTTPS_PROTOCOL; }### Answer:
@Test void testRouteMatchesWithHostBasedUriWithPort() { boolean actualResult = UriUtil.routeMatchesUri(route, HOST_BASED_URI_WITH_PORT); Assertions.assertFalse(actualResult); }
@Test void testRouteMatchesWithHostBasedUriWithoutPort() { boolean actualResult = UriUtil.routeMatchesUri(route, HOST_BASED_URI_WITHOUT_PORT); Assertions.assertTrue(actualResult); }
@Test void testRouteMatchesWithPortBasedUri() { boolean actualResult = UriUtil.routeMatchesUri(route, PORT_BASED_URI); Assertions.assertFalse(actualResult); } |
### Question:
UriUtil { public static String stripScheme(String uri) { int protocolIndex = uri.indexOf(DEFAULT_SCHEME_SEPARATOR); if (protocolIndex == -1) { return uri; } return uri.substring(protocolIndex + DEFAULT_SCHEME_SEPARATOR.length()); } private UriUtil(); static String stripScheme(String uri); static CloudRoute findRoute(List<CloudRoute> routes, String uri); static boolean routeMatchesUri(CloudRoute route, String uri); static final String DEFAULT_SCHEME_SEPARATOR; static final char DEFAULT_PATH_SEPARATOR; static final char DEFAULT_HOST_DOMAIN_SEPARATOR; static final int STANDARD_HTTP_PORT; static final int STANDARD_HTTPS_PORT; static final String HTTP_PROTOCOL; static final String HTTPS_PROTOCOL; }### Answer:
@Test void testStripSchemeWithScheme() { String actual = UriUtil.stripScheme(PORT_BASED_URI); Assertions.assertEquals(PORT_BASED_URI_WITHOUT_SCHEME, actual); }
@Test void testStripSchemeWithoutScheme() { String actual = UriUtil.stripScheme(PORT_BASED_URI_WITHOUT_SCHEME); Assertions.assertEquals(PORT_BASED_URI_WITHOUT_SCHEME, actual); } |
### Question:
NameUtil { public static String computeValidContainerName(String organization, String space, String serviceName) { String properOrganization = organization.toUpperCase(Locale.US) .replaceAll(NameRequirements.CONTAINER_NAME_ILLEGAL_CHARACTERS, "_"); String properSpace = space.toUpperCase(Locale.US) .replaceAll(NameRequirements.CONTAINER_NAME_ILLEGAL_CHARACTERS, "_"); String properServiceName = serviceName.toUpperCase(Locale.US) .replaceAll(NameRequirements.CONTAINER_NAME_ILLEGAL_CHARACTERS, "_"); return getNameWithProperLength(String.format("%s_%s_%s", properOrganization, properSpace, properServiceName), NameRequirements.CONTAINER_NAME_MAX_LENGTH).toUpperCase(Locale.US); } private NameUtil(); static String computeValidApplicationName(String applicationName, String namespace, boolean applyNamespace); static String computeValidServiceName(String serviceName, String namespace, boolean applyNamespace); static String computeValidContainerName(String organization, String space, String serviceName); static String computeValidXsAppName(String serviceName); static String getNameWithProperLength(String name, int maxLength); static String getNamespacePrefix(String namespace); static UUID getUUID(String name); static String getIndexedName(String resourceName, int index, int entriesCnt, String delimiter); static String getApplicationName(Module module); static String getServiceName(Resource resource); }### Answer:
@Test void testCreateValidContainerName() { String containerName = NameUtil.computeValidContainerName("initial", "initial", "com.sap.cloud.lm.sl.xs2.a.very.very.long.service.name.with.illegal.container.name.characters"); assertEquals("INITIAL_INITIAL_COM_SAP_CLOUD_LM_SL_XS2_A_VERY_VERY_LONG3AC0B612", containerName); assertTrue(containerName.matches(NameRequirements.CONTAINER_NAME_PATTERN)); } |
### Question:
SecurityUtil { public static UserInfo getTokenUserInfo(OAuth2AccessToken token) { TokenProperties tokenProperties = TokenProperties.fromToken(token); return new UserInfo(tokenProperties.getUserId(), tokenProperties.getUserName(), token); } private SecurityUtil(); static OAuth2Authentication createAuthentication(String clientId, Set<String> scope, UserInfo userInfo); static UserInfo getTokenUserInfo(OAuth2AccessToken token); static final String CLIENT_ID; static final String CLIENT_SECRET; }### Answer:
@Test void testGetTokenUserInfo() { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(TOKEN); Map<String, Object> additionalInformation = asMap(USER_ID, USER_NAME); token.setAdditionalInformation(additionalInformation); UserInfo userInfo = SecurityUtil.getTokenUserInfo(token); assertEquals(USER_ID, userInfo.getId()); assertEquals(USER_NAME, userInfo.getName()); assertEquals(TOKEN, userInfo.getToken() .getValue()); } |
### Question:
ApplicationURI { public Map<String, Object> getURIParts() { Map<String, Object> uriParts = new HashMap<>(); uriParts.put(SupportedParameters.HOST, getHost()); uriParts.put(SupportedParameters.DOMAIN, getDomain()); uriParts.put(SupportedParameters.ROUTE_PATH, getPath()); return Collections.unmodifiableMap(uriParts); } ApplicationURI(String initial); ApplicationURI(CloudRoute route); static String getDomainFromURI(String uri); Map<String, Object> getURIParts(); Object getURIPart(String partName); void setURIPart(String partName, String part); @Override String toString(); String getHost(); void setHost(String host); String getDomain(); void setDomain(String domain); String getPath(); void setPath(String path); @Override int hashCode(); @Override boolean equals(Object object); }### Answer:
@Test void testGetURIParts() { ApplicationURI applicationURI = new ApplicationURI(createCloudRoute(CUSTOM + "host", createCloudDomain(CUSTOM + "domain"), null)); Map<String, Object> expectedParts = new HashMap<>(); expectedParts.put(SupportedParameters.HOST, CUSTOM + "host"); expectedParts.put(SupportedParameters.DOMAIN, CUSTOM + "domain"); expectedParts.put(SupportedParameters.ROUTE_PATH, ""); Assertions.assertEquals(expectedParts, applicationURI.getURIParts()); } |
### Question:
ApplicationURI { public Object getURIPart(String partName) { switch (partName) { case SupportedParameters.HOST: return getHost(); case SupportedParameters.DOMAIN: return getDomain(); case SupportedParameters.ROUTE_PATH: return getPath(); default: return null; } } ApplicationURI(String initial); ApplicationURI(CloudRoute route); static String getDomainFromURI(String uri); Map<String, Object> getURIParts(); Object getURIPart(String partName); void setURIPart(String partName, String part); @Override String toString(); String getHost(); void setHost(String host); String getDomain(); void setDomain(String domain); String getPath(); void setPath(String path); @Override int hashCode(); @Override boolean equals(Object object); }### Answer:
@Test void testGetURIPart() { ApplicationURI applicationURI = new ApplicationURI(createCloudRoute(CUSTOM + "host", createCloudDomain(CUSTOM + "domain"), "/" + CUSTOM + "path")); Assertions.assertEquals(CUSTOM + "host", applicationURI.getURIPart(SupportedParameters.HOST)); Assertions.assertEquals(CUSTOM + "domain", applicationURI.getURIPart(SupportedParameters.DOMAIN)); Assertions.assertEquals("/" + CUSTOM + "path", applicationURI.getURIPart(SupportedParameters.ROUTE_PATH)); Assertions.assertNull(applicationURI.getURIPart("invalid-parameter")); } |
### Question:
ApplicationURI { @Override public String toString() { StringBuilder url = new StringBuilder(); if (StringUtils.isNotEmpty(getHost())) { url.append(getHost()) .append(UriUtil.DEFAULT_HOST_DOMAIN_SEPARATOR); } url.append(getDomain()); if (StringUtils.isNotEmpty(getPath())) { url.append(getPath()); } return url.toString(); } ApplicationURI(String initial); ApplicationURI(CloudRoute route); static String getDomainFromURI(String uri); Map<String, Object> getURIParts(); Object getURIPart(String partName); void setURIPart(String partName, String part); @Override String toString(); String getHost(); void setHost(String host); String getDomain(); void setDomain(String domain); String getPath(); void setPath(String path); @Override int hashCode(); @Override boolean equals(Object object); }### Answer:
@Test void testToStringWithValidHostAndPath() { ApplicationURI applicationURI = new ApplicationURI(createCloudRoute(CUSTOM + "host", createCloudDomain(CUSTOM + "domain"), "/" + CUSTOM + "path")); String expectedApplicationURI = CUSTOM + "host." + CUSTOM + "domain/" + CUSTOM + "path"; Assertions.assertEquals(expectedApplicationURI, applicationURI.toString()); }
@Test void testToStringWithValidHostAndWithoutPath() { ApplicationURI applicationURI = new ApplicationURI(createCloudRoute(CUSTOM + "host", createCloudDomain(CUSTOM + "domain"), null)); Assertions.assertEquals(CUSTOM + "host." + CUSTOM + "domain", applicationURI.toString()); }
@Test void testToStringWithoutHostAndWithoutPath() { ApplicationURI applicationURI = new ApplicationURI(createCloudRoute("", createCloudDomain(CUSTOM + "domain"), null)); Assertions.assertEquals(CUSTOM + "domain", applicationURI.toString()); } |
### Question:
ApplicationURI { public static String getDomainFromURI(String uri) { ApplicationURI parsedURI = new ApplicationURI(uri); return parsedURI.getDomain(); } ApplicationURI(String initial); ApplicationURI(CloudRoute route); static String getDomainFromURI(String uri); Map<String, Object> getURIParts(); Object getURIPart(String partName); void setURIPart(String partName, String part); @Override String toString(); String getHost(); void setHost(String host); String getDomain(); void setDomain(String domain); String getPath(); void setPath(String path); @Override int hashCode(); @Override boolean equals(Object object); }### Answer:
@Test void testGetDomainFromURI() { Assertions.assertEquals(CUSTOM + "domain", ApplicationURI.getDomainFromURI("https: } |
### Question:
ConfigurationEntryService extends PersistenceService<ConfigurationEntry, ConfigurationEntryDto, Long> { public ConfigurationEntryQuery createQuery() { return new ConfigurationEntryQueryImpl(createEntityManager(), entryMapper); } ConfigurationEntryService(EntityManagerFactory entityManagerFactory, ConfigurationEntryMapper entryMapper); ConfigurationEntryQuery createQuery(); }### Answer:
@Test void testAdd() { configurationEntryService.add(CONFIGURATION_ENTRY_1); assertEquals(1, configurationEntryService.createQuery() .list() .size()); assertEquals(CONFIGURATION_ENTRY_1.getId(), configurationEntryService.createQuery() .id(CONFIGURATION_ENTRY_1.getId()) .singleResult() .getId()); }
@Test void testAddWithNonEmptyDatabase() { addConfigurationEntries(List.of(CONFIGURATION_ENTRY_1, CONFIGURATION_ENTRY_2)); assertConfigurationEntryExists(CONFIGURATION_ENTRY_1.getId()); assertConfigurationEntryExists(CONFIGURATION_ENTRY_2.getId()); assertEquals(2, configurationEntryService.createQuery() .list() .size()); }
@Test void testQueryByVersion() { addConfigurationEntries(List.of(CONFIGURATION_ENTRY_1, CONFIGURATION_ENTRY_2)); String version = ">3.0.0"; assertEquals(1, configurationEntryService.createQuery() .version(version) .list() .size()); }
@Test void testQueryByProviderNamespace() { addConfigurationEntries(ALL_ENTRIES); ConfigurationEntryQuery allEntries = configurationEntryService.createQuery() .providerNamespace(null, false); assertEquals(3, allEntries.list() .size()); ConfigurationEntryQuery allEntriesNoNamespace = configurationEntryService.createQuery() .providerNamespace(null, true); assertEquals(2, allEntriesNoNamespace.list() .size()); ConfigurationEntryQuery allEntriesNoNamespaceUsingKeyword = configurationEntryService.createQuery() .providerNamespace("default", false); assertEquals(2, allEntriesNoNamespaceUsingKeyword.list() .size()); ConfigurationEntryQuery specificEntryByNamespace = configurationEntryService.createQuery() .providerNamespace("namespace", false); assertEquals(1, specificEntryByNamespace.list() .size()); } |
### Question:
ProgressMessageService extends PersistenceService<ProgressMessage, ProgressMessageDto, Long> { public ProgressMessageQuery createQuery() { return new ProgressMessageQueryImpl(createEntityManager(), progressMessageMapper); } @Inject ProgressMessageService(EntityManagerFactory entityManagerFactory); ProgressMessageQuery createQuery(); }### Answer:
@Test void testAdd() { progressMessageService.add(PROGRESS_MESSAGE_1); assertEquals(1, progressMessageService.createQuery() .list() .size()); assertEquals(PROGRESS_MESSAGE_1.getId(), progressMessageService.createQuery() .id(PROGRESS_MESSAGE_1.getId()) .singleResult() .getId()); }
@Test void testAddWithNonEmptyDatabase() { addProgressMessages(List.of(PROGRESS_MESSAGE_1, PROGRESS_MESSAGE_2)); assertProgressMessageExists(PROGRESS_MESSAGE_1.getId()); assertProgressMessageExists(PROGRESS_MESSAGE_2.getId()); assertEquals(2, progressMessageService.createQuery() .list() .size()); } |
### Question:
ObjectStoreFileStorage implements FileStorage { @Override public void addFile(FileEntry fileEntry, File file) throws FileStorageException { String entryName = fileEntry.getId(); long fileSize = fileEntry.getSize() .longValue(); Blob blob = blobStore.blobBuilder(entryName) .payload(file) .contentDisposition(fileEntry.getName()) .contentType(MediaType.OCTET_STREAM.toString()) .userMetadata(createFileEntryMetadata(fileEntry)) .build(); try { putBlobWithRetries(blob, 3); LOGGER.debug(MessageFormat.format(Messages.STORED_FILE_0_WITH_SIZE_1_SUCCESSFULLY_2, fileEntry.getId(), fileSize)); } catch (ContainerNotFoundException e) { throw new FileStorageException(MessageFormat.format(Messages.FILE_UPLOAD_FAILED, fileEntry.getName(), fileEntry.getNamespace())); } } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer:
@Test void addFileTest() throws Exception { FileEntry fileEntry = addFile(TEST_FILE_LOCATION); assertFileExists(true, fileEntry); } |
### Question:
RestartOnEnvChangeValidator implements ParameterValidator { @Override public String getParameterName() { return SupportedParameters.RESTART_ON_ENV_CHANGE; } @Override boolean isValid(Object restartParameters, final Map<String, Object> context); @Override Class<?> getContainerType(); @Override String getParameterName(); }### Answer:
@Test void testGetParameterName() { assertEquals("restart-on-env-change", validator.getParameterName()); } |
### Question:
RestartOnEnvChangeValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return Module.class; } @Override boolean isValid(Object restartParameters, final Map<String, Object> context); @Override Class<?> getContainerType(); @Override String getParameterName(); }### Answer:
@Test void testGetContainerType() { assertTrue(validator.getContainerType() .isAssignableFrom(Module.class)); } |
### Question:
HostValidator extends RoutePartValidator { @Override public String getParameterName() { return SupportedParameters.HOST; } @Override String getParameterName(); }### Answer:
@Test void testGetParameterName() { assertEquals("host", validator.getParameterName()); } |
### Question:
TasksValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return Module.class; } @SuppressWarnings("unchecked") @Override boolean isValid(Object tasks, final Map<String, Object> context); @Override Class<?> getContainerType(); @Override String getParameterName(); static final String TASK_NAME_KEY; static final String TASK_COMMAND_KEY; static final String TASK_MEMORY_KEY; static final String TASK_DISK_QUOTA_KEY; }### Answer:
@Test void testGetContainerType() { assertTrue(new TasksValidator().getContainerType() .isAssignableFrom(Module.class)); } |
### Question:
RouteValidator implements ParameterValidator { @Override public boolean canCorrect() { return validators.stream() .map(ParameterValidator::canCorrect) .reduce(false, Boolean::logicalOr); } RouteValidator(); @Override String attemptToCorrect(Object route, final Map<String, Object> context); @Override boolean isValid(Object route, final Map<String, Object> context); @Override String getParameterName(); @Override Class<?> getContainerType(); @Override boolean canCorrect(); }### Answer:
@Test void testCanCorrect() { assertTrue(validator.canCorrect()); } |
### Question:
RouteValidator implements ParameterValidator { @Override public String getParameterName() { return SupportedParameters.ROUTE; } RouteValidator(); @Override String attemptToCorrect(Object route, final Map<String, Object> context); @Override boolean isValid(Object route, final Map<String, Object> context); @Override String getParameterName(); @Override Class<?> getContainerType(); @Override boolean canCorrect(); }### Answer:
@Test void testGetParameterName() { assertEquals("route", validator.getParameterName()); } |
### Question:
RouteValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return Module.class; } RouteValidator(); @Override String attemptToCorrect(Object route, final Map<String, Object> context); @Override boolean isValid(Object route, final Map<String, Object> context); @Override String getParameterName(); @Override Class<?> getContainerType(); @Override boolean canCorrect(); }### Answer:
@Test void testGetContainerType() { assertTrue(validator.getContainerType() .isAssignableFrom(Module.class)); } |
### Question:
DomainValidator extends RoutePartValidator { @Override public String getParameterName() { return SupportedParameters.DOMAIN; } @Override String getParameterName(); }### Answer:
@Test void testGetParameterName() { assertEquals("domain", validator.getParameterName()); } |
### Question:
VisibilityValidator implements ParameterValidator { @Override public String getParameterName() { return SupportedParameters.VISIBILITY; } @Override boolean isValid(Object visibleTargets, final Map<String, Object> context); @Override Class<?> getContainerType(); @Override String getParameterName(); }### Answer:
@Test void testGetParameterName() { assertEquals("visibility", validator.getParameterName()); } |
### Question:
ObjectStoreFileStorage implements FileStorage { @Override public List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries) { Set<String> existingFiles = blobStore.list(container) .stream() .map(StorageMetadata::getName) .collect(Collectors.toSet()); return fileEntries.stream() .filter(fileEntry -> { String id = fileEntry.getId(); return !existingFiles.contains(id); }) .collect(Collectors.toList()); } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer:
@Test void getFileEntriesWithoutContent() throws Exception { List<FileEntry> fileEntries = new ArrayList<>(); FileEntry existingFile = addFile(TEST_FILE_LOCATION); fileEntries.add(existingFile); FileEntry existingFile2 = addFile(SECOND_FILE_TEST_LOCATION); fileEntries.add(existingFile2); FileEntry nonExistingFile = createFileEntry(); fileEntries.add(nonExistingFile); List<FileEntry> withoutContent = fileStorage.getFileEntriesWithoutContent(fileEntries); assertEquals(1, withoutContent.size()); assertEquals(nonExistingFile.getId(), withoutContent.get(0) .getId()); } |
### Question:
VisibilityValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return ProvidedDependency.class; } @Override boolean isValid(Object visibleTargets, final Map<String, Object> context); @Override Class<?> getContainerType(); @Override String getParameterName(); }### Answer:
@Test void testGetContainerType() { assertTrue(validator.getContainerType() .isAssignableFrom(ProvidedDependency.class)); } |
### Question:
DescriptorParametersCompatabilityValidator extends CompatabilityParametersValidator<DeploymentDescriptor> { @Override public DeploymentDescriptor validate() { DeploymentDescriptor castedDescriptor = this.descriptor; validate(castedDescriptor); return castedDescriptor; } DescriptorParametersCompatabilityValidator(DeploymentDescriptor descriptor, UserMessageLogger userMessageLogger); @Override DeploymentDescriptor validate(); }### Answer:
@Test void testDescriptorValidator() { Module module = buildModule(); DeploymentDescriptor descriptor = buildDeploymentDescriptor(module); prepareModuleParametersCompatabilityValidator(module); DescriptorParametersCompatabilityValidator descriptorValidator = new DescriptorParametersCompatabilityValidator(descriptor, userMessageLogger) { @Override protected ModuleParametersCompatabilityValidator getModuleParametersCompatabilityValidator(Module module) { return moduleParametersCompatabilityValidator; } }; DeploymentDescriptor validatedDescriptor = descriptorValidator.validate(); assertModules(module, validatedDescriptor.getModules()); } |
### Question:
ApplicationNameValidator implements ParameterValidator { @Override public boolean isValid(Object applicationName, final Map<String, Object> context) { return false; } ApplicationNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object applicationName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object applicationName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer:
@Test void testValidation() { ApplicationNameValidator applicationNameValidator = new ApplicationNameValidator(NAMESPACE, false); assertFalse(applicationNameValidator.isValid(APPLICATION_NAME, CONTEXT_DO_NOT_APPLY_NAMESPACE)); } |
### Question:
ApplicationNameValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return Module.class; } ApplicationNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object applicationName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object applicationName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer:
@Test void testGetContainerType() { ApplicationNameValidator applicationNameValidator = new ApplicationNameValidator(NAMESPACE, false); assertEquals(Module.class, applicationNameValidator.getContainerType()); } |
### Question:
ApplicationNameValidator implements ParameterValidator { @Override public String getParameterName() { return SupportedParameters.APP_NAME; } ApplicationNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object applicationName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object applicationName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer:
@Test void testGetParameterName() { ApplicationNameValidator applicationNameValidator = new ApplicationNameValidator(NAMESPACE, false); assertEquals(SupportedParameters.APP_NAME, applicationNameValidator.getParameterName()); } |
### Question:
ApplicationNameValidator implements ParameterValidator { @Override public boolean canCorrect() { return true; } ApplicationNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object applicationName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object applicationName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer:
@Test void testCanCorrect() { ApplicationNameValidator applicationNameValidator = new ApplicationNameValidator(NAMESPACE, false); assertTrue(applicationNameValidator.canCorrect()); } |
### Question:
ObjectStoreFileStorage implements FileStorage { @Override public void deleteFile(String id, String space) { blobStore.removeBlob(container, id); } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer:
@Test void deleteFile() throws Exception { FileEntry fileThatWillBeDeleted = addFile(TEST_FILE_LOCATION); FileEntry fileThatStays = addFile(SECOND_FILE_TEST_LOCATION); fileStorage.deleteFile(fileThatWillBeDeleted.getId(), fileThatWillBeDeleted.getSpace()); assertFileExists(false, fileThatWillBeDeleted); assertFileExists(true, fileThatStays); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.