method2testcases
stringlengths
118
6.63k
### Question: ForwardMessage extends SendableMessageRequest<Message> { public static ForwardMessageBuilder forMessage(Message<?> message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder protected ForwardMessage(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, Integer replyToMessageId, Boolean disableNotification, ChatId fromChatId, Integer messageId, ReplyMarkup replyMarkup); static ForwardMessageBuilder forMessage(Message<?> message); }### Answer: @Test public void toForwardMessageRequest_output_same_as_forMessage() { ForwardMessage expected = ForwardMessage.forMessage(messageMock).build(); ForwardMessage actual = messageMock.toForwardRequest().build(); assertEquals(expected, actual); }
### Question: EditMessageLiveLocation extends SendableInlineRequest<Message> { public static EditMessageLiveLocationBuilder forInlineMessage(String inlineMessageId) { Objects.requireNonNull(inlineMessageId, "inline message ID cannot be null"); return builder().inlineMessageId(inlineMessageId); } @Builder protected EditMessageLiveLocation(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, Integer messageId, String inlineMessageId, Float latitude, Float longitude, Integer livePeriod); static EditMessageLiveLocationBuilder forMessage(LocationMessage message); static EditMessageLiveLocationBuilder forInlineMessage(String inlineMessageId); }### Answer: @Test public void builds_with_correct_inlineid() { EditMessageLiveLocation request = EditMessageLiveLocation.forInlineMessage(INLINE_ID).build(); assertNull(request.getChatId()); assertNull(request.getMessageId()); assertEquals(INLINE_ID, request.getInlineMessageId()); }
### Question: EditMessageCaption extends EditMessageRequest<Message> { public static EditMessageCaptionBuilder forMessage(CaptionableMessage<?> message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @Builder EditMessageCaption(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup, String caption, ParseMode parseMode); static EditMessageCaptionBuilder forMessage(CaptionableMessage<?> message); static EditMessageCaptionBuilder forInlineMessage(String inlineMessageId); }### Answer: @Test public void toEditCaptionRequest_output_same_as_forMessage_audio() { EditMessageCaption expected = EditMessageCaption.forMessage(audioMessageMock).build(); EditMessageCaption actual = audioMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); } @Test public void toEditCaptionRequest_output_same_as_forMessage_document() { EditMessageCaption expected = EditMessageCaption.forMessage(documentMessageMock).build(); EditMessageCaption actual = documentMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); } @Test public void toEditCaptionRequest_output_same_as_forMessage_photo() { EditMessageCaption expected = EditMessageCaption.forMessage(photoMessageMock).build(); EditMessageCaption actual = photoMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); } @Test public void toEditCaptionRequest_output_same_as_forMessage_video() { EditMessageCaption expected = EditMessageCaption.forMessage(videoMessageMock).build(); EditMessageCaption actual = videoMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); } @Test public void toEditCaptionRequest_output_same_as_forMessage_video_note() { EditMessageCaption expected = EditMessageCaption.forMessage(videoNoteMessageMock).build(); EditMessageCaption actual = videoNoteMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); } @Test public void toEditCaptionRequest_output_same_as_forMessage_voice() { EditMessageCaption expected = EditMessageCaption.forMessage(voiceMessageMock).build(); EditMessageCaption actual = voiceMessageMock.toEditCaptionRequest().build(); assertEquals(expected, actual); }
### Question: EditMessageCaption extends EditMessageRequest<Message> { public static EditMessageCaptionBuilder forInlineMessage(String inlineMessageId) { Objects.requireNonNull(inlineMessageId, "inline message ID cannot be null"); return builder().inlineMessageId(inlineMessageId); } @Builder EditMessageCaption(Consumer<Message> callback, Consumer<TelegramException> errorHandler, ChatId chatId, int messageId, String inlineMessageId, ReplyMarkup replyMarkup, String caption, ParseMode parseMode); static EditMessageCaptionBuilder forMessage(CaptionableMessage<?> message); static EditMessageCaptionBuilder forInlineMessage(String inlineMessageId); }### Answer: @Test public void builds_with_correct_inlineid() { EditMessageCaption request = EditMessageCaption.forInlineMessage(INLINE_ID).build(); assertNull(request.getChatId()); assertEquals(0, request.getMessageId()); assertEquals(INLINE_ID, request.getInlineMessageId()); }
### Question: ProjectServiceImpl implements ProjectService { @Override public ProjectAccessControl getProjectAccessControl(Project project){ List<UserTask> userTasks = modelService.getTasksBy(project, new ProcessModelType(), UserTask.class); Set<String> users = extractFromTasks(this::selectUsers, userTasks); Set<String> groups = extractFromTasks(this::selectGroups, userTasks); return new ProjectAccessControl(users, groups); } @Autowired ProjectServiceImpl(ProjectRepository projectRepository, ModelService modelService, ModelTypeService modelTypeService, JsonConverter<ProjectDescriptor> descriptorJsonConverter, JsonConverter<Project> jsonConverter, JsonConverter<Map> jsonMetadataConverter, Set<ProjectValidator> projectValidators); @Override Page<Project> getProjects(Pageable pageable, String name); @Override Project createProject(Project project); @Override Project updateProject(Project projectToUpdate, Project newProject); @Override void deleteProject(Project project); @Override Optional<Project> findProjectById(String projectId); @Override FileContent exportProject(Project project); @Override ProjectAccessControl getProjectAccessControl(Project project); @Override Project importProject(MultipartFile file, @Nullable String name); @Override void validateProject(Project project); }### Answer: @Test public void should_getUsersAndGroupsBelongingToAProject_when_getProcessAccessControl() { List<UserTask> userTasks = asList(taskOne, taskTwo); when(taskOne.getCandidateGroups()).thenReturn(asList("groupOne", "groupTwo")); when(taskOne.getCandidateUsers()).thenReturn(asList("userOne", "userTwo")); when(taskTwo.getAssignee()).thenReturn("userThree"); when(modelService.getTasksBy(eq(project), any(ProcessModelType.class), eq(UserTask.class))) .thenReturn(userTasks); ProjectAccessControl projectAccessControl = projectService.getProjectAccessControl(project); assertThat(projectAccessControl.getGroups()) .hasSize(2) .contains("groupOne", "groupTwo"); assertThat(projectAccessControl.getUsers()) .hasSize(3) .contains("userOne", "userTwo", "userThree"); } @Test public void should_getUsersAndGroupsBelongingToAProjectExludingExpressions_when_getProcessAccessControl() { List<UserTask> userTasks = asList(taskOne, taskTwo); when(taskOne.getCandidateGroups()).thenReturn(asList("groupOne", "${processsVariable.groupName}", "groupTwo")); when(taskOne.getCandidateUsers()).thenReturn(asList("${username_Var}", "userOne")); when(taskTwo.getAssignee()).thenReturn("${processsVariable.username}"); when(modelService.getTasksBy(eq(project), any(ProcessModelType.class), eq(UserTask.class))) .thenReturn(userTasks); ProjectAccessControl projectAccessControl = projectService.getProjectAccessControl(project); assertThat(projectAccessControl.getGroups()) .hasSize(2) .contains("groupOne", "groupTwo"); assertThat(projectAccessControl.getUsers()) .hasSize(1) .contains("userOne"); } @Test public void should_returnEmptyLists_when_thereAreNotAssigneeAndCandidateUsersAndGroups() { List<UserTask> userTasks = asList(taskOne, taskTwo); when(taskOne.getCandidateGroups()).thenReturn(null); when(taskOne.getCandidateUsers()).thenReturn(null); when(taskTwo.getAssignee()).thenReturn(null); when(modelService.getTasksBy(eq(project), any(ProcessModelType.class), eq(UserTask.class))) .thenReturn(userTasks); ProjectAccessControl projectAccessControl = projectService.getProjectAccessControl(project); assertThat(projectAccessControl.getGroups()).isEmpty(); assertThat(projectAccessControl.getUsers()).isEmpty(); } @Test public void should_returnEmptyLists_when_thereAreNotUserTasks() { List<UserTask> userTasks = new LinkedList<>(); when(modelService.getTasksBy(eq(project), any(ProcessModelType.class), eq(UserTask.class))) .thenReturn(userTasks); ProjectAccessControl projectAccessControl = projectService.getProjectAccessControl(project); assertThat(projectAccessControl.getGroups()).isEmpty(); assertThat(projectAccessControl.getUsers()).isEmpty(); }
### Question: ReferenceIdOverrider implements ReferenceOverrider { @Override public void override(UserTask userTask) { String oldFormKey = userTask.getFormKey(); String newFormKey = modelIdentifiers.get(oldFormKey); if (newFormKey != null) { userTask.setFormKey(newFormKey); } } ReferenceIdOverrider(Map<String, String> modelIdentifiers); @Override void override(UserTask userTask); @Override void override(StartEvent startEvent); }### Answer: @Test public void should_overrideUserTask_when_notNewFormKey() { UserTask userTask = new UserTask(); userTask.setFormKey("notNewFormKey"); referenceIdOverrider.override(userTask); assertThat(userTask.getFormKey()).isEqualTo("notNewFormKey"); } @Test public void should_overrideStartEvent_when_hasNewFormKey() { StartEvent startEvent = new StartEvent(); startEvent.setFormKey("oldFormKey"); referenceIdOverrider.override(startEvent); assertThat(startEvent.getFormKey()).isEqualTo("newFormKey"); } @Test public void should_notOverrideStartEvent_when_sameFormKey() { StartEvent startEvent = new StartEvent(); startEvent.setFormKey("sameFormKey"); referenceIdOverrider.override(startEvent); assertThat(startEvent.getFormKey()).isEqualTo("sameFormKey"); } @Test public void should_overrideStartEvent_when_notNewFormKey() { StartEvent startEvent = new StartEvent(); startEvent.setFormKey("notNewFormKey"); referenceIdOverrider.override(startEvent); assertThat(startEvent.getFormKey()).isEqualTo("notNewFormKey"); } @Test public void should_overrideUserTask_when_hasNewFormKey() { UserTask userTask = new UserTask(); userTask.setFormKey("oldFormKey"); referenceIdOverrider.override(userTask); assertThat(userTask.getFormKey()).isEqualTo("newFormKey"); } @Test public void should_notOverrideUserTask_when_sameFormKey() { UserTask userTask = new UserTask(); userTask.setFormKey("sameFormKey"); referenceIdOverrider.override(userTask); assertThat(userTask.getFormKey()).isEqualTo("sameFormKey"); }
### Question: ModelServiceImpl implements ModelService { @Override public <T extends Task> List<T> getTasksBy(Project project, ModelType processModelType, @NonNull Class<T> clazz) { Assert.notNull(clazz, "Class task type it must not be null"); return getProcessesBy(project, processModelType) .stream() .map(Process::getFlowElements) .flatMap(Collection::stream) .filter(clazz::isInstance) .map(clazz::cast) .collect(Collectors.toList()); } @Autowired ModelServiceImpl(ModelRepository modelRepository, ModelTypeService modelTypeService, ModelContentService modelContentService, ModelExtensionsService modelExtensionsService, JsonConverter<Model> jsonConverter, ProcessModelContentConverter processModelContentConverter); @Override List<Model> getAllModels(Project project); @Override Page<Model> getModels(Project project, ModelType modelType, Pageable pageable); @Override Model buildModel(String type, String name); @Override Model createModel(Project project, Model model); @Override Model updateModel(Model modelToBeUpdated, Model newModel); @Override void deleteModel(Model model); @Override Optional<Model> findModelById(String modelId); @Override Optional<FileContent> getModelExtensionsFileContent(Model model); @Override void cleanModelIdList(); @Override Optional<FileContent> getModelDiagramFile(String modelId); @Override String getExtensionsFilename(Model model); @Override FileContent getModelContentFile(Model model); @Override FileContent exportModel(Model model); @Override Model updateModelContent(Model modelToBeUpdate, FileContent fileContent); @Override FileContent overrideModelContentId(Model model, FileContent fileContent); @Override Optional<ModelContent> createModelContentFromModel(Model model, FileContent fileContent); @Override Model importSingleModel(Project project, ModelType modelType, FileContent fileContent); @Override Model importModel(Project project, ModelType modelType, FileContent fileContent); @Override Model importModelFromContent(Project project, ModelType modelType, FileContent fileContent); @Override List<T> getTasksBy(Project project, ModelType processModelType, @NonNull Class<T> clazz); @Override List<Process> getProcessesBy(Project project, ModelType type); @Override Model convertContentToModel(ModelType modelType, FileContent fileContent); @Override Model createModelFromContent(ModelType modelType, FileContent fileContent); @Override Optional<String> contentFilenameToModelName(String filename, ModelType modelType); @Override void validateModelContent(Model model, ValidationContext validationContext); @Override void validateModelContent(Model model, FileContent fileContent); @Override void validateModelContent(Model model, FileContent fileContent, ValidationContext validationContext); @Override void validateModelExtensions(Model model, ValidationContext validationContext); @Override void validateModelExtensions(Model model, FileContent fileContent); @Override void validateModelExtensions(Model model, FileContent fileContent, ValidationContext validationContext); }### Answer: @Test public void should_returnException_when_classTypeIsNotSpecified() { ProcessModelType modelType = new ProcessModelType(); assertThatThrownBy(() -> modelService.getTasksBy(projectOne, modelType, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Class task type it must not be null"); }
### Question: ProcessModelContentConverter implements ModelContentConverter<BpmnProcessModelContent> { @Override public FileContent overrideModelId(FileContent fileContent, Map<String, String> modelIdentifiers) { FileContent newFileContent; Optional<BpmnProcessModelContent> processModelContent = this.convertToModelContent(fileContent.getFileContent()); if (processModelContent.isPresent()) { BpmnProcessModelContent modelContent = processModelContent.get(); ReferenceIdOverrider referenceIdOverrider = new ReferenceIdOverrider(modelIdentifiers); this.overrideAllProcessDefinition(modelContent, referenceIdOverrider); byte[] overriddenContent = this.convertToBytes(modelContent); newFileContent = new FileContent(fileContent.getFilename(), fileContent.getContentType(), overriddenContent); } else { newFileContent = fileContent; } return newFileContent; } ProcessModelContentConverter(ProcessModelType processModelType, BpmnXMLConverter bpmnConverter); @Override ModelType getHandledModelType(); @Override Optional<BpmnProcessModelContent> convertToModelContent(byte[] bytes); @Override byte[] convertToBytes(BpmnProcessModelContent bpmnProcessModelContent); Optional<BpmnProcessModelContent> convertToModelContent(BpmnModel bpmnModel); BpmnModel convertToBpmnModel(byte[] modelContent); @Override FileContent overrideModelId(FileContent fileContent, Map<String, String> modelIdentifiers); void overrideAllProcessDefinition(BpmnProcessModelContent processModelContent, ReferenceIdOverrider referenceIdOverrider); }### Answer: @Test public void should_notOverrideModelId_whenModelContentEmpty() { FileContent fileContent = mock(FileContent.class); byte[] emptyByteArray = new byte[0]; given(fileContent.getFileContent()).willReturn(emptyByteArray); Map<String, String> modelIds = new HashMap<>(); FileContent result = processModelContentConverter.overrideModelId(fileContent, modelIds); assertThat(result).isSameAs(fileContent); }
### Question: ProcessModelContentConverter implements ModelContentConverter<BpmnProcessModelContent> { public void overrideAllProcessDefinition(BpmnProcessModelContent processModelContent, ReferenceIdOverrider referenceIdOverrider) { processModelContent.getBpmnModel().getProcesses().forEach(process -> { overrideAllIdReferences(process, referenceIdOverrider); }); } ProcessModelContentConverter(ProcessModelType processModelType, BpmnXMLConverter bpmnConverter); @Override ModelType getHandledModelType(); @Override Optional<BpmnProcessModelContent> convertToModelContent(byte[] bytes); @Override byte[] convertToBytes(BpmnProcessModelContent bpmnProcessModelContent); Optional<BpmnProcessModelContent> convertToModelContent(BpmnModel bpmnModel); BpmnModel convertToBpmnModel(byte[] modelContent); @Override FileContent overrideModelId(FileContent fileContent, Map<String, String> modelIdentifiers); void overrideAllProcessDefinition(BpmnProcessModelContent processModelContent, ReferenceIdOverrider referenceIdOverrider); }### Answer: @Test public void should_overrideAllProcessDefinition_when_newProcessId() { Process process = new Process(); process.addFlowElement(flowElement); BpmnModel bpmnModel = new BpmnModel(); bpmnModel.addProcess(process); BpmnProcessModelContent processModelContent = new BpmnProcessModelContent(bpmnModel); processModelContentConverter.overrideAllProcessDefinition(processModelContent, referenceIdOverrider); verify(flowElement).accept(referenceIdOverrider); }
### Question: PathPrunner implements Consumer<Swagger> { @Override public void accept(Swagger swagger) { if(swagger.getPaths() == null) return; prunePaths(swagger); if(swagger.getDefinitions() == null || types.isEmpty()) return; new TypePruner(swagger).prune(); } PathPrunner(String... excludePrefixes); PathPrunner withType(String type); PathPrunner prunePath(String startingWith); @Override void accept(Swagger swagger); }### Answer: @Test public void noChange() { int orgPathsCnt = swagger.getPaths().size(); int orgDefCnt = swagger.getDefinitions().size(); new PathPrunner().accept(swagger); assertEquals(orgPathsCnt, swagger.getPaths().size()); assertEquals(orgDefCnt, swagger.getDefinitions().size()); }
### Question: RemoveUnusedDefinitions implements Consumer<Swagger> { @Override public void accept(Swagger swagger) { int initial = swagger.getDefinitions().size(); Pruner pruner = new Pruner(buildHierarchy(swagger)); while(pruner.hasPruneable()) { Stream<String> prune = pruner.prune(); Map<String, Model> defs = swagger.getDefinitions(); prune.forEach(type -> { log.info("Removing unused type {}", type); defs.remove(type); }); swagger.setDefinitions(defs); } int afterPruning = swagger.getDefinitions().size(); log.debug("Pruned {} of {} definitions.", initial-afterPruning, initial); } @Override void accept(Swagger swagger); }### Answer: @Test public void noChange() { int initial = swagger.getDefinitions().size(); new RemoveUnusedDefinitions().accept(swagger); assertEquals(initial, swagger.getDefinitions().size()); } @Test public void noChangeInClasses() { int initial = swagger.getDefinitions().size(); Map<String, Path> paths = swagger.getPaths(); paths.remove("/b/propE/propF"); swagger.setPaths(paths); new RemoveUnusedDefinitions().accept(swagger); assertEquals(initial, swagger.getDefinitions().size()); } @Test public void removingC() { int initial = swagger.getDefinitions().size(); Map<String, Path> paths = swagger.getPaths().entrySet().stream() .filter(p -> !p.getKey().startsWith("/c")).collect(toMap()); swagger.setPaths(paths); new RemoveUnusedDefinitions().accept(swagger); assertEquals(initial - 2, swagger.getDefinitions().size()); }
### Question: BeaconMapBackground { public static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint) { double distanceInPixels = getPixelDistance(firstReferencePoint, secondReferencePoint); double distanceInMeters = firstReferenceLocation.getDistanceTo(secondReferenceLocation); if (distanceInPixels == 0) { throw new IllegalArgumentException("Reference points must be distinct."); } return (float) (distanceInMeters / distanceInPixels); } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getMetersPerPixel() { double metersPerPixel = BeaconMapBackground.getMetersPerPixel(firstReferenceLocation, firstReferencePoint, secondReferenceLocation, secondReferencePoint); assertEquals(0.016919836401939392, metersPerPixel, 0.001); assertEquals(metersPerPixel, beaconMapBackground.getMetersPerPixel(), 0.001); }
### Question: AdvertisingPacketFactory { protected AP createAdvertisingPacketWithSubFactories(byte[] advertisingData) { for (AdvertisingPacketFactory<AP> advertisingPacketFactory : subFactoryMap.values()) { if (advertisingPacketFactory.canCreateAdvertisingPacketWithSubFactories(advertisingData)) { return advertisingPacketFactory.createAdvertisingPacket(advertisingData); } } return createAdvertisingPacket(advertisingData); } AdvertisingPacketFactory(Class<AP> packetClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(Class advertisingPacketClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(byte[] advertisingData); void addAdvertisingPacketFactory(F factory); void removeAdvertisingPacketFactory(Class<AP> advertisingPacketClass); void removeAdvertisingPacketFactory(F factory); Class<AP> getPacketClass(); }### Answer: @Test public void createAdvertisingPacketWithSubFactories_hasNoSubFactories_createsCorrectPacket() { IBeaconAdvertisingPacketFactory advertisingPacketFactory = new IBeaconAdvertisingPacketFactory(); AdvertisingPacket advertisingPacket = advertisingPacketFactory.createAdvertisingPacketWithSubFactories(BeaconTest.IBEACON_ADVERTISING_DATA); assertTrue(advertisingPacket instanceof IBeaconAdvertisingPacket); }
### Question: AdvertisingPacketFactoryManager { public AdvertisingPacketFactory getAdvertisingPacketFactory(byte[] advertisingData) { AdvertisingPacketFactory factory = null; for (AdvertisingPacketFactory advertisingPacketFactory : advertisingPacketFactories) { factory = advertisingPacketFactory.getAdvertisingPacketFactory(advertisingData); if (factory != null) { break; } } return factory; } AdvertisingPacketFactoryManager(); AdvertisingPacket createAdvertisingPacket(byte[] advertisingData); AdvertisingPacketFactory getAdvertisingPacketFactory(byte[] advertisingData); void addAdvertisingPacketFactory(AdvertisingPacketFactory advertisingPacketFactory); List<AdvertisingPacketFactory> getAdvertisingPacketFactories(); void setAdvertisingPacketFactories(List<AdvertisingPacketFactory> advertisingPacketFactories); }### Answer: @Test public void getAdvertisingPacketFactory_defaultFactories_returnsNull() throws Exception { AdvertisingPacketFactory factory = advertisingPacketFactoryManager.getAdvertisingPacketFactory(new byte[]{}); assertNull(factory); }
### Question: BeaconUtil { public static double getSmallestDistance(List<? extends Beacon> beaconList) { Beacon beacon = getClosestBeacon(beaconList); return (beacon == null) ? Double.MAX_VALUE : beacon.getDistance(); } static float getAdvertisingRange(int transmissionPower); static double getSmallestDistance(List<? extends Beacon> beaconList); static double getSmallestDistance(List<? extends Beacon> beaconList, WindowFilter filter); static Beacon getClosestBeacon(List<? extends Beacon> beaconList); static Beacon getClosestBeacon(List<? extends Beacon> beaconList, WindowFilter filter); static int calculateRssiForDistance(Beacon beacon, float distance); static int calculateRssi(float distance, float calibratedRssi, int calibratedDistance, float pathLossParameter); static int calculateRssi(float distance, float calibratedRssi, float pathLossParameter); static float getAdvertisingRange(int transmissionPower, int calibratedTransmissionPower, int calibratedRange); static String getReadableBeaconType(AdvertisingPacket advertisingPacket); static String getReadableBeaconType(Class<? extends Beacon> beaconClass); static Comparator<Beacon> DescendingRssiComparator; static Comparator<Beacon> AscendingRssiComparator; }### Answer: @Test public void getSmallestDistance_emptyList_returnsDoubleMaxValue() { double distance = BeaconUtil.getSmallestDistance(new ArrayList<Beacon<AdvertisingPacket>>(), new KalmanFilter()); assertEquals("Distance should be initialized with Double.MAX_VALUE", Double.MAX_VALUE, distance, 0); } @Test @SuppressWarnings("unchecked") public void getSmallestDistance_singleBeacon_returnsBeaconDistance() throws Exception { float expectedDistance = 2; List<IBeacon> beacons = new ArrayList<>(); beacons.add(beaconCreator.createBeaconWithAdvertisingPacket(expectedDistance)); double actualDistance = BeaconUtil.getSmallestDistance(beacons, new KalmanFilter(2, TimeUnit.SECONDS)); assertEquals("Actual distance did not match of the given beacon", expectedDistance, actualDistance, 0.01); } @Test @SuppressWarnings("unchecked") public void getSmallestDistance_multipleBeacons_returnsClosestBeaconsDistance() throws Exception { int numberOfBeaconsToUse = 5; float expectedDistance = 2; List<IBeacon> beacons = new ArrayList<>(); for (int i = 0; i < numberOfBeaconsToUse; i++) { beacons.add(beaconCreator.createBeaconWithAdvertisingPacket(expectedDistance + i)); } double actualDistance = BeaconUtil.getSmallestDistance(beacons, new KalmanFilter(2, TimeUnit.SECONDS)); assertEquals("Actual distance did not return distance of closest beacon", expectedDistance, actualDistance, 0.01); }
### Question: BeaconUtil { public static Beacon getClosestBeacon(List<? extends Beacon> beaconList) { if (beaconList.isEmpty()) { return null; } return getClosestBeacon(beaconList, beaconList.get(0).createSuggestedWindowFilter()); } static float getAdvertisingRange(int transmissionPower); static double getSmallestDistance(List<? extends Beacon> beaconList); static double getSmallestDistance(List<? extends Beacon> beaconList, WindowFilter filter); static Beacon getClosestBeacon(List<? extends Beacon> beaconList); static Beacon getClosestBeacon(List<? extends Beacon> beaconList, WindowFilter filter); static int calculateRssiForDistance(Beacon beacon, float distance); static int calculateRssi(float distance, float calibratedRssi, int calibratedDistance, float pathLossParameter); static int calculateRssi(float distance, float calibratedRssi, float pathLossParameter); static float getAdvertisingRange(int transmissionPower, int calibratedTransmissionPower, int calibratedRange); static String getReadableBeaconType(AdvertisingPacket advertisingPacket); static String getReadableBeaconType(Class<? extends Beacon> beaconClass); static Comparator<Beacon> DescendingRssiComparator; static Comparator<Beacon> AscendingRssiComparator; }### Answer: @Test public void getClosestBeacon_noBeacon_returnsNull() { Beacon beacon = BeaconUtil.getClosestBeacon(new ArrayList<Beacon<AdvertisingPacket>>(), new KalmanFilter()); assertNull("Beacon should not be initialized", beacon); } @Test @SuppressWarnings("unchecked") public void getClosestBeacon_singleBeacon_returnsBeacon() throws Exception { List<IBeacon> beacons = new ArrayList<>(); IBeacon<IBeaconAdvertisingPacket> expectedBeacon = beaconCreator.createBeaconWithAdvertisingPacket(2); beacons.add(expectedBeacon); IBeacon<IBeaconAdvertisingPacket> actualBeacon = (IBeacon) BeaconUtil.getClosestBeacon(beacons, new KalmanFilter(2, TimeUnit.SECONDS)); assertEquals("Did not return the only beacon added", expectedBeacon, actualBeacon); } @Test @SuppressWarnings("unchecked") public void getClosestBeacon_multipleBeacons_returnsClosestBeacon() throws Exception { int numberOfBeaconsToUse = 5; float expectedDistance = 2; List<IBeacon> beacons = new ArrayList<>(); for (int i = 1; i < numberOfBeaconsToUse; i++) { beacons.add(beaconCreator.createBeaconWithAdvertisingPacket(expectedDistance + i)); } IBeacon<IBeaconAdvertisingPacket> expectedBeacon = beaconCreator.createBeaconWithAdvertisingPacket(expectedDistance); beacons.add(expectedBeacon); IBeacon<IBeaconAdvertisingPacket> actualBeacon = (IBeacon) BeaconUtil.getClosestBeacon(beacons, new KalmanFilter(2, TimeUnit.SECONDS)); assertEquals("Did not return the closest beacon", expectedBeacon, actualBeacon); }
### Question: BeaconMapBackground { public static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint) { double locationBearing = getBearing(firstReferenceLocation, secondReferenceLocation); double pointBearing = getBearing(firstReferencePoint, secondReferencePoint); return ((locationBearing - pointBearing) + 360) % 360; } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getBearing() { double bearing = BeaconMapBackground.getBearing(firstReferenceLocation, firstReferencePoint, secondReferenceLocation, secondReferencePoint); assertEquals(353.84, bearing, 0.001); assertEquals(bearing, beaconMapBackground.getBearing(), 0.001); }
### Question: BeaconUtil { public static int calculateRssi(float distance, float calibratedRssi, int calibratedDistance, float pathLossParameter) { return calculateRssi(distance, BeaconDistanceCalculator.getCalibratedRssiAtOneMeter(calibratedRssi, calibratedDistance), pathLossParameter); } static float getAdvertisingRange(int transmissionPower); static double getSmallestDistance(List<? extends Beacon> beaconList); static double getSmallestDistance(List<? extends Beacon> beaconList, WindowFilter filter); static Beacon getClosestBeacon(List<? extends Beacon> beaconList); static Beacon getClosestBeacon(List<? extends Beacon> beaconList, WindowFilter filter); static int calculateRssiForDistance(Beacon beacon, float distance); static int calculateRssi(float distance, float calibratedRssi, int calibratedDistance, float pathLossParameter); static int calculateRssi(float distance, float calibratedRssi, float pathLossParameter); static float getAdvertisingRange(int transmissionPower, int calibratedTransmissionPower, int calibratedRange); static String getReadableBeaconType(AdvertisingPacket advertisingPacket); static String getReadableBeaconType(Class<? extends Beacon> beaconClass); static Comparator<Beacon> DescendingRssiComparator; static Comparator<Beacon> AscendingRssiComparator; }### Answer: @Test public void calculateRssi_distanceSmallerOne_returnsRssiGreaterThanCalibrated() { float calibratedRssi = -35; float actualRssi = BeaconUtil.calculateRssi(0.5F, -35, 2F); assertTrue(calibratedRssi < actualRssi); } @Test public void calculateRssi_distanceGreaterOne_returnsRssiSmallerThanCalibrated() { float calibratedRssi = -35; float actualRssi = BeaconUtil.calculateRssi(10, -35, 2F); assertTrue(calibratedRssi > actualRssi); } @Test public void calculateRssi_distanceEqualOne_returnsRssiEqualThanCalibrated() { float calibratedRssi = -35; float actualRssi = BeaconUtil.calculateRssi(1, -35, 2F); assertEquals(calibratedRssi, actualRssi, 0.1); } @Test public void calculateRssi_negativeDistance_throwsException() { exception.expect(IllegalArgumentException.class); BeaconUtil.calculateRssi(-1, -35, 2F); }
### Question: IBeacon extends Beacon<P> { public UUID getProximityUuid() { return proximityUuid; } IBeacon(); @Override BeaconLocationProvider<IBeacon<P>> createLocationProvider(); @Override void applyPropertiesFromAdvertisingPacket(P advertisingPacket); @Override String toString(); UUID getProximityUuid(); void setProximityUuid(UUID proximityUuid); int getMajor(); void setMajor(int major); int getMinor(); void setMinor(int minor); static final int CALIBRATION_DISTANCE_DEFAULT; }### Answer: @Test public void getProximityUuid() { assertEquals(UUID.fromString("9114d61a-67d1-11e8-adc0-fa7ae01bbebc"), kontaktAdvertsingPacket.getProximityUuid()); assertEquals(UUID.fromString("03253fdd-55cb-44c2-a1eb-80c8355f8291"), blueupAdvertsingPacket.getProximityUuid()); }
### Question: IBeacon extends Beacon<P> { public int getMajor() { return major; } IBeacon(); @Override BeaconLocationProvider<IBeacon<P>> createLocationProvider(); @Override void applyPropertiesFromAdvertisingPacket(P advertisingPacket); @Override String toString(); UUID getProximityUuid(); void setProximityUuid(UUID proximityUuid); int getMajor(); void setMajor(int major); int getMinor(); void setMinor(int minor); static final int CALIBRATION_DISTANCE_DEFAULT; }### Answer: @Test public void getMajor() { assertEquals(25840, kontaktAdvertsingPacket.getMajor()); assertEquals(1, blueupAdvertsingPacket.getMajor()); }
### Question: IBeacon extends Beacon<P> { public int getMinor() { return minor; } IBeacon(); @Override BeaconLocationProvider<IBeacon<P>> createLocationProvider(); @Override void applyPropertiesFromAdvertisingPacket(P advertisingPacket); @Override String toString(); UUID getProximityUuid(); void setProximityUuid(UUID proximityUuid); int getMajor(); void setMajor(int major); int getMinor(); void setMinor(int minor); static final int CALIBRATION_DISTANCE_DEFAULT; }### Answer: @Test public void getMinor() { assertEquals(36698, kontaktAdvertsingPacket.getMinor()); assertEquals(2, blueupAdvertsingPacket.getMinor()); }
### Question: Beacon { public P getOldestAdvertisingPacket() { synchronized (advertisingPackets) { if (!hasAnyAdvertisingPacket()) { return null; } return advertisingPackets.get(0); } } Beacon(); @Deprecated static Beacon from(AdvertisingPacket advertisingPacket); boolean hasLocation(); Location getLocation(); static List<Location> getLocations(List<? extends Beacon> beacons); abstract BeaconLocationProvider<? extends Beacon> createLocationProvider(); boolean hasAnyAdvertisingPacket(); P getOldestAdvertisingPacket(); P getLatestAdvertisingPacket(); ArrayList<P> getAdvertisingPacketsBetween(long startTimestamp, long endTimestamp); ArrayList<P> getAdvertisingPacketsFromLast(long amount, TimeUnit timeUnit); ArrayList<P> getAdvertisingPacketsSince(long timestamp); ArrayList<P> getAdvertisingPacketsBefore(long timestamp); void addAdvertisingPacket(P advertisingPacket); void applyPropertiesFromAdvertisingPacket(P advertisingPacket); void trimAdvertisingPackets(); boolean equalsLastAdvertisingPackage(P advertisingPacket); boolean hasBeenSeenSince(long timestamp); boolean hasBeenSeenInThePast(long duration, TimeUnit timeUnit); float getRssi(RssiFilter filter); float getFilteredRssi(); float getDistance(); float getDistance(RssiFilter filter); float getEstimatedAdvertisingRange(); long getLatestTimestamp(); WindowFilter createSuggestedWindowFilter(); @Override String toString(); String getMacAddress(); void setMacAddress(String macAddress); int getRssi(); void setRssi(int rssi); int getCalibratedRssi(); void setCalibratedRssi(int calibratedRssi); int getCalibratedDistance(); void setCalibratedDistance(int calibratedDistance); int getTransmissionPower(); void setTransmissionPower(int transmissionPower); ArrayList<P> getAdvertisingPackets(); LocationProvider getLocationProvider(); void setLocationProvider(BeaconLocationProvider<? extends Beacon> locationProvider); static final long MAXIMUM_PACKET_AGE; @Deprecated static Comparator<Beacon> RssiComparator; }### Answer: @Test public void getOldestAdvertisingPacket() { assertEquals(iBeacon.getAdvertisingPackets().get(0), iBeacon.getOldestAdvertisingPacket()); }
### Question: BeaconMapBackground { public static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing) { double angleInRadians = Math.toRadians(bearing + 90); return new Point( (int) (referencePoint.x - (distanceInPixels * Math.cos(angleInRadians))), (int) (referencePoint.y - (distanceInPixels * Math.sin(angleInRadians))) ); } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getShiftedPoint_zeroReference_correctPoints() { Point referencePoint; Point shiftedPoint; double distance; double angle; referencePoint = new Point(0, 0); distance = 10; angle = 0; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(0, -10), shiftedPoint, 0); angle = 90; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(10, 0), shiftedPoint, 0); angle = 180; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(0, 10), shiftedPoint, 0); angle = 270; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(-10, 0), shiftedPoint, 0); } @Test public void getShiftedPoint_positiveReference_correctPoints() { Point referencePoint; Point shiftedPoint; double distance; double angle; referencePoint = new Point(100, 100); distance = 50; angle = 0; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(100, 50), shiftedPoint, 0); angle = 90; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(150, 100), shiftedPoint, 0); angle = 180; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(100, 150), shiftedPoint, 0); angle = 270; shiftedPoint = BeaconMapBackground.getShiftedPoint(referencePoint, distance, angle); assertPointEquals(new Point(50, 100), shiftedPoint, 0); }
### Question: Beacon { public ArrayList<P> getAdvertisingPacketsFromLast(long amount, TimeUnit timeUnit) { return getAdvertisingPacketsBetween(System.currentTimeMillis() - timeUnit.toMillis(amount), System.currentTimeMillis()); } Beacon(); @Deprecated static Beacon from(AdvertisingPacket advertisingPacket); boolean hasLocation(); Location getLocation(); static List<Location> getLocations(List<? extends Beacon> beacons); abstract BeaconLocationProvider<? extends Beacon> createLocationProvider(); boolean hasAnyAdvertisingPacket(); P getOldestAdvertisingPacket(); P getLatestAdvertisingPacket(); ArrayList<P> getAdvertisingPacketsBetween(long startTimestamp, long endTimestamp); ArrayList<P> getAdvertisingPacketsFromLast(long amount, TimeUnit timeUnit); ArrayList<P> getAdvertisingPacketsSince(long timestamp); ArrayList<P> getAdvertisingPacketsBefore(long timestamp); void addAdvertisingPacket(P advertisingPacket); void applyPropertiesFromAdvertisingPacket(P advertisingPacket); void trimAdvertisingPackets(); boolean equalsLastAdvertisingPackage(P advertisingPacket); boolean hasBeenSeenSince(long timestamp); boolean hasBeenSeenInThePast(long duration, TimeUnit timeUnit); float getRssi(RssiFilter filter); float getFilteredRssi(); float getDistance(); float getDistance(RssiFilter filter); float getEstimatedAdvertisingRange(); long getLatestTimestamp(); WindowFilter createSuggestedWindowFilter(); @Override String toString(); String getMacAddress(); void setMacAddress(String macAddress); int getRssi(); void setRssi(int rssi); int getCalibratedRssi(); void setCalibratedRssi(int calibratedRssi); int getCalibratedDistance(); void setCalibratedDistance(int calibratedDistance); int getTransmissionPower(); void setTransmissionPower(int transmissionPower); ArrayList<P> getAdvertisingPackets(); LocationProvider getLocationProvider(); void setLocationProvider(BeaconLocationProvider<? extends Beacon> locationProvider); static final long MAXIMUM_PACKET_AGE; @Deprecated static Comparator<Beacon> RssiComparator; }### Answer: @Test public void getAdvertisingPacketsFromLast() { long duration = TimeUnit.SECONDS.toMillis(3); long minimumTimestamp = System.currentTimeMillis() - duration; List<IBeaconAdvertisingPacket> advertisingPackets = iBeacon.getAdvertisingPacketsFromLast(duration, TimeUnit.MILLISECONDS); long maximumTimestamp = System.currentTimeMillis(); assertFalse(advertisingPackets.isEmpty()); for (IBeaconAdvertisingPacket advertisingPacket : advertisingPackets) { if (advertisingPacket.getTimestamp() < minimumTimestamp) { fail("Packet timestamp before minimum timestamp"); } else if (advertisingPacket.getTimestamp() >= maximumTimestamp) { fail("Packet timestamp after maximum timestamp"); } } }
### Question: Beacon { public ArrayList<P> getAdvertisingPacketsSince(long timestamp) { return getAdvertisingPacketsBetween(timestamp, System.currentTimeMillis()); } Beacon(); @Deprecated static Beacon from(AdvertisingPacket advertisingPacket); boolean hasLocation(); Location getLocation(); static List<Location> getLocations(List<? extends Beacon> beacons); abstract BeaconLocationProvider<? extends Beacon> createLocationProvider(); boolean hasAnyAdvertisingPacket(); P getOldestAdvertisingPacket(); P getLatestAdvertisingPacket(); ArrayList<P> getAdvertisingPacketsBetween(long startTimestamp, long endTimestamp); ArrayList<P> getAdvertisingPacketsFromLast(long amount, TimeUnit timeUnit); ArrayList<P> getAdvertisingPacketsSince(long timestamp); ArrayList<P> getAdvertisingPacketsBefore(long timestamp); void addAdvertisingPacket(P advertisingPacket); void applyPropertiesFromAdvertisingPacket(P advertisingPacket); void trimAdvertisingPackets(); boolean equalsLastAdvertisingPackage(P advertisingPacket); boolean hasBeenSeenSince(long timestamp); boolean hasBeenSeenInThePast(long duration, TimeUnit timeUnit); float getRssi(RssiFilter filter); float getFilteredRssi(); float getDistance(); float getDistance(RssiFilter filter); float getEstimatedAdvertisingRange(); long getLatestTimestamp(); WindowFilter createSuggestedWindowFilter(); @Override String toString(); String getMacAddress(); void setMacAddress(String macAddress); int getRssi(); void setRssi(int rssi); int getCalibratedRssi(); void setCalibratedRssi(int calibratedRssi); int getCalibratedDistance(); void setCalibratedDistance(int calibratedDistance); int getTransmissionPower(); void setTransmissionPower(int transmissionPower); ArrayList<P> getAdvertisingPackets(); LocationProvider getLocationProvider(); void setLocationProvider(BeaconLocationProvider<? extends Beacon> locationProvider); static final long MAXIMUM_PACKET_AGE; @Deprecated static Comparator<Beacon> RssiComparator; }### Answer: @Test public void getAdvertisingPacketsSince() { long minimumTimestamp = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(3); List<IBeaconAdvertisingPacket> advertisingPackets = iBeacon.getAdvertisingPacketsSince(minimumTimestamp); assertFalse(advertisingPackets.isEmpty()); for (IBeaconAdvertisingPacket advertisingPacket : advertisingPackets) { if (advertisingPacket.getTimestamp() < minimumTimestamp) { fail("Packet timestamp before minimum timestamp"); } } }
### Question: Beacon { public ArrayList<P> getAdvertisingPacketsBefore(long timestamp) { return getAdvertisingPacketsBetween(0, timestamp); } Beacon(); @Deprecated static Beacon from(AdvertisingPacket advertisingPacket); boolean hasLocation(); Location getLocation(); static List<Location> getLocations(List<? extends Beacon> beacons); abstract BeaconLocationProvider<? extends Beacon> createLocationProvider(); boolean hasAnyAdvertisingPacket(); P getOldestAdvertisingPacket(); P getLatestAdvertisingPacket(); ArrayList<P> getAdvertisingPacketsBetween(long startTimestamp, long endTimestamp); ArrayList<P> getAdvertisingPacketsFromLast(long amount, TimeUnit timeUnit); ArrayList<P> getAdvertisingPacketsSince(long timestamp); ArrayList<P> getAdvertisingPacketsBefore(long timestamp); void addAdvertisingPacket(P advertisingPacket); void applyPropertiesFromAdvertisingPacket(P advertisingPacket); void trimAdvertisingPackets(); boolean equalsLastAdvertisingPackage(P advertisingPacket); boolean hasBeenSeenSince(long timestamp); boolean hasBeenSeenInThePast(long duration, TimeUnit timeUnit); float getRssi(RssiFilter filter); float getFilteredRssi(); float getDistance(); float getDistance(RssiFilter filter); float getEstimatedAdvertisingRange(); long getLatestTimestamp(); WindowFilter createSuggestedWindowFilter(); @Override String toString(); String getMacAddress(); void setMacAddress(String macAddress); int getRssi(); void setRssi(int rssi); int getCalibratedRssi(); void setCalibratedRssi(int calibratedRssi); int getCalibratedDistance(); void setCalibratedDistance(int calibratedDistance); int getTransmissionPower(); void setTransmissionPower(int transmissionPower); ArrayList<P> getAdvertisingPackets(); LocationProvider getLocationProvider(); void setLocationProvider(BeaconLocationProvider<? extends Beacon> locationProvider); static final long MAXIMUM_PACKET_AGE; @Deprecated static Comparator<Beacon> RssiComparator; }### Answer: @Test public void getAdvertisingPacketsBefore_packetsWithSmallerTimestamp_returnsCorrectPackets() { long maximumTimestamp = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(3); List<IBeaconAdvertisingPacket> advertisingPackets = iBeacon.getAdvertisingPacketsBefore(maximumTimestamp); assertFalse(advertisingPackets.isEmpty()); for (IBeaconAdvertisingPacket advertisingPacket : advertisingPackets) { if (advertisingPacket.getTimestamp() >= maximumTimestamp) { fail("Packet timestamp after maximum timestamp"); } } }
### Question: SphericalMercatorProjection { public static double latitudeToY(double latitude) { return Math.log(Math.tan(Math.PI / 4 + Math.toRadians(latitude) / 2)) * EARTH_RADIUS; } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void latitudeToY() { double expectedY = 6894701.008722784; double actualY = SphericalMercatorProjection.latitudeToY(LocationTest.BERLIN.getLatitude()); assertEquals(expectedY, actualY, 0.00001); }
### Question: SphericalMercatorProjection { public static double longitudeToX(double longitude) { return Math.toRadians(longitude) * EARTH_RADIUS; } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void longitudeToX() { double expectedX = 1492232.6533872557; double actualX = SphericalMercatorProjection.longitudeToX(LocationTest.BERLIN.getLongitude()); assertEquals(expectedX, actualX, 0.00001); }
### Question: SphericalMercatorProjection { public static double yToLatitude(double y) { return Math.toDegrees(Math.atan(Math.exp(y / EARTH_RADIUS)) * 2 - Math.PI / 2); } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void yToLatitude() { double actualLatitude = SphericalMercatorProjection.yToLatitude(6894701.008722784); assertEquals(LocationTest.BERLIN.getLatitude(), actualLatitude, 0.00001); }
### Question: SphericalMercatorProjection { public static double xToLongitude(double x) { return Math.toDegrees(x / EARTH_RADIUS); } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void xToLongitude() { double actualLongitude = SphericalMercatorProjection.xToLongitude(1492232.6533872557); assertEquals(LocationTest.BERLIN.getLongitude(), actualLongitude, 0.00001); }
### Question: SphericalMercatorProjection { public static double[] geodeticToEcef(double[] geodetic) { double[] ecef = new double[3]; double latitude = geodetic[0]; double longitude = geodetic[1]; double altitude = geodetic[2]; double n = EARTH_RADIUS / Math.sqrt(1 - E2 * Math.sin(latitude) * Math.sin(latitude)); ecef[0] = (n + altitude) * Math.cos(latitude) * Math.cos(longitude); ecef[1] = (n + altitude) * Math.cos(latitude) * Math.sin(longitude); ecef[2] = (n * (1 - E2) + altitude) * Math.sin(latitude); return ecef; } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void geodeticToEcef_location_accurateEcef() { double[] expectedCenter = new double[]{3786292.474596871, 890822.9600122868, 5037857.368752121}; double[] geodetic = new double[]{ Math.toRadians(LocationTest.SOCCER_FIELD_CENTER.getLatitude()), Math.toRadians(LocationTest.SOCCER_FIELD_CENTER.getLongitude()), Math.toRadians(LocationTest.SOCCER_FIELD_CENTER.getAltitude()) }; double[] actualCenter = SphericalMercatorProjection.geodeticToEcef(geodetic); assertEquals(expectedCenter[0], actualCenter[0], 1); assertEquals(expectedCenter[1], actualCenter[1], 1); assertEquals(expectedCenter[2], actualCenter[2], 1); }
### Question: SphericalMercatorProjection { public static double[] ecefToGeodetic(double[] ecef) { double zp, w2, w, r2, r, s2, c2, s, c, ss, g, rg, rf, u, v, m, f, p, x, y, z; double[] geodetic = new double[3]; x = ecef[0]; y = ecef[1]; z = ecef[2]; zp = Math.abs(z); w2 = x * x + y * y; w = Math.sqrt(w2); r2 = w2 + z * z; r = Math.sqrt(r2); geodetic[1] = Math.atan2(y, x); s2 = z * z / r2; c2 = w2 / r2; u = A2 / r; v = A3 - A4 / r; if (c2 > 0.3) { s = (zp / r) * (1.0 + c2 * (A1 + u + s2 * v) / r); geodetic[0] = Math.asin(s); ss = s * s; c = Math.sqrt(1.0 - ss); } else { c = (w / r) * (1.0 - s2 * (A5 - u - c2 * v) / r); geodetic[0] = Math.acos(c); ss = 1.0 - c * c; s = Math.sqrt(ss); } g = 1.0 - E2 * ss; rg = EARTH_RADIUS / Math.sqrt(g); rf = A6 * rg; u = w - rg * c; v = zp - rf * s; f = c * u + s * v; m = c * v - s * u; p = m / (rf / g + f); geodetic[0] = geodetic[0] + p; geodetic[2] = f + m * p / 2.0; if (z < 0.0) { geodetic[0] *= -1.0; } return geodetic; } static double yToLatitude(double y); static double xToLongitude(double x); static double latitudeToY(double latitude); static double longitudeToX(double longitude); static Location ecefToLocation(double[] ecef); static double[] ecefToGeodetic(double[] ecef); static double[] locationToEcef(Location location); static double[] geodeticToEcef(double[] geodetic); static final double EARTH_RADIUS; }### Answer: @Test public void ecefToGeodetic_ecefArray_accurateGeodetic() { double[] expectedGeodetic = new double[]{ LocationTest.SOCCER_FIELD_CENTER.getLatitude(), LocationTest.SOCCER_FIELD_CENTER.getLongitude(), LocationTest.SOCCER_FIELD_CENTER.getAltitude() }; double[] ecefArray = new double[]{3786292.474596871, 890822.9600122868, 5037857.368752121}; double[] actualGeodetic = SphericalMercatorProjection.ecefToGeodetic(ecefArray); assertEquals(expectedGeodetic[0], Math.toDegrees(actualGeodetic[0]), 1); assertEquals(expectedGeodetic[1], Math.toDegrees(actualGeodetic[1]), 1); assertEquals(expectedGeodetic[2], Math.toDegrees(actualGeodetic[2]), 1); }
### Question: Location { public double getAngleTo(Location location) { return getRotationAngleInDegrees(this, location); } Location(); Location(double latitude, double longitude); Location(double latitude, double longitude, double altitude); Location(double latitude, double longitude, double altitude, double elevation); Location(Location location); double getDistanceTo(Location location); double getAngleTo(Location location); void shift(double distance, double angle); Location getShiftedLocation(double distance, double angle); boolean latitudeAndLongitudeEquals(Location location); boolean latitudeAndLongitudeEquals(Location location, double delta); boolean hasLatitudeAndLongitude(); boolean hasAltitude(); boolean hasElevation(); boolean hasAccuracy(); URI generateGoogleMapsUri(); @Override String toString(); static double getRotationAngleInDegrees(Location centerLocation, Location targetLocation); double getLatitude(); void setLatitude(double latitude); double getLongitude(); void setLongitude(double longitude); double getAltitude(); void setAltitude(double altitude); long getTimestamp(); void setTimestamp(long timestamp); double getElevation(); void setElevation(double elevation); double getAccuracy(); void setAccuracy(double accuracy); static final double VALUE_NOT_SET; }### Answer: @Test public void getAngleTo_validLocations_correctAngles() throws Exception { double angle; angle = BERLIN.getAngleTo(NEW_YORK_CITY); assertEquals(360 - 63.975, angle, 0.001); angle = NEW_YORK_CITY.getAngleTo(BERLIN); assertEquals(46.167, angle, 0.001); angle = BERLIN.getAngleTo(BERLIN); assertEquals(0, angle, 0); angle = SOCCER_FIELD_TOP_LEFT.getAngleTo(SOCCER_FIELD_TOP_RIGHT); assertEquals(81.426, angle, 0.001); angle = SOCCER_FIELD_TOP_LEFT.getAngleTo(SOCCER_FIELD_BOTTOM_LEFT); assertEquals(172.045, angle, 0.001); angle = SOCCER_FIELD_BOTTOM_LEFT.getAngleTo(SOCCER_FIELD_TOP_LEFT); assertEquals(360 - 7.955, angle, 0.001); }
### Question: Location { public double getDistanceTo(Location location) { return LocationDistanceCalculator.calculateDistanceBetween(this, location); } Location(); Location(double latitude, double longitude); Location(double latitude, double longitude, double altitude); Location(double latitude, double longitude, double altitude, double elevation); Location(Location location); double getDistanceTo(Location location); double getAngleTo(Location location); void shift(double distance, double angle); Location getShiftedLocation(double distance, double angle); boolean latitudeAndLongitudeEquals(Location location); boolean latitudeAndLongitudeEquals(Location location, double delta); boolean hasLatitudeAndLongitude(); boolean hasAltitude(); boolean hasElevation(); boolean hasAccuracy(); URI generateGoogleMapsUri(); @Override String toString(); static double getRotationAngleInDegrees(Location centerLocation, Location targetLocation); double getLatitude(); void setLatitude(double latitude); double getLongitude(); void setLongitude(double longitude); double getAltitude(); void setAltitude(double altitude); long getTimestamp(); void setTimestamp(long timestamp); double getElevation(); void setElevation(double elevation); double getAccuracy(); void setAccuracy(double accuracy); static final double VALUE_NOT_SET; }### Answer: @Test public void getDistanceTo_validLocations_correctDistance() throws Exception { double distance = NEW_YORK_CITY.getDistanceTo(BERLIN); assertEquals(DISTANCE_NYC_BERLIN, distance, 1); }
### Question: Multilateration { public LeastSquaresOptimizer.Optimum findOptimum() { double[][] positions = getPositions(beacons); double[] distances = getDistances(beacons); return findOptimum(positions, distances); } Multilateration(List<Beacon> beacons); static double[][] getPositions(List<Beacon> beacons); static double[] getDistances(List<Beacon> beacons); LeastSquaresOptimizer.Optimum findOptimum(); static LeastSquaresOptimizer.Optimum findOptimum(double[][] positions, double[] distances); static Location getLocation(LeastSquaresOptimizer.Optimum optimum); double getRMS(); List<Beacon> getBeacons(); Location getLocation(); float getDeviation(); LeastSquaresOptimizer.Optimum getOptimum(); static final int ROOT_MEAN_SQUARE_NOT_SET; }### Answer: @Test public void findOptimum_perfectDistances_perfectOptimum() throws Exception { double[] expectedCenter = new double[]{0, 0}; double[][] positions = new double[][]{{-10, 10}, {10, 10}, {10, -10}, {-10, -10}}; double distance = 7.07106781; double[] distances = new double[]{distance, distance, distance, distance}; LeastSquaresOptimizer.Optimum optimum = Multilateration.findOptimum(positions, distances); double[] actualCenter = optimum.getPoint().toArray(); assertEquals(expectedCenter[0], actualCenter[0], 0); assertEquals(expectedCenter[1], actualCenter[1], 0); } @Test public void findOptimum_realisticDistances_realisticOptimum() throws Exception { double[] expectedCenter = new double[]{0, 0}; double[][] positions = new double[][]{{-10, 10}, {10, 10}, {10, -10}, {-10, -10}}; double[] distances = new double[]{7.02, 7.05, 7.09, 7.1}; LeastSquaresOptimizer.Optimum optimum = Multilateration.findOptimum(positions, distances); double[] actualCenter = optimum.getPoint().toArray(); assertEquals(expectedCenter[0], actualCenter[0], 0.2); assertEquals(expectedCenter[1], actualCenter[1], 0.2); }
### Question: BeaconDistanceCalculator { public static float calculateDistance(float rssi, float calibratedRssi, int calibratedDistance, float pathLossParameter) { return calculateDistance(rssi, getCalibratedRssiAtOneMeter(calibratedRssi, calibratedDistance), pathLossParameter); } static float calculateDistanceTo(Beacon beacon); static float calculateDistanceWithoutElevationDeltaToDevice(Beacon beacon, float rssi, double deviceElevation); static float calculateDistanceTo(Beacon beacon, float rssi); static float calculateDistance(float rssi, float calibratedRssi, int calibratedDistance, float pathLossParameter); static float getCalibratedRssiAtOneMeter(float calibratedRssi, float calibratedDistance); static float calculateDistance(float rssi, float calibratedRssi, float pathLossParameter); static void setPathLossParameter(float pathLossParameter); static float getPathLossParameter(); static final float PATH_LOSS_PARAMETER_OPEN_SPACE; static final float PATH_LOSS_PARAMETER_INDOOR; static final float PATH_LOSS_PARAMETER_OFFICE_HARD_PARTITION; static final int CALIBRATED_RSSI_AT_ONE_METER; static final int SIGNAL_LOSS_AT_ONE_METER; }### Answer: @Test public void calculateDistance() throws Exception { int rssiAtZeroMeters = -45; int rssiAtOneMeter = -65; float calculatedDistance = BeaconDistanceCalculator.calculateDistance(-80, rssiAtOneMeter, BeaconDistanceCalculator.PATH_LOSS_PARAMETER_INDOOR); assertEquals(8, calculatedDistance, 1); calculatedDistance = BeaconDistanceCalculator.calculateDistance(-100, rssiAtOneMeter, BeaconDistanceCalculator.PATH_LOSS_PARAMETER_INDOOR); assertEquals(110, calculatedDistance, 10); } @Test public void calculateDistance_calibratedRssi_calibratedDistance() throws Exception { int rssiAtZeroMeters = -45; int rssiAtOneMeter = -65; float calculatedDistance = BeaconDistanceCalculator.calculateDistance(rssiAtZeroMeters, rssiAtOneMeter, BeaconDistanceCalculator.PATH_LOSS_PARAMETER_INDOOR); assertEquals(0, calculatedDistance, 0.1); calculatedDistance = BeaconDistanceCalculator.calculateDistance(rssiAtOneMeter, rssiAtOneMeter, BeaconDistanceCalculator.PATH_LOSS_PARAMETER_INDOOR); assertEquals(1, calculatedDistance, 0.1); }
### Question: DistanceUtil { public static Location speedFilter(Location oldLocation, Location newLocation, double maximumSpeed) { double distance = oldLocation.getDistanceTo(newLocation); long timestampDelta = newLocation.getTimestamp() - oldLocation.getTimestamp(); double currentSpeed = 0; if (timestampDelta != 0) { currentSpeed = distance / ((float) timestampDelta / TimeUnit.SECONDS.toMillis(1)); } if (currentSpeed > maximumSpeed) { double angle = oldLocation.getAngleTo(newLocation); Location adjustedLocation = oldLocation.getShiftedLocation(maximumSpeed, angle); adjustedLocation.setTimestamp(newLocation.getTimestamp()); return adjustedLocation; } else { return newLocation; } } static long getClosestEvenDistance(double distance, int evenIncrement); static long getReasonableSmallerEvenDistance(double distance); static int getMaximumEvenIncrement(double distance); static Location walkingSpeedFilter(Location oldLocation, Location newLocation); static Location speedFilter(Location oldLocation, Location newLocation, double maximumSpeed); static final double HUMAN_WALKING_SPEED; }### Answer: @Test public void speedFilter_largerDistanceThanMaximumSpeed_correctChange() throws Exception { Location oldLocation = LocationPredictorTest.GENDARMENMARKT; oldLocation.setTimestamp(0); Location newLocation = oldLocation.getShiftedLocation(5, 0); newLocation.setTimestamp(1000); Location expectedLocation = oldLocation.getShiftedLocation(2, 0); Location actualLocation = DistanceUtil.speedFilter(oldLocation, newLocation, 2); assertEquals(expectedLocation.getLatitude(), actualLocation.getLatitude(), 0); assertEquals(expectedLocation.getLongitude(), actualLocation.getLongitude(), 0); } @Test public void speedFilter_exactlyMaximumSpeed_noChange() throws Exception { float maximumSpeed = 2; Location oldLocation = LocationPredictorTest.GENDARMENMARKT; oldLocation.setTimestamp(0); Location newLocation = oldLocation.getShiftedLocation(maximumSpeed, 0); newLocation.setTimestamp(1000); Location expectedLocation = oldLocation.getShiftedLocation(maximumSpeed, 0); Location actualLocation = DistanceUtil.speedFilter(oldLocation, newLocation, maximumSpeed); assertEquals(expectedLocation.getLatitude(), actualLocation.getLatitude(), 0); assertEquals(expectedLocation.getLongitude(), actualLocation.getLongitude(), 0); } @Test public void speedFilter_exactLocations_noChange() throws Exception { float maximumSpeed = 2; Location oldLocation = LocationPredictorTest.GENDARMENMARKT; oldLocation.setTimestamp(0); Location expectedLocation = oldLocation; Location actualLocation = DistanceUtil.speedFilter(oldLocation, oldLocation, maximumSpeed); assertEquals(expectedLocation.getLatitude(), actualLocation.getLatitude(), 0); assertEquals(expectedLocation.getLongitude(), actualLocation.getLongitude(), 0); } @Test public void speedFilter_smallerDistanceThanMaximumSpeed_noChange() throws Exception { Location oldLocation = LocationPredictorTest.GENDARMENMARKT; oldLocation.setTimestamp(0); Location newLocation = oldLocation.getShiftedLocation(1, 0); newLocation.setTimestamp(1000); Location expectedLocation = oldLocation.getShiftedLocation(1, 0); Location actualLocation = DistanceUtil.speedFilter(oldLocation, newLocation, 2); assertEquals(expectedLocation.getLatitude(), actualLocation.getLatitude(), 0); assertEquals(expectedLocation.getLongitude(), actualLocation.getLongitude(), 0); }
### Question: DistanceUtil { public static long getReasonableSmallerEvenDistance(double distance) { return getClosestEvenDistance(distance, getMaximumEvenIncrement(distance)); } static long getClosestEvenDistance(double distance, int evenIncrement); static long getReasonableSmallerEvenDistance(double distance); static int getMaximumEvenIncrement(double distance); static Location walkingSpeedFilter(Location oldLocation, Location newLocation); static Location speedFilter(Location oldLocation, Location newLocation, double maximumSpeed); static final double HUMAN_WALKING_SPEED; }### Answer: @Test public void getReasonableSmallerEvenDistance() throws Exception { long actual = DistanceUtil.getReasonableSmallerEvenDistance(1); assertEquals(1, actual); actual = DistanceUtil.getReasonableSmallerEvenDistance(12); assertEquals(10, actual); actual = DistanceUtil.getReasonableSmallerEvenDistance(52); assertEquals(50, actual); actual = DistanceUtil.getReasonableSmallerEvenDistance(123); assertEquals(100, actual); }
### Question: BeaconMapBackground { public Location getTopLeftLocation() { return topLeftLocation; } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getTopLeftLocation() { Location topLeftLocation = new Location(52.512653658536856, 13.390293996004692); assertEquals(0, topLeftLocation.getDistanceTo(beaconMapBackground.getTopLeftLocation()), 0.001); }
### Question: DistanceUtil { public static int getMaximumEvenIncrement(double distance) { if (distance < 10) { return 1; } return (int) Math.pow(10, Math.floor(Math.log10(distance))); } static long getClosestEvenDistance(double distance, int evenIncrement); static long getReasonableSmallerEvenDistance(double distance); static int getMaximumEvenIncrement(double distance); static Location walkingSpeedFilter(Location oldLocation, Location newLocation); static Location speedFilter(Location oldLocation, Location newLocation, double maximumSpeed); static final double HUMAN_WALKING_SPEED; }### Answer: @Test public void getMaximumEvenIncrement() throws Exception { int actual = DistanceUtil.getMaximumEvenIncrement(1); assertEquals(1, actual); actual = DistanceUtil.getMaximumEvenIncrement(12); assertEquals(10, actual); actual = DistanceUtil.getMaximumEvenIncrement(52); assertEquals(10, actual); actual = DistanceUtil.getMaximumEvenIncrement(123); assertEquals(100, actual); }
### Question: DistanceUtil { public static long getClosestEvenDistance(double distance, int evenIncrement) { return Math.round(distance / evenIncrement) * evenIncrement; } static long getClosestEvenDistance(double distance, int evenIncrement); static long getReasonableSmallerEvenDistance(double distance); static int getMaximumEvenIncrement(double distance); static Location walkingSpeedFilter(Location oldLocation, Location newLocation); static Location speedFilter(Location oldLocation, Location newLocation, double maximumSpeed); static final double HUMAN_WALKING_SPEED; }### Answer: @Test public void getClosestEvenDistance() throws Exception { long actual = DistanceUtil.getClosestEvenDistance(96, 10); assertEquals(100, actual); actual = DistanceUtil.getClosestEvenDistance(94, 10); assertEquals(90, actual); actual = DistanceUtil.getClosestEvenDistance(99, 100); assertEquals(100, actual); actual = DistanceUtil.getClosestEvenDistance(49, 100); assertEquals(0, actual); }
### Question: LocationDistanceCalculator { public static double calculateDistanceBetween(Location fromLocation, Location toLocation) { return calculateDistanceBetween( fromLocation.getLatitude(), fromLocation.getLongitude(), fromLocation.getAltitude(), toLocation.getLatitude(), toLocation.getLongitude(), toLocation.getAltitude() ); } static double calculateDistanceBetween(Location fromLocation, Location toLocation); static double calculateDistanceBetween(double fromLatitude, double fromLongitude, double fromAltitude, double toLatitude, double toLongitude, double toAltitude); static final int EARTH_RADIUS; }### Answer: @Test public void calculateDistanceBetween_soccerFieldCorners_correctFieldDimensions() throws Exception { final double tolerableDelta = 1; double calculatedFieldWidth = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.SOCCER_FIELD_TOP_LEFT, LocationTest.SOCCER_FIELD_TOP_RIGHT); assertEquals(LocationTest.SOCCER_FIELD_WIDTH, calculatedFieldWidth, tolerableDelta); calculatedFieldWidth = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.SOCCER_FIELD_BOTTOM_LEFT, LocationTest.SOCCER_FIELD_BOTTOM_RIGHT); assertEquals(LocationTest.SOCCER_FIELD_WIDTH, calculatedFieldWidth, tolerableDelta); double calculatedFieldHeight = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.SOCCER_FIELD_TOP_LEFT, LocationTest.SOCCER_FIELD_BOTTOM_LEFT); assertEquals(LocationTest.SOCCER_FIELD_HEIGHT, calculatedFieldHeight, tolerableDelta); calculatedFieldHeight = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.SOCCER_FIELD_TOP_RIGHT, LocationTest.SOCCER_FIELD_BOTTOM_RIGHT); assertEquals(LocationTest.SOCCER_FIELD_HEIGHT, calculatedFieldHeight, tolerableDelta); } @Test public void calculateDistanceBetween_newYorkBerlin_correctDistance() throws Exception { final double tolerableDelta = 5000; double calculatedDistance = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.NEW_YORK_CITY, LocationTest.BERLIN); assertEquals(LocationTest.DISTANCE_NYC_BERLIN, calculatedDistance, tolerableDelta); calculatedDistance = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.BERLIN, LocationTest.NEW_YORK_CITY); assertEquals(LocationTest.DISTANCE_NYC_BERLIN, calculatedDistance, tolerableDelta); } @Test public void calculateDistanceBetween_swappedLocations_sameDistance() throws Exception { double calculatedDistance1 = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.NEW_YORK_CITY, LocationTest.BERLIN); double calculatedDistance2 = LocationDistanceCalculator.calculateDistanceBetween(LocationTest.BERLIN, LocationTest.NEW_YORK_CITY); assertEquals(calculatedDistance1, calculatedDistance2, 0); } @Test public void calculateDistanceBetween_locationsWithElevation_correctDistance() throws Exception { Location lowLocation = new Location(0, 0, 0, 0); Location highLocation = new Location(0, 0, 0, 10); double calculatedDistance = LocationDistanceCalculator.calculateDistanceBetween(lowLocation, highLocation); assertEquals(0, calculatedDistance, 0); } @Test public void calculateDistanceBetween_locationsWithAltitude_correctDistance() throws Exception { Location lowLocation = new Location(0, 0, 0, 0); Location highLocation = new Location(0, 0, 10, 0); double calculatedDistance = LocationDistanceCalculator.calculateDistanceBetween(lowLocation, highLocation); assertEquals(10, calculatedDistance, 0); } @Test public void calculateDistanceBetween_locationsWithAltitudeAndElevation_correctDistance() throws Exception { Location lowLocation = new Location(0, 0, 0, 0); Location highLocation = new Location(0, 0, 10, 10); double calculatedDistance = LocationDistanceCalculator.calculateDistanceBetween(lowLocation, highLocation); assertEquals(10, calculatedDistance, 0); }
### Question: LocationUtil { public static Location calculateMeanLocation(Location... locations) { return calculateMeanLocation(Arrays.asList(locations)); } static Location calculateMeanLocationFromLast(List<Location> locationList, long amount, TimeUnit timeUnit); static Location calculateMeanLocation(Location... locations); static Location calculateMeanLocation(List<Location> locationList); static List<Location> getLocationsBetween(List<Location> locationList, long minimumTimestamp, long maximumTimestamp); static List<Location> getLocationsFromLast(List<Location> locationList, long amount, TimeUnit timeUnit); static List<Location> getLocationsSince(List<Location> locationList, long timestamp); static List<Location> getLocationsBefore(List<Location> locationList, long timestamp); }### Answer: @Test public void meanLocation_multipleLocations_correctMeanLocation() throws Exception { List<Location> locationList = new ArrayList<>(Arrays.asList( LocationTest.NEW_YORK_CITY, LocationTest.BERLIN )); Location expectedLocation = new Location(46.61639095, -30.3005094); Location actualLocation = LocationUtil.calculateMeanLocation(locationList); assertTrue(actualLocation.latitudeAndLongitudeEquals(expectedLocation, 0.00000001)); } @Test public void meanLocation_multipleLocationsCloseDistances_correctMeanLocation() throws Exception { List<Location> locationList = new ArrayList<>(Arrays.asList( LocationTest.SOCCER_FIELD_BOTTOM_LEFT, LocationTest.SOCCER_FIELD_BOTTOM_RIGHT, LocationTest.SOCCER_FIELD_TOP_LEFT, LocationTest.SOCCER_FIELD_TOP_RIGHT, LocationTest.SOCCER_FIELD_CENTER )); Location expectedLocation = LocationTest.SOCCER_FIELD_CENTER; Location actualLocation = LocationUtil.calculateMeanLocation(locationList); assertTrue(actualLocation.latitudeAndLongitudeEquals(expectedLocation, 0.00001)); } @Test public void meanLocation_singleLocation_correctLocation() throws Exception { List<Location> singleLocationList = new ArrayList<>(Arrays.asList( LocationTest.BERLIN )); Location expectedLocation = new Location(LocationTest.BERLIN); Location actualLocation = LocationUtil.calculateMeanLocation(singleLocationList); assertTrue(actualLocation.latitudeAndLongitudeEquals(expectedLocation)); } @Test public void meanLocation_emptyLocationList_correctMeanLocation() throws Exception { List<Location> emptyLocationList = new ArrayList<>(); Location expectedLocation = null; Location actualLocation = LocationUtil.calculateMeanLocation(emptyLocationList); assertEquals(expectedLocation, actualLocation); }
### Question: BeaconMapBackground { public Location getBottomRightLocation() { return bottomRightLocation; } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getBottomRightLocation() { Location bottomRightLocation = new Location(52.512295922346524, 13.391304257299764); assertEquals(0, bottomRightLocation.getDistanceTo(beaconMapBackground.getBottomRightLocation()), 0.001); }
### Question: LocationUtil { public static List<Location> getLocationsBetween(List<Location> locationList, long minimumTimestamp, long maximumTimestamp) { List<Location> matchingLocations = new ArrayList<>(); for (Location location : locationList) { if (location.getTimestamp() < minimumTimestamp || location.getTimestamp() >= maximumTimestamp) { continue; } matchingLocations.add(location); } return matchingLocations; } static Location calculateMeanLocationFromLast(List<Location> locationList, long amount, TimeUnit timeUnit); static Location calculateMeanLocation(Location... locations); static Location calculateMeanLocation(List<Location> locationList); static List<Location> getLocationsBetween(List<Location> locationList, long minimumTimestamp, long maximumTimestamp); static List<Location> getLocationsFromLast(List<Location> locationList, long amount, TimeUnit timeUnit); static List<Location> getLocationsSince(List<Location> locationList, long timestamp); static List<Location> getLocationsBefore(List<Location> locationList, long timestamp); }### Answer: @Test public void getLocationsBetween_locationListWithTimestamps_correctTimestampFilteredLocations() throws Exception { final Location firstLocation = LocationTest.SOCCER_FIELD_TOP_LEFT; final Location secondLocation = LocationTest.SOCCER_FIELD_TOP_RIGHT; final Location thirdLocation = LocationTest.SOCCER_FIELD_BOTTOM_LEFT; firstLocation.setTimestamp(0); secondLocation.setTimestamp(1); thirdLocation.setTimestamp(2); List<Location> timestampLocationList = new ArrayList<>(Arrays.asList( firstLocation, secondLocation, thirdLocation )); List<Location> actualLocations = LocationUtil.getLocationsBetween(timestampLocationList, 1, 2); List<Location> expectedLocations = new ArrayList<>(Arrays.asList( secondLocation )); assertEquals(expectedLocations, actualLocations); }
### Question: AngleUtil { public static double calculateMeanAngle(double[] angles) { if (angles == null || angles.length == 0) { return 0; } if (angles.length == 1) { return angles[0]; } float sumSin = 0; float sumCos = 0; for (double angle : angles) { sumSin += Math.sin(Math.toRadians(angle)); sumCos += Math.cos(Math.toRadians(angle)); } return Math.toDegrees(Math.atan2(sumSin, sumCos)); } static double calculateMeanAngle(double[] angles); static double calculateMeanAngle(List<Location> deviceLocations); static double angleDistance(double alpha, double beta); }### Answer: @Test public void calculateAngleMean_validAngles_correctAngle() throws Exception { double angles[] = {10, 350, 0, 20, 340}; double expectedAngle = 0; double actualAngle = calculateMeanAngle(angles); assertEquals(expectedAngle, actualAngle, 0.00001); angles = new double[]{10}; expectedAngle = 10; actualAngle = calculateMeanAngle(angles); assertEquals(expectedAngle, actualAngle, 0); angles = new double[]{0, 0, 90}; expectedAngle = 26.565; actualAngle = calculateMeanAngle(angles); assertEquals(expectedAngle, actualAngle, 0.0001); } @Test public void calculateAngleMean_invalidAngles_correctAngle() throws Exception { double angles[] = null; double expectedAngle = 0; double actualAngle = calculateMeanAngle(angles); assertEquals(expectedAngle, actualAngle, 0); angles = new double[]{}; expectedAngle = 0; actualAngle = calculateMeanAngle(angles); assertEquals(expectedAngle, actualAngle, 0); } @Test public void calculateAngleMean_negativeAngles_unequalAngles() throws Exception { double angles[] = new double[]{-90}; double negativeAngle = calculateMeanAngle(angles); angles = new double[]{270}; double positiveAngle = calculateMeanAngle(angles); assertNotEquals(negativeAngle, positiveAngle); }
### Question: BeaconMapBackground { public Point getTopLeftPoint() { return topLeftPoint; } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getTopLeftPoint() { assertPointEquals(new Point(0, 0), beaconMapBackground.getTopLeftPoint(), 0); }
### Question: BeaconMapBackground { public Point getBottomRightPoint() { return bottomRightPoint; } private BeaconMapBackground(Bitmap imageBitmap); Location getLocation(@NonNull Point point); Point getPoint(@NonNull Location location); static float getMetersPerPixel(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Location firstReferenceLocation, @NonNull Point firstReferencePoint, @NonNull Location secondReferenceLocation, @NonNull Point secondReferencePoint); static double getBearing(@NonNull Point firstPoint, @NonNull Point secondPoint); static double getBearing(@NonNull Location firstLocation, @NonNull Location secondLocation); static double getPixelDistance(@NonNull Point firstPoint, @NonNull Point secondPoint); static Location getLocation(@NonNull Point point, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getPoint(@NonNull Location location, @NonNull Location referenceLocation, @NonNull Point referencePoint, double metersPerPixel, double backgroundBearing); static Point getShiftedPoint(@NonNull Point referencePoint, double distanceInPixels, double bearing); Bitmap getImageBitmap(); double getMetersPerPixel(); void setMetersPerPixel(double metersPerPixel); double getBearing(); void setBearing(double bearing); Location getTopLeftLocation(); void setTopLeftLocation(@NonNull Location topLeftLocation); Location getBottomRightLocation(); void setBottomRightLocation(@NonNull Location bottomRightLocation); Point getTopLeftPoint(); void setTopLeftPoint(@NonNull Point topLeftPoint); Point getBottomRightPoint(); void setBottomRightPoint(@NonNull Point bottomRightPoint); }### Answer: @Test public void getBottomRightPoint() { assertPointEquals(new Point(backgroundImage.getWidth(), backgroundImage.getHeight()), beaconMapBackground.getBottomRightPoint(), 0); }
### Question: AdvertisingPacketFactory { protected boolean canCreateAdvertisingPacketWithSubFactories(byte[] advertisingData) { for (AdvertisingPacketFactory<AP> advertisingPacketFactory : subFactoryMap.values()) { if (advertisingPacketFactory.canCreateAdvertisingPacketWithSubFactories(advertisingData)) { return true; } } return canCreateAdvertisingPacket(advertisingData); } AdvertisingPacketFactory(Class<AP> packetClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(Class advertisingPacketClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(byte[] advertisingData); void addAdvertisingPacketFactory(F factory); void removeAdvertisingPacketFactory(Class<AP> advertisingPacketClass); void removeAdvertisingPacketFactory(F factory); Class<AP> getPacketClass(); }### Answer: @Test public void canCreateAdvertisingPacket_validData_returnsTrue() { IBeaconAdvertisingPacketFactory advertisingPacketFactory = new IBeaconAdvertisingPacketFactory(); assertTrue(advertisingPacketFactory.canCreateAdvertisingPacketWithSubFactories(BeaconTest.IBEACON_ADVERTISING_DATA)); }
### Question: AdvertisingPacketFactory { abstract boolean canCreateAdvertisingPacket(byte[] advertisingData); AdvertisingPacketFactory(Class<AP> packetClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(Class advertisingPacketClass); AdvertisingPacketFactory<AP> getAdvertisingPacketFactory(byte[] advertisingData); void addAdvertisingPacketFactory(F factory); void removeAdvertisingPacketFactory(Class<AP> advertisingPacketClass); void removeAdvertisingPacketFactory(F factory); Class<AP> getPacketClass(); }### Answer: @Test public void canCreateAdvertisingPacket_invalidData_returnsFalse() { IBeaconAdvertisingPacketFactory advertisingPacketFactory = new IBeaconAdvertisingPacketFactory(); assertFalse(advertisingPacketFactory.canCreateAdvertisingPacket(new byte[5])); }
### Question: SplashPresenter extends BasePresenter<V> implements SplashMvpPresenter<V> { @Override public void onAttach(V mvpView) { super.onAttach(mvpView); startActivityWithDelay(); } @Inject SplashPresenter(SchedulerProvider schedulerProvider, CompositeDisposable compositeDisposable, DataManager dataManager); @Override void onAttach(V mvpView); }### Answer: @Test public void decideNextActivity_UserNotLoggedIn_OpenLoginActivity() throws InterruptedException { when(dataManager.getCurrentUserLoggedInMode()). thenReturn(DataManager.LoggedInMode.LOGGED_IN_MODE_LOGGED_OUT.getType()); splashPresenter.onAttach(splashMvpView); Thread.sleep(2000); verify(splashMvpView).openLoginActivity(); } @Test public void decideNextActivity_UserLoggedIn_OpenMainActivity() throws InterruptedException { when(dataManager.getCurrentUserLoggedInMode()). thenReturn(DataManager.LoggedInMode.LOGGED_IN_MODE_LOGGED_SERVER.getType()); splashPresenter.onAttach(splashMvpView); Thread.sleep(2500); verify(splashMvpView).openMainActivity(); }
### Question: CommonUtils { public static Long getNegativeLong(int number) { return ( - (long) number); } private CommonUtils(); static ProgressDialog showLoadingDialog(Context context); static boolean isEmailValid(String email); static String getTimeStamp(); static Long getNegativeLong(int number); }### Answer: @Test public void getNegativeLong_NegativeInt_PositiveLong() { assertThat(CommonUtils.getNegativeLong(-2), is(2l)); } @Test public void getNegativeLong_PositiveInt_NegativeLong() { assertThat(CommonUtils.getNegativeLong(2), is(-2l)); }
### Question: CommonUtils { public static boolean isEmailValid(String email) { Pattern pattern; Matcher matcher; final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; pattern = Pattern.compile(EMAIL_PATTERN); matcher = pattern.matcher(email); return matcher.matches(); } private CommonUtils(); static ProgressDialog showLoadingDialog(Context context); static boolean isEmailValid(String email); static String getTimeStamp(); static Long getNegativeLong(int number); }### Answer: @Test public void isEmailValid_NoAtTheRate_False() { assertFalse(CommonUtils.isEmailValid(NO_AT_THE_RATE)); } @Test public void isEmailValid_NoDomain_False() { assertFalse(CommonUtils.isEmailValid(NO_DOMAIN)); } @Test public void isEmailValid_NoAtTheRateAndDomain_False() { assertFalse(CommonUtils.isEmailValid(NO_AT_THE_RATE_AND_DOMAIN)); } @Test public void isEmailValid_UnAllowedSpecialCharacters1_False() { assertFalse(CommonUtils.isEmailValid(UN_ALLOWED_SPECIAL_CHARACTERS1)); } @Test public void isEmailValid_UnAllowedSpecialCharacters2_False() { assertFalse(CommonUtils.isEmailValid(UN_ALLOWED_SPECIAL_CHARACTERS2)); } @Test public void isEmailValid_UnAllowedSpecialCharacters3_False() { assertFalse(CommonUtils.isEmailValid(UN_ALLOWED_SPECIAL_CHARACTERS3)); } @Test public void isEmailValid_CorrectInput_True() { assertTrue(CommonUtils.isEmailValid(CORRECT_INPUT)); }
### Question: AardvarkHelpMode extends GosuMode { static void printHelp(PrintWriter out) { out.println("Usage:"); out.println(" vark [-f FILE] [options] [targets...]"); out.println(); out.println("Options:"); IArgKeyList keys = Launch.factory().createArgKeyList(); for (IArgKey key : AardvarkOptions.getArgKeys()) { keys.register(key); } keys.printHelp(out); } @Override int getPriority(); @Override boolean accept(); @Override int run(); }### Answer: @Test public void printHelp() { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); AardvarkHelpMode.printHelp(out); String eol = System.getProperty("line.separator"); assertEquals( "Usage:" + eol + " vark [-f FILE] [options] [targets...]" + eol + "" + eol + "Options:" + eol + " -f, -file FILE load a file-based Gosu source" + eol + " -url URL load a url-based Gosu source" + eol + " -classpath PATH additional elements for the classpath, separated by commas" + eol + " -p, -projecthelp show project help (e.g. targets)" + eol + " -logger LOGGERFQN class name for a logger to use" + eol + " -q, -quiet run with logging in quiet mode" + eol + " -v, -verbose run with logging in verbose mode" + eol + " -d, -debug run with logging in debug mode" + eol + " -g, -graphical starts the graphical Aardvark editor" + eol + " -verify verifies the Gosu source" + eol + " -version displays the version of Aardvark" + eol + " -h, -help displays this command-line help" + eol + "", writer.toString()); }
### Question: GlusterWatchService implements WatchService { public WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds) { if (!running) { throw new ClosedWatchServiceException(); } for (GlusterWatchKey k : paths) { if (k.getPath().equals(path)) { k.setKinds(kinds); return k; } } GlusterWatchKey key = new GlusterWatchKey(path, kinds); paths.add(key); return key; } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer: @Test(expected = ClosedWatchServiceException.class) public void testRegisterPath_whenNotRunning() { watchService.setRunning(false); GlusterPath mockPath = mock(GlusterPath.class); watchService.registerPath(mockPath); } @Test public void testRegisterPath() { watchService.setRunning(true); GlusterPath mockPath = mock(GlusterPath.class); WatchEvent.Kind mockKind = mock(WatchEvent.Kind.class); watchService.registerPath(mockPath, mockKind); GlusterWatchKey event = watchService.getPaths().iterator().next(); assertEquals(mockPath, event.getPath()); assertEquals(mockKind, event.getKinds()[0]); } @Test public void testRegisterPath_whenPathExists() { watchService.setRunning(true); GlusterPath mockPath = mock(GlusterPath.class); GlusterWatchKey keyFix = new GlusterWatchKey(mockPath, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_MODIFY}); watchService.getPaths().add(keyFix); watchService.registerPath(mockPath, StandardWatchEventKinds.ENTRY_CREATE); GlusterWatchKey event = watchService.getPaths().iterator().next(); assertEquals(mockPath, event.getPath()); assertEquals(StandardWatchEventKinds.ENTRY_CREATE, event.getKinds()[0]); }
### Question: GlusterFileSystem extends FileSystem { @Override public boolean isOpen() { return volptr > 0; } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testIsOpen_whenClosed() { fileSystem.setVolptr(-1); assertEquals(false, fileSystem.isOpen()); } @Test public void testIsOpen_whenOpen() { assertEquals(true, fileSystem.isOpen()); }
### Question: GlusterFileSystem extends FileSystem { @Override public boolean isReadOnly() { return false; } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testIsReadOnly() { assertFalse(fileSystem.isReadOnly()); }
### Question: GlusterFileSystem extends FileSystem { @Override public String getSeparator() { return SEPARATOR; } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testGetSeparator() { assertEquals("/", fileSystem.getSeparator()); }
### Question: GlusterFileSystem extends FileSystem { @Override public Iterable<Path> getRootDirectories() { GlusterPath root = new GlusterPath(this, "/"); List<Path> list = new ArrayList<Path>(1); list.add(root); return Collections.unmodifiableList(list); } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testGetRootDirectories() { Iterable<Path> pi = fileSystem.getRootDirectories(); Iterator<Path> iterator = pi.iterator(); Path path = new GlusterPath(fileSystem, "/"); assertEquals(path, iterator.next()); assertFalse(iterator.hasNext()); }
### Question: GlusterFileSystem extends FileSystem { @Override public Iterable<FileStore> getFileStores() { GlusterFileStore store = new GlusterFileStore(this); List<FileStore> stores = new ArrayList<FileStore>(1); stores.add(store); return Collections.unmodifiableList(stores); } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testGetFileStores() { GlusterFileStore correctStore = new GlusterFileStore(fileSystem); Iterable<FileStore> stores = fileSystem.getFileStores(); Iterator<FileStore> iterator = stores.iterator(); assertEquals(correctStore, iterator.next()); assertFalse(iterator.hasNext()); }
### Question: GlusterFileSystem extends FileSystem { @Override public Path getPath(String s, String... strings) { boolean absolute = s.startsWith("/"); if (absolute) { s = s.substring(1); } String[] parts; if (null != strings && strings.length > 0) { parts = new String[1 + strings.length]; parts[0] = s; System.arraycopy(strings, 0, parts, 1, strings.length); } else { parts = new String[]{s}; } return new GlusterPath(this, parts, absolute); } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testGetPath() { Path correctPath = new GlusterPath(fileSystem, "/foo/bar/baz"); Path returnedPath = fileSystem.getPath("/foo", "bar", "baz"); assertEquals(correctPath, returnedPath); }
### Question: GlusterFileSystem extends FileSystem { public String toString() { return provider.getScheme() + ": } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test public void testToString() { doReturn("gluster").when(mockFileSystemProvider).getScheme(); String string = "gluster: assertEquals(string, fileSystem.toString()); verify(mockFileSystemProvider).getScheme(); }
### Question: GlusterFileSystem extends FileSystem { @Override public PathMatcher getPathMatcher(String s) { if (!s.contains(":")) { throw new IllegalArgumentException("PathMatcher requires input syntax:expression"); } String[] parts = s.split(":", 2); Pattern pattern; if ("glob".equals(parts[0])) { pattern = GlobPattern.compile(parts[1]); } else if ("regex".equals(parts[0])) { pattern = Pattern.compile(parts[1]); } else { throw new UnsupportedOperationException("Unknown PathMatcher syntax: " + parts[0]); } return new GlusterPathMatcher(pattern); } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testGetPathMatcher_whenBadInput() { fileSystem.getPathMatcher("foo"); } @Test(expected = UnsupportedOperationException.class) public void testGetPathMatcher_whenBadSyntax() { fileSystem.getPathMatcher("foo:bar"); } @Test(expected = PatternSyntaxException.class) public void testGetPathMatcher_whenBadExpression() { fileSystem.getPathMatcher("regex:["); }
### Question: GlusterWatchService implements WatchService { @Override public WatchKey poll() { if (!running) { throw new ClosedWatchServiceException(); } WatchKey pending = popPending(); if (null != pending) { return pending; } for (GlusterWatchKey k : paths) { if (k.isValid() && k.isReady() && k.update()) { pendingPaths.add(k); } } return popPending(); } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer: @Test public void testPollTimeout() throws InterruptedException { long timeout = 150L; TimeUnit unit = TimeUnit.MILLISECONDS; WatchKey mockKey = mock(WatchKey.class); PowerMockito.when(watchService.poll()).thenReturn(null).thenReturn(mockKey); PowerMockito.spy(Thread.class); PowerMockito.doThrow(new InterruptedException()).when(Thread.class); Thread.sleep(GlusterWatchService.PERIOD); WatchKey key = watchService.poll(timeout, unit); assertEquals(mockKey, key); Mockito.verify(watchService, Mockito.times(2)).poll(); PowerMockito.verifyStatic(Mockito.times(1)); Thread.sleep(GlusterWatchService.PERIOD); } @Test(expected = ClosedWatchServiceException.class) public void testPoll_whenNotRunning() { watchService.setRunning(false); watchService.poll(); } @Test public void testPoll_whenPending() { watchService.setRunning(true); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPendingPaths().add(mockKey); WatchKey key = watchService.poll(); assertEquals(mockKey, key); } @Test public void testPoll_whenReadyAndNoEvent() { watchService.setRunning(true); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPaths().add(mockKey); doReturn(true).when(mockKey).isValid(); doReturn(true).when(mockKey).isReady(); doReturn(false).when(mockKey).update(); WatchKey key = watchService.poll(); assertEquals(null, key); Mockito.verify(mockKey).isValid(); Mockito.verify(mockKey).isReady(); Mockito.verify(mockKey).update(); }
### Question: GlusterDirectoryIterator implements Iterator<GlusterPath> { @Override public GlusterPath next() { if (nextPath == null) { throw new NoSuchElementException("No more entries"); } return nextPath; } @Override boolean hasNext(); @Override GlusterPath next(); @Override void remove(); }### Answer: @Test(expected = NoSuchElementException.class) public void testNext_whenNoNext() { iterator.next(); } @Test public void testNext() { iterator.setNextPath(fakeResultPath); GlusterPath path = iterator.next(); assertEquals(fakeResultPath, path); }
### Question: GlusterDirectoryIterator implements Iterator<GlusterPath> { @Override public void remove() { throw new UnsupportedOperationException(); } @Override boolean hasNext(); @Override GlusterPath next(); @Override void remove(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testRemove() { iterator.remove(); }
### Question: GlusterPath implements Path { @Override public boolean isAbsolute() { return absolute; } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testIsAbsolute() { Path p = new GlusterPath(mockFileSystem, "foo/bar"); assertFalse(p.isAbsolute()); p = new GlusterPath(mockFileSystem, "/foo/bar"); assertTrue(p.isAbsolute()); }
### Question: GlusterPath implements Path { @Override public Path getRoot() { if (absolute) { return fileSystem.getRootDirectories().iterator().next(); } else { return null; } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testGetRoot_absolute() { List<Path> paths = new LinkedList<Path>(); GlusterPath root = new GlusterPath(mockFileSystem, "/"); paths.add(root); doReturn(paths).when(mockFileSystem).getRootDirectories(); Path p = new GlusterPath(mockFileSystem, "/foo/bar"); Path returned = p.getRoot(); verify(mockFileSystem).getRootDirectories(); assertEquals(root, returned); } @Test public void testGetRoot_relative() { Path p = new GlusterPath(mockFileSystem, "foo/bar"); Path returned = p.getRoot(); verify(mockFileSystem, times(0)).getRootDirectories(); assertEquals(null, returned); }
### Question: GlusterPath implements Path { @Override public URI toUri() { try { GlusterFileSystem fs = getFileSystem(); String authority = fs.getHost() + ":" + fs.getVolname(); return new URI(fs.provider().getScheme(), authority, toString(), null, null); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testToUri() throws URISyntaxException { GlusterFileSystemProvider mockProvider = mock(GlusterFileSystemProvider.class); String scheme = GlusterFileSystemProvider.GLUSTER; doReturn(scheme).when(mockProvider).getScheme(); doReturn(mockProvider).when(mockFileSystem).provider(); String host = "localhost"; doReturn(host).when(mockFileSystem).getHost(); String volname = "foo"; doReturn(volname).when(mockFileSystem).getVolname(); String path = "/foo/bar"; GlusterPath p = spy(new GlusterPath(mockFileSystem, path)); doReturn(mockFileSystem).when(p).getFileSystem(); doReturn(path).when(p).toString(); String authority = host + ":" + volname; URI expected = new URI(scheme, authority, path, null, null); assertEquals(expected, p.toUri()); }
### Question: GlusterPath implements Path { @Override public Path getFileName() { if (parts.length == 0 || parts[0].isEmpty()) { return null; } else { return new GlusterPath(fileSystem, parts[parts.length - 1]); } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testGetFileName() { Path p = new GlusterPath(mockFileSystem, "/"); assertEquals(null, p.getFileName()); p = new GlusterPath(mockFileSystem, "/bar"); assertEquals(new GlusterPath(mockFileSystem, "bar"), p.getFileName()); p = new GlusterPath(mockFileSystem, "foo/bar"); assertEquals(new GlusterPath(mockFileSystem, "bar"), p.getFileName()); }
### Question: GlusterPath implements Path { @Override public Path getParent() { if (parts.length <= 1 || parts[0].isEmpty()) { if (absolute) { return getRoot(); } else { return null; } } else { return new GlusterPath(fileSystem, Arrays.copyOfRange(parts, 0, parts.length - 1), absolute); } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testGetParent() { List<Path> roots = new LinkedList<Path>(); roots.add(mockGlusterPath); doReturn(roots).when(mockFileSystem).getRootDirectories(); Path p = new GlusterPath(mockFileSystem, "/"); assertEquals(mockGlusterPath, p.getParent()); p = new GlusterPath(mockFileSystem, "/bar"); assertEquals(mockGlusterPath, p.getParent()); p = new GlusterPath(mockFileSystem, "/bar/baz"); assertEquals(new GlusterPath(mockFileSystem, "/bar"), p.getParent()); p = new GlusterPath(mockFileSystem, "foo/bar"); assertEquals(new GlusterPath(mockFileSystem, "foo"), p.getParent()); p = new GlusterPath(mockFileSystem, "bar"); assertEquals(null, p.getParent()); verify(mockFileSystem, times(2)).getRootDirectories(); }
### Question: GlusterPath implements Path { @Override public int getNameCount() { if (parts.length <= 1 && parts[0].isEmpty()) { if (absolute) { return 0; } else { throw new IllegalStateException("Only the root path should have one empty part"); } } else { return parts.length; } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testGetNameCount() { Path p = new GlusterPath(mockFileSystem, "/"); assertEquals(0, p.getNameCount()); p = new GlusterPath(mockFileSystem, "/bar"); assertEquals(1, p.getNameCount()); p = new GlusterPath(mockFileSystem, "/foo/bar"); assertEquals(2, p.getNameCount()); p = new GlusterPath(mockFileSystem, "foo/bar"); assertEquals(2, p.getNameCount()); }
### Question: GlusterWatchService implements WatchService { @Override public WatchKey take() { while (running) { WatchKey key = poll(); if (key != null) { return key; } try { Thread.sleep(PERIOD); } catch (InterruptedException e) { } } throw new ClosedWatchServiceException(); } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer: @Test(expected = ClosedWatchServiceException.class) public void testTake_whenClosed() { watchService.setRunning(false); watchService.take(); } @Test public void testTake() throws Exception { WatchKey mockKey = mock(WatchKey.class); doReturn(null).doReturn(mockKey).when(watchService).poll(); PowerMockito.spy(Thread.class); PowerMockito.doThrow(new InterruptedException()).when(Thread.class); Thread.sleep(GlusterWatchService.PERIOD); WatchKey key = watchService.take(); assertEquals(mockKey, key); Mockito.verify(watchService, Mockito.times(2)).poll(); PowerMockito.verifyStatic(); Thread.sleep(GlusterWatchService.PERIOD); }
### Question: GlusterPath implements Path { @Override public Path getName(int i) { if (i < 0 || i >= parts.length || (0 == i && parts.length <= 1 && parts[0].isEmpty())) { throw new IllegalArgumentException("invalid name index"); } return new GlusterPath(fileSystem, Arrays.copyOfRange(parts, 0, i + 1), absolute); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testGetName_noName() { Path p = new GlusterPath(mockFileSystem, "/"); p.getName(0); } @Test(expected = IllegalArgumentException.class) public void testGetName_negative() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.getName(-1); } @Test(expected = IllegalArgumentException.class) public void testGetName_excessive() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.getName(4); } @Test public void testGetName() { Path p = new GlusterPath(mockFileSystem, "/foo/bar/baz"); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo"}, true), p.getName(0)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo", "bar"}, true), p.getName(1)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo", "bar", "baz"}, true), p.getName(2)); p = new GlusterPath(mockFileSystem, "foo/bar/baz"); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo"}, false), p.getName(0)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo", "bar"}, false), p.getName(1)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo", "bar", "baz"}, false), p.getName(2)); } @Test(expected = IllegalArgumentException.class) public void testSubpath_noName() { Path p = new GlusterPath(mockFileSystem, "/"); p.getName(0); }
### Question: GlusterPath implements Path { @Override public Path subpath(int i, int i2) { if ((0 == i && parts.length <= 1 && parts[0].isEmpty()) || i < 0 || i2 < 0 || i >= parts.length || i2 > parts.length || i > i2) { throw new IllegalArgumentException("invalid indices"); } return new GlusterPath(fileSystem, Arrays.copyOfRange(parts, i, i2), absolute); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testSubpath_negativeStart() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.subpath(-1, 0); } @Test(expected = IllegalArgumentException.class) public void testSubpath_negativeEnd() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.subpath(0, -1); } @Test(expected = IllegalArgumentException.class) public void testSubpath_excessiveStart() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.subpath(4, 5); } @Test(expected = IllegalArgumentException.class) public void testSubpath_excessiveEnd() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.subpath(0, 4); } @Test(expected = IllegalArgumentException.class) public void testSubpath_Inverted() { Path p = new GlusterPath(mockFileSystem, "/foo"); p.subpath(2, 1); } @Test public void testSubpath() { Path p = new GlusterPath(mockFileSystem, "/foo/bar/baz"); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo"}, true), p.subpath(0, 1)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"bar"}, true), p.subpath(1, 2)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"bar", "baz"}, true), p.subpath(1, 3)); p = new GlusterPath(mockFileSystem, "foo/bar/baz"); assertEquals(new GlusterPath(mockFileSystem, new String[]{"foo"}, false), p.subpath(0, 1)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"bar"}, false), p.subpath(1, 2)); assertEquals(new GlusterPath(mockFileSystem, new String[]{"bar", "baz"}, false), p.subpath(1, 3)); }
### Question: GlusterPath implements Path { @Override public boolean startsWith(Path path) { GlusterPath otherPath = (GlusterPath) path; if (this.equals(otherPath)) { return true; } if (otherPath.getParts().length > parts.length) { return false; } if (absolute && otherPath.isAbsolute() && otherPath.getParts()[0].isEmpty()) { return true; } String[] thisPrefix = Arrays.copyOfRange(parts, 0, otherPath.getParts().length); return ((absolute == otherPath.isAbsolute()) && (Arrays.equals(thisPrefix, otherPath.getParts()))); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testStartsWith() { Path p1 = new GlusterPath(mockFileSystem, "/"); assertTrue(p1.startsWith(p1)); Path p2 = new GlusterPath(mockFileSystem, "/foo"); assertFalse(p1.startsWith(p2)); assertTrue(p2.startsWith(p1)); p1 = new GlusterPath(mockFileSystem, "/bar"); assertFalse(p1.startsWith(p2)); } @Test public void testStartsWith_String() { Path p1 = new GlusterPath(mockFileSystem, "/"); assertTrue(p1.startsWith("/")); Path p2 = new GlusterPath(mockFileSystem, "/foo"); assertFalse(p1.startsWith("/foo")); assertTrue(p2.startsWith("/")); p1 = new GlusterPath(mockFileSystem, "/bar"); assertFalse(p1.startsWith("/foo")); }
### Question: GlusterPath implements Path { @Override public boolean endsWith(Path path) { GlusterPath otherPath = (GlusterPath) path; if (this.equals(otherPath)) { return true; } if (otherPath.getParts().length > parts.length) { return false; } if (absolute && otherPath.isAbsolute() && otherPath.getParts()[0].isEmpty()) { return true; } String[] thisSuffix = Arrays.copyOfRange(parts, parts.length - otherPath.getParts().length, parts.length); return ((!otherPath.isAbsolute()) && (Arrays.equals(thisSuffix, otherPath.getParts()))); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testEndsWith() { Path p1 = new GlusterPath(mockFileSystem, "/"); assertTrue(p1.endsWith(p1)); Path p2 = new GlusterPath(mockFileSystem, "/foo"); assertFalse(p1.endsWith(p2)); p1 = new GlusterPath(mockFileSystem, "/foo"); assertTrue(p1.endsWith(p2)); p2 = new GlusterPath(mockFileSystem, "foo"); assertTrue(p1.endsWith(p2)); p1 = new GlusterPath(mockFileSystem, "foo/bar"); p2 = new GlusterPath(mockFileSystem, "bar"); assertTrue(p1.endsWith(p2)); p2 = new GlusterPath(mockFileSystem, "/bar"); assertFalse(p1.endsWith(p2)); }
### Question: GlusterPath implements Path { @Override public Path normalize() { List<String> newParts = new LinkedList<String>(); for (String part : parts) { if (part.equals("..")) { newParts.remove(newParts.size() - 1); } else if (!part.equals(".") && !part.isEmpty()) { newParts.add(part); } } return new GlusterPath(fileSystem, newParts.toArray(new String[]{}), absolute); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testNormalize() { Path p = new GlusterPath(mockFileSystem, "foo assertEquals(new GlusterPath(mockFileSystem, "foo/bar"), p.normalize()); p = new GlusterPath(mockFileSystem, "foo/./bar"); assertEquals(new GlusterPath(mockFileSystem, "foo/bar"), p.normalize()); p = new GlusterPath(mockFileSystem, "foo/././bar"); assertEquals(new GlusterPath(mockFileSystem, "foo/bar"), p.normalize()); p = new GlusterPath(mockFileSystem, "foo/baz/../bar"); assertEquals(new GlusterPath(mockFileSystem, "foo/bar"), p.normalize()); p = new GlusterPath(mockFileSystem, "foo/baz/../baz/../bar"); assertEquals(new GlusterPath(mockFileSystem, "foo/bar"), p.normalize()); }
### Question: GlusterPath implements Path { @Override public Path resolve(Path path) { GlusterPath otherPath = (GlusterPath) path; if (!fileSystem.equals(otherPath.getFileSystem())) { throw new IllegalArgumentException("Can not resolve other path because it's on a different filesystem"); } if (otherPath.isAbsolute() || (absolute && parts.length == 1 && parts[0].isEmpty())) { return new GlusterPath(fileSystem, otherPath.getParts(), true); } if (otherPath.getParts().length == 1 && otherPath.getParts()[0].isEmpty()) { return this; } String[] newParts = Arrays.copyOf(parts, parts.length + otherPath.getParts().length); System.arraycopy(otherPath.getParts(), 0, newParts, parts.length, otherPath.getParts().length); return new GlusterPath(fileSystem, newParts, absolute); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testResolve() { Path path = new GlusterPath(mockFileSystem, "/"); Path otherPath = new GlusterPath(mockFileSystem, "/bar"); assertEquals(otherPath, path.resolve(otherPath)); otherPath = new GlusterPath(mockFileSystem, "bar"); assertEquals(new GlusterPath(mockFileSystem, "/bar"), path.resolve(otherPath)); otherPath = new GlusterPath(mockFileSystem, ""); assertEquals(path, path.resolve(otherPath)); } @Test public void testResolve_string() { Path path = new GlusterPath(mockFileSystem, "/"); assertEquals(new GlusterPath(mockFileSystem, "/bar"), path.resolve("/bar")); assertEquals(new GlusterPath(mockFileSystem, "/bar"), path.resolve("bar")); assertEquals(path, path.resolve("")); path = new GlusterPath(mockFileSystem, "/foo"); assertEquals(new GlusterPath(mockFileSystem, "/foo/bar"), path.resolve("bar")); }
### Question: GlusterPath implements Path { @Override public Path resolveSibling(Path path) { return getParent().resolve(path); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testResolveSibling() { Path p = new GlusterPath(mockFileSystem, "foo/bar"); Path other = new GlusterPath(mockFileSystem, "baz"); Path finalPath = p.resolveSibling(other); assertEquals(new GlusterPath(mockFileSystem, "foo/baz"), finalPath); } @Test public void testResolveSibling_string() { Path p = new GlusterPath(mockFileSystem, "foo/bar"); Path finalPath = p.resolveSibling("baz"); assertEquals(new GlusterPath(mockFileSystem, "foo/baz"), finalPath); }
### Question: GlusterWatchService implements WatchService { long timeoutToMillis(long timeout, TimeUnit unit) { switch (unit) { case DAYS: return (timeout * MILLIS_PER_DAY); case HOURS: return (timeout * MILLIS_PER_HOUR); case MINUTES: return (timeout * MILLIS_PER_MINUTE); case SECONDS: return (timeout * MILLIS_PER_SECOND); case MILLISECONDS: return timeout; default: return -1; } } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer: @Test public void testTimeoutToMillis() { long time = 12345L; Assert.assertEquals(-1, watchService.timeoutToMillis(time, TimeUnit.NANOSECONDS)); Assert.assertEquals(-1, watchService.timeoutToMillis(time, TimeUnit.MICROSECONDS)); Assert.assertEquals(time, watchService.timeoutToMillis(time, TimeUnit.MILLISECONDS)); Assert.assertEquals(time * GlusterWatchService.MILLIS_PER_SECOND, watchService.timeoutToMillis(time, TimeUnit.SECONDS)); Assert.assertEquals(time * GlusterWatchService.MILLIS_PER_MINUTE, watchService.timeoutToMillis(time, TimeUnit.MINUTES)); Assert.assertEquals(time * GlusterWatchService.MILLIS_PER_HOUR, watchService.timeoutToMillis(time, TimeUnit.HOURS)); Assert.assertEquals(time * GlusterWatchService.MILLIS_PER_DAY, watchService.timeoutToMillis(time, TimeUnit.DAYS)); }
### Question: GlusterPath implements Path { @Override public Path toAbsolutePath() { if (!absolute) { throw new UnsupportedOperationException(); } else { return this; } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testToAbsolutePath_whenRelative() { Path p = new GlusterPath(mockFileSystem, "foo"); p.toAbsolutePath(); } @Test public void testToAbsolutePath() { Path p = new GlusterPath(mockFileSystem, "/foo"); assertEquals(p, p.toAbsolutePath()); }
### Question: GlusterPath implements Path { @Override public Iterator<Path> iterator() { List<Path> list = new ArrayList<Path>(parts.length); if (parts.length >= 1 && !parts[0].isEmpty()) { for (String p : parts) { list.add(new GlusterPath(fileSystem, p)); } } return Collections.unmodifiableList(list).iterator(); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testIterator() { Path p = new GlusterPath(mockFileSystem, "/foo/bar"); Iterator<Path> it = p.iterator(); assertEquals(new GlusterPath(mockFileSystem, "foo"), it.next()); assertEquals(new GlusterPath(mockFileSystem, "bar"), it.next()); p = new GlusterPath(mockFileSystem, "/"); it = p.iterator(); assertFalse(it.hasNext()); }
### Question: GlusterPath implements Path { @Override public int compareTo(Path path) { if (!getClass().equals(path.getClass())) { throw new ClassCastException(); } if (!fileSystem.equals(path.getFileSystem())) { throw new IllegalArgumentException("Can not compare other path because it's on a different filesystem"); } GlusterPath other = (GlusterPath) path; String[] otherParts = other.getParts(); for (int i = 0; i < Math.min(parts.length, otherParts.length); i++) { int c = parts[i].compareTo(otherParts[i]); if (c != 0) { return c; } } return parts.length - otherParts.length; } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test(expected = ClassCastException.class) public void testCompareTo_differentProvider() { Path path = new GlusterPath(mockFileSystem, ""); Path zipfile = Paths.get("/codeSamples/zipfs/zipfstest.zip"); path.compareTo(zipfile); } @Test public void testCompareTo() { Path p = new GlusterPath(mockFileSystem, "/foo"); Path other = new GlusterPath(mockFileSystem, "/bar"); assertTrue(p.compareTo(other) > 0); p = new GlusterPath(mockFileSystem, "/bar"); other = new GlusterPath(mockFileSystem, "/foo"); assertTrue(p.compareTo(other) < 0); p = new GlusterPath(mockFileSystem, "/foo"); other = new GlusterPath(mockFileSystem, "/foo"); assertEquals(0, p.compareTo(other)); p = new GlusterPath(mockFileSystem, "/"); other = new GlusterPath(mockFileSystem, "/foo"); assertTrue(p.compareTo(other) < 0); p = new GlusterPath(mockFileSystem, "/foo"); other = new GlusterPath(mockFileSystem, "/"); assertTrue(p.compareTo(other) > 0); }
### Question: GlusterPath implements Path { public String toString() { return getString(); } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testToString_whenPathString() { String pathString = "/bar/baz"; Path p = new GlusterPath(mockFileSystem, pathString); String filesystemString = "gluster: doReturn(filesystemString).when(mockFileSystem).toString(); assertEquals(pathString, p.toString()); } @Test public void testToString_whenNoPathString() { Path p = new GlusterPath(mockFileSystem, new String[]{"a", "b"}, true); assertEquals("/a/b", p.toString()); }
### Question: GlusterDirectoryStream implements DirectoryStream<Path> { public void open(GlusterPath path) { dir = path; if (dirHandle == 0) { dirHandle = GLFS.glfs_opendir(path.getFileSystem().getVolptr(), path.getString()); } else { throw new IllegalStateException("Already open!"); } } @Override Iterator<Path> iterator(); @Override void close(); void open(GlusterPath path); }### Answer: @Test(expected = IllegalStateException.class) public void testOpenDirectory_whenAlreadyOpen() { stream.setDirHandle(1); stream.open(mockPath); } @Test public void testOpenDirectory() { String fakePath = "/foo/baz"; doReturn(mockFileSystem).when(mockPath).getFileSystem(); doReturn(fsHandle).when(mockFileSystem).getVolptr(); doReturn(fakePath).when(mockPath).getString(); mockStatic(GLFS.class); when(GLFS.glfs_opendir(fsHandle, fakePath)).thenReturn(dirHandle); stream.open(mockPath); assertEquals(dirHandle, stream.getDirHandle()); assertEquals(false, stream.isClosed()); assertEquals(mockPath, stream.getDir()); verify(mockPath).getFileSystem(); verify(mockFileSystem).getVolptr(); verify(mockPath).getString(); verifyStatic(); GLFS.glfs_opendir(fsHandle, fakePath); }
### Question: GlusterPath implements Path { public String getString() { if (null != pathString) { return pathString; } else { StringBuilder sb = new StringBuilder((absolute ? fileSystem.getSeparator() : "")); for (String p : parts) { sb.append(p).append(fileSystem.getSeparator()); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test public void testGetString_whenPathString() { String string = "/foo/bar"; GlusterPath path = new GlusterPath(mockFileSystem, string); path.setParts(new String[]{"a", "b"}); assertEquals(string, path.getString()); } @Test public void testGetString_whenNoPathString() { GlusterPath path = new GlusterPath(mockFileSystem, new String[]{"a", "b"}, false); assertEquals("a/b", path.getString()); }
### Question: GlusterPath implements Path { void guardRegisterWatchService(WatchService watchService) { Class<? extends WatchService> watchServiceClass = watchService.getClass(); if (!GlusterWatchService.class.equals(watchServiceClass)) { throw new UnsupportedOperationException("GlusterPaths can only be watched by GlusterWatchServices. WatchService given: " + watchServiceClass); } } GlusterPath(GlusterFileSystem fileSystem, String path); GlusterPath(GlusterFileSystem fileSystem, String[] parts, boolean absolute); @Override boolean isAbsolute(); @Override Path getRoot(); @Override Path getFileName(); @Override Path getParent(); @Override int getNameCount(); @Override Path getName(int i); @Override Path subpath(int i, int i2); @Override boolean startsWith(Path path); @Override boolean startsWith(String s); @Override boolean endsWith(Path path); @Override boolean endsWith(String s); @Override Path normalize(); @Override Path resolve(Path path); @Override Path resolve(String s); @Override Path resolveSibling(Path path); @Override Path resolveSibling(String s); @Override Path relativize(Path path); @Override URI toUri(); @Override Path toAbsolutePath(); @Override Path toRealPath(LinkOption... linkOptions); @Override File toFile(); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>[] kinds, WatchEvent.Modifier... modifiers); @Override WatchKey register(WatchService watchService, WatchEvent.Kind<?>... kinds); @Override Iterator<Path> iterator(); @Override int compareTo(Path path); String toString(); String getString(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGuardRegisterWatchService() { GlusterPath path = spy(new GlusterPath(mockFileSystem, new String[]{}, false)); WatchService mockWatchService = mock(WatchService.class); path.guardRegisterWatchService(mockWatchService); }
### Question: GlusterFileStore extends FileStore { @Override public String name() { return fileSystem.getVolname(); } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testName() { String volname = "testvol"; doReturn(volname).when(mockFileSystem).getVolname(); assertEquals(volname, fileStore.name()); }
### Question: GlusterFileStore extends FileStore { @Override public String type() { return GLUSTERFS; } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testType() { assertEquals("glusterfs", fileStore.type()); }
### Question: GlusterFileStore extends FileStore { @Override public boolean isReadOnly() { return false; } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testIsReadOnly() { assertFalse(fileStore.isReadOnly()); }
### Question: GlusterFileStore extends FileStore { @Override public long getTotalSpace() throws IOException { GlusterFileSystemProvider provider = (GlusterFileSystemProvider) fileSystem.provider(); return provider.getTotalSpace(fileSystem.getVolptr()); } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testGetTotalSpace() throws IOException { long volptr = 4321l; long space = 1234l; doReturn(volptr).when(mockFileSystem).getVolptr(); doReturn(space).when(mockProvider).getTotalSpace(volptr); long totalSpace = fileStore.getTotalSpace(); verify(mockProvider).getTotalSpace(volptr); verify(mockFileSystem).getVolptr(); assertEquals(space, totalSpace); }
### Question: GlusterFileStore extends FileStore { @Override public long getUsableSpace() throws IOException { GlusterFileSystemProvider provider = (GlusterFileSystemProvider) fileSystem.provider(); return provider.getUsableSpace(fileSystem.getVolptr()); } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testGetUsableSpace() throws IOException { long volptr = 4321l; long space = 1234l; doReturn(volptr).when(mockFileSystem).getVolptr(); doReturn(space).when(mockProvider).getUsableSpace(volptr); long usableSpace = fileStore.getUsableSpace(); verify(mockProvider).getUsableSpace(volptr); verify(mockFileSystem).getVolptr(); assertEquals(space, usableSpace); }
### Question: GlusterFileStore extends FileStore { @Override public long getUnallocatedSpace() throws IOException { GlusterFileSystemProvider provider = (GlusterFileSystemProvider) fileSystem.provider(); return provider.getUnallocatedSpace(fileSystem.getVolptr()); } @Override String name(); @Override String type(); @Override boolean isReadOnly(); @Override long getTotalSpace(); @Override long getUsableSpace(); @Override long getUnallocatedSpace(); @Override boolean supportsFileAttributeView(Class<? extends FileAttributeView> aClass); @Override boolean supportsFileAttributeView(String s); @Override V getFileStoreAttributeView(Class<V> vClass); @Override Object getAttribute(String s); static final String GLUSTERFS; }### Answer: @Test public void testGetUnallocatedSpace() throws IOException { long volptr = 4321l; long space = 1234l; doReturn(volptr).when(mockFileSystem).getVolptr(); doReturn(space).when(mockProvider).getUnallocatedSpace(volptr); long unallocatedSpace = fileStore.getUnallocatedSpace(); verify(mockProvider).getUnallocatedSpace(volptr); verify(mockFileSystem).getVolptr(); assertEquals(space, unallocatedSpace); }
### Question: GlusterDirectoryStream implements DirectoryStream<Path> { @Override public Iterator<Path> iterator() { if (null != iterator || closed) { throw new IllegalStateException("Already iterating!"); } GlusterDirectoryIterator iterator = new GlusterDirectoryIterator(); iterator.setStream(this); iterator.setFilter(filter); this.iterator = iterator; return iterator; } @Override Iterator<Path> iterator(); @Override void close(); void open(GlusterPath path); }### Answer: @Test(expected = IllegalStateException.class) public void testIterator_whenAlreadyIterating() { stream.setIterator(mockIterator); stream.iterator(); } @Test(expected = IllegalStateException.class) public void testIterator_whenClosed() { stream.setClosed(true); stream.iterator(); } @Test public void testIterator() throws Exception { stream.setClosed(false); stream.setFilter(mockFilter); whenNew(GlusterDirectoryIterator.class). withNoArguments().thenReturn(mockIterator); stream.setDirHandle(dirHandle); Iterator<Path> iterator = stream.iterator(); verifyNew(GlusterDirectoryIterator.class).withNoArguments(); assertEquals(mockIterator, iterator); assertEquals(mockIterator, stream.getIterator()); verify(mockIterator).setStream(stream); verify(mockIterator).setFilter(mockFilter); }
### Question: GlusterDirectoryStream implements DirectoryStream<Path> { @Override public void close() throws IOException { if (!closed) { GLFS.glfs_close(dirHandle); closed = true; } } @Override Iterator<Path> iterator(); @Override void close(); void open(GlusterPath path); }### Answer: @Test public void testClose_whenAlreadyClosed() throws IOException { stream.setDirHandle(dirHandle); stream.setClosed(true); mockStatic(GLFS.class); stream.close(); verifyStatic(Mockito.never()); GLFS.glfs_close(dirHandle); } @Test public void testClose() throws IOException { stream.setDirHandle(dirHandle); mockStatic(GLFS.class); Mockito.when(GLFS.glfs_close(dirHandle)).thenReturn(0); stream.close(); verifyStatic(); GLFS.glfs_close(dirHandle); }
### Question: GlusterFileChannel extends FileChannel { int parseOptions(Set<? extends OpenOption> options) { int opt = 0; for (OpenOption o : options) { if (!optionMap.containsKey(o)) { throw new UnsupportedOperationException("Option " + o + " is not supported at this time"); } opt |= optionMap.get(o); } return opt; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer: @Test public void testParseOptions() { Set<StandardOpenOption> options = new HashSet<StandardOpenOption>(); options.add(StandardOpenOption.APPEND); options.add(StandardOpenOption.WRITE); int result = channel.parseOptions(options); assertEquals(GlusterOpenOption.O_RDWR | GlusterOpenOption.O_APPEND, result); }
### Question: GlusterFileChannel extends FileChannel { @Override public int read(ByteBuffer byteBuffer) throws IOException { guardClosed(); byte[] bytes = byteBuffer.array(); long read = GLFS.glfs_read(fileptr, bytes, bytes.length, 0); if (read < 0) { throw new IOException(UtilJNI.strerror()); } position += read; byteBuffer.position((int)read); return (int) read; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer: @Test(expected = ClosedChannelException.class) public void testRead3Arg_whenClosed() throws IOException { channel.setClosed(true); ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = mockBuffer; buffers[1] = mockBuffer; int offset = 0; int length = 2; channel.read(buffers, offset, length); } @Test(expected = ClosedChannelException.class) public void testRead2Arg_whenClosed() throws IOException { long position = 5L; channel.setClosed(true); channel.read(mockBuffer, position); }
### Question: GlusterFileChannel extends FileChannel { long readHelper(ByteBuffer[] byteBuffers, int offset, int length) throws IOException { long totalRead = 0L; boolean endOfStream = false; for (int i = offset; i < length + offset && !endOfStream; i++) { byte[] bytes = byteBuffers[i].array(); int remaining; while ((remaining = byteBuffers[i].remaining()) > 0) { long read = GLFS.glfs_read(fileptr, bytes, remaining, 0); if (read < 0) { throw new IOException(UtilJNI.strerror()); } totalRead += read; byteBuffers[i].position((int) read); if (0 == read) { endOfStream = true; break; } } } if (endOfStream && totalRead == 0) { return -1; } return totalRead; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer: @Test public void testReadHelper() throws IOException { long fileptr = 1234L; channel.setFileptr(fileptr); ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = mockBuffer; buffers[1] = mockBuffer; int offset = 0; int length = 2; byte[] bytes = new byte[]{'h', 'e', 'l', 'l', 'o'}; doReturn(bytes).when(mockBuffer).array(); when(mockBuffer.remaining()).thenReturn(5, 0, 5, 0); mockStatic(GLFS.class); when(GLFS.glfs_read(fileptr, bytes, 5, 0)).thenReturn(5L); doReturn(mockBuffer).when(mockBuffer).position(5); channel.readHelper(buffers, offset, length); verify(mockBuffer, times(2)).position(5); verifyStatic(times(2)); GLFS.glfs_read(fileptr, bytes, 5, 0); verify(mockBuffer, times(4)).remaining(); verify(mockBuffer, times(2)).array(); } @Test(expected = IOException.class) public void testReadHelper_whenReadFails() throws IOException { long fileptr = 1234L; channel.setFileptr(fileptr); ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = mockBuffer; buffers[1] = mockBuffer; int offset = 0; int length = 2; byte[] bytes = new byte[]{'h', 'e', 'l', 'l', 'o'}; doReturn(bytes).when(mockBuffer).array(); when(mockBuffer.remaining()).thenReturn(5, 0, 5, 0); mockStatic(GLFS.class); when(GLFS.glfs_read(fileptr, bytes, 5, 0)).thenReturn(-1L); channel.readHelper(buffers, offset, length); }
### Question: GlusterFileChannel extends FileChannel { @Override public int write(ByteBuffer byteBuffer) throws IOException { guardClosed(); byte[] buf = byteBuffer.array(); int written = GLFS.glfs_write(fileptr, buf, buf.length, 0); if (written < 0) { throw new IOException(UtilJNI.strerror()); } position += written; byteBuffer.position(written); return written; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer: @Test(expected = ClosedChannelException.class) public void testWrite3Arg_whenClosedChannel() throws IOException { channel.setClosed(true); int length = 2; int offset = 0; ByteBuffer buffer1 = Mockito.mock(ByteBuffer.class); ByteBuffer buffer2 = Mockito.mock(ByteBuffer.class); ByteBuffer[] buffers = new ByteBuffer[]{buffer1, buffer2}; channel.write(buffers, offset, length); } @Test(expected = ClosedChannelException.class) public void testWrite2Arg_whenChannelClosed() throws IOException { channel.setClosed(true); ByteBuffer buffer = Mockito.mock(ByteBuffer.class); long position = 0L; channel.write(buffer, position); }