method2testcases
stringlengths 118
3.08k
|
---|
### Question:
UpdateK8sSecurityGroupMemberLabelMetaTask extends TransactionalMetaTask { UpdateK8sSecurityGroupMemberLabelMetaTask create(SecurityGroupMember sgm, KubernetesPodApi k8sPodApi) { UpdateK8sSecurityGroupMemberLabelMetaTask task = new UpdateK8sSecurityGroupMemberLabelMetaTask(); task.sgm = sgm; task.labelPodCreateTask = this.labelPodCreateTask; task.labelPodDeleteTask = this.labelPodDeleteTask; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; task.k8sPodApi = this.k8sPodApi; return task; } @Override TaskGraph getTaskGraph(); @Override String getName(); @Override void executeTransaction(EntityManager em); @Override Set<LockObjectReference> getObjects(); }### Answer:
@Test public void testExecute_WithVariousSGM_ExpectCorrectTaskGraph() throws Exception { UpdateK8sSecurityGroupMemberLabelMetaTask task = this.factoryTask.create(this.sgm, this.k8sPodApi); task.labelPodCreateTask = new CreateK8sLabelPodTask(); task.labelPodDeleteTask = new DeleteK8sLabelPodTask(); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
### Question:
UpdateOrDeleteK8sSecurityGroupMetaTask extends TransactionalMetaTask { public UpdateOrDeleteK8sSecurityGroupMetaTask create(SecurityGroup sg) { UpdateOrDeleteK8sSecurityGroupMetaTask task = new UpdateOrDeleteK8sSecurityGroupMetaTask(); task.sg = sg; task.checkK8sSecurityGroupLabelMetaTask = this.checkK8sSecurityGroupLabelMetaTask; task.portGroupCheckMetaTask = this.portGroupCheckMetaTask; task.deleteSecurityGroupFromDbTask = this.deleteSecurityGroupFromDbTask; task.markSecurityGroupInterfaceDeleteTask = this.markSecurityGroupInterfaceDeleteTask; task.securityGroupMemberMapPropagateMetaTask = this.securityGroupMemberMapPropagateMetaTask; task.checkPortGroupHookMetaTask = this.checkPortGroupHookMetaTask; task.deleteSecurityGroupInterfaceTask = this.deleteSecurityGroupInterfaceTask; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } UpdateOrDeleteK8sSecurityGroupMetaTask create(SecurityGroup sg); @Override TaskGraph getTaskGraph(); @Override String getName(); @Override void executeTransaction(EntityManager em); @Override Set<LockObjectReference> getObjects(); }### Answer:
@Test public void testExecute_WithVariousSecurityGroups_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.checkK8sSecurityGroupLabelMetaTask = new CheckK8sSecurityGroupLabelMetaTask(); this.factoryTask.portGroupCheckMetaTask = new PortGroupCheckMetaTask(); this.factoryTask.deleteSecurityGroupFromDbTask = new DeleteSecurityGroupFromDbTask(); this.factoryTask.markSecurityGroupInterfaceDeleteTask = new MarkSecurityGroupInterfaceDeleteTask(); this.factoryTask.securityGroupMemberMapPropagateMetaTask = new SecurityGroupMemberMapPropagateMetaTask(); this.factoryTask.checkPortGroupHookMetaTask = new CheckPortGroupHookMetaTask(); this.factoryTask.deleteSecurityGroupInterfaceTask = new DeleteSecurityGroupInterfaceTask(); UpdateOrDeleteK8sSecurityGroupMetaTask task = this.factoryTask.create(this.sg); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
### Question:
MarkSecurityGroupInterfaceDeleteTask extends TransactionalTask { public MarkSecurityGroupInterfaceDeleteTask create(SecurityGroupInterface sgi) { MarkSecurityGroupInterfaceDeleteTask task = new MarkSecurityGroupInterfaceDeleteTask(); task.sgi = sgi; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } @Override String getName(); @Override void executeTransaction(EntityManager em); MarkSecurityGroupInterfaceDeleteTask create(SecurityGroupInterface sgi); }### Answer:
@Test public void testExecute_WithVariousSGM_ExpectMarkedInTheEnd() throws Exception { MarkSecurityGroupInterfaceDeleteTask task = this.factoryTask.create(this.sgi); task.execute(); SecurityGroupInterface sgi = this.txControl.required(() -> this.em.find(SecurityGroupInterface.class, this.sgi.getId())); assertTrue(sgi.getMarkedForDeletion()); }
|
### Question:
MarkSecurityGroupMemberDeleteTask extends TransactionalTask { public MarkSecurityGroupMemberDeleteTask create(SecurityGroupMember sgm) { MarkSecurityGroupMemberDeleteTask task = new MarkSecurityGroupMemberDeleteTask(); task.sgm = sgm; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } @Override String getName(); @Override void executeTransaction(EntityManager em); MarkSecurityGroupMemberDeleteTask create(SecurityGroupMember sgm); }### Answer:
@Test public void testExecute_WithVariousSGM_ExpectMarkedInTheEnd() throws Exception { MarkSecurityGroupMemberDeleteTask task = this.factoryTask.create(this.sgm); task.execute(); SecurityGroupMember sgm = this.txControl.required(() -> this.em.find(SecurityGroupMember.class, this.sgm.getId())); assertTrue(sgm.getMarkedForDeletion()); }
|
### Question:
MgrSecurityGroupCheckMetaTask extends TransactionalMetaTask { public MgrSecurityGroupCheckMetaTask create(VirtualSystem vs) { MgrSecurityGroupCheckMetaTask task = new MgrSecurityGroupCheckMetaTask(); task.vs = vs; task.name = task.getName(); task.createMgrSecurityGroupTask = this.createMgrSecurityGroupTask; task.updateMgrSecurityGroupTask = this.updateMgrSecurityGroupTask; task.deleteMgrSecurityGroupTask = this.deleteMgrSecurityGroupTask; task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } MgrSecurityGroupCheckMetaTask create(VirtualSystem vs); MgrSecurityGroupCheckMetaTask create(VirtualSystem vs, SecurityGroup sg); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer:
@Test public void testExecute_WithVariousSecurityGroups_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.createMgrSecurityGroupTask = new CreateMgrSecurityGroupTask(); this.factoryTask.updateMgrSecurityGroupTask = new UpdateMgrSecurityGroupTask(); this.factoryTask.deleteMgrSecurityGroupTask = new DeleteMgrSecurityGroupTask(); MgrSecurityGroupCheckMetaTask task = this.factoryTask.create(this.vs, this.sg); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
### Question:
DeleteImageReferenceTask extends TransactionalTask { public DeleteImageReferenceTask create(OsImageReference imageReference, VirtualSystem vs) { DeleteImageReferenceTask task = new DeleteImageReferenceTask(); task.imageReference = imageReference; task.vs = vs; task.name = task.getName(); task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } DeleteImageReferenceTask create(OsImageReference imageReference, VirtualSystem vs); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); }### Answer:
@Test public void testExecuteTransaction_WithImage_DeletesAndUpdatesVS() throws Exception { DeleteImageReferenceTask task = this.factory.create(this.imageReference, this.vs); task.execute(); Mockito.verify(this.em).remove(this.imageReference); Mockito.verify(this.em).merge(Mockito.argThat(new ImageReferenceIsEmptyMatcher(this.vs))); Mockito.verify(this.em).merge(this.vs); }
@Test public void testExecuteTransaction_WithImageNotInVS_DeletesAndUpdatesVS() throws Exception { DeleteImageReferenceTask task = this.factory.create(this.otherImageReference, this.vs); task.execute(); Mockito.verify(this.em).remove(this.otherImageReference); Mockito.verify(this.em).merge(this.vs); }
|
### Question:
DSUpdateOrDeleteMetaTask extends TransactionalMetaTask { public DSUpdateOrDeleteMetaTask create(DeploymentSpec ds, Endpoint endPoint) { DSUpdateOrDeleteMetaTask task = new DSUpdateOrDeleteMetaTask(); task.ds = ds; task.endPoint = endPoint; task.name = task.getName(); task.osSvaCreateMetaTask = this.osSvaCreateMetaTask; task.osDAIConformanceCheckMetaTask = this.osDAIConformanceCheckMetaTask; task.mgrCheckDevicesMetaTask = this.mgrCheckDevicesMetaTask; task.deleteSvaServerAndDAIMetaTask = this.deleteSvaServerAndDAIMetaTask; task.deleteOSSecurityGroup = this.deleteOSSecurityGroup; task.deleteDsFromDb = this.deleteDsFromDb; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } DSUpdateOrDeleteMetaTask create(DeploymentSpec ds, Endpoint endPoint); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override TaskGraph getTaskGraph(); @Override Set<LockObjectReference> getObjects(); }### Answer:
@Test public void testExecuteTransaction_WithVariousDeploymentSpecs_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.osSvaCreateMetaTask = new OsSvaCreateMetaTask(); this.factoryTask.osDAIConformanceCheckMetaTask = new OsDAIConformanceCheckMetaTask(); this.factoryTask.mgrCheckDevicesMetaTask = new MgrCheckDevicesMetaTask(); this.factoryTask.deleteSvaServerAndDAIMetaTask = new DeleteSvaServerAndDAIMetaTask(); this.factoryTask.deleteOSSecurityGroup = new DeleteOsSecurityGroupTask(); this.factoryTask.deleteDsFromDb = new DeleteDSFromDbTask(); DSUpdateOrDeleteMetaTask task = this.factoryTask.create(this.ds, this.novaApiMock); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
### Question:
UpdatePortGroupHookTask extends BasePortGroupHookTask { public UpdatePortGroupHookTask create(SecurityGroupInterface sgi, DistributedApplianceInstance dai){ UpdatePortGroupHookTask task = new UpdatePortGroupHookTask(sgi, dai); task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } UpdatePortGroupHookTask(); private UpdatePortGroupHookTask(SecurityGroupInterface sgi, DistributedApplianceInstance dai); UpdatePortGroupHookTask create(SecurityGroupInterface sgi, DistributedApplianceInstance dai); @Override void executeTransaction(EntityManager em); @Override String getName(); }### Answer:
@Test public void testExecute_WhenUpdateInspectionHookFails_ThrowsTheUnhandledException() throws Exception { SecurityGroup sg = newSecurityGroup(); SecurityGroupInterface sgi = registerNewSGI(sg, 2L); DistributedApplianceInstance dai = registerNewDAI(); SdnRedirectionApi redirectionApi = mockUpdateInspectionHook(sgi, dai, new IllegalStateException()); registerNetworkRedirectionApi(redirectionApi, sgi.getVirtualSystem()); this.exception.expect(IllegalStateException.class); UpdatePortGroupHookTask task = this.factory.create(sgi, dai); task.execute(); }
@Test public void testExecute_WhenUpdateInspectionHookSucceeds_ExecutionFinishes() throws Exception { SecurityGroup sg = newSecurityGroup(); SecurityGroupInterface sgi = registerNewSGI(sg, 2L); DistributedApplianceInstance dai = registerNewDAI(); SdnRedirectionApi redirectionApi = mockUpdateInspectionHook(sgi, dai, null); registerNetworkRedirectionApi(redirectionApi, sgi.getVirtualSystem()); UpdatePortGroupHookTask task = this.factory.create(sgi, dai); task.execute(); Mockito.verify(redirectionApi, Mockito.times(1)) .updateInspectionHook(argThat(new InspectionHookMatcher(dai, sgi))); }
|
### Question:
CheckPortGroupHookMetaTask extends TransactionalMetaTask { public CheckPortGroupHookMetaTask create(SecurityGroupInterface sgi, boolean isDeleteTg) { CheckPortGroupHookMetaTask task = new CheckPortGroupHookMetaTask(); task.sgi = sgi; task.isDeleteTaskGraph = isDeleteTg; task.allocateDai = this.allocateDai; task.deallocateDai = this.deallocateDai; task.createPortGroupHook = this.createPortGroupHook; task.removePortGroupHook = this.removePortGroupHook; task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } CheckPortGroupHookMetaTask create(SecurityGroupInterface sgi, boolean isDeleteTg); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); @Override TaskGraph getTaskGraph(); }### Answer:
@Test public void testExecuteTransaction_WithVariousSecurityGroupInterfaces_ExpectsValidTaskGraphOrException() throws Exception { this.factoryTask.allocateDai = new AllocateDAIWithSGIMembersTask(); this.factoryTask.deallocateDai = new DeallocateDAIOfSGIMembersTask(); this.factoryTask.createPortGroupHook = new CreatePortGroupHookTask(); this.factoryTask.removePortGroupHook = new RemovePortGroupHookTask(); CheckPortGroupHookMetaTask task = this.factoryTask.create(this.sgi, this.isDeleteTg); if (this.expectedExceptionMessage != null) { this.exception.expect(VmidcBrokerValidationException.class); this.exception.expectMessage(this.expectedExceptionMessage); } task.execute(); if (this.expectedGraph != null) { TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); } }
|
### Question:
PortGroupCheckMetaTask extends TransactionalMetaTask { public PortGroupCheckMetaTask create(SecurityGroup sg, boolean deleteTg, String domainId) { PortGroupCheckMetaTask task = new PortGroupCheckMetaTask(); task.createPortGroupTask = this.createPortGroupTask; task.updatePortGroupTask = this.updatePortGroupTask; task.deletePortGroupTask = this.deletePortGroupTask; task.securityGroup = sg; task.deleteTg = deleteTg; task.domainId = domainId; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } PortGroupCheckMetaTask create(SecurityGroup sg, boolean deleteTg, String domainId); @Override void executeTransaction(EntityManager em); @Override String getName(); @Override Set<LockObjectReference> getObjects(); @Override TaskGraph getTaskGraph(); }### Answer:
@Test public void testExecuteTransaction_WithVariousSecurityGroups_ExpectsCorrectTaskGraph() throws Exception { this.factoryTask.createPortGroupTask = new CreatePortGroupTask(); this.factoryTask.updatePortGroupTask = new UpdatePortGroupTask(); this.factoryTask.deletePortGroupTask = new DeletePortGroupTask(); PortGroupCheckMetaTask task = this.factoryTask.create(this.sg, this.isDeleteTg, this.domainId); task.execute(); TaskGraphHelper.validateTaskGraph(task, this.expectedGraph); }
|
### Question:
DeletePortGroupTask extends TransactionalTask { public DeletePortGroupTask create(SecurityGroup securityGroup, NetworkElementImpl portGroup){ DeletePortGroupTask task = new DeletePortGroupTask(); task.securityGroup = securityGroup; task.portGroup = portGroup; task.apiFactoryService = this.apiFactoryService; task.dbConnectionManager = this.dbConnectionManager; task.txBroadcastUtil = this.txBroadcastUtil; return task; } DeletePortGroupTask create(SecurityGroup securityGroup, NetworkElementImpl portGroup); @Override void executeTransaction(EntityManager em); @Override String getName(); }### Answer:
@Test public void testExecute_WhenCreateNetworkRedirectionApiFails_ThrowsTheUnhandledException() throws Exception { SecurityGroup sg = registerSecurityGroup("SG", 1L, null); when(this.apiFactoryServiceMock.createNetworkRedirectionApi(sg.getVirtualizationConnector())) .thenThrow(new IllegalStateException()); this.exception.expect(IllegalStateException.class); DeletePortGroupTask task = this.factoryTask.create(sg, null); task.execute(); }
|
### Question:
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(); }### Answer:
@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); }
|
### Question:
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(); }### Answer:
@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(); }
|
### Question:
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(); }### Answer:
@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(); }
|
### Question:
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(); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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)); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@Test public void testDeleteBackupFiles_withNoArguments_callsDeleteDefaultBackupFiles() { doCallRealMethod().when(this.target).deleteBackupFiles(); this.target.deleteBackupFiles(); verify(this.target, times(1)).deleteBackupFiles("BrokerServerDBBackup"); }
|
### Question:
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; } }### Answer:
@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")); }
|
### Question:
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; } }### Answer:
@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")); }
|
### Question:
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; }### Answer:
@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) { } }
|
### Question:
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; }### Answer:
@Test public void testValidateDaName() { for(String item : validDaNames) { assertTrue(ValidateUtil.validateDaName(item)); } for(String item : invalidDaNames) { assertFalse(ValidateUtil.validateDaName(item)); } }
|
### Question:
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; }### Answer:
@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) { } } }
|
### Question:
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; }### Answer:
@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) { } } }
|
### Question:
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; }### Answer:
@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); }
|
### Question:
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; }### Answer:
@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); }
|
### Question:
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; }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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) { } } }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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()); }
|
### Question:
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(); }### Answer:
@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); }
|
### Question:
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(); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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"); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
DefaultLocaleResolver implements LocaleResolver { @Override public Locale getLocale() { return Locale.getDefault(); } @Override Locale getLocale(); }### Answer:
@Test public void testGetLocale() throws Exception { Locale.setDefault(Locale.FRENCH); Locale locale = localeResolver.getLocale(); assertThat(locale).isNotNull().isEqualTo(Locale.FRENCH); }
|
### Question:
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); }### Answer:
@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(); }
|
### Question:
SpringLocaleResolver implements LocaleResolver { @Override public Locale getLocale() { return LocaleContextHolder.getLocale(); } @Override Locale getLocale(); }### Answer:
@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()); }
|
### Question:
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; }### Answer:
@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()); }
|
### Question:
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(); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@Test public void serialize() throws Exception { assertThat(influxDbResponseConverter.toBody(results), is(nullValue())); }
|
### Question:
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; }### Answer:
@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")); } }
|
### Question:
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; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testInvalidSymbolsInMediaIDStructure() throws Exception { fail(MediaIDHelper.createMediaID(null, "BY|GENRE/2", "Classic 70's")); }
|
### Question:
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; }### Answer:
@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)); }
|
### Question:
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; }### Answer:
@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"); }
|
### Question:
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; }### Answer:
@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); }
|
### Question:
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; }### Answer:
@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"); }
|
### Question:
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; }### Answer:
@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} % %%\\)\\."); }
|
### Question:
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); }### Answer:
@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()); }
|
### Question:
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); }### Answer:
@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); }
|
### Question:
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); }### Answer:
@Test public void testNmToMeters(){ double result = Converter.nmToMeters(5.0); assertEquals(9260.0, result, 0.0); }
|
### Question:
TitleModel extends AbstractComponentModel { public String getTitle() { return title; } String getTitle(); String getType(); }### Answer:
@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()); }
|
### Question:
TitleModel extends AbstractComponentModel { public String getType() { return type; } String getTitle(); String getType(); }### Answer:
@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()); }
|
### Question:
TitleModel extends AbstractComponentModel { @Override protected String getIdPrefix() { return ID_PREFIX; } String getTitle(); String getType(); }### Answer:
@Test public void testIdPrefix() { underTest = context.request().adaptTo(TitleModel.class); assertEquals("title", underTest.getIdPrefix()); }
|
### Question:
JavaClass { public int returnInputValue(int input) { return input; } int returnInputValue(int input); }### Answer:
@Test public void shouldReturnGivenValue() { JavaClass javaClass = new JavaClass(); int returnedValue = javaClass.returnInputValue(TEST_VALUE); assertThat(returnedValue).isEqualTo(TEST_VALUE); }
|
### Question:
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(); }### Answer:
@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(); }
|
### Question:
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(); }### Answer:
@Test public void testRemoveNonExistingEntity() { assertNull( cache.remove( new Simple( 1 ) ) ); }
|
### Question:
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); }### Answer:
@Test public void latitude_string_url_values_are_correct() { Latitude l = new Latitude(-0.000066); assertEquals("-0.000066", l.toString()); }
|
### Question:
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); }### Answer:
@Test public void longitude_string_url_values_are_correct() { Longitude l = new Longitude(-0.000066); assertEquals("-0.000066", l.toString()); }
|
### Question:
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); }### Answer:
@Test public void testGetJvmLocation() { System.out.printf("%s", API.getJvmLocation()); }
|
### Question:
API { @NotNull public static List<String> generateCDepCall( @NotNull GeneratorEnvironment environment, String ... args) throws MalformedURLException { List<String> result = new ArrayList<>(); result.addAll(callCDep(environment)); Collections.addAll(result, args); return result; } @NotNull static List<String> generateCDepCall(
@NotNull GeneratorEnvironment environment,
String ... args); }### Answer:
@Test public void testExecute() throws Exception { String result = execute(API.generateCDepCall(environment, "show", "folders")); System.out.print(result); assertThat(result).contains("cdep"); }
|
### Question:
Resolver { @Nullable public ResolvedManifest resolveAny(@NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { ResolvedManifest resolved = null; for (CoordinateResolver resolver : resolvers) { ResolvedManifest attempt = resolver.resolve(manifestProvider, dependency); if (attempt != null) { require(resolved == null, "Multiple resolvers matched coordinate: " + dependency.compile); resolved = attempt; } } if (resolved != null) { CDepManifestYmlUtils.checkManifestSanity(resolved.cdepManifestYml); } return resolved; } Resolver(ManifestProvider manifestProvider); Resolver(ManifestProvider manifestProvider, CoordinateResolver resolvers[]); @NotNull ResolutionScope resolveAll(@NotNull SoftNameDependency[] roots); void resolveAll(@NotNull ResolutionScope scope); @Nullable ResolvedManifest resolveAny(@NotNull SoftNameDependency dependency); }### Answer:
@Test public void twoResolversMatch() throws Exception { ManifestProvider provider = mock(ManifestProvider.class); when(provider.tryGetManifest(ADMOB_COORDINATE, new URL(ADMOB_URL))).thenReturn(ADMOB_MANIFEST); CoordinateResolver resolvers[] = new CoordinateResolver[]{new GithubReleasesCoordinateResolver(), new GithubReleasesCoordinateResolver()}; Resolver resolver = new Resolver(provider, resolvers); try { assert ADMOB_COORDINATE != null; resolver.resolveAny(new SoftNameDependency(ADMOB_COORDINATE.toString())); fail("Expected exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Multiple resolvers matched coordinate: com.github.jomof:firebase/admob:2.1.3-rev7"); } }
|
### Question:
GithubReleasesCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String user = match.group(1); String artifactId = match.group(2); String version = match.group(3); String subArtifact = ""; if (artifactId.contains("/")) { int pos = artifactId.indexOf("/"); subArtifact = "-" + artifactId.substring(pos + 1); artifactId = artifactId.substring(0, pos); } String manifest = String.format("https: user, artifactId, version, subArtifact); return urlResolver.resolve(environment, new SoftNameDependency(manifest)); } return null; } @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); }### Answer:
@Test public void testCompound() throws Exception { ResolvedManifest resolved = new GithubReleasesCoordinateResolver().resolve(environment, new SoftNameDependency("com.github" + ".jomof:firebase/database:2.1.3-rev5")); assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(21); }
|
### Question:
ResolutionScope { public boolean isResolutionComplete() { return unresolved.isEmpty(); } ResolutionScope(@NotNull SoftNameDependency[] roots); ResolutionScope(); void addUnresolved(@NotNull SoftNameDependency softname); boolean isResolutionComplete(); @NotNull Collection<SoftNameDependency> getUnresolvedReferences(); @NotNull Collection<String> getUnresolvableReferences(); @NotNull Unresolvable getUnresolveableReason(@NotNull String softname); void recordResolved(@NotNull SoftNameDependency softname,
@NotNull ResolvedManifest resolved,
@NotNull List<HardNameDependency> transitiveDependencies); void recordUnresolvable(@NotNull SoftNameDependency softname); @NotNull ResolvedManifest getResolution(@NotNull String name); @NotNull Collection<String> getResolutions(); @NotNull Collection<Coordinate> getUnificationWinners(); @NotNull Collection<Coordinate> getUnificationLosers(); @NotNull
final public Map<Coordinate, List<Coordinate>> forwardEdges; @NotNull
final public Map<Coordinate, List<Coordinate>> backwardEdges; }### Answer:
@Test public void testNoRoots() throws IOException { ResolutionScope scope = new ResolutionScope(new SoftNameDependency[0]); assertThat(scope.isResolutionComplete()).isTrue(); }
|
### Question:
CommandLineUtils { @NotNull public static String getLibraryNameFromLibraryFilename(@NotNull File library) { String name = library.getName(); if (failIf(!name.startsWith("lib"), "Library name from manifest wasn't in the form libXXXX.a")) { return name; } if (failIf(!name.endsWith(".a"), "Library name from manifest wasn't in the form libXXXX.a")) { return name; } name = name.substring(3, name.length() - 2); return name; } @NotNull static String getLibraryNameFromLibraryFilename(@NotNull File library); }### Answer:
@Test public void testBasic() { assertThat(CommandLineUtils.getLibraryNameFromLibraryFilename( new File("/path/to/libmyfile.a"))).isEqualTo("myfile"); }
|
### Question:
StringUtils { public static boolean isNumeric(@NotNull String str) { for (char c : str.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }### Answer:
@Test public void isNumeric() throws Exception { assertThat(StringUtils.isNumeric("x")).isFalse(); assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNumber() { assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNotNumber() { assertThat(StringUtils.isNumeric("x")).isFalse(); }
|
### Question:
StringUtils { public static String joinOn(String delimiter, @NotNull Object array[]) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; ++i) { if (i != 0) { sb.append(delimiter); } sb.append(array[i]); } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }### Answer:
@Test public void joinOn() throws Exception { assertThat(StringUtils.joinOn("+", "1", "2", "3")).isEqualTo("1+2+3"); }
@Test public void joinOn1() throws Exception { assertThat(StringUtils.joinOn("+", new Integer[]{1, 2, 3})).isEqualTo("1+2+3"); }
@Test public void joinOn2() throws Exception { List<String> list = new ArrayList<>(); list.add("1"); list.add("3"); assertThat(StringUtils.joinOn("+", list)).isEqualTo("1+3"); }
|
### Question:
StringUtils { public static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings) { StringBuilder sb = new StringBuilder(); int i = 0; for (String string : strings) { if (string == null || string.isEmpty()) { continue; } if (i != 0) { sb.append(delimiter); } sb.append(string); ++i; } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); }### Answer:
@Test public void joinOnSkipNull() throws Exception { assertThat(StringUtils.joinOnSkipNullOrEmpty("+", "1", null, "3")).isEqualTo("1+3"); }
|
### Question:
Invariant { public static void require(boolean check, @NotNull String format, Object... parameters) { if (check) { return; } report(new RuntimeException(safeFormat(format, parameters))); } @SuppressWarnings("Convert2Diamond") static void pushScope(); static void pushScope(boolean showOutput); static List<RuntimeException> popScope(); static int errorsInScope(); static void fail(@NotNull String format); static void fail(@NotNull String format, Object... parameters); static void require(boolean check, @NotNull String format, Object... parameters); static boolean failIf(boolean check, @NotNull String format, Object... parameters); static void require(boolean check); }### Answer:
@Test public void testRequireFalse() { try { require(false); throw new RuntimeException("Expected an exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Invariant violation"); } }
@Test public void testRequireTrue() { require(true); }
|
### Question:
CDepManifestYmlUtils { @NotNull public static CDepManifestYml convertStringToManifest(@NotNull String content) { Yaml yaml = new Yaml(new Constructor(CDepManifestYml.class)); CDepManifestYml manifest; try { manifest = (CDepManifestYml) yaml.load( new ByteArrayInputStream(content.getBytes(StandardCharsets .UTF_8))); if (manifest != null) { manifest.sourceVersion = CDepManifestYmlVersion.vlatest; } } catch (YAMLException e) { try { manifest = V3Reader.convertStringToManifest(content); } catch (YAMLException e2) { require(false, e.toString()); return new CDepManifestYml( EMPTY_COORDINATE ); } } require(manifest != null, "Manifest was empty"); assert manifest != null; return new ConvertNullToDefaultRewriter().visitCDepManifestYml(manifest); } @NotNull static String convertManifestToString(@NotNull CDepManifestYml manifest); @NotNull static CDepManifestYml convertStringToManifest(@NotNull String content); static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml); @NotNull static List<HardNameDependency> getTransitiveDependencies(@NotNull CDepManifestYml cdepManifestYml); }### Answer:
@Test public void readPartial() throws IOException { CDepManifestYml partial = CDepManifestYmlUtils.convertStringToManifest( FileUtils.readAllText(new File("../third_party/stb/cdep/cdep-manifest-divide.yml"))); }
|
### Question:
ObjectUtils { @NotNull public static <T> T nullToDefault(@Nullable T value, @NotNull T $default) { if (value == null) { return $default; } @NotNull static T nullToDefault(@Nullable T value, @NotNull T $default) {
if (value == null); }### Answer:
@Test public void nullToDefault() throws Exception { assertThat(ObjectUtils.nullToDefault(null, "bob")).isEqualTo("bob"); assertThat(ObjectUtils.nullToDefault("tom", "bob")).isEqualTo("tom"); }
|
### Question:
Bootstrap { public static void main(String[] args) throws Exception { new Bootstrap(getDownloadsFolder(), System.out).go(args); } Bootstrap(File downloadFolder, PrintStream out); static void main(String[] args); }### Answer:
@Test public void testVersion() throws Exception { assertThat(main("--version")).contains(BuildInfo.PROJECT_VERSION); }
@Test public void testCDep() throws Exception { main("https: }
|
### Question:
FakeService implements Repository { @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { return Single.just(RESPONSE); } @Inject FakeService(); @NonNull @Override Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); static final ServiceResponse RESPONSE; }### Answer:
@Test public void should_return_list_of_animals() { TestObserver<ServiceResponse> observer = service.fetchResponse(DateTime.now()).test(); observer.assertNoErrors(); observer.assertValue(FakeService.RESPONSE); }
|
### Question:
Service implements Repository { @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try { return api.loadProviderJson(DateHelper.encodeDate(dateTime)) .onErrorResumeNext(this::mapError); } catch (UnsupportedEncodingException e) { return Single.error(e); } } @Inject Service(@NonNull Api api); @NonNull @Override Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); }### Answer:
@Test public void should_process_json_payload_from_provider() { ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog"))); when(api.loadProviderJson(any())).thenReturn(Single.just(response)); TestObserver<ServiceResponse> observer = service.fetchResponse(DateTime.now()).test(); observer.assertNoErrors(); observer.assertValue(response); }
|
### Question:
Presenter implements Contract.Presenter { @Override public void onStart() { setLoading(); binder.bind(getAnimals(), this::setAnimals, this::setError, this::setComplete); } Presenter(@NonNull Repository repository,
@NonNull Contract.View view,
@NonNull RxBinder binder,
@NonNull Logger logger); @Override void onStart(); @Override void onStop(); }### Answer:
@Test public void should_show_error_when_fetch_fails() { ServiceException exception = new ServiceException(); when(repository.fetchResponse(any())).thenReturn(Single.error(exception)); presenter.onStart(); verify(view).setViewState(ViewState.Error.create(R.string.error_message)); }
@Test public void should_show_empty_when_fetch_returns_nothing() { when(repository.fetchResponse(any())).thenReturn(Single.just(new ServiceResponse(null, Collections.emptyList()))); presenter.onStart(); verify(view).setViewState(ViewState.Empty.create(R.string.empty_message)); }
|
### Question:
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public void rebuild() { if ((useCache || useCacheWhenNotConnectedToDataSource) && connector.isConnected()) { try { cache.rebuild(); allowUseCache(); log.debug("Successfully rebuilt cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild cache for path={}", path, e); } } } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }### Answer:
@Test public void testRebuildDoNotUseCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); testee.rebuild(); verify(cache, never()).rebuild(); }
|
### Question:
ZkPathChildrenCacheWrapper extends BaseCacheWrapper implements IPathChildrenCacheWrapper { @Override public void rebuildNode(final String path) { if (useCache || useCacheWhenNotConnectedToDataSource) { try { cache.rebuildNode(path); log.debug("Successfully rebuilt node cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild node cache for path={}", path, e); } } } ZkPathChildrenCacheWrapper(IDataSourceConnector connector,
String path,
boolean dataIsCompressed,
PathChildrenCache cache); @Override void start(final PathChildrenCache.StartMode startMode); @Override void addListener(PathChildrenCacheListener listener); @Override void rebuild(); @Override void close(); @Override void rebuildNode(final String path); @Override Map<String, byte[]> getNodeIdToDataMap(); @Override byte[] getCurrentData(String fullPath); boolean isUseCache(); }### Answer:
@Test public void testRebuildNodeDoNotUseCache() throws Exception { testee = new ZkPathChildrenCacheWrapper(client, "/test", false, null); testee.rebuildNode("/test"); verify(cache, never()).rebuildNode(anyString()); }
|
### Question:
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { public boolean isUseCache() { return useCache; } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }### Answer:
@Test public void testConstructWithCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", cache); Assert.assertTrue(testee.isUseCache()); }
@Test public void testConstructWithoutCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); Assert.assertFalse(testee.isUseCache()); }
|
### Question:
ZkNodeCacheWrapper extends BaseCacheWrapper implements INodeCacheWrapper { @Override public void rebuild() { if ((useCache || useCacheWhenNotConnectedToDataSource) && connector.isConnected()) { try { cache.rebuild(); allowUseCache(); log.debug("Successfully rebuild cache for path={}", path); } catch (Exception e) { log.error("Failed to rebuild cache for path={} {}", path, e); } } } ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean dataIsCompressed, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); ZkNodeCacheWrapper(IDataSourceConnector connector, String path, NodeCache cache, boolean useCache, boolean useCacheWhenNotConnectedToDataSource); @Override void start(final boolean buildInitial); @Override void addListener(NodeCacheListener listener); @Override void rebuild(); @Override void close(); @Override byte[] getCurrentData(); @Override int getCurrentDataVersion(); @Override String getPath(); boolean isUseCache(); }### Answer:
@Test public void testRebuildDoNotUseCache() throws Exception { testee = new ZkNodeCacheWrapper(client, "/test", null); testee.rebuild(); verify(cache, never()).rebuild(); }
|
### Question:
PathHelper implements IPathHelper { @Override public String getRawPath(String... childId) { return baseNodePath + DELIMETER + entityPath + StringUtils.join(childId, DELIMETER); } PathHelper(String basePath, String rootPath, String entityPath); static synchronized IPathHelper getOrCreateHelper(String basePath, String rootPath, String entityPath); @Override String getPath(EntityType entityType); @Override String getPath(EntityType entityType, String... childId); @Override String getRawPath(String... childId); @Override String getPath(); @Override String getPath(String... childId); @Override String getPathByService(String serviceName); @Override String getPathByService(String serviceName, String... childId); @Override String getPathByService(String serviceName, EntityType entityType, String... childId); static IPathHelper getPathHelper(EntityType entityType, String basePath); static IPathHelper getPathHelper(EntityCategory entityCategory, String basePath); static final String DELIMETER; }### Answer:
@Test public void testGetRawPath() throws Exception { IPathHelper helper = PathHelper.getPathHelper(EntityType.STACK, "/test"); Assert.assertEquals("/test/services/PO/POC7/1.45/xreGuide", helper.getRawPath("/PO/POC7/1.45", "xreGuide")); }
|
### Question:
PathHelper implements IPathHelper { @Override public String getPathByService(String serviceName) { return baseNodePath + DELIMETER + serviceName + getJoinedChildren(entityPath); } PathHelper(String basePath, String rootPath, String entityPath); static synchronized IPathHelper getOrCreateHelper(String basePath, String rootPath, String entityPath); @Override String getPath(EntityType entityType); @Override String getPath(EntityType entityType, String... childId); @Override String getRawPath(String... childId); @Override String getPath(); @Override String getPath(String... childId); @Override String getPathByService(String serviceName); @Override String getPathByService(String serviceName, String... childId); @Override String getPathByService(String serviceName, EntityType entityType, String... childId); static IPathHelper getPathHelper(EntityType entityType, String basePath); static IPathHelper getPathHelper(EntityCategory entityCategory, String basePath); static final String DELIMETER; }### Answer:
@Test public void testGetPathByService() throws Exception { IPathHelper helper = PathHelper.getPathHelper(EntityType.RULE, "/test"); Assert.assertEquals("/test/Redirector/services/xreGuide/rules", helper.getPathByService("xreGuide")); }
|
### Question:
Distribution extends VisitableExpression implements java.io.Serializable, Expressions { public void setRules(List<Rule> rules) { this.rules = rules; } Distribution(); static Distribution newInstance(Distribution distribution); List<Rule> getRules(); void setRules(List<Rule> rules); void addRule(Rule rule); Server getDefaultServer(); void setDefaultServer(Server server); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testCreateObject() throws Exception { Distribution distribution = new Distribution(); List<Rule> rules = new ArrayList<>(); for (int i = 0; i < 5; i++) { Rule rule = new Rule(); rule.setPercent(i); Server serv = new Server(); serv.setName("name" + i); serv.setPath("path" + i); serv.setUrl("url" + i); rule.setServer(serv); rules.add(rule); } distribution.setRules(rules); String result = serializeIt(distribution, true); System.out.println(result); assertNotNull(result); }
|
### Question:
Partners implements Expressions { public void setPartners(Set<Partner> partners) { this.partners = partners; } Set<Partner> getPartners(); void setPartners(Set<Partner> partners); void addPartner(Partner partner); }### Answer:
@Test public void testCreateObject() throws Exception { Partners partners = new Partners(); Set<Partner> partnersList = new LinkedHashSet<>(); for (int y = 0; y < 3; y++) { Set<PartnerProperty> properties = new LinkedHashSet<>(); for (int i = 0; i < 5; i++) { PartnerProperty prop = new PartnerProperty(); prop.setName("id" + i); prop.setValue("xre: properties.add(prop); } Partner newPartner = new Partner("test"); newPartner.setProperties(properties); partnersList.add(newPartner); } partners.setPartners(partnersList); String result = serializeIt(partners, true); System.out.println(result); assertNotNull(result); }
|
### Question:
StackData { public Optional<List<HostIPs>> getHosts() { return hosts; } StackData(String path, List<HostIPs> hosts); StackData(String path); StackData(String dataCenter, String availabilityZone, String flavor, String serviceName, List<HostIPs> hosts); StackData(String dataCenter, String availabilityZone, String flavor, String serviceName); String getDataCenter(); String getAvailabilityZone(); String getFlavor(); String getServiceName(); String getPath(); String getStackOnlyPath(); @Override String toString(); Optional<List<HostIPs>> getHosts(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testConstructWithHosts() throws Exception { List<HostIPs> hosts = new ArrayList<>(); hosts.add(new HostIPs("ipv4_1", "ipv6_1")); hosts.add(new HostIPs("ipv4_2", "ipv6_2")); StackData stackData = new StackData("/A/B/C/D", hosts); Assert.assertEquals(hosts, stackData.getHosts().get()); }
|
### Question:
AnnotationScanner { public static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages) { Set<String> annotationsToScan = Stream.of(annotations).map(Class::getSimpleName).collect(toSet()); ClassLoader cl = AnnotationScanner.class.getClassLoader(); try { ClassPath cp = ClassPath.from(cl); return Stream.of(packages) .flatMap(packageName -> cp.getTopLevelClassesRecursive(packageName).stream()) .filter(isClassAnnotatedByScannedAnnotations(annotationsToScan)) .map(ClassPath.ClassInfo::load) .collect(toSet()); } catch (IOException e) { log.error("Failed to get annotated classes", e); return Collections.emptySet(); } } static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages); }### Answer:
@Test public void annotatedClassesAreFound() throws Exception { Class[] annotations = {Scannable.class}; String[] packages = {"com.comcast.redirector.common.util.annotation.scanner.sample"}; Set<Class<?>> result = AnnotationScanner.getAnnotatedClasses(annotations, packages); Assert.assertTrue(result.contains(Annotated.class)); Assert.assertTrue(result.contains(OneMoreAnnotated.class)); Assert.assertFalse(result.contains(NotAnnotated.class)); Assert.assertFalse(result.contains(AnnotadedByIgnoredAnnotation.class)); }
|
### Question:
UrlUtils { public static String buildUrl(final String finalBaseUri, final String finalEndpoint) { StringBuffer url = new StringBuffer(); if (finalBaseUri != null) { String baseUri = finalBaseUri.trim(); if (baseUri.endsWith("/")) { url.append(baseUri.substring(0, baseUri.length() - 1)); } else { url.append(baseUri); } if (finalEndpoint != null) { String endpoint = finalEndpoint.trim(); if (endpoint.length() > 0 ) { url.append("/"); if (endpoint.startsWith("/")) { url.append(endpoint.substring(1, endpoint.length())); } else { url.append(endpoint); } } } return url.toString(); } return null; } static String buildUrl(final String finalBaseUri, final String finalEndpoint); }### Answer:
@Test public void testBuildUrl() throws Exception { String expectedString = "http: String actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); actualString = UrlUtils.buildUrl("http: Assert.assertEquals(expectedString, actualString); }
|
### Question:
NextFlavorRulesEntityViewService implements IEntityViewService<SelectServer> { @Override public SelectServer getEntity(String serviceName) { PendingChangesStatus pendingChanges = changesStatusService.getPendingChangesStatus(serviceName); SelectServer rules = flavorRulesService.getAllRules(serviceName); return getEntity(pendingChanges, rules); } @Override SelectServer getEntity(String serviceName); @Override SelectServer getEntity(PendingChangesStatus pendingChangesStatus, SelectServer currentEntity); }### Answer:
@Test public void testGetEntity() throws Exception { String serviceName = "xreGuide"; Distribution distribution = new Distribution(); distribution.setDefaultServer(ServerHelper.prepareServer(RedirectorConstants.DEFAULT_SERVER_NAME, "NewDefaultFlavor")); SelectServer expectedSelectServer = RulesUtils.buildSelectServer( prepareSimpleFlavorRules(new HashMap<Expressions, String>() {{ put(new Equals("mac", "receiverMacAddress1"), "rule2-flavor"); }}), distribution ); Collection<IfExpression> rules = prepareSimpleFlavorRules(new HashMap<Expressions, String>() {{ put(new Equals("receiverType", "Native"), "rule1-flavor"); put(new Equals("mac", "receiverMacAddress"), "rule2-flavor"); }}); SelectServer currentSelectServer = new SelectServer(); PendingChangesStatus pendingChangesStatus = getPendingChangesStatus(); currentSelectServer.setItems(rules); currentSelectServer.setDistribution(distribution); when(flavorRulesService.getAllRules(serviceName)).thenReturn(currentSelectServer); when(changesStatusService.getPendingChangesStatus(serviceName)).thenReturn(pendingChangesStatus); SelectServer selectServer = testee.getEntity(serviceName); verifyRuleExpressionsEqual(expectedSelectServer.getItems(), selectServer.getItems()); assertEquals(expectedSelectServer.getDistribution(), selectServer.getDistribution()); }
|
### Question:
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public List<T> getAll(String serviceName) { try { return getAll(getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }### Answer:
@Test public void testGetAll() throws Exception { String id = "id"; String service = "service"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); List<TestModel> result = testee.getAll(service); Assert.assertEquals(id, result.get(0).getId()); }
@Test(expected = RedirectorDataSourceException.class) public void testGetAllExceptionHappens() throws Exception { setupExceptionOnGetAll(new RedirectorDataSourceException(new Exception())); testee.getAll(ANY_SERVICE); }
@Test(expected = RedirectorNoNodeInPathException.class) public void testGetAllNoConnection() throws Exception { setupExceptionOnGetAll(new RedirectorNoNodeInPathException(new KeeperException.ConnectionLossException())); testee.getAll(ANY_SERVICE); }
@Test public void testGetAllCantSerialize() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnMap(id, resultSerialized); setupDeserializeThrowsException(); List<TestModel> result = testee.getAll(ANY_SERVICE); Assert.assertEquals(0, result.size()); }
|
### Question:
NamespacesChangesService { public NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); errorList = null; if (namespaceChangesStatus != null && namespaceChangesStatus.getNamespaceChanges() != null && namespacedList != null) { Map<NamespacedList, ActionType> removedNamespacesChangesMap = namespaceChangesStatus.getNamespaceChanges().entrySet().stream() .filter(filterToSaveAlone(namespacedList)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); namespaceChangesStatus.setNamespaceChanges(removedNamespacesChangesMap); save(serviceName, namespaceChangesStatus); } if (errorList != null) { throw new WebApplicationException(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR, Response.status(Response.Status.BAD_REQUEST).entity(new ErrorMessage(FAILED_TO_SAVE_NAMESPACE_DUE_TO_VALIDATION_ERROR)).build()); } return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }### Answer:
@Test public void approveTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.approve(SERVICE_NAME, namespacedList1); verify(namespacedListsService, atLeastOnce()).addNamespacedList(namespacedList1); Assert.assertEquals(2, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
|
### Question:
ListServiceDAO extends BaseListDAO<T> implements IListServiceDAO<T> { @Override public void deleteById(String serviceName, String id) { try { super.deleteByPath(pathHelper.getPathByService(serviceName, id), getCache(serviceName)); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } ListServiceDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean isCompressed,
boolean useCache); @Override List<T> getAll(String serviceName); @Override Map<String, T> getAllInMap(String serviceName); @Override T getById(String serviceName, String id); @Override void saveById(T data, String serviceName, String id); @Override void deleteById(String serviceName, String id); @Override void addCacheListener(String serviceName, ICacheListener listener); }### Answer:
@Test public void testDeleteById() throws Exception { String path = "/path"; setupPathHelperReturn(path); testee.deleteById(ANY_SERVICE, ANY_ID); verify(connector, times(1)).delete(path); verify(getWrapper(), times(1)).rebuild(); }
@Test(expected = RedirectorDataSourceException.class) public void testDeleteByIdExceptionHappens() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorDataSourceException(new Exception())); testee.deleteById(ANY_SERVICE, ANY_ID); }
@Test(expected = RedirectorNoConnectionToDataSourceException.class) public void testDeleteByIdNoConnection() throws Exception { String path = "/path"; setupPathHelperReturn(path); setupExceptionOnDelete(new RedirectorNoConnectionToDataSourceException(new Exception())); testee.deleteById(ANY_SERVICE, ANY_ID); }
|
### Question:
SimpleDAO extends BaseDAO<T> implements ISimpleDAO<T>, ICacheableDAO { @Override public T get() { try { return deserializeOrReturnNull(getCache().getCurrentData()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean compressed,
boolean useCache); @Override T get(); @Override void save(T data); @Override void addCacheListener(ICacheListener listener); @Override synchronized void rebuildCache(); @Override void close(); }### Answer:
@Test public void testGet() throws Exception { String id = "id"; String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserialize(resultSerialized, new TestModel(id)); TestModel result = testee.get(); assertEquals(id, result.getId()); }
@Test public void testGetExceptionHappens() throws Exception { exception.expect(RedirectorDataSourceException.class); setupExceptionOnGetOne(new RedirectorDataSourceException("Test")); testee.get(); }
@Test public void testGetNoConnection() throws Exception { exception.expect(RedirectorNoConnectionToDataSourceException.class); setupExceptionOnGetOne(new RedirectorNoConnectionToDataSourceException(new KeeperException.ConnectionLossException())); testee.get(); }
@Test public void testGetCantDeserialize() throws Exception { String resultSerialized = "testModel"; setupCacheReturnResult(resultSerialized); setupDeserializeThrowsException(); TestModel result = testee.get(); assertNull(result); }
|
### Question:
NamespacesChangesService { public NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList) { NamespaceChangesStatus namespaceChangesStatus = getNamespaceChangesStatus(serviceName); namespaceChangesStatus.getNamespaceChanges().remove(namespacedList); save(serviceName, namespaceChangesStatus); return namespaceChangesStatus; } void save(String serviceName, NamespaceChangesStatus namespaceChangesStatus); NamespaceChangesStatus getNamespaceChangesStatus(String serviceName); NamespaceChangesStatus approve(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus cancelAll(String serviceName); NamespaceChangesStatus cancel(String serviceName, NamespacedList namespacedList); NamespaceChangesStatus approveAll(String serviceName); }### Answer:
@Test public void cancelTest() { NamespaceChangesStatus namespacesChangesStatusReturned = namespacesChangesService.cancel(SERVICE_NAME, namespacedList1); verify(namespacedListsService, never()).addNamespacedList(namespacedList1); Assert.assertEquals(2, namespacesChangesStatusReturned.getNamespaceChanges().size()); }
|
### Question:
SimpleDAO extends BaseDAO<T> implements ISimpleDAO<T>, ICacheableDAO { @Override public void save(T data) throws SerializerException { try { save(serialize(data), pathHelper.getPath()); } catch (DataSourceConnectorException e) { throw new RedirectorDataSourceException(e); } } SimpleDAO(Class<T> clazz,
Serializer marshalling,
IDataSourceConnector connector,
IPathHelper pathHelper,
boolean compressed,
boolean useCache); @Override T get(); @Override void save(T data); @Override void addCacheListener(ICacheListener listener); @Override synchronized void rebuildCache(); @Override void close(); }### Answer:
@Test public void testSave() throws Exception { String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); testee.save(new TestModel(ANY_ID)); verifySave(resultSerialized, path); }
@Test public void testSaveExceptionHappens() throws Exception { exception.expect(RedirectorDataSourceException.class); String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException("Test")); testee.save(new TestModel(ANY_ID)); }
@Test public void testSaveNoConnection() throws Exception { exception.expect(RedirectorDataSourceException.class); String path = "/path"; String resultSerialized = "testModel"; setupPathHelperReturn(path); setupSerialize(resultSerialized); setupExceptionOnSave(new RedirectorDataSourceException(new Exception())); testee.save(new TestModel(ANY_ID)); }
@Test public void testSaveCantSerialize() throws Exception { exception.expect(SerializerException.class); String path = "/path"; setupPathHelperReturn(path); setupSerializeThrowsException(); testee.save(new TestModel(ANY_ID)); }
|
### Question:
TransactionalDAO implements ITransactionalDAO { @Override public ITransaction beginTransaction() { return new Transaction(); } TransactionalDAO(IDataSourceConnector connector, Serializer serializer, IRegisteringDAOFactory daoFactory); @Override ITransaction beginTransaction(); }### Answer:
@Test public void testCommitAndRebuildCache() throws Exception { ICacheableDAO mockCacheableDAO = mock(ICacheableDAO.class); IDataSourceConnector.Transaction mockTransaction = mock(IDataSourceConnector.Transaction.class); when(connector.createTransaction()).thenReturn(mockTransaction); when(serializer.serialize(anyObject(), anyBoolean())).thenReturn(ANY_SERIALIZED_DATA); when(daoFactory.getRegisteredCacheableDAO(any(EntityType.class))).thenReturn(mockCacheableDAO); ITransactionalDAO.ITransaction transaction = testee.beginTransaction(); transaction.save(new IfExpression(), EntityType.RULE, ANY_SERVICE, ANY_ID); transaction.save(new Server(), EntityType.SERVER, ANY_SERVICE, ANY_ID); transaction.save(new Whitelisted(), EntityType.WHITELIST, ANY_SERVICE); transaction.operationByActionType(new IfExpression(), EntityType.URL_RULE, ANY_SERVICE, ANY_ID, ActionType.DELETE); transaction.incVersion(EntityType.MODEL_CHANGED, ANY_SERVICE); transaction.commit(); verify(mockTransaction, times(1)).commit(); }
@Test(expected = RedirectorDataSourceException.class) public void testExceptionOnSerialize() throws Exception { when(serializer.serialize(anyObject(), anyBoolean())).thenReturn(null); ITransactionalDAO.ITransaction transaction = testee.beginTransaction(); transaction.save(new IfExpression(), EntityType.RULE, ANY_SERVICE, ANY_ID); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.