method2testcases
stringlengths 118
3.08k
|
---|
### Question:
EditMessageLiveLocation extends SendableInlineRequest<Message> { public static EditMessageLiveLocationBuilder forMessage(LocationMessage message) { Objects.requireNonNull(message, "message cannot be null"); return builder() .chatId(message.getChat().getChatId()) .messageId(message.getMessageId()); } @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 toEditLiveLocationRequest_output_same_as_forMessage() { EditMessageLiveLocation expected = EditMessageLiveLocation.forMessage(locationMessageMock).build(); EditMessageLiveLocation actual = locationMessageMock.toEditLiveLocationRequest().build(); assertEquals(expected, actual); } |
### 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 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:
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:
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:
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:
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:
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:
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:
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:
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:
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 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 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 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 { 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 { void guardClosed() throws ClosedChannelException { if (closed) { throw new ClosedChannelException(); } } @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 testGuardClosed_whenNotClosed() throws ClosedChannelException { channel.setClosed(false); channel.guardClosed(); }
@Test(expected = ClosedChannelException.class) public void testGuardClosed_whenClosed() throws ClosedChannelException { channel.setClosed(true); channel.guardClosed(); } |
### Question:
GlusterFileChannel extends FileChannel { @Override public long position() throws IOException { guardClosed(); return position; } @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 = IllegalArgumentException.class) public void testSetPosition_whenNegative() throws IOException { long position = -1l; channel.position(position); } |
### Question:
GlusterFileChannel extends FileChannel { @Override public void force(boolean b) throws IOException { guardClosed(); int fsync = GLFS.glfs_fsync(fileptr); if (0 != fsync) { throw new IOException("Unable to fsync"); } } @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 = IOException.class) public void testForce_whenFailing() throws IOException { long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_fsync(fileptr)).thenReturn(-1); channel.force(true); }
@Test public void testForce() throws IOException { doNothing().when(channel).guardClosed(); long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_fsync(fileptr)).thenReturn(0); channel.force(true); verify(channel).guardClosed(); verifyStatic(); GLFS.glfs_fsync(fileptr); } |
### Question:
GlusterWatchKey implements WatchKey { public boolean update() { DirectoryStream<Path> paths; try { paths = Files.newDirectoryStream(path); } catch (IOException e) { return false; } List<Path> files = new LinkedList<>(); boolean newEvents = false; for (Path f : paths) { newEvents |= processExistingFile(files, f); } for (Path f : events.keySet()) { newEvents |= checkDeleted(files, f); } return newEvents; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testUpdate_whenIOException() throws IOException { PowerMockito.mockStatic(Files.class); when(Files.newDirectoryStream(mockPath)).thenThrow(new IOException()); assertFalse(key.update()); PowerMockito.verifyStatic(); Files.newDirectoryStream(mockPath); } |
### Question:
GlusterWatchKey implements WatchKey { boolean processExistingFile(List<Path> files, Path f) { if (Files.isDirectory(f)) { return false; } files.add(f); long lastModified; try { lastModified = Files.getLastModifiedTime(f).toMillis(); } catch (IOException e) { return false; } GlusterWatchEvent event = events.get(f); if (null != event) { return checkModified(event, lastModified); } else { return checkCreated(f, lastModified); } } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testProcessExistingFile() { } |
### Question:
GlusterWatchService implements WatchService { @Override public void close() throws IOException { if (running) { running = false; for (GlusterWatchKey k : paths) { k.cancel(); } } } 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 testClose_whenNotRunning() throws IOException { watchService.setRunning(false); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPaths().add(mockKey); watchService.close(); Mockito.verify(mockKey, Mockito.never()).cancel(); }
@Test public void testClose() throws IOException { watchService.setRunning(true); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPaths().add(mockKey); watchService.close(); Mockito.verify(mockKey).cancel(); assertFalse(watchService.isRunning()); } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkDeleted(List<Path> files, Path f) { GlusterWatchEvent event = events.get(f); if (!files.contains(f) && !StandardWatchEventKinds.ENTRY_DELETE.name().equals(event.kind().name())) { event.setLastModified((new Date()).getTime()); event.setKind(StandardWatchEventKinds.ENTRY_DELETE); event.setCount(event.getCount() + 1); return true; } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckDeleted() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkCreated(Path f, long lastModified) { GlusterWatchEvent event = new GlusterWatchEvent(f.getFileName()); event.setLastModified(lastModified); events.put(f, event); return (lastModified > lastPolled); } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckCreated() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkModified(GlusterWatchEvent event, long lastModified) { if (lastModified > event.getLastModified()) { event.setLastModified(lastModified); if (event.kind().name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())) { event.setKind(StandardWatchEventKinds.ENTRY_CREATE); event.setCount(0); } else { event.setKind(StandardWatchEventKinds.ENTRY_MODIFY); event.setCount(event.getCount() + 1); } return true; } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckModified() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean kindsContains(WatchEvent.Kind kind) { for (WatchEvent.Kind k : kinds) { if (k.name().equals(kind.name())) { return true; } } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testKindsContains() { } |
### Question:
GlusterWatchKey implements WatchKey { @Override synchronized public List<WatchEvent<?>> pollEvents() { if (!ready) { return new LinkedList<>(); } ready = false; return findPendingEvents(); } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testPollEvents_whenNotReady() { key.setReady(false); assertTrue(key.pollEvents().isEmpty()); } |
### Question:
GlusterWatchKey implements WatchKey { LinkedList<WatchEvent<?>> findPendingEvents() { long maxModifiedTime = lastPolled; LinkedList<WatchEvent<?>> pendingEvents = new LinkedList<>(); for (Path p : events.keySet()) { long lastModified = queueEventIfPending(pendingEvents, p); maxModifiedTime = Math.max(maxModifiedTime, lastModified); } lastPolled = maxModifiedTime; return pendingEvents; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testFindPendingEvents() { } |
### Question:
GlusterWatchKey implements WatchKey { @Override synchronized public boolean reset() { if (!valid || ready) { return false; } else { ready = true; return true; } } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testReset_whenInvalid() { key.setValid(false); Assert.assertFalse(key.reset()); }
@Test public void testReset_whenReady() { WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{mock(WatchEvent.Kind.class)}; GlusterPath path = mock(GlusterPath.class); GlusterWatchKey key = new GlusterWatchKey(path, kinds); key.setValid(true); key.setReady(true); Assert.assertFalse(key.reset()); } |
### Question:
GlusterWatchKey implements WatchKey { @Override public void cancel() { valid = false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCancel() { WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{mock(WatchEvent.Kind.class)}; GlusterPath path = mock(GlusterPath.class); GlusterWatchKey key = new GlusterWatchKey(path, kinds); key.setValid(true); key.setReady(false); assertTrue(key.reset()); assertTrue(key.isReady()); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public String getScheme() { return GLUSTER; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testGetScheme() { GlusterFileSystemProvider p = new GlusterFileSystemProvider(); assertEquals("gluster", p.getScheme()); } |
### Question:
GlusterWatchService implements WatchService { WatchKey popPending() { Iterator<GlusterWatchKey> iterator = pendingPaths.iterator(); try { GlusterWatchKey key = iterator.next(); iterator.remove(); return key; } catch (NoSuchElementException e) { return null; } } 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 testPopPending_whenNonePending() { WatchKey key = watchService.popPending(); assertEquals(null, key); assertEquals(0, watchService.getPendingPaths().size()); }
@Test public void testPopPending() { GlusterPath mockPath = mock(GlusterPath.class); GlusterWatchKey keyFix = new GlusterWatchKey(mockPath, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE}); watchService.getPendingPaths().add(keyFix); WatchKey key = watchService.popPending(); assertEquals(keyFix, key); assertEquals(0, watchService.getPendingPaths().size()); } |
### Question:
GlusterFileSystem extends FileSystem { @Override public FileSystemProvider provider() { return provider; } @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 testProvider() { assertEquals(mockFileSystemProvider, fileSystem.provider()); } |
### Question:
GlusterFileSystem extends FileSystem { @Override public void close() throws IOException { if (isOpen()) { int fini = provider.close(volptr); if (0 != fini) { throw new IOException("Unable to close filesystem: " + volname); } volptr = -1; } } @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 = IOException.class) public void testClose_whenFailing() throws IOException { doReturn(11).when(mockFileSystemProvider).close(VOLPTR); fileSystem.close(); }
@Test public void testClose() throws IOException { doReturn(0).when(mockFileSystemProvider).close(VOLPTR); fileSystem.close(); verify(mockFileSystemProvider).close(VOLPTR); assertEquals(-1, fileSystem.getVolptr()); } |
### Question:
PhoneNumber { public static boolean isValid(PhoneNumber phoneNumber) { return phoneNumber != null && !EMPTY_PHONE_NUMBER.equals(phoneNumber) && !TextUtils .isEmpty(phoneNumber.getPhoneNumber()) && !TextUtils.isEmpty(phoneNumber .getCountryCode()) && !TextUtils.isEmpty(phoneNumber.getCountryIso()); } PhoneNumber(String phoneNumber, String countryIso, String countryCode); static PhoneNumber emptyPhone(); String getCountryCode(); String getPhoneNumber(); String getCountryIso(); static boolean isValid(PhoneNumber phoneNumber); static boolean isCountryValid(PhoneNumber phoneNumber); }### Answer:
@Test public void testIsValid_nullPhone() throws Exception { assertFalse(PhoneNumber.isValid(null)); }
@Test public void testIsValid_emptyMembers() throws Exception { PhoneNumber invalidPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, PhoneTestConstants .US_COUNTRY_CODE); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, "", PhoneTestConstants .US_COUNTRY_CODE); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, PhoneTestConstants.US_ISO2, ""); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); }
@Test public void testIsValid() throws Exception { final PhoneNumber validPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, PhoneTestConstants .US_ISO2, PhoneTestConstants.US_COUNTRY_CODE); assertTrue(PhoneNumber.isValid(validPhoneNumber)); } |
### Question:
PhoneNumber { public static boolean isCountryValid(PhoneNumber phoneNumber) { return phoneNumber != null && !EMPTY_PHONE_NUMBER.equals(phoneNumber) && !TextUtils .isEmpty(phoneNumber.getCountryCode()) && !TextUtils.isEmpty(phoneNumber .getCountryIso()); } PhoneNumber(String phoneNumber, String countryIso, String countryCode); static PhoneNumber emptyPhone(); String getCountryCode(); String getPhoneNumber(); String getCountryIso(); static boolean isValid(PhoneNumber phoneNumber); static boolean isCountryValid(PhoneNumber phoneNumber); }### Answer:
@Test public void testIsCountryValid_nullPhone() throws Exception { assertFalse(PhoneNumber.isCountryValid(null)); }
@Test public void testIsCountryValid_emptyMembers() throws Exception { PhoneNumber invalidPhoneNumber = new PhoneNumber("", "", PhoneTestConstants.US_COUNTRY_CODE); assertFalse(PhoneNumber.isCountryValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, ""); assertFalse(PhoneNumber.isCountryValid(invalidPhoneNumber)); }
@Test public void testIsCountryValid() throws Exception { final PhoneNumber validPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, PhoneTestConstants.US_COUNTRY_CODE); assertTrue(PhoneNumber.isCountryValid(validPhoneNumber)); } |
### Question:
SpacedEditText extends AppCompatEditText { @Override public void setText(CharSequence text, BufferType type) { originalText = new SpannableStringBuilder(text); final SpannableStringBuilder spacedOutString = getSpacedOutString(text); super.setText(spacedOutString, BufferType.SPANNABLE); } SpacedEditText(Context context); SpacedEditText(Context context, AttributeSet attrs); @Override void setText(CharSequence text, BufferType type); @Override void setSelection(int index); Editable getUnspacedText(); }### Answer:
@Test public void testSpacedEditText_setTextEmpty() throws Exception { spacedEditText.setText(""); testSpacing("", "", spacedEditText); }
@Test public void testSpacedEditText_setTextNonEmpty() throws Exception { spacedEditText.setText("123456"); testSpacing("1 2 3 4 5 6", "123456", spacedEditText); }
@Test public void testSpacedEditText_setTextWithOneCharacter() throws Exception { spacedEditText.setText("1"); testSpacing("1", "1", spacedEditText); }
@Test public void testSpacedEditText_setTextWithExistingSpaces() throws Exception { spacedEditText.setText("1 2 3"); testSpacing("1 2 3", "1 2 3", spacedEditText); } |
### Question:
PhoneVerificationActivity extends AppCompatBase { public static Intent createIntent(Context context, FlowParameters flowParams, String phone) { return BaseHelper.createBaseIntent(context, PhoneVerificationActivity.class, flowParams) .putExtra(ExtraConstants.EXTRA_PHONE, phone); } static Intent createIntent(Context context, FlowParameters flowParams, String phone); @Override void onBackPressed(); void submitConfirmationCode(String confirmationCode); }### Answer:
@Test public void testPhoneNumberFromSmartlock_prePopulatesPhoneNumberInBundle() { Intent startIntent = PhoneVerificationActivity.createIntent(RuntimeEnvironment .application, TestHelper.getFlowParameters(Collections.singletonList(AuthUI .PHONE_VERIFICATION_PROVIDER)), YE_RAW_PHONE); mActivity = Robolectric.buildActivity(PhoneVerificationActivity.class).withIntent (startIntent).create(new Bundle()).start().visible().get(); VerifyPhoneNumberFragment verifyPhoneNumberFragment = (VerifyPhoneNumberFragment) mActivity.getSupportFragmentManager().findFragmentByTag(VerifyPhoneNumberFragment .TAG); assertNotNull(verifyPhoneNumberFragment); mPhoneEditText = (EditText) mActivity.findViewById(R.id.phone_number); mCountryListSpinner = (CountryListSpinner) mActivity.findViewById(R.id.country_list); assertEquals(PHONE_NO_COUNTRY_CODE, mPhoneEditText.getText().toString()); assertEquals(YE_COUNTRY_CODE, String.valueOf(((CountryInfo) mCountryListSpinner.getTag()) .countryCode)); } |
### Question:
PhoneVerificationActivity extends AppCompatBase { @VisibleForTesting(otherwise = VisibleForTesting.NONE) protected AlertDialog getAlertDialog() { return mAlertDialog; } static Intent createIntent(Context context, FlowParameters flowParams, String phone); @Override void onBackPressed(); void submitConfirmationCode(String confirmationCode); }### Answer:
@Test @Config(shadows = {BaseHelperShadow.class, ActivityHelperShadow.class}) public void testSubmitCode_badCodeShowsAlertDialog() { reset(BaseHelperShadow.sPhoneAuthProvider); when(ActivityHelperShadow.sFirebaseAuth.signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask<AuthResult>(null, true, new FirebaseAuthInvalidCredentialsException(ERROR_INVALID_VERIFICATION, "any_msg"))); testSendConfirmationCode(); SpacedEditText mConfirmationCodeEditText = (SpacedEditText) mActivity.findViewById(R.id .confirmation_code); Button mSubmitConfirmationButton = (Button) mActivity.findViewById(R.id .submit_confirmation_code); mConfirmationCodeEditText.setText("123456"); mSubmitConfirmationButton.performClick(); assertEquals(mActivity.getString(R.string.incorrect_code_dialog_body), getAlertDialogMessage()); android.support.v7.app.AlertDialog a = mActivity.getAlertDialog(); Button ok = (Button) a.findViewById(android.R.id.button1); ok.performClick(); assertEquals("- - - - - -", mConfirmationCodeEditText.getText().toString()); } |
### Question:
PhoneNumberUtils { protected static PhoneNumber getPhoneNumber(@NonNull String providedPhoneNumber) { String countryCode = DEFAULT_COUNTRY_CODE; String countryIso = DEFAULT_LOCALE.getCountry(); String phoneNumber = providedPhoneNumber; if (providedPhoneNumber.startsWith("+")) { countryCode = countryCodeForPhoneNumber(providedPhoneNumber); countryIso = countryIsoForCountryCode(countryCode); phoneNumber = stripCountryCode(providedPhoneNumber, countryCode); } return new PhoneNumber(phoneNumber, countryIso, countryCode); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetPhoneNumber() throws Exception { final PhoneNumber number = getPhoneNumber(RAW_PHONE); assertEquals(PhoneTestConstants.PHONE_NO_COUNTRY_CODE, number.getPhoneNumber()); assertEquals(PhoneTestConstants.US_COUNTRY_CODE, number.getCountryCode()); assertEquals(PhoneTestConstants.US_ISO2, number.getCountryIso()); } |
### Question:
PhoneNumberUtils { @Nullable public static Integer getCountryCode(String countryIso) { return countryIso == null ? null : CountryCodeByIsoMap.get(countryIso.toUpperCase(Locale.getDefault())); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetCountryCode() throws Exception { assertEquals(new Integer(86), getCountryCode(Locale.CHINA.getCountry())); assertEquals(null, getCountryCode(null)); assertEquals(null, getCountryCode(new Locale("", "DJJZ").getCountry())); } |
### Question:
PhoneNumberUtils { @NonNull static CountryInfo getCurrentCountryInfo(@NonNull Context context) { Locale locale = getSimBasedLocale(context); if (locale == null) { locale = getOSLocale(); } if (locale == null) { return DEFAULT_COUNTRY; } Integer countryCode = PhoneNumberUtils.getCountryCode(locale.getCountry()); return countryCode == null ? DEFAULT_COUNTRY : new CountryInfo(locale, countryCode); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetCurrentCountryInfo_fromSim() { Context context = mock(Context.class); TelephonyManager telephonyManager = mock(TelephonyManager.class); when(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(telephonyManager); when(telephonyManager.getSimCountryIso()).thenReturn("IN"); assertEquals(new CountryInfo(new Locale("", "IN"), 91), getCurrentCountryInfo(context)); } |
### Question:
FileTaskAccessor implements TaskAccessor { @Override public List<Task> loadTasks() { List<Task> tasks = new ArrayList<>(); File[] taskFiles = FileAccessSupport.getTaskFiles(DEFAULT_TASK_PATH); for (File taskFile : taskFiles) { Task task = FileParser.parseTask(taskFile, false); tasks.add(task); } return tasks; } @Override List<Task> loadTasks(); @Override Task loadTaskByName(String taskName); @Override Host loadHostById(String hostId); @Override void createSnapshot(HostSnapshot snapshot); @Override void saveCrawledResult(CrawledResult crawledResult, List<ErrorPageDTO> errorPages); @Override HostResult getHostResult(String hostId); @Override List<ErrorPageDTO> getErrorPages(String hostId, int startPos, int size); @Override int getErrorPageNum(String hostId); @Override void rollbackHost(String hostId); }### Answer:
@Test public void loadTasks() { List<Task> tasks = fileTaskLoader.loadTasks(); Assert.assertEquals(1, tasks.size()); } |
### Question:
FieldDescriptors { public FieldDescriptors and(FieldDescriptor... additionalDescriptors) { return andWithPrefix("", additionalDescriptors); } FieldDescriptors(FieldDescriptor... fieldDescriptors); FieldDescriptors and(FieldDescriptor... additionalDescriptors); FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors); }### Answer:
@Test public void should_combine_descriptors() { fieldDescriptors = givenFieldDescriptors(); then(fieldDescriptors.and(fieldWithPath("c")).getFieldDescriptors()) .extracting(FieldDescriptor::getPath).contains("a", "b", "c"); } |
### Question:
FieldDescriptors { public FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) { List<FieldDescriptor> combinedDescriptors = new ArrayList<>(fieldDescriptors); combinedDescriptors.addAll(applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); return new FieldDescriptors(combinedDescriptors); } FieldDescriptors(FieldDescriptor... fieldDescriptors); FieldDescriptors and(FieldDescriptor... additionalDescriptors); FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors); }### Answer:
@Test public void should_combine_descriptors_with_prefix() { fieldDescriptors = givenFieldDescriptors(); then(fieldDescriptors.andWithPrefix("d.", fieldWithPath("c")).getFieldDescriptors()) .extracting(FieldDescriptor::getPath).contains("a", "b", "d.c"); } |
### Question:
BujintMojo extends AbstractMojo { String nowTimeImageUrl() throws Exception { String time = DateFormatUtils.format(new Date(), "hhmm"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet("http: httpget.setHeader("Referer", "http: HttpResponse response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != 200) { getLog().error("美人時計忙しいらしいよ。なんか200じゃないの返してくる。"); return null; } String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); httpclient.getConnectionManager().shutdown(); return "http: } void execute(); }### Answer:
@Test public void testNowTimeImageUrl() throws Exception { BujintMojo target = new BujintMojo(); String result = target.nowTimeImageUrl(); System.out.println(result); } |
### Question:
BujintMojo extends AbstractMojo { String getImagePath(String str) throws Exception { DOMParser parser = new DOMParser(); parser.parse(new InputSource(new StringReader(str))); NodeList nodeList = XPathAPI.selectNodeList(parser.getDocument(), "/HTML/BODY/TABLE/TR/TH[1]/IMG"); String path = null; for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); path = element.getAttribute("src"); } return path; } void execute(); }### Answer:
@Test public void testGetImagePath() throws Exception { InputStream is = getClass().getClassLoader().getResourceAsStream( "test.html"); String str = IOUtils.toString(is, "UTF-8"); BujintMojo target = new BujintMojo(); assertEquals("結果が不正です", "/jp/img/clk/6976221_31.jpg", target .getImagePath(str)); } |
### Question:
BujintMojo extends AbstractMojo { BufferedImage getFittingImage(String url) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url)); httpget.setHeader("Referer", "http: HttpResponse response = httpclient.execute(httpget); BufferedImage image = ImageIO.read(response.getEntity().getContent()); httpclient.getConnectionManager().shutdown(); int width = image.getWidth() / 10 * 4; int height = image.getHeight() / 10 * 4; BufferedImage resizedImage = null; resizedImage = new BufferedImage(width, height, image.getType()); resizedImage.getGraphics().drawImage( image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0, 0, width, height, null); return resizedImage; } void execute(); }### Answer:
@Test public void testGetFittingImage() throws Exception { BujintMojo target = new BujintMojo(); BufferedImage image = target.getFittingImage(target.nowTimeImageUrl()); ImageIO.write(image, "jpg", new File("test.jpg")); } |
### Question:
BujintMojo extends AbstractMojo { public void execute() throws MojoExecutionException { try { String imgUrl = nowTimeImageUrl(); if (imgUrl == null) { return; } getLog().info("\n" + getAsciiArt(getFittingImage(imgUrl))); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("なんかエラー", e); } } void execute(); }### Answer:
@Test public void testExecute() throws Exception { BujintMojo target = new BujintMojo(); target.execute(); } |
### Question:
XLSXSample { public void makeXlsxFile() throws Exception { String fileName = "test.xlsx"; FileOutputStream fileOut = new FileOutputStream(fileName); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("test"); Row row = sheet.createRow((short)0); Cell cell = row.createCell(0); cell.setCellValue("日本語は通る?"); wb.write(fileOut); fileOut.close(); } void makeXlsxFile(); }### Answer:
@Test public void test() throws Exception { XLSXSample target = new XLSXSample(); target.makeXlsxFile(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.