src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CreatePortGroupHookTask extends BasePortGroupHookTask { @Override public CreatePortGroupHookTask create(SecurityGroupInterface sgi, DistributedApplianceInstance dai){ CreatePortGroupHookTask task = new CreatePortGroupHookTask(sgi, dai); task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } CreatePortGroupHookTask(); private CreatePortGroupHookTask(SecurityGroupInterface sgi, DistributedApplianceInstance dai); @Override CreatePortGroupHookTask create(SecurityGroupInterface sgi, DistributedApplianceInstance dai); @Override void executeTransaction(EntityManager em); @Override String getName(); }
|
@Test public void testExecute_WhenInstallInspectionHookFails_ThrowsTheUnhandledException() throws Exception { SecurityGroup sg = newSecurityGroup(); SecurityGroupInterface sgi = registerNewSGI(sg, 2L); DistributedApplianceInstance dai = registerNewDAI(); SdnRedirectionApi redirectionApi = mockInstallInspectionHook(sgi, dai, new IllegalStateException()); registerNetworkRedirectionApi(redirectionApi, sgi.getVirtualSystem()); this.exception.expect(IllegalStateException.class); CreatePortGroupHookTask task = this.factory.create(sgi, dai); task.execute(); }
@Test public void testExecute_WhenInstallInspectionHookSucceeds_SGIIsUpdatedWithHookId() throws Exception { SecurityGroup sg = newSecurityGroup(); SecurityGroupInterface sgi = registerNewSGI(sg, 4L); DistributedApplianceInstance dai = registerNewDAI(); String inspectionHookId = UUID.randomUUID().toString(); SdnRedirectionApi redirectionApi = mockInstallInspectionHook(sgi, dai, inspectionHookId); registerNetworkRedirectionApi(redirectionApi, sgi.getVirtualSystem()); CreatePortGroupHookTask task = this.factory.create(sgi, dai); task.execute(); Assert.assertEquals("", inspectionHookId, sgi.getNetworkElementId()); verify(this.em, Mockito.timeout(1)).merge(sgi); }
|
SfcFlowClassifierUpdateTask extends TransactionalTask { public SfcFlowClassifierUpdateTask create(SecurityGroup securityGroup, VMPort port) { SfcFlowClassifierUpdateTask task = new SfcFlowClassifierUpdateTask(); task.securityGroup = securityGroup; task.sfc = securityGroup.getServiceFunctionChain(); task.port = port; task.vmName = port.getVm() != null ? port.getVm().getName() : port.getSubnet().getName(); task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } SfcFlowClassifierUpdateTask create(SecurityGroup securityGroup, VMPort port); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }
|
@Test public void testExecute_WithInspectionHook_ExpectUpdate() throws Exception { SfcFlowClassifierUpdateTask updateTask = this.task.create(this.sg, this.port); updateTask.execute(); verify(this.sdnApi, times(1)).updateInspectionHook( argThat(new InspectionHookElementMatcher(INSPECTION_HOOK_ID, OPENSTACK_VMPORT_ID, OPENSTACK_SFC_ID))); verify(this.port, times(0)).setInspectionHookId(any()); }
@Test public void testExecute_WithInspectionHook_ExpectFailure() throws Exception { doThrow(new Exception()).when(this.sdnApi).updateInspectionHook(any()); this.exception.expect(Exception.class); SfcFlowClassifierUpdateTask updateTask = this.task.create(this.sg, this.port); updateTask.execute(); }
|
DeleteServiceFunctionChainTask extends TransactionalTask { public DeleteServiceFunctionChainTask create(SecurityGroup securityGroup) { DeleteServiceFunctionChainTask task = new DeleteServiceFunctionChainTask(); task.securityGroup = securityGroup; task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } DeleteServiceFunctionChainTask create(SecurityGroup securityGroup); @Override void executeTransaction(EntityManager em); @Override Set<LockObjectReference> getObjects(); @Override String getName(); }
|
@Test public void testExecute_WithSFCBoundAndSGUnbound_NullsSGNetworkElementId() throws Exception { DeleteServiceFunctionChainTask deleteTask = this.task.create(SG_SFC_UNBINDED); deleteTask.execute(); assertEquals(SecurityGroupEntityMgr.findById(this.em, SG_SFC_BINDED.getId()).getNetworkElementId(), SG_SFC_BINDED.getNetworkElementId()); assertEquals( SecurityGroupEntityMgr.findById(this.em, SG_SFC_UNBINDED.getId()).getNetworkElementId(), null); }
@Test public void testExecute_WhenDeleteNetworkElementSucceeds_DeleteSFCAndNullsSGNetworkElementId() throws Exception { DeleteServiceFunctionChainTask deleteTask = this.task.create(SG_SFC_UNBIND_DELETE_SFC); mockDeleteNetworkElement(SG_SFC_UNBIND_DELETE_SFC, new NetworkElementImpl(SG_SFC_UNBIND_DELETE_SFC.getNetworkElementId()), null); deleteTask.execute(); assertEquals( SecurityGroupEntityMgr.findById(this.em, SG_SFC_UNBIND_DELETE_SFC.getId()).getNetworkElementId(), null); }
@Test public void testExecute_WhenDeleteNetworkElementFails_ThrowsUnhandledException() throws Exception { DeleteServiceFunctionChainTask deleteTask = this.task.create(SG_SFC_FAIL_ELEMENT_EXISTS); mockDeleteNetworkElement(SG_SFC_FAIL_ELEMENT_EXISTS, new NetworkElementImpl(SG_SFC_FAIL_ELEMENT_EXISTS.getNetworkElementId()), new IllegalStateException()); this.exception.expect(IllegalStateException.class); deleteTask.execute(); assertEquals( SecurityGroupEntityMgr.findById(this.em, SG_SFC_FAIL_ELEMENT_EXISTS.getId()).getNetworkElementId(), SG_SFC_FAIL_ELEMENT_EXISTS.getNetworkElementId()); }
|
CreateServiceFunctionChainTask extends TransactionalTask { public CreateServiceFunctionChainTask create(SecurityGroup securityGroup, List<NetworkElement> portPairGroups) { CreateServiceFunctionChainTask task = new CreateServiceFunctionChainTask(); task.sfc = securityGroup.getServiceFunctionChain(); task.securityGroup = securityGroup; task.portPairGroups = portPairGroups; task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } CreateServiceFunctionChainTask create(SecurityGroup securityGroup, List<NetworkElement> portPairGroups); @Override void executeTransaction(EntityManager em); @Override Set<LockObjectReference> getObjects(); @Override String getName(); }
|
@Test public void testExecute_WithSecurityGroupSFCBoundAndExistingSGElementIdNull_ExpectCreate() throws Exception { CreateServiceFunctionChainTask task = this.task .create(NEW_SG_SAME_SFC_BINDED_EXISTING_SG_ELEMENT_ID_NULL_CREATE_ELEMENT, this.portPairGroup); registerNetworkElement(NEW_SG_SAME_SFC_BINDED_EXISTING_SG_ELEMENT_ID_NULL_CREATE_ELEMENT, new PortPairGroupNetworkElementImpl( NEW_SG_SAME_SFC_BINDED_EXISTING_SG_ELEMENT_ID_NULL_CREATE_ELEMENT.getNetworkElementId()), null); task.execute(); assertEquals( SecurityGroupEntityMgr .findById(this.em, NEW_SG_SAME_SFC_BINDED_EXISTING_SG_ELEMENT_ID_NULL_CREATE_ELEMENT.getId()) .getNetworkElementId(), NEW_SG_SAME_SFC_BINDED_EXISTING_SG_ELEMENT_ID_NULL_CREATE_ELEMENT.getNetworkElementId()); }
@Test public void testExecute_WithSecurityGroupBoundToSFCAlreadyBound_ExpectUpdateSFCElementId() throws Exception { CreateServiceFunctionChainTask task = this.task.create(NEW_SECURITY_GROUP_SAME_SFC_BINDED_UPDATE_ELEMENT_ID, this.portPairGroup); task.execute(); assertEquals(SecurityGroupEntityMgr .findById(this.em, NEW_SECURITY_GROUP_SAME_SFC_BINDED_UPDATE_ELEMENT_ID.getId()).getNetworkElementId(), SECURITY_GROUP_SFC_BINDED.getNetworkElementId()); }
@Test public void testExecute_WhenSDNReturnsNullNetworkElement_ThrowsUnhandledException() throws Exception { CreateServiceFunctionChainTask task = this.task.create(SECURITY_GROUP_SFC, this.portPairGroup); registerNetworkElement(SECURITY_GROUP_SFC, null, new IllegalStateException()); this.exception.expect(IllegalStateException.class); task.execute(); Mockito.verify(this.em, Mockito.never()).merge(any()); }
|
UpdateServiceFunctionChainTask extends TransactionalTask { public UpdateServiceFunctionChainTask create(SecurityGroup securityGroup, List<NetworkElement> updatedPortPairGroups) { UpdateServiceFunctionChainTask task = new UpdateServiceFunctionChainTask(); task.sfc = securityGroup.getServiceFunctionChain(); task.securityGroup = securityGroup; task.updatedPortPairGroups = updatedPortPairGroups; task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } UpdateServiceFunctionChainTask create(SecurityGroup securityGroup,
List<NetworkElement> updatedPortPairGroups); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }
|
@Test public void testExecute_WithSecurityGroupSFCIdSetToNull_ExpectUpdate() throws Exception { UpdateServiceFunctionChainTask updateTask = this.task.create(this.sg, this.networkElementList); this.sg.setNetworkElementId(null); Mockito.when(this.sdnApi .updateNetworkElement(argThat(new ElementIdMatcher<NetworkElement>(this.sg.getNetworkElementId())), any())) .thenReturn(new NetworkElementImpl("UPDATED_SFC_ID")); updateTask.execute(); assertEquals(this.sg.getNetworkElementId(), "UPDATED_SFC_ID"); }
@Test public void testExecute_WithSecurityGroupSFCIdSetToNotEmpty_ExpectUpdate() throws Exception { this.sg.setNetworkElementId("OLD_SFC_ID"); UpdateServiceFunctionChainTask updateTask = this.task.create(this.sg, this.networkElementList); Mockito.when(this.sdnApi .updateNetworkElement(argThat(new ElementIdMatcher<NetworkElement>(this.sg.getNetworkElementId())), any())) .thenReturn(new NetworkElementImpl("UPDATED_SFC_ID")); updateTask.execute(); assertEquals(this.sg.getNetworkElementId(), "UPDATED_SFC_ID"); }
@Test public void testExecute_CallsSDNUpdateWithProvidedParameters_ExpectUpdate() throws Exception { this.sg.setNetworkElementId("OLD_SFC_ID"); this.networkElementList = new ArrayList<>(); UpdateServiceFunctionChainTask updateTask = this.task.create(this.sg, this.networkElementList); Mockito.when(this.sdnApi.updateNetworkElement( argThat(new ElementIdMatcher<NetworkElement>(this.sg.getNetworkElementId())), this.neListCaptor.capture())) .thenReturn(new NetworkElementImpl("UPDATED_SFC_ID")); updateTask.execute(); assertEquals(this.networkElementList, this.neListCaptor.getValue()); }
|
SfcFlowClassifierCreateTask extends TransactionalTask { public SfcFlowClassifierCreateTask create(SecurityGroup securityGroup, VMPort port) { SfcFlowClassifierCreateTask task = new SfcFlowClassifierCreateTask(); task.securityGroup = securityGroup; task.sfc = securityGroup.getServiceFunctionChain(); task.port = port; task.vmName = port.getVm() != null ? port.getVm().getName() : port.getSubnet().getName(); task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } SfcFlowClassifierCreateTask create(SecurityGroup securityGroup, VMPort port); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }
|
@Test public void testExecute_CreateInspectionHook_ExpectUpdate() throws Exception { when(this.sdnApi.installInspectionHook(any(), any(), any(), any(), any(), any())) .thenReturn(INSPECTION_HOOK_ID); SfcFlowClassifierCreateTask createTask = this.task.create(this.sg, this.port); createTask.execute(); verify(this.sdnApi, times(1)).installInspectionHook(argThat(new ElementIdMatcher<NetworkElement>(OPENSTACK_VMPORT_ID)), argThat(new ElementIdMatcher<InspectionPortElement>(OPENSTACK_SFC_ID)), (Long) isNull(), (TagEncapsulationType) isNull(), (Long) isNull(), (FailurePolicyType) isNull()); verify(this.port).setInspectionHookId(INSPECTION_HOOK_ID); }
@Test public void testExecute_CreateInspectionHook_ExpectFailure() throws Exception { doThrow(new Exception()).when(this.sdnApi).installInspectionHook(any(), any(), any(), any(), any(), any()); this.exception.expect(Exception.class); SfcFlowClassifierCreateTask createTask = this.task.create(this.sg, this.port); createTask.execute(); verify(this.port, times(0)).setInspectionHookId(any()); }
|
SfcFlowClassifierDeleteTask extends TransactionalTask { public SfcFlowClassifierDeleteTask create(SecurityGroup securityGroup, VMPort port) { SfcFlowClassifierDeleteTask task = new SfcFlowClassifierDeleteTask(); task.securityGroup = securityGroup; task.port = port; task.vmName = port.getVm() != null ? port.getVm().getName() : port.getSubnet().getName(); task.apiFactory = this.apiFactory; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } SfcFlowClassifierDeleteTask create(SecurityGroup securityGroup, VMPort port); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }
|
@Test public void testExecute_WithInspectionHook_ExpectUpdate() throws Exception { SfcFlowClassifierDeleteTask deleteTask = this.task.create(this.sg, this.port); deleteTask.execute(); verify(this.sdnApi, times(1)).removeInspectionHook(INSPECTION_HOOK_ID); verify(this.port).setInspectionHookId(null); }
@Test public void testExecute_WithoutInspectionHook_ExpectSuccess() throws Exception { when(this.port.getInspectionHookId()).thenReturn(null); SfcFlowClassifierDeleteTask deleteTask = this.task.create(this.sg, this.port); deleteTask.execute(); verifyZeroInteractions(this.sdnApi); assertNull(this.port.getInspectionHookId()); }
@Test public void testExecute_WithInspectionHook_ExpectFailure() throws Exception { doThrow(new Exception()).when(this.sdnApi).removeInspectionHook(INSPECTION_HOOK_ID); this.exception.expect(Exception.class); SfcFlowClassifierDeleteTask deleteTask = this.task.create(this.sg, this.port); deleteTask.execute(); }
|
CheckServiceFunctionChainMetaTask extends TransactionalMetaTask { public CheckServiceFunctionChainMetaTask create(SecurityGroup sg) { CheckServiceFunctionChainMetaTask task = new CheckServiceFunctionChainMetaTask(); task.createServiceFunctionChainTask = this.createServiceFunctionChainTask; task.updateServiceFunctionChainTask = this.updateServiceFunctionChainTask; task.deleteServiceFunctionChainTask = this.deleteServiceFunctionChainTask; task.securityGroup = sg; task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } CheckServiceFunctionChainMetaTask create(SecurityGroup sg); @Override void executeTransaction(EntityManager em); @Override Set<LockObjectReference> getObjects(); @Override TaskGraph getTaskGraph(); @Override String getName(); }
|
@Test public void testExecuteTransaction_WithVariousSecurityGroups_ExpectsCorrectTaskGraph() throws Exception { this.task.createServiceFunctionChainTask = new CreateServiceFunctionChainTask(); this.task.updateServiceFunctionChainTask = new UpdateServiceFunctionChainTask(); this.task.deleteServiceFunctionChainTask = new DeleteServiceFunctionChainTask(); CheckServiceFunctionChainMetaTask task = this.task.create(this.sg); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
DeleteDistributedApplianceService extends ServiceDispatcher<BaseDeleteRequest, BaseJobResponse> implements DeleteDistributedApplianceServiceApi { Job startDeleteDAJob(final DistributedAppliance da, UnlockObjectMetaTask ult) throws Exception { try { if (ult == null) { ult = LockUtil.tryLockDA(da, da.getApplianceManagerConnector()); } Job job; TaskGraph tg = new TaskGraph(); for (VirtualSystem vs : da.getVirtualSystems()) { TaskGraph vsDeleteTaskGraph = new TaskGraph(); vsDeleteTaskGraph.appendTask(this.vsConformanceCheckMetaTask.create(vs)); tg.addTaskGraph(vsDeleteTaskGraph); } tg.appendTask(this.deleteDAFromDbTask.create(da), TaskGuard.ALL_ANCESTORS_SUCCEEDED); tg.appendTask(ult, TaskGuard.ALL_PREDECESSORS_COMPLETED); log.info("Start Submitting Delete DA Job"); job = JobEngine.getEngine().submit("Delete Distributed Appliance '" + da.getName() + "'", tg, LockObjectReference.getObjectReferences(da), new JobCompletionListener() { @Override public void completed(Job job) { if (!job.getStatus().getStatus().isSuccessful()) { try { DeleteDistributedApplianceService.this.dbConnectionManager.getTransactionControl().required(() -> new CompleteJobTransaction<DistributedAppliance>(DistributedAppliance.class, DeleteDistributedApplianceService.this.txBroadcastUtil) .run(DeleteDistributedApplianceService.this.dbConnectionManager.getTransactionalEntityManager(), new CompleteJobTransactionInput(da.getId(), job.getId()))); } catch (Exception e) { log.error("A serious error occurred in the Job Listener", e); throw new RuntimeException("No Transactional resources are available", e); } } } }); log.info("Done submitting with jobId: " + job.getId()); return job; } catch (Exception e) { LockUtil.releaseLocks(ult); throw e; } } @Override BaseJobResponse exec(BaseDeleteRequest request, EntityManager em); }
|
@Test public void testStartDeleteDAJob_WithoutUnlockObjectMetaTask_ExpectsSuccess() throws Exception { this.deleteDistributedApplianceService.startDeleteDAJob(VALID_DA, null); PowerMockito.verifyStatic(Mockito.times(1)); LockUtil.tryLockDA(VALID_DA, null); }
|
CompleteJobTransaction { public Void run(EntityManager em, CompleteJobTransactionInput param) throws Exception { T entity = em.find(this.entityType, param.getEntityId()); if (entity == null) { throw new IllegalArgumentException(String.format("Entity with Id '%d' does not exist.", param.getEntityId())); } JobRecord jobRecord = em.find(JobRecord.class, param.getJobId()); if (jobRecord == null) { throw new IllegalArgumentException(String.format("Job record with id '%d' does not exist.", param.getJobId())); } entity.setLastJob(em.find(JobRecord.class, param.getJobId())); OSCEntityManager.update(em, entity, this.txBroadcastUtil); return null; } CompleteJobTransaction(Class<T> entityType, TransactionalBroadcastUtil txBroadcastUtil); Void run(EntityManager em, CompleteJobTransactionInput param); }
|
@Test public void testRun_WithValidInput_UpdatesEntityProperly() throws Exception { this.target.run(this.em,new CompleteJobTransactionInput(this.existingEntityId, this.existingJobId)); verify(this.testEntity, times(1)).setLastJob(this.testLastJobRecord); }
@Test public void testRun_WithInvalidEntityId_ThrowsIllegalArgumentException() throws Exception { this.expectException.expect(IllegalArgumentException.class); this.target.run(this.em,new CompleteJobTransactionInput(this.missingEntityId, this.existingJobId)); }
@Test public void testRun_WithInvalidJobId_ThrowsIllegalArgumentException() throws Exception { this.expectException.expect(IllegalArgumentException.class); this.target.run(this.em,new CompleteJobTransactionInput(this.existingEntityId, this.missingJobId)); }
|
ServiceDispatcher implements ServiceDispatcherApi<I, O> { @Override public O dispatch(I request) throws Exception { log.info("Service dispatch " + this.getClass().getSimpleName() + ". User: " + this.userContext.getCurrentUser() + ", Request: " + request); if (Server.isInMaintenance()) { log.warn("Incoming request (pid:" + ServerUtil.getCurrentPid() + ") while server is in maintenance mode."); throw new VmidcException(Server.PRODUCT_NAME + " server is in maintenance mode."); } if (this.em == null) { this.em = getEntityManager(); } TransactionControl txControl = getTransactionControl(); O response = null; try { response = txControl.required(() -> exec(request, this.em)); } catch (ScopedWorkException e) { handleException(e.getCause()); } ChainedDispatch<O> nextDispatch; while ((nextDispatch = popChain()) != null) { try { final O previousResponse = response; final ChainedDispatch<O> tempNext = nextDispatch; response = txControl.required(() -> tempNext.dispatch(previousResponse, this.em)); } catch (ScopedWorkException e) { handleException(e.getCause()); } } log.info("Service response: " + response); return response; } @Override O dispatch(I request); }
|
@Test public void testExecuteValidRequest() throws Exception { ServiceDispatcher<?, ?> mockServiceDispatcher = new ServiceDispatcher<Request, Response>() { { this.userContext = Mockito.mock(UserContextApi.class); } @Override public Response exec(Request request, EntityManager em) throws Exception { return null; } @Override protected EntityManager getEntityManager() { return ServiceDispatcherTest.this.mockEM; } @Override protected TransactionControl getTransactionControl() throws InterruptedException, VmidcException { return ServiceDispatcherTest.this.mockedTxControl; } }; mockServiceDispatcher.dispatch(null); Mockito.verify(this.mockedTransaction).begin(); Mockito.verify(this.mockedTransaction).commit(); }
@Test(expected = Exception.class) public void testExecuteInvalidRequest() throws Exception { ServiceDispatcher<?, ?> mockServiceDispatcher = new ServiceDispatcher<Request, Response>() { { this.userContext = Mockito.mock(UserContextApi.class); } @Override protected EntityManager getEntityManager() { return ServiceDispatcherTest.this.mockEM; } @Override protected TransactionControl getTransactionControl() throws InterruptedException, VmidcException { return ServiceDispatcherTest.this.mockedTxControl; } @Override public Response exec(Request request, EntityManager em) throws Exception { throw new Exception(""); } }; mockServiceDispatcher.dispatch(null); Mockito.verify(this.mockedTransaction).rollback(); }
|
DistributedApplianceDtoValidator implements DtoValidator<DistributedApplianceDto, DistributedAppliance> { @Override public void validateForCreate(DistributedApplianceDto dto) throws Exception { validate(dto); OSCEntityManager<DistributedAppliance> emgr = new OSCEntityManager<DistributedAppliance>(DistributedAppliance.class, this.em, this.txBroadcastUtil); if (emgr.isExisting("name", dto.getName())) { throw new VmidcBrokerValidationException("Distributed Appliance Name: " + dto.getName() + " already exists."); } } DistributedApplianceDtoValidator create(EntityManager em); @Override void validateForCreate(DistributedApplianceDto dto); @Override DistributedAppliance validateForUpdate(DistributedApplianceDto dto); static void checkForNullFields(DistributedApplianceDto dto); static void checkFieldLength(DistributedApplianceDto dto); }
|
@Test public void testValidateForCreate_WhenDistributedApplianceExists_ThrowsValidationException() throws Exception { DistributedApplianceDto existingDaDto= createDistributedApplianceDto(); existingDaDto.setName(DA_NAME_EXISTING_DA); existingDaDto.setApplianceId(this.app.getId()); existingDaDto.setMcId(this.amc.getId()); for (VirtualSystemDto vsDto : existingDaDto.getVirtualizationSystems()) { vsDto.setVcId(this.vc.getId()); vsDto.setDomainId(this.domain.getId()); } this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(MessageFormat.format("Distributed Appliance Name: {0} already exists.", DA_NAME_EXISTING_DA)); this.validator.validateForCreate(existingDaDto); }
@Test public void testValidateForCreate_WhenDistributedApplianceIsValid_ValidationSucceeds() throws Exception { DistributedApplianceDto newDaDto= createDistributedApplianceDto(); newDaDto.setName(DA_NAME_NEW_DA); newDaDto.setApplianceId(this.app.getId()); newDaDto.setMcId(this.amc.getId()); for (VirtualSystemDto vsDto : newDaDto.getVirtualizationSystems()) { vsDto.setVcId(this.vc.getId()); vsDto.setDomainId(this.domain.getId()); } this.validator.validateForCreate(newDaDto); }
|
DistributedApplianceDtoValidator implements DtoValidator<DistributedApplianceDto, DistributedAppliance> { @Override public DistributedAppliance validateForUpdate(DistributedApplianceDto dto) throws Exception { BaseDtoValidator.checkForNullId(dto); DistributedAppliance da = this.em.find(DistributedAppliance.class, dto.getId()); if (da == null) { throw new VmidcBrokerValidationException("Distributed Appliance entry with name: " + dto.getName() + ") is not found."); } ValidateUtil.checkMarkedForDeletion(da, da.getName()); if (!dto.getMcId().equals(da.getApplianceManagerConnector().getId())) { throw new VmidcBrokerValidationException("Appliance Manager Connector change is not allowed."); } validate(dto, false, da); return da; } DistributedApplianceDtoValidator create(EntityManager em); @Override void validateForCreate(DistributedApplianceDto dto); @Override DistributedAppliance validateForUpdate(DistributedApplianceDto dto); static void checkForNullFields(DistributedApplianceDto dto); static void checkFieldLength(DistributedApplianceDto dto); }
|
@Test public void testValidateForUpdate_WithNullDaId_ThrowsInvalidEntryException() throws Exception { DistributedApplianceDto daDto = createDistributedApplianceDto(); daDto.setId(null); this.exception.expect(VmidcBrokerInvalidEntryException.class); this.exception.expectMessage("Id " + EMPTY_VALUE_ERROR_MESSAGE); this.validator.validateForUpdate(daDto); }
@Test public void testValidateForUpdate_WhenDistributedApplianceNotFound_ThrowsValidationException() throws Exception { Long notFoundDaId = 2000L; DistributedApplianceDto daDto = createDistributedApplianceDto(); daDto.setId(notFoundDaId); this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(MessageFormat.format("Distributed Appliance entry with name: {0}) is not found.", daDto.getName())); this.validator.validateForUpdate(daDto); }
@Test public void testValidateForUpdate_WhenManagerConnectorIdMismatches_ThrowsValidationException() throws Exception { DistributedApplianceDto daDto = createDistributedApplianceDto(); daDto.setId(this.da.getId()); daDto.setName(DA_NAME_EXISTING_DA); daDto.setApplianceId(this.app.getId()); daDto.setMcId(this.amc.getId() + 1); this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage("Appliance Manager Connector change is not allowed."); this.validator.validateForUpdate(daDto); }
@Test @Ignore public void testValidateForUpdate_WhenDistributedApplianceExists_ExpectsCorrespondentDa() throws Exception { DistributedApplianceDto daDto = createDistributedApplianceDto(); daDto.setId(DA_ID_EXISTING_DA); DistributedAppliance da = this.validator.validateForUpdate(daDto); Assert.assertNotNull("The returned da should not be null.", da); Assert.assertEquals("The id of the returned da was different than expected.", this.da.getId(), da.getId()); }
@Test public void testValidateForUpdate_WhenDAUpdateRemovesAssignedVS_ThrowsInvalidEntryException() throws Exception { DistributedAppliance assignedDA = new DistributedAppliance(this.amc); assignedDA.setName("DA_WITH_ASSIGNED_VS"); assignedDA.setApplianceVersion(this.asv.getApplianceSoftwareVersion()); assignedDA.setAppliance(this.app); VirtualSystem assignedVS = new VirtualSystem(assignedDA); assignedVS.setName("VS_WITH_ASSIGNED_DS"); assignedVS.setApplianceSoftwareVersion(this.asv); assignedVS.setVirtualizationConnector(this.vc); assignedDA.getVirtualSystems().add(assignedVS); DeploymentSpec assignedDS = new DeploymentSpec(assignedVS, null, null, null, null, null); assignedDS.setName("DS_WITH_ASSIGNED_DAI"); assignedDS.setInstanceCount(1); assignedVS.getDeploymentSpecs().add(assignedDS); DistributedApplianceInstance assignedDAI = new DistributedApplianceInstance(assignedVS); assignedDAI.setName("ASSIGNED_DAI"); assignedDS.getDistributedApplianceInstances().add(assignedDAI); PodPort podPort = new PodPort(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); this.em.getTransaction().begin(); this.em.persist(assignedDA); this.em.persist(assignedVS); this.em.persist(assignedDS); this.em.persist(assignedDAI); this.em.persist(podPort); assignedDAI.addProtectedPort(podPort); podPort.addDai(assignedDAI); this.em.getTransaction().commit(); DistributedApplianceDto daDto = createDistributedApplianceDto(); daDto.setId(assignedDA.getId()); daDto.setMcId(this.amc.getId()); daDto.setApplianceId(this.app.getId()); daDto.getVirtualizationSystems().iterator().next().setVcId(this.vc.getId()); daDto.getVirtualizationSystems().iterator().next().setDomainId(this.domain.getId()); this.exception.expect(VmidcBrokerInvalidEntryException.class); this.exception.expectMessage(String.format("The virtual system '%s' cannot be deleted. It is currently assigned to protect a workload.", assignedVS.getName())); this.validator.validateForUpdate(daDto); }
|
ApplianceSoftwareVersionDtoValidator implements DtoValidator<ApplianceSoftwareVersionDto, ApplianceSoftwareVersion> { @Override public void validateForCreate(ApplianceSoftwareVersionDto dto) throws Exception { checkForNullFields(dto); checkFieldLength(dto); ApplianceSoftwareVersion asv = ApplianceSoftwareVersionEntityMgr.findByImageUrl(this.em, dto.getImageUrl()); if (asv != null) { throw new VmidcBrokerValidationException("Image file: " + dto.getImageUrl() + " already exists. Cannot add an image with the same name."); } } ApplianceSoftwareVersionDtoValidator create(EntityManager em); @Override void validateForCreate(ApplianceSoftwareVersionDto dto); @Override ApplianceSoftwareVersion validateForUpdate(ApplianceSoftwareVersionDto dto); }
|
@Test public void testValidateforCreate_UsingExistingImageUrl_ThrowsVmidcBrokerValidationException() throws Exception { ApplianceSoftwareVersionDto dto = newApplianceSoftwareVersionDto(); dto.setImageUrl(EXISTING_IMAGE_URL); this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(String.format("Image file: %s already exists. Cannot add an image with the same name.", EXISTING_IMAGE_URL)); this.validator.validateForCreate(dto); }
@Test public void testValidateforCreate_UsingValidNewImage_Suceeds() throws Exception { ApplianceSoftwareVersionDto dto = newApplianceSoftwareVersionDto(); this.validator.validateForCreate(dto); }
|
ApplianceDtoValidator implements DtoValidator<ApplianceDto, Appliance> { @Override public void validateForCreate(ApplianceDto dto) throws Exception { checkForNullFields(dto); checkFieldLength(dto); Appliance existingAppliance = ApplianceEntityMgr.findByModel(this.em, dto.getModel()); if (existingAppliance != null) { throw new VmidcBrokerValidationException("Appliance already exists for model: " + dto.getModel()); } } ApplianceDtoValidator create(EntityManager em); @Override void validateForCreate(ApplianceDto dto); @Override Appliance validateForUpdate(ApplianceDto dto); }
|
@Test public void testValidateforCreate_UsingExistingModel_ThrowsVmidcBrokerValidationException() throws Exception { ApplianceDto dto = new ApplianceDto(EXISTING_MODEL, UUID.randomUUID().toString(), UUID.randomUUID().toString()); this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(String.format("Appliance already exists for model: " + EXISTING_MODEL)); this.validator.validateForCreate(dto); }
@Test public void testValidateforCreate_UsingValidNewModel_Suceeds() throws Exception { ApplianceDto dto = new ApplianceDto(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString()); this.validator.validateForCreate(dto); }
|
UserDtoValidator implements DtoValidator<UserDto, User> { void validate(UserDto dto) throws Exception { UserDtoValidator.checkForNullFields(dto); UserDtoValidator.checkFieldLength(dto); if (!StringUtils.isBlank(dto.getEmail())) { ValidateUtil.checkForValidEmailAddress(dto.getEmail()); } ValidateUtil.checkForValidUsername(dto.getLoginName()); ValidateUtil.checkForValidPassword(dto.getPassword()); } UserDtoValidator(EntityManager em, TransactionalBroadcastUtil txBroadcastUtil); @Override void validateForCreate(UserDto dto); @Override User validateForUpdate(UserDto dto); static void checkForNullFields(UserDto dto); static void checkFieldLength(UserDto dto); }
|
@Test @Parameters(method = "getInvalidFieldsTestData") public void testValidate_UsingInvalidField_ThrowsInvalidEntryException(UserDto dto, String expectedErrorMessage) throws Exception { this.exception.expect(VmidcBrokerInvalidEntryException.class); this.exception.expectMessage(expectedErrorMessage); this.validator.validate(dto); }
|
UserDtoValidator implements DtoValidator<UserDto, User> { @Override public void validateForCreate(UserDto dto) throws Exception { validate(dto); OSCEntityManager<User> emgr = new OSCEntityManager<User>(User.class, this.em, this.txBroadcastUtil); if (emgr.isExisting("loginName", dto.getLoginName())) { throw new VmidcBrokerValidationException("User Login Name: " + dto.getLoginName() + " already exists."); } } UserDtoValidator(EntityManager em, TransactionalBroadcastUtil txBroadcastUtil); @Override void validateForCreate(UserDto dto); @Override User validateForUpdate(UserDto dto); static void checkForNullFields(UserDto dto); static void checkFieldLength(UserDto dto); }
|
@Test public void testValidateForCreate_WithExistingUser_ThrowsInvalidEntryException() throws Exception { this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(MessageFormat.format("User Login Name: {0} already exists.", this.existingUserDto.getLoginName())); this.validator.validateForCreate(this.existingUserDto); }
@Test public void testValidateForCreate_WithValidNewUser_ValidationSucceeds() throws Exception { this.validator.validateForCreate(this.newUserDto); }
|
UserDtoValidator implements DtoValidator<UserDto, User> { @Override public User validateForUpdate(UserDto dto) throws Exception { BaseDtoValidator.checkForNullId(dto); validate(dto); OSCEntityManager<User> emgr = new OSCEntityManager<User>(User.class, this.em, this.txBroadcastUtil); User user = emgr.findByPrimaryKey(dto.getId()); if (user == null) { throw new VmidcBrokerValidationException("User entry with name " + dto.getLoginName() + " is not found."); } return user; } UserDtoValidator(EntityManager em, TransactionalBroadcastUtil txBroadcastUtil); @Override void validateForCreate(UserDto dto); @Override User validateForUpdate(UserDto dto); static void checkForNullFields(UserDto dto); static void checkFieldLength(UserDto dto); }
|
@Test public void testValidateForUpdate_WithValidExistingUser_ReturnsExistingUser() throws Exception { User response = null; response = this.validator.validateForUpdate(this.existingUserDto); Assert.assertNotNull("The validation response should not be null.", response); Assert.assertEquals("The user id was different than expected.", this.existingUserDto.getId(), response.getId()); }
@Test public void testValidateForUpdate_WithUserMissingId_ThrowsInvalidEntryException() throws Exception { this.exception.expect(VmidcBrokerInvalidEntryException.class); this.exception.expectMessage("Id " + EMPTY_VALUE_ERROR_MESSAGE); this.validator.validateForUpdate(this.newUserDto); }
@Test public void testValidateForUpdate_WhenUserNotFound_ThrowsInvalidEntryException() throws Exception { Long idNotFound = 10L; this.existingUserDto.setId(idNotFound); this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(MessageFormat.format("User entry with name {0} is not found.", this.existingUserDto.getLoginName())); this.validator.validateForUpdate(this.existingUserDto); }
|
KubernetesPodApi extends KubernetesApi { public List<KubernetesPod> getPodsByLabel(String label) throws VmidcException { List<KubernetesPod> resultPodList = new ArrayList<KubernetesPod>(); if (label == null) { throw new IllegalArgumentException("Label should not be null"); } try { PodList pods = getKubernetesClient().pods().withLabel(label).list(); if (pods == null || pods.getItems() == null || pods.getItems().isEmpty()) { return resultPodList; } for (Pod pod : pods.getItems()) { resultPodList.add( new KubernetesPod( pod.getMetadata().getName(), pod.getMetadata().getNamespace(), pod.getMetadata().getUid(), pod.getSpec().getNodeName()) ); } } catch (KubernetesClientException e) { throw new VmidcException("Failed to get Pods"); } return resultPodList; } KubernetesPodApi(KubernetesClient client); List<KubernetesPod> getPodsByLabel(String label); KubernetesPod getPodById(String uid, String namespace, String name); }
|
@Test public void testGetPodsbyLabel_WithNullLabel_ThrowsIllegalArgumentException() throws Exception { this.exception.expect(IllegalArgumentException.class); this.service.getPodsByLabel(null); }
@Test public void testGetPodsbyLabel_WhenK8ClientThrowsKubernetesClientException_ThrowsVmidcException() throws Exception { this.exception.expect(VmidcException.class); when(this.fabric8Client.pods()).thenThrow(new KubernetesClientException("")); this.service.getPodsByLabel("sample_label"); }
@Test public void testGetPodsbyLabel_WhenK8sReturnsNull_ReturnsEmptyList() throws Exception { String label = UUID.randomUUID().toString(); mockPodsByLabel(label, null); List<KubernetesPod> result = this.service.getPodsByLabel(label); assertNotNull("The result should not be null.", result); assertTrue(result.isEmpty()); }
@Test public void testGetPodsbyLabel_WhenK8sReturnsEmptyList_ReturnsEmptyList() throws Exception { String label = UUID.randomUUID().toString(); mockPodsByLabel(label, new ArrayList<Pod>()); List<KubernetesPod> result = this.service.getPodsByLabel(label); assertNotNull("The result should not be null.", result); assertTrue(result.isEmpty()); }
|
VirtualizationConnectorDtoValidator implements DtoValidator<VirtualizationConnectorDto, VirtualizationConnector> { @Override public void validateForCreate(VirtualizationConnectorDto dto) throws Exception { OSCEntityManager<VirtualizationConnector> emgr = new OSCEntityManager<>( VirtualizationConnector.class, this.em, this.txBroadcastUtil); if (dto.getType().isKubernetes() && !dto.isControllerDefined()) { throw new VmidcBrokerValidationException( "Virtualization connectors for Kubernetes must have a SDN controller."); } boolean usesProviderCreds = dto.isControllerDefined() && this.apiFactoryService.usesProviderCreds(dto.getControllerType()); VirtualizationConnectorDtoValidator.checkForNullFields(dto, usesProviderCreds); VirtualizationConnectorDtoValidator.checkFieldLength(dto); if (dto.getType().isOpenstack()) { dto.setSoftwareVersion(OpenstackSoftwareVersion.OS_ICEHOUSE.toString()); } if (emgr.isExisting("name", dto.getName())) { throw new VmidcBrokerValidationException( "Virtualization Connector Name: " + dto.getName() + " already exists."); } if (dto.isControllerDefined() && !this.apiFactoryService.usesProviderCreds(dto.getControllerType())) { ValidateUtil.checkForValidIpAddressFormat(dto.getControllerIP()); if (emgr.isExisting("controllerIpAddress", dto.getControllerIP())) { throw new VmidcBrokerValidationException( "Controller IP Address: " + dto.getControllerIP() + " already exists."); } } VirtualizationConnectorDtoValidator.checkFieldFormat(dto); if (emgr.isExisting("providerIpAddress", dto.getProviderIP())) { throw new VmidcBrokerValidationException( "Provider IP Address: " + dto.getProviderIP() + " already exists."); } } VirtualizationConnectorDtoValidator(EntityManager em, TransactionalBroadcastUtil txBroadcastUtil, ApiFactoryService apiFactoryService); @Override void validateForCreate(VirtualizationConnectorDto dto); @Override VirtualizationConnector validateForUpdate(VirtualizationConnectorDto dto); static void checkForNullFields(VirtualizationConnectorDto dto, boolean skipPasswordNullCheck, boolean usesProviderCreds); static void checkForNullFields(VirtualizationConnectorDto dto, boolean usesProviderCreds); static void checkFieldLength(VirtualizationConnectorDto dto); static void checkFieldFormat(VirtualizationConnectorDto dto); }
|
@Test public void testValidateForCreate_WhenVcRequest_ReturnsSuccessful() throws Exception { this.dtoValidator.validateForCreate(VirtualizationConnectorDtoValidatorTestData.OPENSTACK_NOCONTROLLER_VC); Assert.assertTrue(true); }
@Test public void testValidateForCreate_WhenVcNameExistsRequest_ThrowsValidationException() throws Exception { this.exception.expect(VmidcBrokerValidationException.class); VirtualizationConnectorDto dto = VirtualizationConnectorDtoValidatorTestData.OPENSTACK_NAME_ALREADY_EXISTS_NOCONTROLLER_VC; this.exception.expectMessage("Virtualization Connector Name: " + dto.getName() + " already exists."); this.dtoValidator.validateForCreate(dto); }
@Test public void testValidateForCreate_WhenControllerIpExists_ThrowsValidationException() throws Exception { this.exception.expect(VmidcBrokerValidationException.class); VirtualizationConnectorDto dto = VirtualizationConnectorDtoValidatorTestData.OPENSTACK_CONTROLLER_IP_ALREADY_EXISTS_VC; this.exception.expectMessage("Controller IP Address: " + dto.getControllerIP() + " already exists."); this.dtoValidator.validateForCreate(dto); }
@Test public void testValidateForCreate_WhenProviderIpExists_ThrowsValidationException() throws Exception { this.exception.expect(VmidcBrokerValidationException.class); VirtualizationConnectorDto dto = VirtualizationConnectorDtoValidatorTestData.PROVIDER_IP_ALREADY_EXISTS_OPENSTACK_VC; this.exception.expectMessage("Provider IP Address: " + dto.getProviderIP() + " already exists."); this.dtoValidator.validateForCreate(dto); }
|
BackupService extends BackupFileService<BackupRequest, BackupResponse> implements BackupServiceApi { @Override public void deleteBackupFiles() { deleteBackupFiles(DEFAULT_BACKUP_FILE_NAME); } @Override BackupResponse exec(BackupRequest request, EntityManager em); @Override void deleteBackupFilesFrom(String directory); void deleteBackupFilesFrom(String directory, String backupFileName); @Override void deleteBackupFiles(); void deleteBackupFiles(String backupFileName); @Override File getEncryptedBackupFile(); @Override File getEncryptedBackupFile(String backupFileName); }
|
@Test public void testDeleteBackupFiles_withNoArguments_callsDeleteDefaultBackupFiles() { doCallRealMethod().when(this.target).deleteBackupFiles(); this.target.deleteBackupFiles(); verify(this.target, times(1)).deleteBackupFiles("BrokerServerDBBackup"); }
|
JobQueuer { public synchronized void putJob(JobRequest job) { try { log.info(String.format("Job %s put into queue", job.getName())); jobQueue.put(job); } catch (InterruptedException e) { log.warn("Putting job in queue was interrupted.", e); } } private JobQueuer(); static synchronized JobQueuer getInstance(); synchronized void putJob(JobRequest job); }
|
@Test @Ignore public void testPutJob() { final TaskGraph tg = new TaskGraph(); tg.addTask(this.A); tg.addTask(this.B); tg.addTask(this.C, this.A); tg.addTask(this.D, this.A); final TaskGraph tg2 = new TaskGraph(); tg2.addTask(this.A); tg2.addTask(this.B); tg2.addTask(this.C, this.A); tg2.addTask(this.D, this.A); final TaskGraph tg3 = new TaskGraph(); tg3.addTask(this.A); tg3.addTask(this.B); tg3.addTask(this.C, this.A); tg3.addTask(this.D, this.A); @SuppressWarnings("unchecked") final List<String> mockList = mock(List.class); JobEngine.getEngine().addJobCompletionListener(new JobCompletionListener() { @Override public void completed(Job job) { mockList.add(job.getName()); } }); Runnable job1Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested1", tg, false)); } }; Runnable job2Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested2", tg2, false)); } }; Runnable job3Runnable = new Runnable() { @Override public void run() { JobQueuer.getInstance().putJob(new JobRequest("Job-parallel-nested3", tg3, false)); } }; new Thread(job1Runnable).start(); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } new Thread(job2Runnable).start(); new Thread(job3Runnable).start(); InOrder inOrder = inOrder(mockList); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested1"); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested2"); verify(mockList, new Timeout(5000, new InOrderWrapper(new Times(1), (InOrderImpl) inOrder))).add( "Job-parallel-nested3"); verifyNoMoreInteractions(mockList); }
|
JobEngine { public Job submit(String name, TaskGraph taskGraph, JobCompletionListener listener, boolean persistent) throws Exception { return initJob(name, taskGraph, null, listener, null, persistent); } private JobEngine(); synchronized void init(int jobThreadPoolSize, int taskThreadPoolSize); static synchronized JobEngine getEngine(); void shutdown(); void logStatus(); Job submit(String name, TaskGraph taskGraph, JobCompletionListener listener, boolean persistent); Job submit(String name, TaskGraph taskGraph, JobCompletionListener jobListener,
TaskChangeListener taskListener, boolean persistent); Job submit(String name, TaskGraph taskGraph, boolean persistent); Job submit(String name, TaskGraph taskGraph, Set<LockObjectReference> objects, JobCompletionListener listener); Job submit(String name, TaskGraph taskGraph, Set<LockObjectReference> objects,
JobCompletionListener jobListener, TaskChangeListener taskListener); Job submit(String name, TaskGraph taskGraph, Set<LockObjectReference> objects); Job submit(String name, TaskGraph taskGraph, Set<LockObjectReference> objects,
JobCompletionListener jobCompletionListener, TaskChangeListener taskChangeListener, boolean persistent); boolean isActive(); static void setJobThreadPoolSize(String value); static void setTaskThreadPoolSize(String value); synchronized void abortJob(Long jobId, String reason); void addJobCompletionListener(JobCompletionListener listener); void removeJobCompletionListener(JobCompletionListener listener); synchronized Job getJobByTask(Task task); static final int DEFAULT_JOB_THREAD_POOL_SIZE; static final int DEFAULT_TASK_THREAD_POOL_SIZE; }
|
@Ignore @Test public void testTaskDependencyExecutionOrder() throws Exception { this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B); this.tg.addTask(this.C, this.A); this.tg.addTask(this.D, this.A); this.job = this.je.submit("Job-parallel-nested", this.tg, true); this.job.waitForCompletion(); assertTrue(this.C.taskOrder > this.A.taskOrder); assertTrue(this.D.taskOrder > this.A.taskOrder); this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B); this.tg.addTask(this.C, this.A); this.tg.addTask(this.D, this.B); this.job = this.je.submit("Job-parallel-branches", this.tg, true); this.job.waitForCompletion(); assertTrue(this.C.taskOrder > this.A.taskOrder); assertTrue(this.D.taskOrder > this.B.taskOrder); this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B, this.A); this.tg.addTask(this.C, this.B); this.tg.addTask(this.D, this.C); this.job = this.je.submit("Job-sequential-tasks", this.tg, true); this.job.waitForCompletion(); assertTrue(this.B.taskOrder > this.A.taskOrder); assertTrue(this.C.taskOrder > this.B.taskOrder); assertTrue(this.D.taskOrder > this.C.taskOrder); this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B); this.tg.addTask(this.C); this.tg.addTask(this.D); this.job = this.je.submit("Job-parallel-tasks", this.tg, true); this.job.waitForCompletion(); verifyJobPersistence(this.job); }
@Test public void testConcurrentGraphModification() throws Exception { String jobName = "Test-Concurrent-Graph-Modification"; this.tg = new TaskGraph(); for (int i = 0; i < 200; i++) { this.tg.addTask(new EmptyTask("Task " + i)); } this.tg.addTask(new BaseTask("Reader task") { @Override public void execute() throws Exception { Set<TaskNode> predecessors =JobEngineTest.this.tg.getGraph().getPredecessors(JobEngineTest.this.tg.getEndTaskNode()); System.out.println(getName() + " : I have a task with " + predecessors.size() + " nodes"); } @Override public Set<LockObjectReference> getObjects() { return emptySet(); }}); this.tg.addTask(new BaseTask("Appender task") { @Override public void execute() throws Exception { JobEngineTest.this.tg.appendTask(new EmptyTask("A dummy task just to be appended")); } @Override public Set<LockObjectReference> getObjects() { return emptySet(); }}); this.job = this.je.submit(jobName, this.tg, new JobCompletionListener() { @Override public void completed(Job job) { System.out.println(job.getName() +" : " + job.getStatus()); } }, false); this.job.waitForCompletion(); Assert.assertNotNull(this.job); Assert.assertEquals(JobStatus.PASSED, this.job.getStatus().getStatus()); }
@Test public void testConcurrentAppends() throws Exception { String jobName = "Test-Concurrent-Appends"; this.tg = new TaskGraph(); for (int i = 0; i < 20; i++) { this.tg.addTask(new BaseTask("Appender task " + i) { @Override public void execute() throws Exception { JobEngineTest.this.tg.appendTask(new EmptyTask("A dummy task just to be appended")); } @Override public Set<LockObjectReference> getObjects() { return emptySet(); }}); } this.job = this.je.submit(jobName, this.tg, new JobCompletionListener() { @Override public void completed(Job job) { System.out.println(job.getName() +" : " + job.getStatus()); } }, false); this.job.waitForCompletion(); Assert.assertNotNull(this.job); Assert.assertEquals(JobStatus.PASSED, this.job.getStatus().getStatus()); }
@Test public void testTaskConcurrency() throws Exception { for (int i = 0; i < 100; i++) { this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B); this.tg.addTask(this.C); this.tg.addTask(this.D); this.job = this.je.submit("Job-" + i, this.tg, false); } waitForJobsCompletion(this.je); }
@Test public void testTaskInputOutput() throws Exception { OutputTask A = new OutputTask("A-OutputTask"); InputTask B = new InputTask("B-Input"); InputTask C = new InputTask("C-Input"); this.tg = new TaskGraph(); this.tg.addTask(A); this.tg.addTask(B, A); this.tg.addTask(C, B); this.job = this.je.submit("Job-input-output", this.tg, true); this.job.waitForCompletion(); assertEquals(A.id, B.id); assertEquals(B.id, C.id); }
@Test public void testSkippedTasks() throws Exception { Task A = new FailedTask("A-Failed"); Task B = new EmptyTask("B"); Task C = new EmptyTask("C"); Task D = new EmptyTask("D"); Task E = new EmptyTask("E"); Task F = new EmptyTask("F"); Task G = new EmptyTask("G"); this.tg = new TaskGraph(); this.tg.addTask(A); this.tg.addTask(B); this.tg.addTask(C); this.tg.addTask(D, TaskGuard.ALL_PREDECESSORS_SUCCEEDED, A, B); this.tg.addTask(E, TaskGuard.ALL_PREDECESSORS_SUCCEEDED, D); this.tg.addTask(F, TaskGuard.ALL_PREDECESSORS_COMPLETED, C, D); this.tg.addTask(G, TaskGuard.ALL_ANCESTORS_SUCCEEDED, F); this.job = this.je.submit("Job-skipped-task", this.tg, true); this.job.waitForCompletion(); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(A).getStatus()).getStatus(), TaskStatus.FAILED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(B).getStatus()).getStatus(), TaskStatus.PASSED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(C).getStatus()).getStatus(), TaskStatus.PASSED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(D).getStatus()).getStatus(), TaskStatus.SKIPPED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(E).getStatus()).getStatus(), TaskStatus.SKIPPED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(F).getStatus()).getStatus(), TaskStatus.PASSED); assertEquals(((TaskStatusElementImpl)this.job.getTaskGraph().getTaskNode(G).getStatus()).getStatus(), TaskStatus.SKIPPED); }
@Test public void testJobCompletionListener() throws Exception { this.tg.addTask(this.A); this.tg.addTask(this.B); this.tg.addTask(this.C); JobCompletionResponder responder = new JobCompletionResponder(); this.job = this.je.submit("Job-completion-listener", this.tg, responder, false); this.job.waitForCompletion(); assertTrue(responder.isCalled()); }
@Test public void testAddTaskGraph() throws Exception { this.A = new EmptyTask("TG-A"); this.B = new EmptyTask("TG-B"); this.C = new EmptyTask("TG-C"); this.D = new EmptyTask("TG-D"); this.tg = new TaskGraph(); this.tg.addTask(this.A); this.tg.addTask(this.B, this.A); this.tg.addTask(this.C, this.B); this.tg.addTask(this.D, this.C); Task A = new EmptyTask("TG1-A"); Task B = new EmptyTask("TG1-B"); Task C = new EmptyTask("TG1-C"); Task D = new EmptyTask("TG1-D"); TaskGraph tg1 = new TaskGraph(); tg1.addTask(A); tg1.addTask(B, A); tg1.addTask(C, B); tg1.addTask(D, C); Task E = new EmptyTask("TG2-E"); Task F = new EmptyTask("TG2-F"); Task G = new EmptyTask("TG2-G"); Task H = new EmptyTask("TG2-H"); TaskGraph tg2 = new TaskGraph(); tg2.addTask(E); tg2.addTask(F, E); tg2.addTask(G, F); tg2.addTask(H, G); this.tg.addTaskGraph(tg1); this.tg.addTaskGraph(tg2, this.D); this.job = this.je.submit("Job-task-graph-wiring", this.tg, true); this.job.waitForCompletion(); }
@Test public void testMetaTask() throws Exception { EmptyTask A = new EmptyTask("TG-A"); EmptyMetaTask B = new EmptyMetaTask("TG-B (Meta)"); EmptyTask C = new EmptyTask("TG-C"); EmptyTask D = new EmptyTask("TG-D"); this.tg = new TaskGraph(); this.tg.addTask(A); this.tg.addTask(B, A); this.tg.addTask(C, B); this.tg.addTask(D, B); this.job = this.je.submit("Job-meta-task-wiring", this.tg, true); this.job.waitForCompletion(); }
|
RequirementParser { static List<Requirement> parseRequireBundle(String header) throws IllegalArgumentException { if (header == null) { return Collections.emptyList(); } Clause[] clauses = Parser.parseHeader(header); List<Requirement> requirements = new ArrayList<>(clauses.length); for (Clause requireClause : clauses) { String bsn = requireClause.getName(); String versionRangeStr = requireClause.getAttribute(org.osgi.framework.Constants.BUNDLE_VERSION_ATTRIBUTE); String filter = toBundleFilter(bsn, versionRangeStr); Requirement requirement = new RequirementBuilderImpl(BundleNamespace.BUNDLE_NAMESPACE) .addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter) .build(); requirements.add(requirement); } return requirements; } }
|
@Test public void testParseRequireBundle() { List<Requirement> actual = RequirementParser.parseRequireBundle("foo;bundle-version=1.0.0, bar;bundle-version=\"[1.0,1.1)\", baz;bundle-version=\"[2.0,3.0)\", fnarg"); assertEquals(4, actual.size()); assertEquals("(&(osgi.wiring.bundle=foo)(bundle-version>=1.0.0))", actual.get(0).getDirectives().get("filter")); assertEquals("(&(osgi.wiring.bundle=bar)(bundle-version>=1.0.0)(!(bundle-version>=1.1.0)))", actual.get(1).getDirectives().get("filter")); assertEquals("(&(osgi.wiring.bundle=baz)(bundle-version>=2.0.0)(!(bundle-version>=3.0.0)))", actual.get(2).getDirectives().get("filter")); assertEquals("(osgi.wiring.bundle=fnarg)", actual.get(3).getDirectives().get("filter")); }
|
RequirementParser { static List<Requirement> parseRequireCapability(String header) throws IllegalArgumentException { if (header == null) { return Collections.emptyList(); } Clause[] clauses = Parser.parseHeader(header); List<Requirement> reqs = new ArrayList<>(clauses.length); for (Clause clause : clauses) { String namespace = clause.getName(); RequirementBuilderImpl reqBuilder = new RequirementBuilderImpl(namespace); for (Attribute attrib : clause.getAttributes()) { reqBuilder.addAttribute(attrib.getName(), attrib.getValue()); } for (Directive directive : clause.getDirectives()) { reqBuilder.addDirective(directive.getName(), directive.getValue()); } reqs.add(reqBuilder.build()); } return reqs; } }
|
@Test public void testParseRequireCapability() { List<Requirement> actual = RequirementParser.parseRequireCapability("osgi.extender; filter:=\"(&(osgi.extender=osgi.ds)(version>=1.0))\"; effective:=active, osgi.service; filter:=\"(objectClass=org.example.Foo)\""); assertEquals(2, actual.size()); assertEquals("(&(osgi.extender=osgi.ds)(version>=1.0))", actual.get(0).getDirectives().get("filter")); assertEquals("active", actual.get(0).getDirectives().get("effective")); }
|
PluginResolveContext extends ResolveContext { static boolean match(Requirement requirement, Capability capability) { return match(requirement, capability, null); } PluginResolveContext(BundleContext bundleContext, ResolveRequest request, LogService log); @Override Collection<Resource> getMandatoryResources(); @Override List<Capability> findProviders(Requirement requirement); @Override int insertHostedCapability(List<Capability> capabilities, HostedCapability hc); @Override boolean isEffective(Requirement requirement); @Override Map<Resource, Wiring> getWirings(); }
|
@Test public void testMatchRequirementsEffectiveResolve() throws Exception { assertTrue("effective should match: req=default, cap=default", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", null), createCapability("foo", null, new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertTrue("effective should match: req=default, cap=resolve", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", null), createCapability("foo", "resolve", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertTrue("effective should match: req=resolve, cap=default", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "resolve"), createCapability("foo", null, new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertTrue("effective should match: req=resolve, cap=resolve", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "resolve"), createCapability("foo", "resolve", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); }
@Test public void testEffectiveResolveCapsMatchAnyRequirement() throws Exception { assertTrue("effective should match: req=blah, cap=default", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "blah"), createCapability("foo", null, new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertTrue("effective should match: req=blah, cap=resolve", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "blah"), createCapability("foo", "resolve", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); }
@Test public void testEffectiveNonResolveCapsMatchRequirementWithSame() throws Exception { assertTrue("effective should match: req=blah, cap=blah", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "blah"), createCapability("foo", "blah", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertFalse("effective should NOT match: req=default, cap=blah", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", null), createCapability("foo", "blah", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertFalse("effective should NOT match: req=default, cap=blah", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "resolve"), createCapability("foo", "blah", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); assertFalse("effective should NOT match: req=wibble, cap=blah", PluginResolveContext.match( createRequirement("foo", "(foo=bar)", "wibble"), createCapability("foo", "blah", new HashMap<String,Object>() {{ put("foo", "bar"); }}) )); }
|
KubernetesPodApi extends KubernetesApi { public KubernetesPod getPodById(String uid, String namespace, String name) throws VmidcException { if (uid == null) { throw new IllegalArgumentException("Uid should not be null"); } if (name == null) { throw new IllegalArgumentException("Name should not be null"); } if (namespace == null) { throw new IllegalArgumentException("Namespace should not be null"); } KubernetesPod pod = getPodsByName(namespace, name); return (pod == null || !pod.getUid().equals(uid)) ? null : pod; } KubernetesPodApi(KubernetesClient client); List<KubernetesPod> getPodsByLabel(String label); KubernetesPod getPodById(String uid, String namespace, String name); }
|
@Test public void testGetPodsbyId_WithNullName_ThrowsIllegalArgumentException() throws Exception { this.exception.expect(IllegalArgumentException.class); this.service.getPodById("1234", null, "sample_namespace"); }
@Test public void testGetPodsbyId_WithNullUid_ThrowsIllegalArgumentException() throws Exception { this.exception.expect(IllegalArgumentException.class); this.service.getPodById(null, "sample_name", "sample_namespace"); }
@Test public void testGetPodsbyId_WithNullNameSpace_ThrowsIllegalArgumentException() throws Exception { this.exception.expect(IllegalArgumentException.class); this.service.getPodById("1234", "sample_name", null); }
@Test public void testGetPodById_WhenK8ClientThrowsKubernetesClientException_ThrowsVmidcException() throws Exception { this.exception.expect(VmidcException.class); when(this.fabric8Client.pods()).thenThrow(new KubernetesClientException("")); this.service.getPodById("1234", "sample_name", "sample_label"); }
@Test public void testGetPodsbyId_WhenK8sReturnsNull_ReturnsNull() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); mockPodsByName(namespace, name, null); KubernetesPod result = this.service.getPodById(UUID.randomUUID().toString(), namespace, name); assertNull("The result should be null.", result); }
@Test public void testGetPodsbyLabel_WhenK8sReturnsPodWithMismatchingId_ReturnsEmptyList() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); mockPodsByName(namespace, name, newPod(UUID.randomUUID().toString(), name, namespace, "node")); KubernetesPod result = this.service.getPodById(UUID.randomUUID().toString(), namespace, name); assertNull("The result should be null.", result); }
@Test public void testGetPodsbyLabel_WhenK8sReturnsPodWithMatchingId_ReturnsPod() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); String uid = UUID.randomUUID().toString(); Pod pod = newPod(uid, namespace, name, UUID.randomUUID().toString()); mockPodsByName(namespace, name, pod); KubernetesPod result = this.service.getPodById(uid, namespace, name); assertNotNull("The result should not be null.", result); assertPodFields(pod, result); }
|
ValidateUtil implements ValidationApi { public static void checkForNullFields(Map<String, Object> map) throws VmidcBrokerInvalidEntryException { for (Entry<String, Object> entry : map.entrySet()) { String field = entry.getKey(); Object value = entry.getValue(); if (value == null || value.equals("")) { throw new VmidcBrokerInvalidEntryException(field + " should not have an empty value."); } } } static void checkForNullFields(Map<String, Object> map); static void validateFieldsAreNull(Map<String, Object> map); static void checkForValidIpAddressFormat(String ipAddress); static boolean validateDaName(String name); static void validateFieldLength(Map<String, String> map, int maxLen); static void checkForValidEmailAddress(String email); static void checkForValidUsername(String username); static void checkForValidPassword(String password); static void checkForValidFqdn(String smtpServer); static void checkForValidPortNumber(String port); static void checkMarkedForDeletion(IscEntity entity, String name); static boolean isEmpty(Collection<?> collection); @Override void checkValidIpAddress(String value); @Override void checkValidPassword(String value); @Override boolean isValidDaName(String string); static final int DEFAULT_MAX_LEN; }
|
@Test public void testCheckForNullFields() { HashMap<String, Object> map = new HashMap<>(); map.put("foo", new Object()); map.put("foo1", new Object()); map.put("foo2", new Object()); map.put("foo3", new Object()); try { ValidateUtil.checkForNullFields(map); } catch (VmidcBrokerInvalidEntryException e) { fail("Error in checkForNullFields. No fields are null and exception happens"); } map.clear(); map.put("foo", new Object()); map.put("foo1", null); map.put("foo2", new Object()); map.put("foo3", new Object()); try { ValidateUtil.checkForNullFields(map); fail("Error in checkForNullFields, fields are null and exception does not happen"); } catch (VmidcBrokerInvalidEntryException e) { } }
|
ValidateUtil implements ValidationApi { public static boolean validateDaName(String name) { char ch = name.charAt(0); if (name.length() > 13 || name.length() < 1) { return false; } if (!(ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122)) { return false; } if (hasInvalidCharacters(name, new String[] {"-"})) { return false; } return true; } static void checkForNullFields(Map<String, Object> map); static void validateFieldsAreNull(Map<String, Object> map); static void checkForValidIpAddressFormat(String ipAddress); static boolean validateDaName(String name); static void validateFieldLength(Map<String, String> map, int maxLen); static void checkForValidEmailAddress(String email); static void checkForValidUsername(String username); static void checkForValidPassword(String password); static void checkForValidFqdn(String smtpServer); static void checkForValidPortNumber(String port); static void checkMarkedForDeletion(IscEntity entity, String name); static boolean isEmpty(Collection<?> collection); @Override void checkValidIpAddress(String value); @Override void checkValidPassword(String value); @Override boolean isValidDaName(String string); static final int DEFAULT_MAX_LEN; }
|
@Test public void testValidateDaName() { for(String item : validDaNames) { assertTrue(ValidateUtil.validateDaName(item)); } for(String item : invalidDaNames) { assertFalse(ValidateUtil.validateDaName(item)); } }
|
ValidateUtil implements ValidationApi { public static void validateFieldLength(Map<String, String> map, int maxLen) throws VmidcBrokerInvalidEntryException { for (Entry<String, String> entry : map.entrySet()) { String field = entry.getKey(); String value = entry.getValue(); if (value != null && value.length() > maxLen) { throw new VmidcBrokerInvalidEntryException(field + " length should not exceed " + maxLen + " characters. The provided field exceeds this limit by " + (value.length() - maxLen) + " characters."); } } } static void checkForNullFields(Map<String, Object> map); static void validateFieldsAreNull(Map<String, Object> map); static void checkForValidIpAddressFormat(String ipAddress); static boolean validateDaName(String name); static void validateFieldLength(Map<String, String> map, int maxLen); static void checkForValidEmailAddress(String email); static void checkForValidUsername(String username); static void checkForValidPassword(String password); static void checkForValidFqdn(String smtpServer); static void checkForValidPortNumber(String port); static void checkMarkedForDeletion(IscEntity entity, String name); static boolean isEmpty(Collection<?> collection); @Override void checkValidIpAddress(String value); @Override void checkValidPassword(String value); @Override boolean isValidDaName(String string); static final int DEFAULT_MAX_LEN; }
|
@Test public void testValidateFieldLength() { HashMap<String, String> map = new HashMap<>(); map.put("foo1", "foo_value1"); map.put("foo2", "foo_value2_longer"); map.put("foo3", "foo_"); map.put("foo4", "foo_value4_veryLong_value"); try { ValidateUtil.validateFieldLength(map, 30); } catch (VmidcBrokerInvalidEntryException e) { fail("Error in validateFieldLength"); } map.clear(); map.put("foo1", "foo_value1"); map.put("foo2", "foo_value2_longer"); map.put("foo3", "foo_"); map.put("foo4", "foo_value4_veryLong_value"); try { ValidateUtil.validateFieldLength(map, 11); fail("Error in validateFieldLength, We should not get here"); } catch (VmidcBrokerInvalidEntryException e) { } }
|
ValidateUtil implements ValidationApi { public static void checkForValidEmailAddress(String email) throws VmidcBrokerInvalidEntryException { String pattern = "^([a-zA-Z0-9_\\.\\-+])+@(([a-zA-Z0-9-])+\\.)+([a-zA-Z0-9]{2,4})+$"; if (!email.matches(pattern)) { throw new VmidcBrokerInvalidEntryException("Email: " + email + " has invalid format."); } } static void checkForNullFields(Map<String, Object> map); static void validateFieldsAreNull(Map<String, Object> map); static void checkForValidIpAddressFormat(String ipAddress); static boolean validateDaName(String name); static void validateFieldLength(Map<String, String> map, int maxLen); static void checkForValidEmailAddress(String email); static void checkForValidUsername(String username); static void checkForValidPassword(String password); static void checkForValidFqdn(String smtpServer); static void checkForValidPortNumber(String port); static void checkMarkedForDeletion(IscEntity entity, String name); static boolean isEmpty(Collection<?> collection); @Override void checkValidIpAddress(String value); @Override void checkValidPassword(String value); @Override boolean isValidDaName(String string); static final int DEFAULT_MAX_LEN; }
|
@Test public void testCheckForValidEmailAddress() { for (String item : validEmails) { try { ValidateUtil.checkForValidEmailAddress(item); } catch (VmidcBrokerInvalidEntryException e) { fail("Error in checkForValidEmailAddress. " + item + " Is a valid email address."); } } for (String item : invalidEmails) { try { ValidateUtil.checkForValidEmailAddress(item); fail("Error in checkForValidEmailAddress. " + item + " Is a not a valid email address."); } catch (VmidcBrokerInvalidEntryException e) { } } }
|
ValidateUtil implements ValidationApi { public static void checkForValidIpAddressFormat(String ipAddress) throws VmidcBrokerInvalidEntryException { if (!InetAddresses.isInetAddress(ipAddress)) { throw new VmidcBrokerInvalidEntryException("IP Address: '" + ipAddress + "' has invalid format."); } } static void checkForNullFields(Map<String, Object> map); static void validateFieldsAreNull(Map<String, Object> map); static void checkForValidIpAddressFormat(String ipAddress); static boolean validateDaName(String name); static void validateFieldLength(Map<String, String> map, int maxLen); static void checkForValidEmailAddress(String email); static void checkForValidUsername(String username); static void checkForValidPassword(String password); static void checkForValidFqdn(String smtpServer); static void checkForValidPortNumber(String port); static void checkMarkedForDeletion(IscEntity entity, String name); static boolean isEmpty(Collection<?> collection); @Override void checkValidIpAddress(String value); @Override void checkValidPassword(String value); @Override boolean isValidDaName(String string); static final int DEFAULT_MAX_LEN; }
|
@Test public void testCheckForValidIpAddressFormat() { for (String item : validIps) { try { ValidateUtil.checkForValidIpAddressFormat(item); } catch (VmidcBrokerInvalidEntryException e) { fail("Error in checkForValidIpAddressFormat. " + item + " Is an invalid ip address."); } } for (String item : invalidIps) { try { ValidateUtil.checkForValidIpAddressFormat(item); fail("Error in checkForValidIpAddressFormat. " + item + " Is a not an invalid ip address."); } catch (VmidcBrokerInvalidEntryException e) { } } }
|
PKIUtil { public static void writeBytesToFile(byte[] bytes, String parentFolderName, String fileName) { StringBuilder sb = new StringBuilder(parentFolderName) .append(File.separator) .append(fileName); Path file = Paths.get(sb.toString()); Path backup = Paths.get(sb.append(".org").toString()); log.info("Start writing " + bytes.length + " bytes to file " + file); if(StringUtils.equals(String.valueOf(file.getFileName()),fileName)) { try { if (Files.exists(file)) { log.info("Renaming/backup existing file"); Files.move(file, backup, StandardCopyOption.REPLACE_EXISTING); } try { Files.write(file, bytes); log.info("Successfully wrote " + bytes.length + " bytes to file '" + file + "'"); } catch (Exception ex) { log.error("Failed to convert bytes to file", ex); if (Files.exists(backup)) { Files.move(backup, file, StandardCopyOption.REPLACE_EXISTING); } } Files.deleteIfExists(backup); } catch (Exception e) { log.error("Failed to write bytes to file" + file, e); } } else { log.warn("Filename: " + fileName + " is not valid"); } } static byte[] generateMD5Checksum(String fileName); static String toBase64EncodedString(byte[] bytes); static void writeInputStreamToFile(InputStream is, String parentFolderName, String fileName); static void writeBytesToFile(byte[] bytes, String parentFolderName, String fileName); static byte[] readBytesFromFile(File file); static byte[] generateKeyStore(); static boolean verifyKeyPair(byte[] keyStoreBytes, PublicKey pubKey); static PublicKey getPubKey(byte[] keyStoreBytes); static byte[] extractCertificate(byte[] keyStoreBytes); static byte[] extractPrivateKey(byte[] keyStoreBytes); }
|
@Test public void writeBytesToFile_fileNotExists_expectedSuccess() { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); PKIUtil.writeBytesToFile(FILE_TEXT.getBytes(), DIR_PATH, FILE_NAME); Assert.assertTrue("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.succesMessageBytes, logs.toString().contains(this.succesMessageBytes)); Assert.assertFalse("Logs should not contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeBytesToFile_fileExists_expectedSuccess() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); Files.write(file, FILE_TEXT.getBytes()); PKIUtil.writeBytesToFile(FILE_TEXT.getBytes(), DIR_PATH, FILE_NAME); Assert.assertTrue("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.succesMessageBytes, logs.toString().contains(this.succesMessageBytes)); Assert.assertTrue("Logs should contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeBytesToFile_fileNotExists_expectedFailOnMoveFileToBackup() throws Exception { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(INVALID_DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); PKIUtil.writeBytesToFile(FILE_TEXT.getBytes(), INVALID_DIR_PATH, FILE_NAME); Assert.assertFalse("File should not exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.failedMessageBytes, logs.toString().contains(this.failedMessageBytes)); Assert.assertFalse("Logs should contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeBytesToFile_fileNotExistsAndPathTraversalInFileName_expectedFail() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME_WITH_TRAVERSAL); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME_WITH_TRAVERSAL + ".org"); Writer logs = getLogs(); PKIUtil.writeBytesToFile(FILE_TEXT.getBytes(), DIR_PATH, FILE_NAME_WITH_TRAVERSAL); Assert.assertFalse("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertFalse("Logs should contatin message: " + this.succesMessageInputStream, logs.toString().contains(this.succesMessageInputStream)); Assert.assertFalse("Logs should not contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); Assert.assertTrue("Logs should contatin message: " + this.traversalMessage, logs.toString().contains(this.traversalMessage)); }
|
PKIUtil { public static void writeInputStreamToFile(InputStream is, String parentFolderName, String fileName) { StringBuilder sb = new StringBuilder(parentFolderName) .append(File.separator) .append(fileName); Path file = Paths.get(sb.toString()); Path backup = Paths.get(sb.append(".org").toString()); log.info("Start writing input stream to file: " + file); if(StringUtils.equals(String.valueOf(file.getFileName()),fileName)) { try { if (Files.exists(file)) { log.info("Renaming/backup existing file"); Files.move(file, backup, StandardCopyOption.REPLACE_EXISTING); } try { Files.copy(is, file); log.info("Successfully wrote input stream to file '" + file + "'"); } catch (Exception ex) { log.error("Failed to write input stream to file", ex); if (Files.exists(backup)) { Files.move(backup, file, StandardCopyOption.REPLACE_EXISTING); } } Files.deleteIfExists(backup); } catch (Exception e) { log.error("Failed to write input stream to file" + file, e); } } else { log.warn("Filename: " + fileName + " is not valid"); } } static byte[] generateMD5Checksum(String fileName); static String toBase64EncodedString(byte[] bytes); static void writeInputStreamToFile(InputStream is, String parentFolderName, String fileName); static void writeBytesToFile(byte[] bytes, String parentFolderName, String fileName); static byte[] readBytesFromFile(File file); static byte[] generateKeyStore(); static boolean verifyKeyPair(byte[] keyStoreBytes, PublicKey pubKey); static PublicKey getPubKey(byte[] keyStoreBytes); static byte[] extractCertificate(byte[] keyStoreBytes); static byte[] extractPrivateKey(byte[] keyStoreBytes); }
|
@Test public void writeInputStreamToFile_fileNotExists_expectedSuccess() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); PKIUtil.writeInputStreamToFile(IOUtils.toInputStream(FILE_TEXT, "UTF-8"), DIR_PATH, FILE_NAME); Assert.assertTrue("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.succesMessageInputStream, logs.toString().contains(this.succesMessageInputStream)); Assert.assertFalse("Logs should not contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeInputStreamToFile_fileExists_expectedSuccess() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); Files.write(file, FILE_TEXT.getBytes()); PKIUtil.writeInputStreamToFile(IOUtils.toInputStream(FILE_TEXT, "UTF-8"), DIR_PATH, FILE_NAME); Assert.assertTrue("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.succesMessageInputStream, logs.toString().contains(this.succesMessageInputStream)); Assert.assertTrue("Logs should contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeInputStreamToFile_fileNotExists_expectedFailOnMoveFileToBackup() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME); Path backup = Paths.get(INVALID_DIR_PATH + File.separator + FILE_NAME + ".org"); Writer logs = getLogs(); PKIUtil.writeInputStreamToFile(IOUtils.toInputStream(FILE_TEXT, "UTF-8"), INVALID_DIR_PATH, FILE_NAME); Assert.assertFalse("File should not exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertTrue("Logs should contatin message: " + this.failedMessageInputStream, logs.toString().contains(this.failedMessageInputStream)); Assert.assertFalse("Logs should contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); }
@Test public void writeInputStreamToFile_fileNotExistsAndPathTraversalInFileName_expectedFail() throws IOException { Path file = Paths.get(DIR_PATH + File.separator + FILE_NAME_WITH_TRAVERSAL); Path backup = Paths.get(DIR_PATH + File.separator + FILE_NAME_WITH_TRAVERSAL + ".org"); Writer logs = getLogs(); PKIUtil.writeInputStreamToFile(IOUtils.toInputStream(FILE_TEXT, "UTF-8"), DIR_PATH, FILE_NAME_WITH_TRAVERSAL); Assert.assertFalse("File should exist: " + file, Files.exists(file)); Assert.assertFalse("File should not exist: " + file, Files.exists(backup)); Assert.assertFalse("Logs should contatin message: " + this.succesMessageInputStream, logs.toString().contains(this.succesMessageInputStream)); Assert.assertFalse("Logs should not contatin message: " + this.renameMesage, logs.toString().contains(this.renameMesage)); Assert.assertTrue("Logs should contatin message: " + this.traversalMessage, logs.toString().contains(this.traversalMessage)); }
|
EncryptionUtil implements EncryptionApi { static String encryptPbkdf2(String plainText) throws EncryptionException { return new PBKDF2Derivation().derive(plainText); } @Override byte[] encryptAESGCM(byte[] plainText, SecretKey key, byte[] iv, byte[] aad); @Override byte[] decryptAESGCM(byte[] cipherText, SecretKey key, byte[] iv, byte[] aad); @Override String encryptAESCTR(String plainText); @Override String decryptAESCTR(String cipherText); @Override boolean validateAESCTR(String plainText, String validCipherText); @Override @Deprecated // DESDecryption is used only to support legacy upgrade purposes String decryptDES(String cipherText); static final String SECURITY_PROPS_RESOURCE_PATH; }
|
@Test public void testEncryptPbkdf2_WithValidMessage_ExpectsPbkdf2Hash() throws EncryptionException { String encryption = EncryptionUtil.encryptPbkdf2(this.unEncryptedMessage); assertTrue(encryption.startsWith("4000")); assertEquals(encryption.length(), 102); }
@Test public void testEncryptPbkdf2_WithEmptyMessage_ExpectsEmptyMessage() throws EncryptionException { String encryption = EncryptionUtil.encryptPbkdf2(""); assertEquals("", encryption); }
@Test public void testEncryptPbkdf2_WithNullMessage_ExpectsNull() throws EncryptionException { String encryption = EncryptionUtil.encryptPbkdf2(null); assertEquals(null, encryption); }
|
EncryptionUtil implements EncryptionApi { @Override public String encryptAESCTR(String plainText) throws EncryptionException { return new AESCTREncryption().encrypt(plainText); } @Override byte[] encryptAESGCM(byte[] plainText, SecretKey key, byte[] iv, byte[] aad); @Override byte[] decryptAESGCM(byte[] cipherText, SecretKey key, byte[] iv, byte[] aad); @Override String encryptAESCTR(String plainText); @Override String decryptAESCTR(String cipherText); @Override boolean validateAESCTR(String plainText, String validCipherText); @Override @Deprecated // DESDecryption is used only to support legacy upgrade purposes String decryptDES(String cipherText); static final String SECURITY_PROPS_RESOURCE_PATH; }
|
@Test public void testEncryptAesCtr_WithValidMessage_ExpectsAesCtrHash() throws Exception { String encryption = new EncryptionUtil().encryptAESCTR(this.unEncryptedMessage); assertEquals(encryption.substring(32,33), ":"); assertEquals(encryption.length(), 53); }
@Test public void testEncryptAesCtr_WithEmptyMessage_ExpectsEmptyMessage() throws EncryptionException { String encryption = new EncryptionUtil().encryptAESCTR(""); assertEquals("", encryption); }
@Test public void testEncryptAesCtr_WithNullMessage_ExpectsNull() throws EncryptionException { String encryption = new EncryptionUtil().encryptAESCTR(null); assertEquals(null, encryption); }
|
KubernetesDeploymentApi extends KubernetesApi { public void deleteDeployment(String uid, String namespace, String name) throws VmidcException { if (uid == null) { throw new IllegalArgumentException("Uid should not be null"); } if (name == null) { throw new IllegalArgumentException("Name should not be null"); } if (namespace == null) { throw new IllegalArgumentException("Namespace should not be null"); } KubernetesDeployment deployment = getDeploymentById(uid, namespace, name); if (deployment == null) { LOG.info(String.format("The deployment with id %s, name %s and namespace %s was not found. Nothing to do.", uid, name, namespace)); return; } try { getKubernetesClient().resource(deployment.getDeploymentResource()).delete(); } catch (KubernetesClientException e) { throw new VmidcException("Failed to delete the deployment"); } } KubernetesDeploymentApi(KubernetesClient client); KubernetesDeployment getDeploymentById(String uid, String namespace, String name); void deleteDeployment(String uid, String namespace, String name); void updateDeploymentReplicaCount(String uid, String namespace, String name, int replicaCount); String createDeployment(KubernetesDeployment deployment); final static String OSC_DEPLOYMENT_LABEL_NAME; }
|
@Test public void testDeleteDeployment_WhenK8ClientThrowsKubernetesClientException_ThrowsVmidcException() throws Exception { this.exception.expect(VmidcException.class); when(this.extensionsApiMock.deployments()).thenThrow(new KubernetesClientException("")); this.deploymentApi.deleteDeployment("1234", "sample_name", "sample_label"); }
@Test public void testDeleteDeployment_WhenK8sReturnsNull_DoesNothing() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); mockDeploymentByName(namespace, name, null); this.deploymentApi.deleteDeployment(UUID.randomUUID().toString(), namespace, name); verify(this.deploymentMock, never()).delete(); }
@Test public void testDeleteDeployment_WhenK8sReturnsDeploymentWithMismatchingId_DoesNothing() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); mockDeploymentByName(namespace, name, newDeployment(UUID.randomUUID().toString(), name, namespace, 1, "image-sample-name")); this.deploymentApi.deleteDeployment(UUID.randomUUID().toString(), namespace, name); verify(this.deploymentMock, never()).delete(); }
@Test public void testDelete_WhenK8sReturnsDeploymentWithMatchingId_ResourceDeleted() throws Exception { String name = UUID.randomUUID().toString(); String namespace = UUID.randomUUID().toString(); String uid = UUID.randomUUID().toString(); Deployment deployment = newDeployment(uid, namespace, name, 1, "image-sample-name"); mockDeploymentByName(namespace, name, deployment); this.deploymentApi.deleteDeployment(uid, namespace, name); verify(this.deploymentMock, times(1)).delete(); }
|
EncryptionUtil implements EncryptionApi { @Override public String decryptAESCTR(String cipherText) throws EncryptionException { return new AESCTREncryption().decrypt(cipherText); } @Override byte[] encryptAESGCM(byte[] plainText, SecretKey key, byte[] iv, byte[] aad); @Override byte[] decryptAESGCM(byte[] cipherText, SecretKey key, byte[] iv, byte[] aad); @Override String encryptAESCTR(String plainText); @Override String decryptAESCTR(String cipherText); @Override boolean validateAESCTR(String plainText, String validCipherText); @Override @Deprecated // DESDecryption is used only to support legacy upgrade purposes String decryptDES(String cipherText); static final String SECURITY_PROPS_RESOURCE_PATH; }
|
@Test public void testDecryptAesCtr_WithValidMessage_ExpectsDecryptedMessage() throws EncryptionException { String decryption = new EncryptionUtil().decryptAESCTR(this.aesCtrEncryptedMessage); assertEquals(this.unEncryptedMessage, decryption); }
@Test public void testDecryptAesCtr_WithNullMessage_ExpectsNull() throws EncryptionException { String decryption = new EncryptionUtil().decryptAESCTR(null); assertEquals(null, decryption); }
@Test public void testDecryptAesCtr_WithEmptyMessage_ExpectsEmptyMessage() throws EncryptionException { String decryption = new EncryptionUtil().decryptAESCTR(""); assertEquals("", decryption); }
|
EncryptionUtil implements EncryptionApi { @Override public byte[] encryptAESGCM(byte[] plainText, SecretKey key, byte[] iv, byte[] aad) throws EncryptionException { return new AESGCMEncryption().encrypt(plainText, key, iv, aad); } @Override byte[] encryptAESGCM(byte[] plainText, SecretKey key, byte[] iv, byte[] aad); @Override byte[] decryptAESGCM(byte[] cipherText, SecretKey key, byte[] iv, byte[] aad); @Override String encryptAESCTR(String plainText); @Override String decryptAESCTR(String cipherText); @Override boolean validateAESCTR(String plainText, String validCipherText); @Override @Deprecated // DESDecryption is used only to support legacy upgrade purposes String decryptDES(String cipherText); static final String SECURITY_PROPS_RESOURCE_PATH; }
|
@Test public void testEncryptAESGCM_withValidInputParameters_encryptionSucceeds() throws EncryptionException { byte[] encrypted = new EncryptionUtil().encryptAESGCM(this.plainText, this.key, this.iv, this.aad); assertEquals(this.plainText.length + 16 , encrypted.length); assertFalse(Arrays.equals(this.plainText, Arrays.copyOfRange(encrypted, 0, this.plainText.length))); }
@Test public void testEncryptAESGCM_withNullPlainText_throwsEncryptionException() throws EncryptionException { byte[] plainText = null; this.exception.expect(EncryptionException.class); new EncryptionUtil().encryptAESGCM(plainText, this.key, this.iv, this.aad); }
@Test public void testEncryptAESGCM_withEmptyPlainText_encryptionSucceeds() throws EncryptionException { byte[] plainText = new byte[0]; byte[] encrypted = new EncryptionUtil().encryptAESGCM(plainText, this.key, this.iv, this.aad); assertEquals(16 , encrypted.length); }
@Test public void testEncryptAESGCM_withNullKey_throwsEncryptionException() throws EncryptionException { SecretKey key = null; this.exception.expect(EncryptionException.class); new EncryptionUtil().encryptAESGCM(this.plainText, key, this.iv, this.aad); }
@Test public void testEncryptAESGCM_withNullIV_throwsEncryptionException() throws EncryptionException { byte[] iv = null; this.exception.expect(EncryptionException.class); new EncryptionUtil().encryptAESGCM(this.plainText, this.key, iv, this.aad); }
@Test public void testEncryptAESGCM_withInvalidIVLength_throwsEncryptionException() throws EncryptionException { byte[] iv = "123456789".getBytes(); this.exception.expect(EncryptionException.class); new EncryptionUtil().encryptAESGCM(this.plainText, this.key, iv, this.aad); }
|
AuthUtil { public void authenticate(ContainerRequestContext request, String validUserName, String validPass) { authenticate(request, ImmutableMap.of(validUserName, validPass)); } void authenticate(ContainerRequestContext request, String validUserName, String validPass); void authenticate(ContainerRequestContext request, Map<String, String> usernamePasswordMap); void authenticateLocalRequest(ContainerRequestContext request); }
|
@Test(expected = WebApplicationException.class) public void testAuthenticateMissingAuthorization() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn(null); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
@Test(expected = WebApplicationException.class) public void testAuthenticateInvalidTokensNull() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn(""); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
@Test(expected = WebApplicationException.class) public void testAuthenticateInvalidTokensLength() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn("abc\\s+xyz\\+s"); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
@Test(expected = WebApplicationException.class) public void testAuthenticateInvalidTokensBasic() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn("BASIC1\\+s"); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
@Test(expected = WebApplicationException.class) public void testInvalidCredentials() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn("Basic YWRtaW4xOmFkbWluMTIzNDU="); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
@Test public void validAuthenticate() { Mockito.when(this.mockRequest.getHeaderString("Authorization")).thenReturn("Basic YWRtaW46YWRtaW4xMjM="); this.authUtil.authenticate(this.mockRequest, USER, ENCRYPTED_PASSWORD); }
|
AuthUtil { public void authenticateLocalRequest(ContainerRequestContext request) { WebApplicationException wae = new WebApplicationException( Response.status(Response.Status.UNAUTHORIZED).entity("not authorized").build()); if(request.getUriInfo()!=null && request.getUriInfo().getRequestUri()!=null) { String remoteAddr = request.getUriInfo().getRequestUri().getHost(); if (remoteAddr == null || !(remoteAddr.equals("127.0.0.1") || remoteAddr.equals("localhost"))) { throw wae; } } else { throw wae; } } void authenticate(ContainerRequestContext request, String validUserName, String validPass); void authenticate(ContainerRequestContext request, Map<String, String> usernamePasswordMap); void authenticateLocalRequest(ContainerRequestContext request); }
|
@Test(expected = WebApplicationException.class) public void testAuthenticateLocalRequestMissing() { this.authUtil.authenticateLocalRequest(this.mockRequest); }
@Test(expected = WebApplicationException.class) public void testAuthenticateLocalInvalidAddress() throws URISyntaxException { Mockito.when(this.uriInfo.getRequestUri()).thenReturn(new URI("http: Mockito.when(this.mockRequest.getUriInfo()).thenReturn(this.uriInfo); this.authUtil.authenticateLocalRequest(this.mockRequest); }
@Test public void validAuthenticateLocalRequestByIp() throws URISyntaxException { Mockito.when(this.uriInfo.getRequestUri()).thenReturn(new URI("http: Mockito.when(this.mockRequest.getUriInfo()).thenReturn(this.uriInfo); this.authUtil.authenticateLocalRequest(this.mockRequest); }
@Test public void validAuthenticateLocalRequestByDomain() throws URISyntaxException { Mockito.when(this.uriInfo.getRequestUri()).thenReturn(new URI("http: Mockito.when(this.mockRequest.getUriInfo()).thenReturn(this.uriInfo); this.authUtil.authenticateLocalRequest(this.mockRequest); }
|
NetworkUtil { public static int getPrefixLength(String netmask) { if (!validNetMasks.contains(netmask)) { throw new IllegalArgumentException(netmask + " is not a valid netmask."); } String[] octets = netmask.split("\\."); int octet1 = Integer.parseInt(octets[0]); int octet2 = Integer.parseInt(octets[1]); int octet3 = Integer.parseInt(octets[2]); int octet4 = Integer.parseInt(octets[3]); int mask = Integer.bitCount(octet1) + Integer.bitCount(octet2) + Integer.bitCount(octet3) + Integer.bitCount(octet4); return mask; } static String getHostIpAddress(); static int getPrefixLength(String netmask); static String resolveIpToName(String ipAddress); }
|
@Test public void testGetPrefixLength() { List<Integer> prefixLength = Arrays.asList(32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); for (int i = 0; i < NetworkUtil.validNetMasks.size(); i++) { assertEquals(Integer.valueOf(NetworkUtil.getPrefixLength(NetworkUtil.validNetMasks.get(i))), prefixLength.get(i)); } List<String> invalidNetMasks = Arrays.asList("192.168.0.1", "foo", "127.0.0.1"); for (String invalidNetMask : invalidNetMasks) { try { NetworkUtil.getPrefixLength(invalidNetMask); fail("Expected to throw IllegalArgument exception"); } catch (IllegalArgumentException iae) { } } }
|
FileUtil { public static File[] getFileListFromDirectory(String directory) throws FileNotFoundException { if (directory == null) { throw new FileNotFoundException("Cannot obtain list of files from directory - null given"); } File fileDir = new File(directory); if (fileDir.exists()) { File[] listFiles = fileDir.listFiles(); if (listFiles != null) { return listFiles; } } return new File[0]; } static File[] getFileListFromDirectory(String directory); static Properties loadProperties(String propertiesFilePath); }
|
@Test public void testGetFileListFromDirectory_WithNullPath_ThrowsFileNotFound() throws FileNotFoundException { this.exception.expect(FileNotFoundException.class); this.exception.expectMessage("Cannot obtain list of files from directory - null given"); FileUtil.getFileListFromDirectory(null); }
@Test public void testGetFileListFromDirectory_WithAvailablePath_ReturnsList() throws IOException { cleanRegularFile(); populateTemporaryFolder(); File[] fileList = FileUtil.getFileListFromDirectory(this.homeDirectory.getAbsolutePath()); Assert.assertEquals("File list should contain all files", this.numberOfFilesInDirectory, fileList.length); for (File loadedFile : fileList) { Assert.assertTrue(loadedFile.getName().contains("test_")); } }
@Test public void testGetFileListFromDirectory_WithInvalidPath_ReturnsEmptyList() throws IOException { File[] fileList = FileUtil.getFileListFromDirectory("testInvalidDir"); Assert.assertEquals("File list should contain empty list", 0, fileList.length); }
|
FileUtil { public static Properties loadProperties(String propertiesFilePath) throws IOException { Properties prop = new Properties(); try (FileInputStream fileInputStream = new FileInputStream(propertiesFilePath)) { prop.load(fileInputStream); } return prop; } static File[] getFileListFromDirectory(String directory); static Properties loadProperties(String propertiesFilePath); }
|
@Test public void testLoadProperties_WithAvailableConfigFile_ReturnsLoadedConfigFile() throws IOException { Files.write(this.regularFile.toPath(), this.sampleConfigFile.getBytes(), StandardOpenOption.APPEND); Properties prop = FileUtil.loadProperties(this.regularFile.getAbsolutePath()); Assert.assertEquals("Different size of loaded properties file", 4, prop.size()); Assert.assertEquals("Improper value obtained from properties", "8666", prop.getProperty("server.port")); Assert.assertEquals("Improper value obtained from properties", "true", prop.getProperty("devMode")); Assert.assertEquals("Improper value obtained from properties", "0", prop.getProperty("server.reboots")); Assert.assertEquals("Improper value obtained from properties", "AUTO_SERVER=TRUE;", prop.getProperty("h2db.connection.url.extraArgs")); }
@Test public void testLoadProperties_WithUnavailableConfigFile_ThrowsIOException() throws IOException { File regularFile = new File(this.homeDirectory, this.CONFIG_FILE); if(this.regularFile.exists()){ boolean isDeleted = this.regularFile.delete(); Assert.assertTrue(isDeleted); } this.exception.expect(FileNotFoundException.class); Properties prop = FileUtil.loadProperties(regularFile.getAbsolutePath()); Assert.assertEquals("Different size of loaded properties file", 0, prop.size()); }
|
NetworkSettingsApi { String getIPv4LocalNetMask() { String netMask = ""; String[] cmd = { "/bin/sh", "-c", "ip addr show eth0 |grep inet|tr -s ' ' |cut -d' ' -f3" }; List<String> outlines = new ArrayList<>(); int exitCode = ServerUtil.execWithLog(cmd, outlines); if (exitCode != 0) { log.error("Encountered error during: {} execution", cmd); return null; } for(String line:outlines) { netMask = line; break; } return netMask; } NetworkSettingsDto getNetworkSettings(); }
|
@Test public void testGetIPv4LocalNetMask_With_IPCommand_ReturnNetMask() throws IOException { PowerMockito.mockStatic(ServerUtil.class); PowerMockito.when(ServerUtil.execWithLog(Matchers.anyString(), Matchers.anyList())).thenReturn(0); String netmask = this.networkSettingsApi.getIPv4LocalNetMask(); assertNotNull(netmask); }
|
NetworkSettingsApi { String getDefaultGateway() { String defaultGateway = ""; String[] cmd = { "/bin/sh", "-c", "ip route|grep default|tr -s ' ' |cut -d' ' -f3" }; List<String> outlines = new ArrayList<>(); int exitCode = ServerUtil.execWithLog(cmd, outlines); if (exitCode != 0) { log.error("Encountered error during: {} execution", cmd); return null; } for (String line:outlines) { defaultGateway = line; break; } return defaultGateway; } NetworkSettingsDto getNetworkSettings(); }
|
@Test public void testGetDefaultGateway_With_IPCommand_Exec_ReturnDefaultGateway() throws IOException { PowerMockito.mockStatic(ServerUtil.class); PowerMockito.when(ServerUtil.execWithLog(Matchers.anyString(), Matchers.anyList())).thenReturn(0); String defaultGateway = this.networkSettingsApi.getDefaultGateway(); assertNotNull(defaultGateway); }
|
ServerUtil { static void killProcess(String oldPid) throws InterruptedException { int retries = 10; boolean pidFound = false; while (retries > 0) { List<String> lines = new ArrayList<>(); ServerUtil.execWithLines("ps " + oldPid, lines); pidFound = false; for (String line : lines) { if (line.contains(oldPid)) { pidFound = true; break; } } if (!pidFound) { break; } log.info("Old process (" + oldPid + ") is still running. Retry (" + retries + ") wait for graceful termination."); retries--; Thread.sleep(500); } if (pidFound) { log.warn("Old process (" + oldPid + ") is still running. Triggering forceful termination."); ServerUtil.execWithLog("kill -9 " + oldPid); } } static long getUptime(); static String uptimeToString(); static String uptimeToString(long uptime); static Long getUsableDiscSpaceInGB(); static boolean isEnoughSpace(); static String getCurrentPid(); static boolean isWindows(); static void stopServerProcess(String pidFile); static void terminateProcessByPid(Integer pid); static void writePIDToFile(String filename); static void writePIDToFile(String filename, String pid); static String getPidByProcessName(String processName); static void deletePidFileIfOwned(String filename); static boolean startAgentProcess(); static boolean startAgentProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker,
boolean isRebootAfterFailure); static int execWithLog(String cmd); static int execWithLog(String[] cmd); static int execWithLog(String cmd, List<String> lines); static int execWithLog(String[] cmd, List<String> lines); static int execWithLog(String[] cmd, boolean logCommandLine); static int execWithLog(String[] cmd, List<String> lines, boolean logCommandLine); static int execWithLines(String cmd, List<String> outLines); static int execWithLines(String[] cmd, List<String> outLines, boolean logCommand); static String getServerIP(); static void setServerIP(String serverIP); static Thread getTimeMonitorThread(final TimeChangeCommand timeChangeCommand, final long timeChangeThreshold,
final long sleepInterval); }
|
@Test @SuppressWarnings("unchecked") public void testKillProcess_WithLongRunningProcessId_UsesForcedShutdown() throws Exception { final boolean[] testPassed = new boolean[1]; final List<String> gentleShutdownIterationsCounter = new ArrayList<>(); replace(method(ServerUtil.class, "execWithLines", String.class, List.class)).with( new InvocationHandler() { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { if (arguments[0].equals("ps " + ServerUtilTest.this.oldProcessId)) { List<String> test = (List<String>) arguments[1]; test.addAll(ServerUtilTest.this.cmdOutput); gentleShutdownIterationsCounter.add("invocation"); return 0; } else { return method.invoke(object, arguments); } } }); replaceExecWithLogMethod(this.oldProcessId, testPassed); ServerUtil.killProcess(this.oldProcessId); Assert.assertTrue(gentleShutdownIterationsCounter.size() == 10); Assert.assertTrue(testPassed[0]); }
@Test @SuppressWarnings("unchecked") public void testKillProcess_WithShortRunningProcessId_UsesGentleShutdown() throws Exception { final boolean[] testPassed = new boolean[1]; final List<String> gentleShutdownIterationsCounter = new ArrayList<>(); replace(method(ServerUtil.class, "execWithLines", String.class, List.class)).with( new InvocationHandler() { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { if (arguments[0].equals("ps " + ServerUtilTest.this.oldProcessId)) { if (gentleShutdownIterationsCounter.size() < 3) { List<String> test = (List<String>) arguments[1]; test.addAll(ServerUtilTest.this.cmdOutput); } gentleShutdownIterationsCounter.add("invocation"); return 0; } else { return method.invoke(object, arguments); } } }); replaceExecWithLogMethod(this.oldProcessId, testPassed); ServerUtil.killProcess(this.oldProcessId); Assert.assertTrue(gentleShutdownIterationsCounter.size() == 4); Assert.assertFalse(testPassed[0]); }
|
ServerUtil { public static String getPidByProcessName(String processName) { try { String psArg = ""; if (isWindows()) { psArg += "-W"; } Process p = java.lang.Runtime.getRuntime().exec("ps " + psArg); int exitVal = p.waitFor(); log.info("ps process terminated with exit code " + exitVal); try(InputStream inputStream = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){ String s; while ((s = reader.readLine()) != null) { s = s.trim(); log.debug(s); if (s.endsWith(processName)) { String pid = s.split(" +", -3)[0]; log.info("Found PID for " + processName + ": " + pid); return pid; } } } } catch (Exception e) { log.error("Fail to find process PID for '" + processName + "'", e); } return null; } static long getUptime(); static String uptimeToString(); static String uptimeToString(long uptime); static Long getUsableDiscSpaceInGB(); static boolean isEnoughSpace(); static String getCurrentPid(); static boolean isWindows(); static void stopServerProcess(String pidFile); static void terminateProcessByPid(Integer pid); static void writePIDToFile(String filename); static void writePIDToFile(String filename, String pid); static String getPidByProcessName(String processName); static void deletePidFileIfOwned(String filename); static boolean startAgentProcess(); static boolean startAgentProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker,
boolean isRebootAfterFailure); static int execWithLog(String cmd); static int execWithLog(String[] cmd); static int execWithLog(String cmd, List<String> lines); static int execWithLog(String[] cmd, List<String> lines); static int execWithLog(String[] cmd, boolean logCommandLine); static int execWithLog(String[] cmd, List<String> lines, boolean logCommandLine); static int execWithLines(String cmd, List<String> outLines); static int execWithLines(String[] cmd, List<String> outLines, boolean logCommand); static String getServerIP(); static void setServerIP(String serverIP); static Thread getTimeMonitorThread(final TimeChangeCommand timeChangeCommand, final long timeChangeThreshold,
final long sleepInterval); }
|
@Test public void testGetPidByProcessName_WithProperData_ReturnsProperProcessId() throws IOException, InterruptedException { InputStream stubInputStream = IOUtils.toInputStream( " PID TTY STAT TIME COMMAND\n 9990 ? Ss 0:07 /test/java\n " + this.oldProcessId + " ? Ss 0:07 /osc/java", Charset.defaultCharset()); PowerMockito.when(this.processMock.getInputStream()).thenReturn(stubInputStream); PowerMockito.when(this.runtimeMock.exec(Matchers.anyString())).thenReturn(this.processMock); Mockito.when(Runtime.getRuntime()).thenReturn(this.runtimeMock); String foundPid = ServerUtil.getPidByProcessName("/osc/java"); Assert.assertEquals(this.oldProcessId, foundPid); }
@Test public void testGetPidByProcessName_WithImproperData_ReturnsNothing() throws IOException, InterruptedException { InputStream stubInputStream = IOUtils.toInputStream( " PID TTY STAT TIME COMMAND\n 9990 ? Ss 0:07 /test/java\n " + this.oldProcessId + " ? Ss 0:07 /osc/java", Charset.defaultCharset()); PowerMockito.when(this.processMock.getInputStream()).thenReturn(stubInputStream); PowerMockito.when(this.runtimeMock.exec(this.linuxProcessExec)).thenReturn(this.processMock); Mockito.when(Runtime.getRuntime()).thenReturn(this.runtimeMock); String foundPid = ServerUtil.getPidByProcessName("/osc/test"); Assert.assertNull(foundPid); }
@Test public void testGetPidByProcessName_WithImproperData_ThrowsInputStreamException() throws IOException, InterruptedException { PowerMockito.when(this.processMock.getInputStream()).thenReturn(null); PowerMockito.when(this.runtimeMock.exec(this.linuxProcessExec)).thenReturn(this.processMock); Mockito.when(Runtime.getRuntime()).thenReturn(this.runtimeMock); String foundPid = ServerUtil.getPidByProcessName("/osc/java"); Assert.assertNull(foundPid); }
@Test public void testGetPidByProcessName_WithWindowsMachineFlag_ReturnsProperProcessId() throws IOException, InterruptedException { InputStream stubInputStream = IOUtils.toInputStream( " PID TTY STAT TIME COMMAND\n 9990 ? Ss 0:07 /test/java\n " + this.oldProcessId + " ? Ss 0:07 /osc/java", Charset.defaultCharset()); PowerMockito.when(this.processMock.getInputStream()).thenReturn(stubInputStream); PowerMockito.when(this.runtimeMock.exec(this.linuxProcessExec + "-W")).thenReturn(this.processMock); replace(method(ServerUtil.class, "isWindows")).with( new InvocationHandler() { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { return true; } }); Mockito.when(Runtime.getRuntime()).thenReturn(this.runtimeMock); String foundPid = ServerUtil.getPidByProcessName("/osc/java"); Assert.assertEquals("Process id is different than expected", this.oldProcessId, foundPid); }
|
ServerUtil { static Integer readPIDFromFile(String filename) throws CorruptedPidException { if (!new File(filename).exists()) { return null; } String PID = null; try (BufferedReader in = new BufferedReader(new FileReader(filename))){ PID = in.readLine(); } catch (IOException e) { log.debug("Fail to read process id from file", e); } return (PID != null) ? filterPidNumber(PID) : null; } static long getUptime(); static String uptimeToString(); static String uptimeToString(long uptime); static Long getUsableDiscSpaceInGB(); static boolean isEnoughSpace(); static String getCurrentPid(); static boolean isWindows(); static void stopServerProcess(String pidFile); static void terminateProcessByPid(Integer pid); static void writePIDToFile(String filename); static void writePIDToFile(String filename, String pid); static String getPidByProcessName(String processName); static void deletePidFileIfOwned(String filename); static boolean startAgentProcess(); static boolean startAgentProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker,
boolean isRebootAfterFailure); static int execWithLog(String cmd); static int execWithLog(String[] cmd); static int execWithLog(String cmd, List<String> lines); static int execWithLog(String[] cmd, List<String> lines); static int execWithLog(String[] cmd, boolean logCommandLine); static int execWithLog(String[] cmd, List<String> lines, boolean logCommandLine); static int execWithLines(String cmd, List<String> outLines); static int execWithLines(String[] cmd, List<String> outLines, boolean logCommand); static String getServerIP(); static void setServerIP(String serverIP); static Thread getTimeMonitorThread(final TimeChangeCommand timeChangeCommand, final long timeChangeThreshold,
final long sleepInterval); }
|
@Test public void testReadPIDFromFile_WithValidPIDFile_ReturnsNumericPID() throws IOException, CorruptedPidException { Files.write(this.regularFile.toPath(), "1000".getBytes(), StandardOpenOption.APPEND); Integer pidFromFile = ServerUtil.readPIDFromFile(this.regularFile.getPath()); Assert.assertTrue(Integer.valueOf(1000).equals(pidFromFile)); }
@Test public void testReadPIDFromFile_WithOverflowedPID_ThrowsCorruptedPidException() throws IOException, CorruptedPidException { Files.write(this.regularFile.toPath(), String.valueOf(Integer.MAX_VALUE).getBytes(), StandardOpenOption.APPEND); this.exception.expect(CorruptedPidException.class); ServerUtil.readPIDFromFile(this.regularFile.getPath()); }
@Test public void testReadPIDFromFile_WithCorruptedPID_ThrowsCorruptedPidException() throws IOException, CorruptedPidException { Files.write(this.regularFile.toPath(), "notnumber".getBytes(), StandardOpenOption.APPEND); this.exception.expect(CorruptedPidException.class); ServerUtil.readPIDFromFile(this.regularFile.getPath()); }
@Test public void testReadPIDFromFile_WithoutFile_ReturnsNull() throws IOException, CorruptedPidException { this.regularFile = new File(this.homeDirectory, this.PID_FILE); if (this.regularFile.exists()) { boolean isDeleted = this.regularFile.delete(); Assert.assertTrue(isDeleted); } Integer pidFromFile = ServerUtil.readPIDFromFile(this.regularFile.getPath()); Assert.assertNull(pidFromFile); }
|
ServerUtil { public static void deletePidFileIfOwned(String filename) { Integer filePid; try { filePid = readPIDFromFile(filename); } catch (CorruptedPidException e) { log.error("PID number is corrupted", e); return; } if (filePid != null) { String PID = String.valueOf(filePid); if (PID.equals(getCurrentPid())) { log.info("Pid from File " + filename + " Matches current pid. Deleting the PID."); new File(filename).delete(); } else { log.info("Pid: " + filePid + " Does not match current Pid: " + getCurrentPid() + " Assuming upgrade, Not deleting pid file:" + filename); } } } static long getUptime(); static String uptimeToString(); static String uptimeToString(long uptime); static Long getUsableDiscSpaceInGB(); static boolean isEnoughSpace(); static String getCurrentPid(); static boolean isWindows(); static void stopServerProcess(String pidFile); static void terminateProcessByPid(Integer pid); static void writePIDToFile(String filename); static void writePIDToFile(String filename, String pid); static String getPidByProcessName(String processName); static void deletePidFileIfOwned(String filename); static boolean startAgentProcess(); static boolean startAgentProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker); static boolean startServerProcess(int waitTimeout, ServerServiceChecker serverServiceChecker,
boolean isRebootAfterFailure); static int execWithLog(String cmd); static int execWithLog(String[] cmd); static int execWithLog(String cmd, List<String> lines); static int execWithLog(String[] cmd, List<String> lines); static int execWithLog(String[] cmd, boolean logCommandLine); static int execWithLog(String[] cmd, List<String> lines, boolean logCommandLine); static int execWithLines(String cmd, List<String> outLines); static int execWithLines(String[] cmd, List<String> outLines, boolean logCommand); static String getServerIP(); static void setServerIP(String serverIP); static Thread getTimeMonitorThread(final TimeChangeCommand timeChangeCommand, final long timeChangeThreshold,
final long sleepInterval); }
|
@Test public void testDeletePidFileIfOwned_WithProperPidFile_RemovesPIDFile() throws IOException { mockGetCurrentPid("1000"); Files.write(this.regularFile.toPath(), "1000".getBytes(), StandardOpenOption.APPEND); Assert.assertTrue(this.regularFile.exists()); ServerUtil.deletePidFileIfOwned(this.regularFile.getPath()); Assert.assertFalse(this.regularFile.exists()); }
@Test public void testDeletePidFileIfOwned_WithDifferentCurrentPid_PreservesPIDFile() throws IOException { mockGetCurrentPid("1100"); Files.write(this.regularFile.toPath(), "1000".getBytes(), StandardOpenOption.APPEND); Assert.assertTrue(this.regularFile.exists()); ServerUtil.deletePidFileIfOwned(this.regularFile.getPath()); Assert.assertTrue(this.regularFile.exists()); }
|
MessageTag extends TagSupport implements DynamicAttributes { public void setCode(String code) { this.code = code; } @Override int doStartTag(); void setCode(String code); void setCount(int count); void setSelector(String selector); void setArguments(Object arguments); void setHtmlEscape(Boolean htmlEscape); @Override void setDynamicAttribute(String uri, String name, Object value); }
|
@Test public void testWithNoArguments() throws Exception { String code = "test.code"; String message = "This is test message"; tag.setCode(code); when(localization.getMessage(code)).thenReturn(message); renderTag(); verify(jspWriter).write(message); }
@Test public void testWithNullMessage() throws Exception { String code = "test.code"; tag.setCode(code); when(localization.getMessage(code)).thenReturn(null); renderTag(); verify(jspWriter).write("null"); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Boolean getBoolean(String key) { return getPropertyResolver().getBoolean(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetBoolean() throws Exception { String key = "boolean.key"; Boolean value = Boolean.TRUE; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getBoolean(key)).thenReturn(value); Boolean result = localizationProvider.getBoolean(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getBoolean(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Integer getInteger(String key) { return getPropertyResolver().getInteger(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetInteger() throws Exception { String key = "integer.key"; Integer value = Integer.MAX_VALUE; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getInteger(key)).thenReturn(value); Integer result = localizationProvider.getInteger(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getInteger(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Long getLong(String key) { return getPropertyResolver().getLong(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetLong() throws Exception { String key = "long.key"; Long value = Long.MIN_VALUE; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getLong(key)).thenReturn(value); Long result = localizationProvider.getLong(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getLong(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Float getFloat(String key) { return getPropertyResolver().getFloat(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetFloat() throws Exception { String key = "float.key"; Float value = Float.MIN_VALUE; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getFloat(key)).thenReturn(value); Float result = localizationProvider.getFloat(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getFloat(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Double getDouble(String key) { return getPropertyResolver().getDouble(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetDouble() throws Exception { String key = "double.key"; Double value = Double.MAX_VALUE; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getDouble(key)).thenReturn(value); Double result = localizationProvider.getDouble(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getDouble(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public List<String> getStringList(String key) { return getPropertyResolver().getStringList(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetStringList() throws Exception { String key = "string.list.key"; List<String> value = Arrays.asList("Saturday", "Sunday"); LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getStringList(key)).thenReturn(value); List<String> result = localizationProvider.getStringList(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getStringList(key); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public Map<String, String> getStringMap(String key) { return getPropertyResolver().getStringMap(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test public void testGetStringMap() throws Exception { String key = "boolean.key"; Map<String, String> value = new HashMap<String, String>(); value.put("red", "#FF0000"); value.put("cyan", "#00FFFF"); value.put("white", "#FFFFFF"); value.put("black", "#000000"); value = Collections.unmodifiableMap(value); LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getStringMap(key)).thenReturn(value); Map<String, String> result = localizationProvider.getStringMap(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getStringMap(key); inOrder.verifyNoMoreInteractions(); }
|
PluralRuleProvider { public PluralRule getPluralRule(String languageCode) { checkNotNull(languageCode); if (languageCode.isEmpty()) { return DEFAULT_PLURAL_RULE; } Class<?> pluralClass = loadPluralClass(languageCode); if (pluralClass == null) { return DEFAULT_PLURAL_RULE; } try { @SuppressWarnings("unchecked") PluralRule pluralRule = (PluralRule) pluralClass.newInstance(); return pluralRule; } catch (InstantiationException e) { throw new LocalizationException(e); } catch (IllegalAccessException e) { throw new LocalizationException(e); } } PluralRule getPluralRule(String languageCode); }
|
@Test public void testGetPluralRuleWithUnknownLanguageCode() throws Exception { PluralRule pluralRule = pluralRuleProvider.getPluralRule("blablabla"); assertThat(pluralRule).isNotNull().isInstanceOf(DefaultPluralRule.class); }
@Test public void testGetPluralRuleWithEmptyLanguageCode() throws Exception { PluralRule pluralRule = pluralRuleProvider.getPluralRule(""); assertThat(pluralRule).isNotNull().isInstanceOf(DefaultPluralRule.class); }
@Test(expected = NullPointerException.class) public void testGetPluralRuleWithNullLanguageCode() throws Exception { pluralRuleProvider.getPluralRule(null); }
@Test public void testGetPluralRuleWithValidLanguageCode() throws Exception { assertThat(pluralRuleProvider.getPluralRule("en")).isNotNull().isInstanceOf(PluralRule_en.class); assertThat(pluralRuleProvider.getPluralRule("es")).isNotNull().isInstanceOf(PluralRule_es.class); assertThat(pluralRuleProvider.getPluralRule("ru")).isNotNull().isInstanceOf(PluralRule_ru.class); assertThat(pluralRuleProvider.getPluralRule("shi")).isNotNull().isInstanceOf(PluralRule_shi.class); assertThat(pluralRuleProvider.getPluralRule("tig")).isNotNull().isInstanceOf(PluralRule_tig.class); }
|
DefaultMessageFormatFactory implements MessageFormatFactory { @Override public MessageFormat create(Locale locale, String format) { checkNotNull(locale); checkNotNull(format); return new ExtendedMessageFormat(format, locale, formatFactoryRegistry); } DefaultMessageFormatFactory(); @Override MessageFormat create(Locale locale, String format); }
|
@Test(expected = NullPointerException.class) public void testCreateWithNullLocale() throws Exception { messageFormatFactory.create(null, "Test"); }
@Test(expected = NullPointerException.class) public void testCreateWithNullFormat() throws Exception { messageFormatFactory.create(Locale.ITALY, null); }
@Test public void testDefaultWithString() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "My name is {0}"); String result = messageFormat.format(new Object[]{"Tamerlan"}); assertThat(result).isNotNull().isEqualTo("My name is Tamerlan"); }
@Test public void testDefaultWithInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "I am {0} years old"); String result = messageFormat.format(new Object[]{3}); assertThat(result).isNotNull().isEqualTo("I am 3 years old"); }
@Test public void testDefaultWithDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "My weight is {0} lb"); String result = messageFormat.format(new Object[]{15.3753}); assertThat(result).isNotNull().isEqualTo("My weight is 15.375 lb"); }
@Test public void testDefaultWithDate() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "Now is {0}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 2/5/13 8:47 PM"); }
@Test public void testDefaultWithAnyObject() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "Weekends: {0}"); String result = messageFormat.format(new Object[]{Arrays.asList("Sunday", "Saturday")}); assertThat(result).isNotNull().isEqualTo("Weekends: [Sunday, Saturday]"); }
@Test public void testTimeWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, time}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47:23"); }
@Test public void testTimeWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, time, short}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47"); }
@Test public void testTimeWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, time, medium}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 8:47:23 PM"); }
@Test public void testTimeWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, time, long}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 8:47:23 PM " + TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)); }
@Test public void testTimeWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, time, full}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 20.47.23 " + TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)); }
@Test public void testTimeWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, HH:mm:ss}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47:23"); }
@Test public void testDateWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, date}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 5 févr. 2013"); }
@Test public void testDateWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, date, short}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 05/02/13"); }
@Test public void testDateWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, date, medium}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is Feb 5, 2013"); }
@Test public void testDateWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, date, long}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is February 5, 2013"); }
@Test public void testDateWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, date, full}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is martedì 5 febbraio 2013"); }
@Test public void testDateWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, yyyy-MM-dd}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05"); }
@Test public void testDateTimeWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, datetime}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 5 févr. 2013 20:47:23"); }
@Test public void testDateTimeWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, datetime, short}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 05/02/13 20:47"); }
@Test public void testDateTimeWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, medium}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is Feb 5, 2013 8:47:23 PM"); }
@Test public void testDateTimeWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, long}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is February 5, 2013 8:47:23 PM " + TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)); }
@Test public void testDateTimeWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, datetime, full}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is martedì 5 febbraio 2013 20.47.23 " + TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)); }
@Test public void testDateTimeWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, yyyy-MM-dd HH:mm:ss}"); String result = messageFormat.format(new Object[]{createDate()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05 20:47:23"); }
@Test public void testJodaTimeWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, time}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47:23.037"); }
@Test public void testJodaTimeWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, time, short}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47"); }
@Test public void testJodaTimeWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, time, medium}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 8:47:23 PM"); }
@Test public void testJodaTimeWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, time, long}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 8:47:23 PM "); }
@Test public void testJodaTimeWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, time, full}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 20.47.23 "); }
@Test public void testJodaTimeWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, HH:mm:ss}"); String result = messageFormat.format(new Object[]{createJodaTime()}); assertThat(result).isNotNull().isEqualTo("Now is 20:47:23"); }
@Test public void testJodaDateWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, date}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05"); }
@Test public void testJodaDateWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, date, short}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is 05/02/13"); }
@Test public void testJodaDateWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, date, medium}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is Feb 5, 2013"); }
@Test public void testJodaDateWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, date, long}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is February 5, 2013"); }
@Test public void testJodaDateWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, date, full}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is martedì 5 febbraio 2013"); }
@Test public void testJodaDateWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, yyyy-MM-dd}"); String result = messageFormat.format(new Object[]{createJodaDate()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05"); }
@Test public void testJodaDateTimeWithDefaultStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, datetime}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05T20:47:23.037Z"); }
@Test public void testJodaDateTimeWithShortStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.FRENCH, "Now is {0, datetime, short}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is 05/02/13 20:47"); }
@Test public void testJodaDateTimeWithMediumStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, medium}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is Feb 5, 2013 8:47:23 PM"); }
@Test public void testJodaDateTimeWithLongStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, long}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is February 5, 2013 8:47:23 PM UTC"); }
@Test public void testJodaDateTimeWithFullStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ITALY, "Now is {0, datetime, full}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is martedì 5 febbraio 2013 20.47.23 UTC"); }
@Test public void testJodaDateTimeWithCustomStyle() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "Now is {0, datetime, yyyy-MM-dd HH:mm:ss}"); String result = messageFormat.format(new Object[]{createJodaDateTime()}); assertThat(result).isNotNull().isEqualTo("Now is 2013-02-05 20:47:23"); }
@Test public void testNumberWithDefaultStyleAndInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number} lb"); String result = messageFormat.format(new Object[]{10003}); assertThat(result).isNotNull().isEqualTo("10,003 lb"); }
@Test public void testNumberWithDefaultStyleAndDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number} lb"); String result = messageFormat.format(new Object[]{10003.751}); assertThat(result).isNotNull().isEqualTo("10,003.751 lb"); }
@Test public void testNumberWithDefaultStyleAndBigDecimal() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number} lb"); String result = messageFormat.format(new Object[]{BigDecimal.valueOf(10001375, 3)}); assertThat(result).isNotNull().isEqualTo("10,001.375 lb"); }
@Test public void testNumberWithIntegerStyleAndInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, integer} lb"); String result = messageFormat.format(new Object[]{10003}); assertThat(result).isNotNull().isEqualTo("10,003 lb"); }
@Test public void testNumberWithIntegerStyleAndDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, integer} lb"); String result = messageFormat.format(new Object[]{10003.75}); assertThat(result).isNotNull().isEqualTo("10,004 lb"); }
@Test public void testNumberWithIntegerStyleAndBigDecimal() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, integer} lb"); String result = messageFormat.format(new Object[]{BigDecimal.valueOf(10001375, 3)}); assertThat(result).isNotNull().isEqualTo("10,001 lb"); }
@Test public void testNumberWithCurrencyStyleAndInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "{0, number, currency}/lb"); String result = messageFormat.format(new Object[]{10003}); assertThat(result).isNotNull().isEqualTo("$10,003.00/lb"); }
@Test public void testNumberWithCurrencyStyleAndDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "{0, number, currency}/lb"); String result = messageFormat.format(new Object[]{10003.751}); assertThat(result).isNotNull().isEqualTo("$10,003.75/lb"); }
@Test public void testNumberWithCurrencyStyleAndBigDecimal() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.US, "{0, number, currency}/lb"); String result = messageFormat.format(new Object[]{BigDecimal.valueOf(10001375, 3)}); assertThat(result).isNotNull().isEqualTo("$10,001.38/lb"); }
@Test public void testNumberWithPercentStyleAndInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, percent} of lb"); String result = messageFormat.format(new Object[]{79}); assertThat(result).isNotNull().isEqualTo("7,900% of lb"); }
@Test public void testNumberWithPercentStyleAndDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, percent} of lb"); String result = messageFormat.format(new Object[]{0.751}); assertThat(result).isNotNull().isEqualTo("75% of lb"); }
@Test public void testNumberWithPercentStyleAndBigDecimal() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number, percent} of lb"); String result = messageFormat.format(new Object[]{BigDecimal.valueOf(333, 3)}); assertThat(result).isNotNull().isEqualTo("33% of lb"); }
@Test public void testNumberWithCustomStyleAndInteger() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number,#,##.000} lb"); String result = messageFormat.format(new Object[]{10003}); assertThat(result).isNotNull().isEqualTo("1,00,03.000 lb"); }
@Test public void testNumberWithCustomStyleAndDouble() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number,#,##.000} lb"); String result = messageFormat.format(new Object[]{10003.75}); assertThat(result).isNotNull().isEqualTo("1,00,03.750 lb"); }
@Test public void testNumberWithCustomStyleAndBigDecimal() throws Exception { MessageFormat messageFormat = messageFormatFactory.create(Locale.ENGLISH, "{0, number,#,##.000} lb"); String result = messageFormat.format(new Object[]{BigDecimal.valueOf(10001375, 3)}); assertThat(result).isNotNull().isEqualTo("1,00,01.375 lb"); }
|
LocalizationContextUtils { public static void setLocalization(ServletRequest servletRequest, Localization localization) { servletRequest.setAttribute(ATTRIBUTE_NAME, localization); } private LocalizationContextUtils(); static void setLocalization(ServletRequest servletRequest, Localization localization); static Localization getLocalization(ServletRequest servletRequest); static void setLocalization(ServletContext servletContext, Localization localization); static Localization getLocalization(ServletContext servletContext); }
|
@Test public void testSetLocalizationWithServletRequest() throws Exception { ServletRequest servletRequest = mock(ServletRequest.class); LocalizationContextUtils.setLocalization(servletRequest, localization); verify(servletRequest).setAttribute(ATTRIBUTE_NAME, localization); }
@Test public void testSetLocalizationWithServletContext() throws Exception { ServletContext servletContext = mock(ServletContext.class); LocalizationContextUtils.setLocalization(servletContext, localization); verify(servletContext).setAttribute(ATTRIBUTE_NAME, localization); }
|
LocalizationContextUtils { public static Localization getLocalization(ServletRequest servletRequest) { return (Localization) servletRequest.getAttribute(ATTRIBUTE_NAME); } private LocalizationContextUtils(); static void setLocalization(ServletRequest servletRequest, Localization localization); static Localization getLocalization(ServletRequest servletRequest); static void setLocalization(ServletContext servletContext, Localization localization); static Localization getLocalization(ServletContext servletContext); }
|
@Test public void testGetLocalizationWithServletRequest() throws Exception { ServletRequest servletRequest = mock(ServletRequest.class); when(servletRequest.getAttribute(ATTRIBUTE_NAME)).thenReturn(localization); Localization result = LocalizationContextUtils.getLocalization(servletRequest); assertThat(result).isNotNull().isEqualTo(localization); }
@Test public void testGetLocalizationWithServletContext() throws Exception { ServletContext servletContext = mock(ServletContext.class); when(servletContext.getAttribute(ATTRIBUTE_NAME)).thenReturn(localization); Localization result = LocalizationContextUtils.getLocalization(servletContext); assertThat(result).isNotNull().isEqualTo(localization); }
|
DefaultLocaleResolver implements LocaleResolver { @Override public Locale getLocale() { return Locale.getDefault(); } @Override Locale getLocale(); }
|
@Test public void testGetLocale() throws Exception { Locale.setDefault(Locale.FRENCH); Locale locale = localeResolver.getLocale(); assertThat(locale).isNotNull().isEqualTo(Locale.FRENCH); }
|
ChainedResourceLoader implements ResourceLoader { @Override public boolean isSupported(String location) { return getSupportedResourceLoader(location) != null; } ChainedResourceLoader(Collection<ResourceLoader> resourceLoaders); @Override boolean isSupported(String location); @Override InputStream openStream(String location); }
|
@Test public void testIsSupportedWithFirstSupported() throws Exception { String location = "schema1:/test/resource"; when(resourceLoader1.isSupported(location)).thenReturn(true); boolean result = resourceLoader.isSupported(location); assertThat(result).isTrue(); InOrder inOrder = resourcesInOrder(); inOrder.verify(resourceLoader1).isSupported(location); inOrder.verifyNoMoreInteractions(); }
@Test public void testIsSupportedWithLastSupported() throws Exception { String location = "schema3:/test/resource"; when(resourceLoader1.isSupported(location)).thenReturn(false); when(resourceLoader2.isSupported(location)).thenReturn(false); when(resourceLoader3.isSupported(location)).thenReturn(true); boolean result = resourceLoader.isSupported(location); assertThat(result).isTrue(); InOrder inOrder = resourcesInOrder(); inOrder.verify(resourceLoader1).isSupported(location); inOrder.verify(resourceLoader2).isSupported(location); inOrder.verify(resourceLoader3).isSupported(location); inOrder.verifyNoMoreInteractions(); }
@Test public void testIsSupportedWithNoneSupported() throws Exception { String location = "schema4:/test/resource"; when(resourceLoader1.isSupported(location)).thenReturn(false); when(resourceLoader2.isSupported(location)).thenReturn(false); when(resourceLoader3.isSupported(location)).thenReturn(false); boolean result = resourceLoader.isSupported(location); assertThat(result).isFalse(); InOrder inOrder = resourcesInOrder(); inOrder.verify(resourceLoader1).isSupported(location); inOrder.verify(resourceLoader2).isSupported(location); inOrder.verify(resourceLoader3).isSupported(location); inOrder.verifyNoMoreInteractions(); }
|
DefaultLocalizationProvider implements LocalizationProvider { @Override public String getString(String key) { return getPropertyResolver().getString(checkNotNull(key)); } private DefaultLocalizationProvider(Builder builder); @Override String getString(String key); @Override Boolean getBoolean(String key); @Override Integer getInteger(String key); @Override Long getLong(String key); @Override Float getFloat(String key); @Override Double getDouble(String key); @Override List<String> getStringList(String key); @Override Map<String, String> getStringMap(String key); @Override String getMessage(String key, Object... parameters); @Override MessageFormat getMessageFormat(String key); @Override String getSelectedMessage(String key, String selector, Object... parameters); @Override MessageFormat getSelectedMessageFormat(String key, String selector); @Override String getPluralMessage(String key, Number count, Object... parameters); MessageFormat getPluralMessageFormat(String key, Number count); static Builder builder(); static final char LOCALE_SEPARATOR; static final char FILE_EXTENSION_SEPARATOR; }
|
@Test(expected = NullPointerException.class) public void testWithNullLocale() throws Exception { LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(null); try { localizationProvider.getString("str.key"); } finally { InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verifyNoMoreInteractions(); } }
@Test public void testWithNotSupportedLocation() throws Exception { thrown.expect(UnsupportedLocationException.class); String expectedMessage = "Unsupported location: '" + LOCATION + "'"; thrown.expectMessage(expectedMessage); LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(false); try { localizationProvider.getString("str.key"); } finally { InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verifyNoMoreInteractions(); } }
@Test public void testGetString() throws Exception { String key = "str.key"; String value = "test value"; LocalizationProvider localizationProvider = createDefault(); when(localeResolver.getLocale()).thenReturn(Locale.ITALY); when(resourceLoader.isSupported(LOCATION)).thenReturn(true); when(resourceLoader.openStream(LOCATION_ITALY)).thenReturn(null); when(resourceLoader.openStream(LOCATION_ITALIAN)).thenReturn(inputStream); when(localizationLoader.load(inputStream)).thenReturn(propertyResolver); when(propertyResolver.getString(key)).thenReturn(value); String result = localizationProvider.getString(key); assertThat(result).isNotNull().isEqualTo(value); InOrder inOrder = inOrder(); inOrder.verify(localeResolver).getLocale(); inOrder.verify(resourceLoader).isSupported(LOCATION); inOrder.verify(resourceLoader).openStream(LOCATION_ITALY); inOrder.verify(resourceLoader).openStream(LOCATION_ITALIAN); inOrder.verify(localizationLoader).load(inputStream); inOrder.verify(propertyResolver).getString(key); inOrder.verifyNoMoreInteractions(); }
|
PropertiesLocalizationLoader implements LocalizationLoader { @Override public PropertyResolver load(InputStream inputStream) throws IOException { MatchingReader reader = new MatchingReader(new BufferedReader(new InputStreamReader(inputStream))); return load(reader); } @Override PropertyResolver load(InputStream inputStream); }
|
@Test public void testLoadWithoutProperties() throws Exception { String content = ""; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver).isNotNull(); assertThat(propertyResolver.getString("")).isNull(); assertThat(propertyResolver.getStringList("")).isNull(); assertThat(propertyResolver.getStringMap("")).isNull(); }
@Test public void testLoadWithoutPropertiesAndWithComments() throws Exception { String content = "" + "\n" + "# Test comment\t \n" + "#\tLine 2\r" + "#Line 3\\\r\n" + "\t \n" + "\n"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver).isNotNull(); assertThat(propertyResolver.getString("")).isNull(); assertThat(propertyResolver.getString("#")).isNull(); }
@Test public void testLoadSingleProperty() throws Exception { String content = "prop=test-value"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver.getString("prop")).isNotNull().isEqualTo("test-value"); }
@Test public void testLoadMultipleProperties() throws Exception { String content = "" + "Truth1 = Beauty1\n" + " Truth2:Beauty2\r" + "Truth3 :Beauty3\r\n" + "Truth4 Beauty4\n" + "fruits apple, banana, pear, \\\n" + " cantaloupe, watermelon, \\\r\n" + " kiwi, mango"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver.getString("Truth1")).isNotNull().isEqualTo("Beauty1"); assertThat(propertyResolver.getString("Truth2")).isNotNull().isEqualTo("Beauty2"); assertThat(propertyResolver.getString("Truth3")).isNotNull().isEqualTo("Beauty3"); assertThat(propertyResolver.getString("Truth4")).isNotNull().isEqualTo("Beauty4"); assertThat(propertyResolver.getString("fruits")).isNotNull().isEqualTo("apple, banana, pear, cantaloupe, watermelon, kiwi, mango"); }
@Test public void testLoadMultiplePropertiesAndWithComments() throws Exception { String content = "" + "#Truth1 = Beauty1\n" + " #\t Truth2:Beauty2\r" + "!Truth3 :Beauty3\r\n" + "fruits# apple, banana, pear, \\\n" + "# cantaloupe, watermelon, \\\r\n" + " kiwi, mango"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver.getString("#")).isNotNull().isEqualTo("Truth2:Beauty2"); assertThat(propertyResolver.getString("fruits#")).isNotNull(). isEqualTo("apple, banana, pear, # cantaloupe, watermelon, kiwi, mango"); }
@Test public void testLoadListProperties() throws Exception { String content = "" + "vegetables=potato,squash,carrot,beat\n" + "fruits apple, banana\t, pear, \\\n" + " cantaloupe, \twatermelon, \\\r\n" + " kiwi , mango"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver.getStringList("vegetables")).isNotNull().hasSize(4). containsExactly("potato", "squash", "carrot", "beat"); assertThat(propertyResolver.getStringList("fruits")).isNotNull().hasSize(7). containsExactly("apple", "banana", "pear", "cantaloupe", "watermelon", "kiwi", "mango"); }
@Test public void testLoadMapProperties() throws Exception { String content = "" + "weekdays[1]=Sunday\n" + "weekdays[2]=Monday\n" + "weekdays[3]=Tuesday\n" + "weekdays[4]=Wednesday\n" + "weekdays[5]=Thursday\n" + "weekdays[6]=Friday\n" + "weekdays[7]=Saturday\n" + "\n" + "colors[red]=#FF0000\n" + "colors[cyan]=#00FFFF\n" + "colors[white]=#FFFFFF\n" + "colors[black]=#000000"; PropertyResolver propertyResolver = load(content); assertThat(propertyResolver.getStringMap("weekdays")).isNotNull().hasSize(7). contains(entry("1", "Sunday"), entry("2", "Monday"), entry("3", "Tuesday"), entry("4", "Wednesday"), entry("5", "Thursday"), entry("6", "Friday"), entry("7", "Saturday")); assertThat(propertyResolver.getStringMap("colors")).isNotNull().hasSize(4). contains(entry("red", "#FF0000"), entry("cyan", "#00FFFF"), entry("white", "#FFFFFF"), entry("black", "#000000")); }
|
SpringLocaleResolver implements LocaleResolver { @Override public Locale getLocale() { return LocaleContextHolder.getLocale(); } @Override Locale getLocale(); }
|
@Test public void testGetLocale() throws Exception { LocaleContextHolder.setLocale(Locale.FRENCH); Locale locale = localeResolver.getLocale(); assertThat(locale).isNotNull().isEqualTo(Locale.FRENCH); }
@Test public void testGetLocaleWithNullLocale() throws Exception { LocaleContextHolder.setLocale(null); Locale locale = localeResolver.getLocale(); assertThat(locale).isNotNull().isEqualTo(Locale.getDefault()); }
|
SetupAndExecuteCanariesStage implements StageDefinitionBuilder { protected Duration calculateLifetime( Instant start, Instant endTime, CanaryAnalysisExecutionRequest canaryAnalysisExecutionRequest) { Duration lifetime; if (endTime != null) { lifetime = Duration.ofMinutes(start.until(endTime, MINUTES)); } else if (canaryAnalysisExecutionRequest.getLifetimeDuration() != null) { lifetime = canaryAnalysisExecutionRequest.getLifetimeDuration(); } else { throw new IllegalArgumentException( "Canary StageExecution configuration must include either `endTime` or `lifetimeDuration`."); } return lifetime; } @Autowired SetupAndExecuteCanariesStage(Clock clock, ObjectMapper kayentaObjectMapper); @Override void taskGraph(@Nonnull StageExecution stage, @Nonnull TaskNode.Builder builder); @Override void beforeStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Override void onFailureStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Override void afterStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Nonnull @Override String getType(); static final String STAGE_TYPE; static final String STAGE_DESCRIPTION; }
|
@Test public void test_that_calculateLifetime_uses_supplied_start_and_end_time_if_provided() { int lifetimeInMinutes = 5; Instant now = Instant.now(); Instant later = now.plus(lifetimeInMinutes, ChronoUnit.MINUTES); CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder().build(); Duration actual = stage.calculateLifetime(now, later, request); Duration expected = Duration.ofMinutes(lifetimeInMinutes); assertEquals("The duration should be 5 minutes", expected, actual); }
@Test public void test_that_calculateLifetime_uses_supplied_lifetime_if_start_and_end_time_not_provided() { long lifetimeInMinutes = 5L; Instant now = Instant.now(); Instant later = null; CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder().lifetimeDurationMins(5L).build(); Duration actual = stage.calculateLifetime(now, later, request); Duration expected = Duration.ofMinutes(lifetimeInMinutes); assertEquals("The duration should be 5 minutes", expected, actual); }
@Test(expected = IllegalArgumentException.class) public void test_that_calculateLifetime_throws_an_error_if_lifetime_and_start_and_endtime_not_provided() { Instant now = Instant.now(); stage.calculateLifetime(now, null, CanaryAnalysisExecutionRequest.builder().build()); }
|
GenerateCanaryAnalysisResultTask implements Task { protected AggregatedJudgement getAggregatedJudgment( Double finalCanaryScore, Double marginalThreshold, Double passThreshold) { boolean didPassThresholds; String msg; if (marginalThreshold == null && passThreshold == null) { didPassThresholds = true; msg = "No score thresholds were specified."; } else if (marginalThreshold != null && finalCanaryScore <= marginalThreshold) { didPassThresholds = false; msg = String.format( "Final canary score %s is not above the marginal score threshold.", finalCanaryScore); } else if (passThreshold == null) { didPassThresholds = true; msg = "No pass score threshold was specified."; } else if (finalCanaryScore < passThreshold) { didPassThresholds = false; msg = String.format( "Final canary score %s is below the pass score threshold.", finalCanaryScore); } else { didPassThresholds = true; msg = String.format( "Final canary score %s met or exceeded the pass score threshold.", finalCanaryScore); } return new AggregatedJudgement(didPassThresholds, msg); } @Autowired GenerateCanaryAnalysisResultTask(ObjectMapper kayentaObjectMapper); @Nonnull @Override TaskResult execute(@Nonnull StageExecution stage); static final String CANARY_ANALYSIS_EXECUTION_RESULT; }
|
@Test @UseDataProvider("dataProviderGetAggregatedJudgment") public void test_getAggregatedJudgment( Double finalCanaryScore, Double marginalThreshold, Double passThreshold, boolean expected) { GenerateCanaryAnalysisResultTask.AggregatedJudgement aggregatedJudgement = task.getAggregatedJudgment(finalCanaryScore, marginalThreshold, passThreshold); assertEquals(expected, aggregatedJudgement.isDidPassThresholds()); }
|
PrometheusMetricDescriptorsCache { @Scheduled(fixedDelayString = "#{@prometheusConfigurationProperties.metadataCachingIntervalMS}") public void updateMetricDescriptorsCache() { Set<AccountCredentials> accountCredentialsSet = accountCredentialsRepository.getAllOf(AccountCredentials.Type.METRICS_STORE); Map<String, List<PrometheusMetricDescriptor>> updatedCache = accountCredentialsSet.stream() .filter(credentials -> credentials instanceof PrometheusNamedAccountCredentials) .map(credentials -> (PrometheusNamedAccountCredentials) credentials) .map(this::listMetricDescriptors) .filter(this::isSuccessful) .filter(this::hasData) .collect( Collectors.toMap( AccountResponse::getMetricsAccountName, this::toPrometheusMetricDescriptors)); this.cache = updatedCache; } PrometheusMetricDescriptorsCache(
AccountCredentialsRepository accountCredentialsRepository); List<Map> getMetadata(String metricsAccountName, String filter); @Scheduled(fixedDelayString = "#{@prometheusConfigurationProperties.metadataCachingIntervalMS}") void updateMetricDescriptorsCache(); }
|
@Test public void updateMetricDescriptorsCache_callsRepo() { cache.updateMetricDescriptorsCache(); verify(accountCredentialRepo).getAllOf(AccountCredentials.Type.METRICS_STORE); }
@Test public void updateMetricDescriptorsCache_ignoresNonPrometheusAccounts() { when(accountCredentialRepo.getAllOf(AccountCredentials.Type.METRICS_STORE)) .thenReturn(Collections.singleton(new TestAccountCredentials())); cache.updateMetricDescriptorsCache(); verify(accountCredentialRepo).getAllOf(AccountCredentials.Type.METRICS_STORE); }
|
PrometheusHealthJob { @Scheduled( initialDelayString = "${kayenta.prometheus.health.initial-delay:PT2S}", fixedDelayString = "${kayenta.prometheus.health.fixed-delay:PT5M}") public void run() { List<PrometheusHealthStatus> healthStatuses = prometheusConfigurationProperties.getAccounts().stream() .map( account -> { String name = account.getName(); return accountCredentialsRepository.getOne(name); }) .filter(Optional::isPresent) .map(Optional::get) .filter(credentials -> credentials instanceof PrometheusNamedAccountCredentials) .map(credentials -> ((PrometheusNamedAccountCredentials) credentials)) .map( credentials -> { try { PrometheusRemoteService remote = credentials.getPrometheusRemoteService(); remote.isHealthy(); return PrometheusHealthStatus.builder() .accountName(credentials.getName()) .status(Status.UP) .build(); } catch (Throwable ex) { log.warn( "Prometheus health FAILED for account: {} with exception: ", credentials.getName(), ex); return PrometheusHealthStatus.builder() .accountName(credentials.getName()) .status(Status.DOWN) .errorDetails(ex.getClass().getName() + ": " + ex.getMessage()) .build(); } }) .collect(Collectors.toList()); healthCache.setHealthStatuses(healthStatuses); } PrometheusHealthJob(
PrometheusConfigurationProperties prometheusConfigurationProperties,
AccountCredentialsRepository accountCredentialsRepository,
PrometheusHealthCache healthCache); @Scheduled( initialDelayString = "${kayenta.prometheus.health.initial-delay:PT2S}", fixedDelayString = "${kayenta.prometheus.health.fixed-delay:PT5M}") void run(); }
|
@Test public void allRemotesAreUp() { when(PROM_REMOTE_1.isHealthy()).thenReturn("OK"); when(PROM_REMOTE_2.isHealthy()).thenReturn("OK"); healthJob.run(); verify(healthCache) .setHealthStatuses( Arrays.asList( PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_1) .status(Status.UP) .build(), PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_2) .status(Status.UP) .build())); }
@Test public void allRemotesAreDown() { when(PROM_REMOTE_1.isHealthy()).thenThrow(new RuntimeException("test 1")); when(PROM_REMOTE_2.isHealthy()).thenThrow(new RuntimeException("test 2")); healthJob.run(); verify(healthCache) .setHealthStatuses( Arrays.asList( PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_1) .status(Status.DOWN) .errorDetails("java.lang.RuntimeException: test 1") .build(), PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_2) .status(Status.DOWN) .errorDetails("java.lang.RuntimeException: test 2") .build())); }
@Test public void oneRemoteIsDown() { when(PROM_REMOTE_1.isHealthy()).thenReturn("OK"); when(PROM_REMOTE_2.isHealthy()).thenThrow(new RuntimeException("test 2")); healthJob.run(); verify(healthCache) .setHealthStatuses( Arrays.asList( PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_1) .status(Status.UP) .build(), PrometheusHealthJob.PrometheusHealthStatus.builder() .accountName(PROM_ACCOUNT_2) .status(Status.DOWN) .errorDetails("java.lang.RuntimeException: test 2") .build())); }
|
SignalFxQueryBuilderService { public String buildQuery( CanaryConfig canaryConfig, SignalFxCanaryMetricSetQueryConfig queryConfig, CanaryScope canaryScope, SignalFxScopeConfiguration scopeConfiguration, SignalFxCanaryScope signalFxCanaryScope) { String aggregationMethod = Optional.ofNullable(queryConfig.getAggregationMethod()).orElse("mean"); List<QueryPair> queryPairs = Optional.ofNullable(queryConfig.getQueryPairs()).orElse(new LinkedList<>()); String[] baseScopeAttributes = new String[] {"scope", "location"}; try { String customFilter = QueryConfigUtils.expandCustomFilter( canaryConfig, queryConfig, canaryScope, baseScopeAttributes); return Optional.ofNullable(customFilter) .orElseGet( () -> getSimpleProgram( queryConfig, scopeConfiguration, signalFxCanaryScope, aggregationMethod, queryPairs)); } catch (Exception e) { throw new RuntimeException("Failed to generate SignalFx SignalFlow program", e); } } String buildQuery(
CanaryConfig canaryConfig,
SignalFxCanaryMetricSetQueryConfig queryConfig,
CanaryScope canaryScope,
SignalFxScopeConfiguration scopeConfiguration,
SignalFxCanaryScope signalFxCanaryScope); }
|
@Test public void test_inline_template_supplied() { String customInlineTemplate = "data('request.count', filter=" + "filter('server_group', 'my_microservice-control-v1'))" + ".mean(by=['server_group']).publish()"; CanaryConfig canaryConfig = CanaryConfig.builder().build(); SignalFxCanaryMetricSetQueryConfig metricSetQueryConfig = SignalFxCanaryMetricSetQueryConfig.builder() .customInlineTemplate(customInlineTemplate) .build(); CanaryScope canaryScope = CanaryScope.builder().build(); SignalFxScopeConfiguration scopeConfiguration = SignalFxScopeConfiguration.builder().build(); SignalFxCanaryScope scope = new SignalFxCanaryScope(); String expected = "data('request.count', filter=" + "filter('server_group', 'my_microservice-control-v1'))" + ".mean(by=['server_group']).publish()"; assertEquals( expected, signalFxQueryBuilderService.buildQuery( canaryConfig, metricSetQueryConfig, canaryScope, scopeConfiguration, scope)); }
@Test public void test_inline_template_and_extended_scope_params_supplied() { String customInlineTemplate = "data('request.count', filter=" + "filter('server_group', 'my_microservice-control-v1'))" + ".mean(by=['${some_key}']).publish()"; SignalFxCanaryScope scope = new SignalFxCanaryScope(); CanaryConfig canaryConfig = CanaryConfig.builder().build(); SignalFxCanaryMetricSetQueryConfig metricSetQueryConfig = SignalFxCanaryMetricSetQueryConfig.builder() .customInlineTemplate(customInlineTemplate) .build(); CanaryScope canaryScope = CanaryScope.builder().build(); canaryScope.setExtendedScopeParams(ImmutableMap.of("some_key", "some_value")); SignalFxScopeConfiguration scopeConfiguration = SignalFxScopeConfiguration.builder().build(); String expected = "data('request.count', filter=" + "filter('server_group', 'my_microservice-control-v1'))" + ".mean(by=['some_value']).publish()"; assertEquals( expected, signalFxQueryBuilderService.buildQuery( canaryConfig, metricSetQueryConfig, canaryScope, scopeConfiguration, scope)); }
|
WavefrontMetricsService implements MetricsService { @Override public String buildQuery( String metricsAccountName, CanaryConfig canaryConfig, CanaryMetricConfig canaryMetricConfig, CanaryScope canaryScope) { WavefrontCanaryMetricSetQueryConfig queryConfig = (WavefrontCanaryMetricSetQueryConfig) canaryMetricConfig.getQuery(); String query = queryConfig.getMetricName(); if (canaryScope.getScope() != null && !canaryScope.getScope().equals("")) { query = query + ", " + canaryScope.getScope(); } query = "ts(" + query + ")"; if (queryConfig.getAggregate() != null && !queryConfig.getAggregate().equals("")) { query = queryConfig.getAggregate() + "(" + query + ")"; } return query; } @Override String getType(); @Override boolean servicesAccount(String accountName); @Override String buildQuery(
String metricsAccountName,
CanaryConfig canaryConfig,
CanaryMetricConfig canaryMetricConfig,
CanaryScope canaryScope); @Override List<MetricSet> queryMetrics(
String accountName,
CanaryConfig canaryConfig,
CanaryMetricConfig canaryMetricConfig,
CanaryScope canaryScope); }
|
@Test public void testBuildQuery_NoScopeProvided() { CanaryScope canaryScope = createScope(""); CanaryMetricConfig canaryMetricSetQueryConfig = queryConfig(AGGREGATE); String query = wavefrontMetricsService.buildQuery("", null, canaryMetricSetQueryConfig, canaryScope); assertThat(query, is(AGGREGATE + "(ts(" + METRIC_NAME + "))")); }
@Test public void testBuildQuery_NoAggregateProvided() { CanaryScope canaryScope = createScope(SCOPE); CanaryMetricConfig canaryMetricSetQueryConfig = queryConfig(""); String query = wavefrontMetricsService.buildQuery("", null, canaryMetricSetQueryConfig, canaryScope); assertThat(query, is("ts(" + METRIC_NAME + ", " + SCOPE + ")")); }
@Test public void testBuildQuery_ScopeAndAggregateProvided() { CanaryScope canaryScope = createScope(SCOPE); CanaryMetricConfig canaryMetricSetQueryConfig = queryConfig("avg"); String query = wavefrontMetricsService.buildQuery("", null, canaryMetricSetQueryConfig, canaryScope); assertThat(query, is(AGGREGATE + "(ts(" + METRIC_NAME + ", " + SCOPE + "))")); }
|
WavefrontCanaryScopeFactory implements CanaryScopeFactory { @Override public CanaryScope buildCanaryScope(CanaryScope scope) { WavefrontCanaryScope wavefrontCanaryScope = new WavefrontCanaryScope(); wavefrontCanaryScope.setScope(scope.getScope()); wavefrontCanaryScope.setLocation(scope.getLocation()); wavefrontCanaryScope.setStart(scope.getStart()); wavefrontCanaryScope.setEnd(scope.getEnd()); wavefrontCanaryScope.setStep(scope.getStep()); wavefrontCanaryScope.setGranularity(generateGranularity(scope.getStep())); wavefrontCanaryScope.setExtendedScopeParams(scope.getExtendedScopeParams()); return wavefrontCanaryScope; } @Override boolean handles(String serviceType); @Override CanaryScope buildCanaryScope(CanaryScope scope); static long SECOND; static long MINUTE; static long HOUR; static long DAY; }
|
@Test public void testBuildCanaryScope_WithSecondGranularity() { CanaryScope canaryScope = new CanaryScope( "scope", "location", Instant.now(), Instant.now(), WavefrontCanaryScopeFactory.SECOND, null); CanaryScope generatedCanaryScope = queryBuilder.buildCanaryScope(canaryScope); WavefrontCanaryScope wavefrontCanaryScope = (WavefrontCanaryScope) generatedCanaryScope; assertThat(wavefrontCanaryScope.getGranularity(), is("s")); }
@Test public void testBuildCanaryScope_WithMinuteGranularity() { CanaryScope canaryScope = new CanaryScope( "scope", "location", Instant.now(), Instant.now(), WavefrontCanaryScopeFactory.MINUTE, null); CanaryScope generatedCanaryScope = queryBuilder.buildCanaryScope(canaryScope); WavefrontCanaryScope wavefrontCanaryScope = (WavefrontCanaryScope) generatedCanaryScope; assertThat(wavefrontCanaryScope.getGranularity(), is("m")); }
@Test public void testBuildCanaryScope_WithHourGranularity() { CanaryScope canaryScope = new CanaryScope( "scope", "location", Instant.now(), Instant.now(), WavefrontCanaryScopeFactory.HOUR, null); CanaryScope generatedCanaryScope = queryBuilder.buildCanaryScope(canaryScope); WavefrontCanaryScope wavefrontCanaryScope = (WavefrontCanaryScope) generatedCanaryScope; assertThat(wavefrontCanaryScope.getGranularity(), is("h")); }
@Test public void testBuildCanaryScope_WithDayGranularity() { CanaryScope canaryScope = new CanaryScope( "scope", "location", Instant.now(), Instant.now(), WavefrontCanaryScopeFactory.DAY, null); CanaryScope generatedCanaryScope = queryBuilder.buildCanaryScope(canaryScope); WavefrontCanaryScope wavefrontCanaryScope = (WavefrontCanaryScope) generatedCanaryScope; assertThat(wavefrontCanaryScope.getGranularity(), is("d")); }
|
InfluxDbResponseConverter implements Converter { @Override public TypedOutput toBody(Object object) { return null; } @Autowired InfluxDbResponseConverter(ObjectMapper kayentaObjectMapper); @Override Object fromBody(TypedInput body, Type type); @Override TypedOutput toBody(Object object); }
|
@Test public void serialize() throws Exception { assertThat(influxDbResponseConverter.toBody(results), is(nullValue())); }
|
InfluxDbResponseConverter implements Converter { @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) { String json = reader.readLine(); log.debug("Converting response from influxDb: {}", json); Map result = getResultObject(json); List<Map> seriesList = (List<Map>) result.get("series"); if (CollectionUtils.isEmpty(seriesList)) { log.warn("Received no data from Influxdb."); return null; } Map series = seriesList.get(0); List<String> seriesColumns = (List<String>) series.get("columns"); List<List> seriesValues = (List<List>) series.get("values"); List<InfluxDbResult> influxDbResultsList = new ArrayList<InfluxDbResult>(seriesValues.size()); for (int i = 1; i < seriesColumns.size(); i++) { String id = seriesColumns.get(i); long firstTimeMillis = extractTimeInMillis(seriesValues, 0); long stepMillis = calculateStep(seriesValues, firstTimeMillis); List<Double> values = new ArrayList<>(seriesValues.size()); for (List<Object> valueRow : seriesValues) { if (valueRow.get(i) != null) { values.add(Double.valueOf((Integer) valueRow.get(i))); } } influxDbResultsList.add(new InfluxDbResult(id, firstTimeMillis, stepMillis, null, values)); } log.debug("Converted response: {} ", influxDbResultsList); return influxDbResultsList; } catch (IOException e) { e.printStackTrace(); } return null; } @Autowired InfluxDbResponseConverter(ObjectMapper kayentaObjectMapper); @Override Object fromBody(TypedInput body, Type type); @Override TypedOutput toBody(Object object); }
|
@Test public void deserialize() throws Exception { TypedInput input = new TypedByteArray(MIME_TYPE, JSON.getBytes()); List<InfluxDbResult> result = (List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List.class); assertThat(result, is(results)); }
@Test(expected = ConversionException.class) public void deserializeWrongValue() throws Exception { TypedInput input = new TypedByteArray(MIME_TYPE, "{\"foo\":\"bar\"}".getBytes()); influxDbResponseConverter.fromBody(input, List.class); }
|
SetupAndExecuteCanariesStage implements StageDefinitionBuilder { protected ScopeTimeConfig calculateStartAndEndForJudgement( CanaryAnalysisExecutionRequest config, long judgementNumber, Duration judgementDuration) { Duration warmupDuration = config.getBeginCanaryAnalysisAfterAsDuration(); Duration offset = judgementDuration.multipliedBy(judgementNumber); ScopeTimeConfig scopeTimeConfig = new ScopeTimeConfig(); Instant startTime = Optional.ofNullable(config.getStartTime()).orElse(now(clock)); scopeTimeConfig.start = startTime; scopeTimeConfig.end = startTime.plus(offset); if (config.getEndTime() == null) { scopeTimeConfig.start = scopeTimeConfig.start.plus(warmupDuration); scopeTimeConfig.end = scopeTimeConfig.end.plus(warmupDuration); } if (config.getLookBackAsInstant().isAfter(ZERO_AS_INSTANT)) { scopeTimeConfig.start = scopeTimeConfig.end.minus(config.getLookBackAsDuration()); } return scopeTimeConfig; } @Autowired SetupAndExecuteCanariesStage(Clock clock, ObjectMapper kayentaObjectMapper); @Override void taskGraph(@Nonnull StageExecution stage, @Nonnull TaskNode.Builder builder); @Override void beforeStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Override void onFailureStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Override void afterStages(@Nonnull StageExecution parent, @Nonnull StageGraphBuilder graph); @Nonnull @Override String getType(); static final String STAGE_TYPE; static final String STAGE_DESCRIPTION; }
|
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_nothing_is_set_in_the_scopes() { CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .scopes(ImmutableList.of(CanaryAnalysisExecutionRequestScope.builder().build())) .build(); Duration intervalDuration = Duration.ofMinutes(3); for (int i = 1; i < 6; i++) { SetupAndExecuteCanariesStage.ScopeTimeConfig conf = stage.calculateStartAndEndForJudgement(request, i, intervalDuration); assertEquals(now, conf.getStart()); assertEquals(now.plus(i * 3, ChronoUnit.MINUTES), conf.getEnd()); } }
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_nothing_is_set_in_the_scopes_with_warmup() { CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .scopes(ImmutableList.of(CanaryAnalysisExecutionRequestScope.builder().build())) .beginAfterMins(4L) .build(); Duration intervalDuration = Duration.ofMinutes(3); for (int i = 1; i < 6; i++) { SetupAndExecuteCanariesStage.ScopeTimeConfig conf = stage.calculateStartAndEndForJudgement(request, i, intervalDuration); assertEquals(now.plus(4, ChronoUnit.MINUTES), conf.getStart()); assertEquals(now.plus(i * 3, ChronoUnit.MINUTES).plus(4, ChronoUnit.MINUTES), conf.getEnd()); } }
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_start_and_end_are_supplied_in_the_scopes() { Instant definedStart = now.minus(5, ChronoUnit.MINUTES); Instant definedEnd = now.plus(20, ChronoUnit.MINUTES); CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .scopes( ImmutableList.of( CanaryAnalysisExecutionRequestScope.builder() .startTimeIso(definedStart.toString()) .endTimeIso(definedEnd.toString()) .build())) .build(); Duration intervalDuration = Duration.ofMinutes(3); for (int i = 1; i < 6; i++) { SetupAndExecuteCanariesStage.ScopeTimeConfig conf = stage.calculateStartAndEndForJudgement(request, i, intervalDuration); assertEquals(definedStart, conf.getStart()); assertEquals(definedStart.plus(i * 3, ChronoUnit.MINUTES), conf.getEnd()); } }
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_start_and_end_are_supplied_in_the_scopes_with_warmup() { Instant definedStart = now.minus(5, ChronoUnit.MINUTES); Instant definedEnd = now.plus(20, ChronoUnit.MINUTES); CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .beginAfterMins(4L) .scopes( ImmutableList.of( CanaryAnalysisExecutionRequestScope.builder() .startTimeIso(definedStart.toString()) .endTimeIso(definedEnd.toString()) .build())) .build(); Duration intervalDuration = Duration.ofMinutes(3); for (int i = 1; i < 6; i++) { SetupAndExecuteCanariesStage.ScopeTimeConfig conf = stage.calculateStartAndEndForJudgement(request, i, intervalDuration); assertEquals(definedStart, conf.getStart()); assertEquals(definedStart.plus(i * 3, ChronoUnit.MINUTES), conf.getEnd()); } }
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_lookback_is_defined() { CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .lookbackMins(5L) .scopes(ImmutableList.of(CanaryAnalysisExecutionRequestScope.builder().build())) .build(); Duration intervalDuration = Duration.ofMinutes(5); for (int i = 1; i < 6; i++) { SetupAndExecuteCanariesStage.ScopeTimeConfig conf = stage.calculateStartAndEndForJudgement(request, i, intervalDuration); assertEquals(now.plus((i - 1) * 5, ChronoUnit.MINUTES), conf.getStart()); assertEquals(now.plus(i * 5, ChronoUnit.MINUTES), conf.getEnd()); } }
@Test public void test_that_calculateStartAndEndForJudgement_has_expected_start_and_end_when_start_iso_only_is_defined() { int interval = 1; String startIso = "2018-12-17T20:56:39.689Z"; Duration lifetimeDuration = Duration.ofMinutes(3L); CanaryAnalysisExecutionRequest request = CanaryAnalysisExecutionRequest.builder() .scopes( ImmutableList.of( CanaryAnalysisExecutionRequestScope.builder().startTimeIso(startIso).build())) .build(); SetupAndExecuteCanariesStage.ScopeTimeConfig actual = stage.calculateStartAndEndForJudgement(request, interval, lifetimeDuration); assertEquals(Instant.parse(startIso), actual.getStart()); assertEquals(Instant.parse(startIso).plus(3L, ChronoUnit.MINUTES), actual.getEnd()); }
|
GenerateCanaryAnalysisResultTask implements Task { @NotNull protected List<StageExecution> getRunCanaryStages(@Nonnull StageExecution stage) { return stage.getExecution().getStages().stream() .filter(s -> s.getType().equals(RunCanaryStage.STAGE_TYPE)) .sorted( Comparator.comparing( s -> Integer.valueOf(StringUtils.substringAfterLast(s.getName(), "#")))) .collect(Collectors.toList()); } @Autowired GenerateCanaryAnalysisResultTask(ObjectMapper kayentaObjectMapper); @Nonnull @Override TaskResult execute(@Nonnull StageExecution stage); static final String CANARY_ANALYSIS_EXECUTION_RESULT; }
|
@Test public void test_that_getRunCanaryStages_returns_the_expected_sorted_list_of_stages_sorted_by_the_number_in_the_stage_name() { StageExecution stage = mock(StageExecution.class); PipelineExecution execution = mock(PipelineExecution.class); when(stage.getExecution()).thenReturn(execution); when(execution.getStages()) .thenReturn( ImmutableList.of( new StageExecutionImpl( null, STAGE_TYPE, "foo #1", Maps.newHashMap(ImmutableMap.of("index", "0"))), new StageExecutionImpl( null, STAGE_TYPE, "foo #3", Maps.newHashMap(ImmutableMap.of("index", "2"))), new StageExecutionImpl( null, STAGE_TYPE, "foo #2", Maps.newHashMap(ImmutableMap.of("index", "1"))), new StageExecutionImpl( null, STAGE_TYPE, "foo #4", Maps.newHashMap(ImmutableMap.of("index", "3"))))); List<StageExecution> actual = task.getRunCanaryStages(stage); for (int i = 0; i < 4; i++) { assertEquals(String.valueOf(i), actual.get(i).getContext().get("index")); } }
|
MediaIDHelper { public static String createMediaID(String musicID, String... categories) { StringBuilder sb = new StringBuilder(); if (categories != null) { for (int i=0; i < categories.length; i++) { if (!isValidCategory(categories[i])) { throw new IllegalArgumentException("Invalid category: " + categories[0]); } sb.append(categories[i]); if (i < categories.length - 1) { sb.append(CATEGORY_SEPARATOR); } } } if (musicID != null) { sb.append(LEAF_SEPARATOR).append(musicID); } return sb.toString(); } static String createMediaID(String musicID, String... categories); static String extractMusicIDFromMediaID(@NonNull String mediaID); static @NonNull String[] getHierarchy(@NonNull String mediaID); static String extractBrowseCategoryValueFromMediaID(@NonNull String mediaID); static boolean isBrowseable(@NonNull String mediaID); static boolean isPlaylist(@NonNull String mediaId); static String getParentMediaID(@NonNull String mediaID); static boolean isMediaItemPlaying(Context context,
MediaBrowserCompat.MediaItem mediaItem); static MediaDescriptionCompat getDescriptionWithRating(MediaMetadataCompat metadata); static final String MEDIA_ID_EMPTY_ROOT; static final String MEDIA_ID_ROOT; static final String MEDIA_ID_MUSICS_BY_GENRE; static final String MEDIA_ID_MUSICS_BY_SEARCH; static final String MEDIA_ID_PLAYLISTS; static final String MEDIA_ID_ARTIST_SONGS; static final String MEDIA_ID_ARTISTS; static final String MEDIA_ID_ALBUMS; }
|
@Test(expected = IllegalArgumentException.class) public void testInvalidSymbolsInMediaIDStructure() throws Exception { fail(MediaIDHelper.createMediaID(null, "BY|GENRE/2", "Classic 70's")); }
|
MediaIDHelper { public static String getParentMediaID(@NonNull String mediaID) { String[] hierarchy = getHierarchy(mediaID); if (!isBrowseable(mediaID)) { return createMediaID(null, hierarchy); } if (hierarchy.length <= 1) { return MEDIA_ID_ROOT; } String[] parentHierarchy = Arrays.copyOf(hierarchy, hierarchy.length-1); return createMediaID(null, parentHierarchy); } static String createMediaID(String musicID, String... categories); static String extractMusicIDFromMediaID(@NonNull String mediaID); static @NonNull String[] getHierarchy(@NonNull String mediaID); static String extractBrowseCategoryValueFromMediaID(@NonNull String mediaID); static boolean isBrowseable(@NonNull String mediaID); static boolean isPlaylist(@NonNull String mediaId); static String getParentMediaID(@NonNull String mediaID); static boolean isMediaItemPlaying(Context context,
MediaBrowserCompat.MediaItem mediaItem); static MediaDescriptionCompat getDescriptionWithRating(MediaMetadataCompat metadata); static final String MEDIA_ID_EMPTY_ROOT; static final String MEDIA_ID_ROOT; static final String MEDIA_ID_MUSICS_BY_GENRE; static final String MEDIA_ID_MUSICS_BY_SEARCH; static final String MEDIA_ID_PLAYLISTS; static final String MEDIA_ID_ARTIST_SONGS; static final String MEDIA_ID_ARTISTS; static final String MEDIA_ID_ALBUMS; }
|
@Test public void testGetParentOfRoot() throws Exception { assertEquals( MediaIDHelper.MEDIA_ID_ROOT, MediaIDHelper.getParentMediaID(MediaIDHelper.MEDIA_ID_ROOT)); }
@Test(expected=NullPointerException.class) public void testGetParentOfNull() throws Exception { fail(MediaIDHelper.getParentMediaID(null)); }
|
LanguageDictionary { public AppleLanguage getLanguage() { return language; } LanguageDictionary(String lprojName); static LanguageDictionary createFromFile(File f); JSONObject readContentFromBinaryFile(File binaryFile); void addJSONContent(JSONObject content); static List<File> getL10NFiles(File aut); static String extractLanguageName(File f); ImmutableList<ContentResult> getPotentialMatches(String string); boolean match(String content, String originalText); static String getRegexPattern(String original); AppleLanguage getLanguage(); @Override int hashCode(); @Override boolean equals(Object obj); String translate(ContentResult res); String getContentForKey(String key); static final Form form; static final Pattern specifierPattern; }
|
@Test public void canGuessLegacyNaming() { String name = "French"; LanguageDictionary dict = new LanguageDictionary(name); Assert.assertEquals(dict.getLanguage().getIsoCode(), "fr"); }
@Test public void canGuessCurrentNaming() { String name = "fr"; LanguageDictionary dict = new LanguageDictionary(name); Assert.assertEquals(dict.getLanguage().getIsoCode(), "fr"); }
|
LanguageDictionary { public static List<File> getL10NFiles(File aut) { List<File> res = new ArrayList<>(); File[] files = aut.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith("lproj"); } }); for (File f : files) { File[] all = f.listFiles(); if (all != null) { for (File potential : all) { String file = potential.getName(); if (file.endsWith(".strings") && !file.endsWith("InfoPlist.strings")) { res.add(potential); } } } } return res; } LanguageDictionary(String lprojName); static LanguageDictionary createFromFile(File f); JSONObject readContentFromBinaryFile(File binaryFile); void addJSONContent(JSONObject content); static List<File> getL10NFiles(File aut); static String extractLanguageName(File f); ImmutableList<ContentResult> getPotentialMatches(String string); boolean match(String content, String originalText); static String getRegexPattern(String original); AppleLanguage getLanguage(); @Override int hashCode(); @Override boolean equals(Object obj); String translate(ContentResult res); String getContentForKey(String key); static final Form form; static final Pattern specifierPattern; }
|
@Test public void reflectionOnProjectToFindLanguageFiles() { File app = new File(SampleApps.getIntlMountainsFile()); List<File> languageFiles = LanguageDictionary.getL10NFiles(app); Assert.assertEquals(languageFiles.size(), 4); }
@Test public void reflectionOnProjectToFindLanguageFiles2() { File app = new File(SampleApps.getUICatalogFile()); List<File> languageFiles = LanguageDictionary.getL10NFiles(app); Assert.assertEquals(languageFiles.size(), 1); }
|
LanguageDictionary { public static String extractLanguageName(File f) { String parent = f.getParentFile().getName(); return parent.replaceFirst(".lproj", ""); } LanguageDictionary(String lprojName); static LanguageDictionary createFromFile(File f); JSONObject readContentFromBinaryFile(File binaryFile); void addJSONContent(JSONObject content); static List<File> getL10NFiles(File aut); static String extractLanguageName(File f); ImmutableList<ContentResult> getPotentialMatches(String string); boolean match(String content, String originalText); static String getRegexPattern(String original); AppleLanguage getLanguage(); @Override int hashCode(); @Override boolean equals(Object obj); String translate(ContentResult res); String getContentForKey(String key); static final Form form; static final Pattern specifierPattern; }
|
@Test public void extractNames() { File en = new File( "/Users/abc/build/intlMountains/Applications/InternationalMountains.app/en.lproj/Localizable.strings"); File fr = new File( "/Users/abc/build/intlMountains/Applications/InternationalMountains.app/fr.lproj/Localizable.strings"); File zh = new File( "/Users/abc/build/intlMountains/Applications/InternationalMountains.app/zh-Hant.lproj/Localizable.strings"); File french = new File( "/Users/abc/build/intlMountains/Applications/InternationalMountains.app/French.lproj/Localizable.strings"); String enStr = LanguageDictionary.extractLanguageName(en); String frStr = LanguageDictionary.extractLanguageName(fr); String zhStr = LanguageDictionary.extractLanguageName(zh); String frenchStr = LanguageDictionary.extractLanguageName(french); Assert.assertEquals(enStr, "en"); Assert.assertEquals(frStr, "fr"); Assert.assertEquals(zhStr, "zh-Hant"); Assert.assertEquals(frenchStr, "French"); }
|
LanguageDictionary { public static String getRegexPattern(String original) { String res = original; res = specialCharsPattern.matcher(res).replaceAll("\\\\$1"); res = specifierPattern.matcher(res).replaceAll("(.*){1}"); return res; } LanguageDictionary(String lprojName); static LanguageDictionary createFromFile(File f); JSONObject readContentFromBinaryFile(File binaryFile); void addJSONContent(JSONObject content); static List<File> getL10NFiles(File aut); static String extractLanguageName(File f); ImmutableList<ContentResult> getPotentialMatches(String string); boolean match(String content, String originalText); static String getRegexPattern(String original); AppleLanguage getLanguage(); @Override int hashCode(); @Override boolean equals(Object obj); String translate(ContentResult res); String getContentForKey(String key); static final Form form; static final Pattern specifierPattern; }
|
@Test public void getRegexPattern() { Assert.assertEquals(LanguageDictionary.getRegexPattern( "%@"), "(.*){1}"); Assert.assertEquals(LanguageDictionary.getRegexPattern( "\\%@"), "\\%@"); Assert.assertEquals(LanguageDictionary.getRegexPattern( "[](){}.?*+"), "\\[\\]\\(\\)\\{\\}\\.\\?\\*\\+"); Assert.assertEquals(LanguageDictionary.getRegexPattern( "% %%"), "% %%"); Assert.assertEquals(LanguageDictionary.getRegexPattern( "(%@ %1$@ %23$@ %d %@ %1$@ %54$@ %d % %%)."), "\\((.*){1} (.*){1} (.*){1} (.*){1} (.*){1} (.*){1} (.*){1} (.*){1} % %%\\)\\."); }
|
Calculator { public static Position findPosition(Position startingLocation, Position endLocation, double distanceTravelled) { double distance = distanceTravelled / 6371000; LatLonPoint result = GreatCircle.pointAtDistanceBetweenPoints( Math.toRadians(startingLocation.getLatitude()), Math.toRadians(startingLocation.getLongitude()), Math.toRadians(endLocation.getLatitude()), Math.toRadians(endLocation.getLongitude()), distance / 2, 512); return Position.create(result.getLatitude(), result.getLongitude()); } static double crossTrackDistance(Position lineStart,
Position lineEnd, Position point); static Position findCenterPosition(Position A, Position B,
CoordinateSystem system); static double range(Position pos1, Position pos2, Heading heading); static double bearing(Position pos1, Position pos2, Heading heading); static double distanceAfterTimeMph(Double mph, long seconds); static Position findPosition(Position startingLocation,
Position endLocation, double distanceTravelled); static Position findPosition(Position startingLocation,
double bearing, double distanceTravelled); static Position calculateEndingGlobalCoordinates(
Ellipsoid ellipsoid, Position start, double startBearing,
double distance, double[] endBearing); static double turn90Plus(double direction); static double turn90Minus(double direction); static double reverseDirection(double direction); }
|
@Test public void testFindPosition() throws FormatException{ double lat = ParseUtils.parseLatitude("61 00.000N"); double lon = ParseUtils.parseLongitude("051 00.000W"); Position start = Position.create(lat, lon); Position result = Calculator.findPosition(start, 45.0, 9260.0); assertNotNull(result); assertEquals("61 03.530N", result.getLatitudeAsString()); assertEquals("050 52.699W", result.getLongitudeAsString()); }
|
Calculator { public static double range(Position pos1, Position pos2, Heading heading) { double meters; if (heading == Heading.RL) { meters = pos1.rhumbLineDistanceTo(pos2); } else { meters = pos1.geodesicDistanceTo(pos2); } return Converter.metersToNm(meters); } static double crossTrackDistance(Position lineStart,
Position lineEnd, Position point); static Position findCenterPosition(Position A, Position B,
CoordinateSystem system); static double range(Position pos1, Position pos2, Heading heading); static double bearing(Position pos1, Position pos2, Heading heading); static double distanceAfterTimeMph(Double mph, long seconds); static Position findPosition(Position startingLocation,
Position endLocation, double distanceTravelled); static Position findPosition(Position startingLocation,
double bearing, double distanceTravelled); static Position calculateEndingGlobalCoordinates(
Ellipsoid ellipsoid, Position start, double startBearing,
double distance, double[] endBearing); static double turn90Plus(double direction); static double turn90Minus(double direction); static double reverseDirection(double direction); }
|
@Test public void testRange() throws FormatException{ double lat = ParseUtils.parseLatitude("61 00.000N"); double lon = ParseUtils.parseLongitude("051 00.000W"); Position start = Position.create(lat, lon); lat = ParseUtils.parseLatitude("61 03.530N"); lon = ParseUtils.parseLongitude("050 52.699W"); Position end = Position.create(lat, lon); double result = Calculator.range(start, end, Heading.RL); assertEquals(5.000017243489917, result, 0.0); }
|
Converter { public static double nmToMeters(double nm) { return new Dist(DistType.NAUTICAL_MILES, nm).in(DistType.METERS).doubleValue(); } static double metersToNm(double meters); static double nmToMeters(double nm); static double milesToNM(double m); static double metersToFeet(double m); static double millisToHours(long millis); }
|
@Test public void testNmToMeters(){ double result = Converter.nmToMeters(5.0); assertEquals(9260.0, result, 0.0); }
|
SAROperation { public RapidResponseData startRapidResponseCalculations(RapidResponseData data) { double difference = (double) (data.getCSSDate().getMillis() - data.getLKPDate().getMillis()) / 60 / 60 / 1000; data.setTimeElasped(difference); return rapidResponse(data); } SAROperation(SAR_TYPE operationType); DatumLineData startDatumLineCalculations(DatumLineData data); RapidResponseData startRapidResponseCalculations(RapidResponseData data); DatumPointData startDatumPointCalculations(DatumPointData data); List<SARData> sarFutureCalculations(SARData data); DatumPointData datumPoint(DatumPointData data); Position applyDriftToPoint(SARData data, Position point, double timeElapsed); static void findRapidResponseBox(Position datum, double radius, RapidResponseData data); SAR_TYPE getOperationType(); void calculateEffortAllocation(SARData data); }
|
@Test public void testRapidResponseWithOneSurfarceDriftPoint(){ SAROperation operation = new SAROperation(SAR_TYPE.RAPID_RESPONSE); DateTime now = DateTime.now(); DateTime lastKnowPositionTs = now.minusHours(1); Position lastKnowPosition = Position.create(61, -51); DateTime css = now; double xError = 1.0; double yError = 0.1; double safetyFactor = 1.0; RapidResponseData data = new RapidResponseData("1", lastKnowPositionTs, css, lastKnowPosition, xError, yError, safetyFactor, 0) ; List<SARWeatherData> surfaceDriftData = new ArrayList<>(); surfaceDriftData.add(new SARWeatherData(45.0, 5.0, 15.0, 30.0, lastKnowPositionTs)); data.setWeatherPoints(surfaceDriftData); operation.startRapidResponseCalculations(data); assertEquals("61 03.328N", data.getDatum().getLatitudeAsString()); assertEquals("050 52.939W", data.getDatum().getLongitudeAsString()); assertEquals(45.78003035557367, data.getRdvDirection(), 0.0); assertEquals(4.7754450213160355, data.getRdvDistance(), 0.0); assertEquals(4.7754450213160355, data.getRdvSpeed(), 0.0); assertEquals(2.5326335063948107, data.getRadius(), 0.0); assertEquals("61 06.905N", data.getA().getLatitudeAsString()); assertEquals("050 52.842W", data.getA().getLongitudeAsString()); assertEquals("61 03.278N", data.getB().getLatitudeAsString()); assertEquals("050 45.541W", data.getB().getLongitudeAsString()); assertEquals("60 59.748N", data.getC().getLatitudeAsString()); assertEquals("050 53.043W", data.getC().getLongitudeAsString()); assertEquals("61 03.375N", data.getD().getLatitudeAsString()); assertEquals("051 00.331W", data.getD().getLongitudeAsString()); }
@Test public void testRapidResponseWithTwoSurfarceDriftPoints(){ SAROperation operation = new SAROperation(SAR_TYPE.RAPID_RESPONSE); DateTime now = DateTime.now(); DateTime lastKnowPositionTs = now.minusHours(1); Position lastKnowPosition = Position.create(61, -51); DateTime css = now; double x = 0.1; double y = 0.1; double safetyFactor = 1.0; RapidResponseData data = new RapidResponseData("1", lastKnowPositionTs, css, lastKnowPosition, x, y, safetyFactor, 0) ; List<SARWeatherData> surfaceDriftData = new ArrayList<>(); surfaceDriftData.add(new SARWeatherData(45.0, 5.0, 15.0, 30.0, lastKnowPositionTs)); surfaceDriftData.add(new SARWeatherData(35.0, 8.0, 10.0, 20.0, lastKnowPositionTs.plusMinutes(30))); data.setWeatherPoints(surfaceDriftData); operation.startRapidResponseCalculations(data); assertEquals("61 04.854N", data.getDatum().getLatitudeAsString()); assertEquals("050 51.794W", data.getDatum().getLongitudeAsString()); assertEquals(35.37281521097134, data.getRdvDirection(), 0.0); assertEquals(3.9141344796902713, data.getRdvDistance(), 0.0); assertEquals(7.828268959380543, data.getRdvSpeed(), 0.0); assertEquals(1.3742403439070814, data.getRadius(), 0.0); assertEquals("61 06.769N", data.getA().getLatitudeAsString()); assertEquals("050 52.467W", data.getA().getLongitudeAsString()); assertEquals("61 05.179N", data.getB().getLatitudeAsString()); assertEquals("050 47.833W", data.getB().getLongitudeAsString()); assertEquals("61 02.939N", data.getC().getLatitudeAsString()); assertEquals("050 51.124W", data.getC().getLongitudeAsString()); assertEquals("61 04.529N", data.getD().getLatitudeAsString()); assertEquals("050 55.753W", data.getD().getLongitudeAsString()); }
|
SAROperation { public DatumPointData startDatumPointCalculations(DatumPointData data) { double difference = (double) (data.getCSSDate().getMillis() - data.getLKPDate().getMillis()) / 60 / 60 / 1000; data.setTimeElasped(difference); return datumPoint(data); } SAROperation(SAR_TYPE operationType); DatumLineData startDatumLineCalculations(DatumLineData data); RapidResponseData startRapidResponseCalculations(RapidResponseData data); DatumPointData startDatumPointCalculations(DatumPointData data); List<SARData> sarFutureCalculations(SARData data); DatumPointData datumPoint(DatumPointData data); Position applyDriftToPoint(SARData data, Position point, double timeElapsed); static void findRapidResponseBox(Position datum, double radius, RapidResponseData data); SAR_TYPE getOperationType(); void calculateEffortAllocation(SARData data); }
|
@Test public void testDatumPointWithOneSurfarceDriftPoint(){ SAROperation operation = new SAROperation(SAR_TYPE.DATUM_POINT); double allowedUncertainty = 0.00005; DateTime now = DateTime.now(); DateTime lastKnowPositionTs = now.minusHours(1); Position lastKnowPosition = Position.create(61, -51); DateTime css = now; double xError = 1.0; double yError = 0.1; double safetyFactor = 1.0; DatumPointData data = new DatumPointData("1", lastKnowPositionTs, css, lastKnowPosition, xError, yError, safetyFactor, 0) ; List<SARWeatherData> surfaceDriftData = new ArrayList<>(); surfaceDriftData.add(new SARWeatherData(45.0, 5.0, 15.0, 30.0, lastKnowPositionTs)); data.setWeatherPoints(surfaceDriftData); operation.startDatumPointCalculations(data); assertEquals("61 03.328N", data.getDatumDownWind().getLatitudeAsString()); assertEquals("050 52.939W", data.getDatumDownWind().getLongitudeAsString()); assertEquals(45.780030, data.getRdvDirectionDownWind(), allowedUncertainty); assertEquals(4.7754450213160355, data.getRdvDistanceDownWind(), allowedUncertainty); assertEquals(4.7754450213160355, data.getRdvSpeedDownWind(), allowedUncertainty); assertEquals(2.5326335063948107, data.getRadiusDownWind(), allowedUncertainty); assertEquals("61 03.413N", data.getDatumMax().getLatitudeAsString()); assertEquals("050 53.115W", data.getDatumMax().getLongitudeAsString()); assertEquals(44.331598, data.getRdvDirectionMax(), allowedUncertainty); assertEquals(4.7752103, data.getRdvDistanceMax(), allowedUncertainty); assertEquals(4.7752103, data.getRdvSpeedMax(), allowedUncertainty); assertEquals(2.5325631, data.getRadiusMax(), allowedUncertainty); assertEquals("61 03.297N", data.getDatumMin().getLatitudeAsString()); assertEquals("050 52.699W", data.getDatumMin().getLongitudeAsString()); assertEquals(47.008245, data.getRdvDirectionMin(), allowedUncertainty); assertEquals(4.8383743, data.getRdvDistanceMin(), allowedUncertainty); assertEquals(4.8383743, data.getRdvSpeedMin(), allowedUncertainty); assertEquals(2.5515123, data.getRadiusMin(), allowedUncertainty); assertEquals("60 59.801N", data.getA().getLatitudeAsString()); assertEquals("050 50.788W", data.getA().getLongitudeAsString()); assertEquals("61 02.460N", data.getB().getLatitudeAsString()); assertEquals("051 00.292W", data.getB().getLongitudeAsString()); assertEquals("61 06.878N", data.getC().getLatitudeAsString()); assertEquals("050 55.017W", data.getC().getLongitudeAsString()); assertEquals("61 04.229N", data.getD().getLatitudeAsString()); assertEquals("050 45.497W", data.getD().getLongitudeAsString()); }
|
TitleModel extends AbstractComponentModel { public String getTitle() { return title; } String getTitle(); String getType(); }
|
@Test public void testTitleFromResource() { resource = context.currentResource(TITLE_RESOURCE); underTest = context.request().adaptTo(TitleModel.class); assertEquals("Blog English Homepage", underTest.getTitle()); }
@Test public void testTitleFromPage() { resource = context.currentResource(EMPTY_TITLE_RESOURCE); underTest = context.request().adaptTo(TitleModel.class); assertEquals("English", underTest.getTitle()); }
|
TitleModel extends AbstractComponentModel { public String getType() { return type; } String getTitle(); String getType(); }
|
@Test public void testType() { resource = context.currentResource(TITLE_RESOURCE); underTest = context.request().adaptTo(TitleModel.class); assertEquals("h2", underTest.getType()); }
@Test public void testTypeNull() { resource = context.currentResource(EMPTY_TITLE_RESOURCE); underTest = context.request().adaptTo(TitleModel.class); assertNull(underTest.getType()); }
|
TitleModel extends AbstractComponentModel { @Override protected String getIdPrefix() { return ID_PREFIX; } String getTitle(); String getType(); }
|
@Test public void testIdPrefix() { underTest = context.request().adaptTo(TitleModel.class); assertEquals("title", underTest.getIdPrefix()); }
|
JavaClass { public int returnInputValue(int input) { return input; } int returnInputValue(int input); }
|
@Test public void shouldReturnGivenValue() { JavaClass javaClass = new JavaClass(); int returnedValue = javaClass.returnInputValue(TEST_VALUE); assertThat(returnedValue).isEqualTo(TEST_VALUE); }
|
EventCache implements Map { public Object put(Object entity, Object copy) { return put( entity, copy, Boolean.FALSE ); } EventCache(EventSource session); void clear(); boolean containsKey(Object entity); boolean containsValue(Object copy); Set entrySet(); Object get(Object entity); boolean isEmpty(); Set keySet(); Object put(Object entity, Object copy); void putAll(Map map); Object remove(Object entity); int size(); Collection values(); boolean isOperatedOn(Object entity); Map invertMap(); }
|
@Test public void testCopyAssociatedWithNewAndExistingEntity() { session.getTransaction().begin(); Simple entity = new Simple( 1 ); Simple copy = new Simple( 0 ); session.persist( entity ); cache.put(entity, copy); session.flush(); try { cache.put( new Simple( 1 ), copy ); fail( "should have thrown IllegalStateException"); } catch( IllegalStateException ex ) { assertTrue( ex.getMessage().startsWith( "Error occurred while storing entity [org.hibernate.event.internal.EventCacheTest$Simple@" ) ); } session.getTransaction().rollback(); }
@Test public void testCopyAssociatedWith2ExistingEntities() { session.getTransaction().begin(); Simple entity1 = new Simple( 1 ); session.persist( entity1 ); Simple copy1 = new Simple( 1 ); cache.put(entity1, copy1); Simple entity2 = new Simple( 2 ); session.persist( entity2 ); Simple copy2 = new Simple( 2 ); cache.put( entity2, copy2 ); session.flush(); try { cache.put( entity1, copy2 ); fail( "should have thrown IllegalStateException"); } catch( IllegalStateException ex ) { assertTrue( ex.getMessage().startsWith( "Error occurred while storing entity [org.hibernate.event.internal.EventCacheTest$Simple#1]." ) ); } session.getTransaction().rollback(); }
|
EventCache implements Map { public Object remove(Object entity) { if ( entity == null ) { throw new NullPointerException( "null entities are not supported by " + getClass().getName() ); } Boolean oldOperatedOn = entityToOperatedOnFlagMap.remove( entity ); Object oldCopy = entityToCopyMap.remove( entity ); Object oldEntity = oldCopy != null ? copyToEntityMap.remove( oldCopy ) : null; if ( oldCopy == null ) { if ( oldOperatedOn != null ) { throw new IllegalStateException( "Removed entity " + printEntity( entity ) + " from EventCache#entityToOperatedOnFlagMap, but EventCache#entityToCopyMap did not contain the entity." ); } } else { if ( oldEntity == null ) { throw new IllegalStateException( "Removed entity " + printEntity( entity ) + " from EventCache#entityToCopyMap, but EventCache#copyToEntityMap did not contain the entity." ); } if ( oldOperatedOn == null ) { throw new IllegalStateException( "EventCache#entityToCopyMap contained an entity " + printEntity( entity ) + ", but EventCache#entityToOperatedOnFlagMap did not." ); } if ( oldEntity != entity ) { throw new IllegalStateException( "An entity copy " + printEntity( oldCopy ) + " was associated with a different entity " + printEntity( oldEntity ) + " than provided " + printEntity( entity ) + "." ); } } return oldCopy; } EventCache(EventSource session); void clear(); boolean containsKey(Object entity); boolean containsValue(Object copy); Set entrySet(); Object get(Object entity); boolean isEmpty(); Set keySet(); Object put(Object entity, Object copy); void putAll(Map map); Object remove(Object entity); int size(); Collection values(); boolean isOperatedOn(Object entity); Map invertMap(); }
|
@Test public void testRemoveNonExistingEntity() { assertNull( cache.remove( new Simple( 1 ) ) ); }
|
Template { public static String renderWhereStringTemplate(String sqlWhereString, Dialect dialect, SQLFunctionRegistry functionRegistry) { return renderWhereStringTemplate(sqlWhereString, TEMPLATE, dialect, functionRegistry); } private Template(); static String renderWhereStringTemplate(String sqlWhereString, Dialect dialect, SQLFunctionRegistry functionRegistry); @Deprecated @SuppressWarnings({ "JavaDoc" }) static String renderWhereStringTemplate(String sqlWhereString, String placeholder, Dialect dialect); static String renderWhereStringTemplate(String sqlWhereString, String placeholder, Dialect dialect, SQLFunctionRegistry functionRegistry ); @Deprecated static String renderOrderByStringTemplate(
String orderByFragment,
Dialect dialect,
SQLFunctionRegistry functionRegistry); static String renderOrderByStringTemplate(
String orderByFragment,
final ColumnMapper columnMapper,
final SessionFactoryImplementor sessionFactory,
final Dialect dialect,
final SQLFunctionRegistry functionRegistry); static OrderByTranslation translateOrderBy(
String orderByFragment,
final ColumnMapper columnMapper,
final SessionFactoryImplementor sessionFactory,
final Dialect dialect,
final SQLFunctionRegistry functionRegistry); static final String TEMPLATE; static OrderByAliasResolver LEGACY_ORDER_BY_ALIAS_RESOLVER; }
|
@Test public void testSqlExtractFunction() { String fragment = "extract( year from col )"; String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "extract(year from " + Template.TEMPLATE + ".col)", template ); }
@Test public void testSqlTrimFunction() { String fragment = "trim( col )"; String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(" + Template.TEMPLATE + ".col)", template ); fragment = "trim( from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( both from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(both from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( leading from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(leading from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( TRAILING from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(TRAILING from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( 'b' from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim('b' from " + Template.TEMPLATE + ".col)", template ); fragment = "trim( both 'b' from col )"; template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY ); assertEquals( "trim(both 'b' from " + Template.TEMPLATE + ".col)", template ); }
|
Latitude implements Serializable { @Override public String toString() { return String.format(Locale.ENGLISH, "%f", value); } Latitude(Double value); Latitude(Integer value); Double value(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
@Test public void latitude_string_url_values_are_correct() { Latitude l = new Latitude(-0.000066); assertEquals("-0.000066", l.toString()); }
|
Longitude implements Serializable { @Override public String toString() { return String.format(Locale.ENGLISH, "%f", value); } Longitude(Double value); Longitude(Integer value); Double value(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
@Test public void longitude_string_url_values_are_correct() { Longitude l = new Longitude(-0.000066); assertEquals("-0.000066", l.toString()); }
|
CDep { public static void main(@NotNull String[] args) { try { new CDep(AnsiConsole.out, AnsiConsole.err, true).go(args, false); } catch (Throwable e) { e.printStackTrace(); System.exit(Integer.MIN_VALUE); } finally { AnsiConsole.out.close(); AnsiConsole.err.close(); } } CDep(@NotNull PrintStream out, @NotNull PrintStream err, boolean ansi); static void main(@NotNull String[] args); }
|
@Test public void lintUsage() throws Exception { assertThat(main("lint")).contains("Usage:"); }
@Test public void lintSomeKnownLibraries() throws Exception { main(main("lint", "com.github.jomof:sqlite:3.16.2-rev25", "com.github.jomof:boost:1.0.63-rev18", "com.github.jomof:sdl2:2.0.5-rev11")); }
@Test public void testVersion() throws Exception { assertThat(main("--version")).contains(BuildInfo.PROJECT_VERSION); }
@Test public void missingConfigurationFile() throws Exception { new File(".test-files/empty-folder").mkdirs(); assertThat(main("-wf", ".test-files/empty-folder")).contains("configuration file"); }
@Test public void workingFolderFlag() throws Exception { assertThat(main("--working-folder", "non-existing-blah")).contains("non-existing-blah"); }
@Test public void wfFlag() throws Exception { assertThat(main("-wf", "non-existing-blah")).contains("non-existing-blah"); }
@Test public void testMissingGithubCoordinate() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/runMathfu/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github.jomof:mathfoo:1.0.2-rev7\n", yaml, StandardCharsets.UTF_8); try { String result = main("-wf", yaml.getParent()); System.out.printf(result); fail("Expected an exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Could not resolve 'com.github.jomof:mathfoo:1.0.2-rev7'. It doesn't exist."); } }
@Test public void unfindableLocalFile() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/unfindableLocalFile/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n", yaml, StandardCharsets.UTF_8); try { main("-wf", yaml.getParent()); fail("Expected failure"); } catch (RuntimeException e) { assertThat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist."); } }
@Test public void sqlite() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/firebase/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); String result = main("-wf", yaml.getParent()); System.out.printf(result); }
@Test public void redownload() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/simpleDependency/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("redownload", "-wf", yaml.getParent()); System.out.printf(result); assertThat(result).contains("Redownload"); }
@Test public void fetch() throws Exception { File folder = new File(".test-files/fetchArchive"); folder.mkdirs(); String result = main("fetch", "com.github.jomof:low-level-statistics:0.0.16", "com.github" + ".jomof:low-level-statistics:0.0.16", "-wf", folder.toString()); System.out.printf(result); assertThat(result).contains("Fetch complete"); }
@Test public void startupInfo() throws Exception { String result = main("startup-info"); System.out.printf(result); }
@Test public void fetchArchive() throws Exception { File folder = new File(".test-files/fetch"); folder.mkdirs(); String result = main("fetch-archive", "com.github.jomof:low-level-statistics:0.0.22", "https: "2035", "1661c899dee3b7cf1bb3e376c1cd504a156a4658904d8554a84db4e5a71ade49", "-wf", folder.toString()); System.out.printf(result); }
@Test public void fetchNotFound() throws Exception { File folder = new File(".test-files/fetch"); folder.mkdirs(); try { main("fetch", "com.github.jomof:low-level-statistics-x:0.0.16", "-wf", folder.toString()); fail("Expected failure"); } catch (RuntimeException e) { assertThat(e).hasMessage("Could not resolve 'com.github.jomof:low-level-statistics-x:0.0.16'. It doesn't exist."); } }
@Test public void createHashes() throws Exception { File yaml = new File(".test-files/simpleDependency/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); String text = main("create", "hashes", "-wf", yaml.getParent()); assertThat(text).contains("Created cdep.sha256"); File hashFile = new File(".test-files/simpleDependency/cdep.sha256"); assertThat(hashFile.isFile()); }
@Test public void checkThatHashesWork() throws Exception { File yaml = new File(".test-files/checkThatHashesWork/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); File hashes = new File(".test-files/checkThatHashesWork/cdep.sha256"); Files.write("- coordinate: com.github.jomof:low-level-statistics:0.0.16\n " + "sha256: dogbone", hashes, StandardCharsets.UTF_8); try { main("-wf", yaml.getParent()); fail("Expected failure"); } catch (RuntimeException e) { assertThat(e).hasMessage("SHA256 of cdep-manifest.yml for package 'com.github.jomof:low-level-statistics:0.0.16' " + "does not agree with constant in cdep.sha256. Something changed."); } }
@Test public void noDependencies() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/simpleDependency/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n", yaml, StandardCharsets.UTF_8); String result1 = main("-wf", yaml.getParent()); System.out.printf(result1); assertThat(result1).contains("Nothing"); }
@Test public void dumpIsSelfHost() throws Exception { System.out.printf("%s\n", System.getProperty("user.home")); CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/simpleConfiguration/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); String result2 = main("show", "manifest", "-wf", yaml.getParent()); assertThat(result2).isEqualTo(result1); }
@Test public void testNakedCall() throws Exception { main(); }
@Test public void showFolders() throws Exception { String result = main("show", "folders"); System.out.printf(result); }
@Test public void showInclude() throws Exception { String result = main("show", "include", "com.github.jomof:boost:1.0.63-rev21"); assertThat(result).contains(".zip"); System.out.printf(result); }
@Test public void showIncludeNoCoordinate() throws Exception { String result = main("show", "include"); assertThat(result).contains("Usage: show include {coordinate}"); System.out.printf(result); }
@Test public void mergeTwo() throws Exception { File output = new File(".test-files/mergeTwo/merged-manifest.yml"); output.delete(); String text = main("merge", "com.github.jomof:sqlite/iOS:3.16.2-rev33", "com.github.jomof:sqlite/android:3.16.2-rev33", output.toString()); System.out.printf(text); }
@Test public void help() throws Exception { String result = main("--help"); System.out.printf(result); assertThat(result).contains("show folders"); }
@Test public void testWrapper() throws Exception { File testFolder = new File(".test-files/testWrapper"); File redistFolder = new File(testFolder, "redist"); File workingFolder = new File(testFolder, "working"); File cdepFile = new File(redistFolder, "cdep"); File cdepBatFile = new File(redistFolder, "cdep.bat"); File cdepYmlFile = new File(redistFolder, "cdep.yml"); File bootstrapJar = new File(redistFolder, "bootstrap/wrapper/bootstrap.jar"); redistFolder.mkdirs(); workingFolder.mkdirs(); bootstrapJar.getParentFile().mkdirs(); Files.write("cdepFile content", cdepFile, Charset.defaultCharset()); Files.write("cdepBatFile content", cdepBatFile, Charset.defaultCharset()); Files.write("cdepYmlFile content", cdepYmlFile, Charset.defaultCharset()); Files.write("bootstrapJar content", bootstrapJar, Charset.defaultCharset()); System.setProperty("io.cdep.appname", new File(redistFolder, "cdep.bat").getAbsolutePath()); String result; try { result = main("wrapper", "-wf", workingFolder.toString()); } finally { System.setProperty("io.cdep.appname", "rando-test-folder"); } System.out.print(result); assertThat(result).contains("Installing cdep"); File cdepToFile = new File(workingFolder, "cdep"); File cdepBatToFile = new File(workingFolder, "cdep.bat"); File cdepYmlToFile = new File(workingFolder, "cdep.yml"); File bootstrapJarToFile = new File(workingFolder, "bootstrap/wrapper/bootstrap.jar"); assertThat(cdepToFile.isFile()).isTrue(); assertThat(cdepBatToFile.isFile()).isTrue(); assertThat(cdepYmlToFile.isFile()).isTrue(); assertThat(bootstrapJarToFile.isFile()).isTrue(); }
@Test public void localPathsWork() throws Exception { File yaml = new File(".test-files/localPathsWork/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); String resultRemote = main("-wf", yaml.getParent()); String localPath = main("show", "local", "com.github.jomof:low-level-statistics:0.0.16"); assertThat(localPath).contains("cdep-manifest.yml"); Files.write(String.format("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: %s\n", localPath), yaml, StandardCharsets.UTF_8); String resultLocal = main("-wf", yaml.getParent(), "-df", new File(yaml.getParent(), "downloads").getPath()); System.out.print(resultLocal); resultLocal = main("-wf", yaml.getParent()); System.out.print(resultLocal); }
@Test public void mergeTwoWithDifferentHash() throws Exception { File left = new File(".test-files/mergeTwo/merged-manifest-left.yml"); File right = new File(".test-files/mergeTwo/merged-manifest-right.yml"); File merged = new File(".test-files/mergeTwo/merged-manifest-merged.yml"); left.delete(); right.delete(); merged.delete(); merged.getParentFile().mkdirs(); Files.write("coordinate:\n" + " groupId: com.github.jomof\n" + " artifactId: sdl2\n" + " version: 2.0.5-rev26\n" + "interfaces:\n" + " headers:\n" + " file: headers.zip\n" + " sha256: e7e61f29f9480209f1cad71c4d4f7cec75d63e7a457bbe9da0ac26a64ad5751b-left\n" + " size: 338812\n" + " include: include", left, StandardCharsets.UTF_8); Files.write("coordinate:\n" + " groupId: com.github.jomof\n" + " artifactId: sdl2\n" + " version: 2.0.5-rev26\n" + "interfaces:\n" + " headers:\n" + " file: headers.zip\n" + " sha256: e7e61f29f9480209f1cad71c4d4f7cec75d63e7a457bbe9da0ac26a64ad5751-right\n" + " size: 338812\n" + " include: include", right, StandardCharsets.UTF_8); merged.getParentFile().mkdirs(); String text = main("merge", left.toString(), right.toString(), merged.toString()); System.out.printf(text); String mergedText = FileUtils.readAllText(merged); System.out.printf(mergedText); assertThat(mergedText).contains("-right"); }
@Test public void fullfill() throws Exception { String text = main("fullfill", "../third_party/stb", "1.0.0", "../third_party/stb/cdep/cdep-manifest-divide.yml", "../third_party/stb/cdep/cdep-manifest-c_lexer.yml"); System.out.printf(text); }
@Test public void mergeHeaders() throws Exception { File output = new File(".test-files/mergeHeaders/merged-manifest.yml"); File zip = new File(".test-files/mergeHeaders/headers.zip"); zip.getParentFile().mkdirs(); Files.write("xyz", zip, StandardCharsets.UTF_8); output.delete(); String text = main("merge", "headers", "com.github.jomof:sqlite:3.16.2-rev48", zip.toString(), "include", output.toString()); assertThat(text).doesNotContain("Usage"); assertThat(text).contains("Merged com.github.jomof:sqlite:3.16.2-rev48 and "); System.out.printf(text); System.out.printf(FileUtils.readAllText(output)); }
@Test public void mergeFirstMissing() throws Exception { File output = new File(".test-files/mergeFirstMissing/merged-manifest.yml"); output.delete(); assertThat(main("merge", "non:existing:1.2.3", "com.github.jomof:firebase/admob:2.1.3-rev8", output.toString())).contains ("Manifest for 'non:existing:1.2.3' didn't exist"); }
@Test public void mergeTwo1() throws Exception { File output = new File(".test-files/mergeTwo1/merged-manifest.yml"); output.delete(); assertThat(main("merge", "com.github.jomof:sqlite/iOS:3.16.2-rev26", "com.github.jomof:sqlite/android:3.16.2-rev26", output .toString())).contains("Merged 2 manifests into"); }
@Test public void mergeTwo2() throws Exception { File output = new File(".test-files/mergeTwo2/merged-manifest.yml"); output.delete(); assertThat(main("merge", "com.github.jomof:cmakeify/iOS:0.0.219", "com.github.jomof:cmakeify/android:0.0.219", output .toString())).contains("Merged 2 manifests into"); }
@Test public void lintBoost() throws Exception { main(main("lint", "com.github.jomof:boost:1.0.63-rev18" )); }
|
API { static String getJvmLocation() { String java = System.getProperties().getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (PlatformUtils.isWindows()) { java += ".exe"; java = java.replace("\\", "/"); } File result = new File(java); require(result.isFile(), "Expected to find java at %s but didn't", result); return java; } @NotNull static List<String> generateCDepCall(
@NotNull GeneratorEnvironment environment,
String ... args); }
|
@Test public void testGetJvmLocation() { System.out.printf("%s", API.getJvmLocation()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.