method2testcases
stringlengths 118
6.63k
|
---|
### Question:
PhoneUtil { public static String hiddenMiddlePhoneNum(String phoneNumber) throws IOException { if (!isPhoneNumber(phoneNumber)) { throw new IOException("phoneNumber invalid"); } return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } @SuppressLint("HardwareIds") static String getIMEI(Context context); @SuppressLint("HardwareIds") static String getIMSI(Context context); static String hiddenMiddlePhoneNum(String phoneNumber); static boolean isPhoneNumber(String phoneNumber); }### Answer:
@Test public void hiddenMiddlePhoneNum() throws Exception { String hiddenPhoneNumber = PhoneUtil.hiddenMiddlePhoneNum("13634429866"); Assert.assertEquals("", "136****9866", hiddenPhoneNumber); }
@Test(expected = IOException.class) public void testErrorPhoneNumber() throws Exception { String hiddenPhoneNumber = PhoneUtil.hiddenMiddlePhoneNum("1363442986"); Assert.assertEquals("", "136****986", hiddenPhoneNumber); }
|
### Question:
PhoneUtil { public static boolean isPhoneNumber(String phoneNumber) { if (phoneNumber == null || phoneNumber.trim().length() != 11) { return false; } Pattern p = Pattern.compile("^[1][0-9]{10}$"); Matcher m = p.matcher(phoneNumber); return m.matches(); } @SuppressLint("HardwareIds") static String getIMEI(Context context); @SuppressLint("HardwareIds") static String getIMSI(Context context); static String hiddenMiddlePhoneNum(String phoneNumber); static boolean isPhoneNumber(String phoneNumber); }### Answer:
@Test public void isPhoneNumber() throws Exception { boolean phoneNumber = PhoneUtil.isPhoneNumber("13634429866"); Assert.assertTrue(phoneNumber); }
|
### Question:
CustomerServiceProxy { public Mono<Optional<GetCustomerResponse>> findCustomerById(String customerId) { Mono<ClientResponse> response = client .get() .uri(customerServiceUrl + "/customers/{customerId}", customerId) .exchange(); return response.flatMap(resp -> { switch (resp.statusCode()) { case OK: return resp.bodyToMono(GetCustomerResponse.class).map(Optional::of); case NOT_FOUND: Mono<Optional<GetCustomerResponse>> notFound = Mono.just(Optional.empty()); return notFound; default: return Mono.error(new UnknownProxyException("Unknown: " + resp.statusCode())); } }) .transformDeferred(TimeLimiterOperator.of(timeLimiter)) .transformDeferred(CircuitBreakerOperator.of(cb)) ; } CustomerServiceProxy(WebClient client, CircuitBreakerRegistry circuitBreakerRegistry, String customerServiceUrl, TimeLimiterRegistry timeLimiterRegistry); Mono<Optional<GetCustomerResponse>> findCustomerById(String customerId); }### Answer:
@Test public void shouldCallCustomerService() throws JSONException { JSONObject json = new JSONObject(); json.put("customerId", 101); json.put("name", "Fred"); json.put("creditLimit", "12.34"); String expectedResponse = json.toString(); stubFor(get(urlEqualTo("/customers/101")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(expectedResponse))); GetCustomerResponse customer = customerServiceProxy.findCustomerById("101").block().get(); assertEquals(new Long(101L), customer.getCustomerId()); verify(getRequestedFor(urlMatching("/customers/101"))); }
@Test(expected = CallNotPermittedException.class) public void shouldTimeoutAndTripCircuitBreaker() { String expectedResponse = "{}"; stubFor(get(urlEqualTo("/customers/99")) .willReturn(aResponse() .withStatus(500) .withHeader("Content-Type", "application/json") .withBody(expectedResponse))); IntStream.range(0, 100).forEach(i -> { try { customerServiceProxy.findCustomerById("99").block(); } catch (CallNotPermittedException e) { throw e; } catch (UnknownProxyException e) { } } ); verify(getRequestedFor(urlMatching("/customers/99"))); }
|
### Question:
ImageUtil { public static void toFile(String oldFile, String newFile, ImageParamDTO params) throws IOException { if (StringUtils.isBlank(oldFile) || StringUtils.isBlank(newFile)) { logger.error("原文件名或目标文件名为空"); return; } Thumbnails.Builder builder = Thumbnails.of(oldFile); fillBuilderWithParams(builder, params); if (null == builder) { return; } builder.toFile(newFile); } static void toFile(String oldFile, String newFile, ImageParamDTO params); static BufferedImage toBufferedImage(String oldFile, ImageParamDTO params); static OutputStream toOutputStream(InputStream input, OutputStream output, ImageParamDTO params); static String getContentType(byte[] content); static final InputStream bytes2InputStream(byte[] buf); static final byte[] inputStream2bytes(InputStream inStream); }### Answer:
@Test public void testToFile() throws IOException { final String oldFile = System.getProperty("user.dir") + "/src/test/resources/images/lion2.jpg"; final String newFile = System.getProperty("user.dir") + "/src/test/resources/images/lion2_watermark"; final String warterFile = System.getProperty("user.dir") + "/src/test/resources/images/wartermark.png"; ImageParamDTO params = new ImageParamDTO(); params.setFormat("png"); params.setWaterMark(new ImageParamDTO.WaterMark(9, warterFile, 0.6f)); ImageUtil.toFile(oldFile, newFile, params); }
|
### Question:
ImageUtil { public static BufferedImage toBufferedImage(String oldFile, ImageParamDTO params) throws IOException { if (StringUtils.isBlank(oldFile)) { logger.error("原文件名或目标文件名为空"); return null; } Thumbnails.Builder builder = Thumbnails.of(oldFile); fillBuilderWithParams(builder, params); if (null == builder) { return null; } return builder.asBufferedImage(); } static void toFile(String oldFile, String newFile, ImageParamDTO params); static BufferedImage toBufferedImage(String oldFile, ImageParamDTO params); static OutputStream toOutputStream(InputStream input, OutputStream output, ImageParamDTO params); static String getContentType(byte[] content); static final InputStream bytes2InputStream(byte[] buf); static final byte[] inputStream2bytes(InputStream inStream); }### Answer:
@Test public void testToBufferedImage() throws IOException { final String oldFile = System.getProperty("user.dir") + "/src/test/resources/images/lion2.jpg"; ImageParamDTO params = new ImageParamDTO(); params.setWidth(64); params.setHeight(64); BufferedImage bufferedImage = ImageUtil.toBufferedImage(oldFile, params); Assert.assertNotNull(bufferedImage); }
|
### Question:
ImageUtil { public static String getContentType(byte[] content) throws MagicParseException, MagicException, MagicMatchNotFoundException { MagicMatch match = Magic.getMagicMatch(content); return match.getMimeType(); } static void toFile(String oldFile, String newFile, ImageParamDTO params); static BufferedImage toBufferedImage(String oldFile, ImageParamDTO params); static OutputStream toOutputStream(InputStream input, OutputStream output, ImageParamDTO params); static String getContentType(byte[] content); static final InputStream bytes2InputStream(byte[] buf); static final byte[] inputStream2bytes(InputStream inStream); }### Answer:
@Test public void testGetContentType() throws MagicParseException, MagicException, MagicMatchNotFoundException, IOException { final String oldFile = System.getProperty("user.dir") + "/src/test/resources/images/lion2.jpg"; byte[] bytes = toBytes(new File(oldFile)); String type = ImageUtil.getContentType(bytes); Assert.assertEquals("image/jpeg", type); }
|
### Question:
QRCodeUtil { public static void encode(String content, BarcodeParamDTO paramDTO) throws WriterException, IOException { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, paramDTO.getBarcodeFormat(), paramDTO.getWidth(), paramDTO.getHeight(), paramDTO.getEncodeHints()); Path path = FileSystems.getDefault().getPath(paramDTO.getFilepath()); MatrixToImageWriter.writeToPath(bitMatrix, paramDTO.getImageFormat(), path); } static void encode(String content, BarcodeParamDTO paramDTO); static String decode(BarcodeParamDTO paramDTO); }### Answer:
@Test public void test01() throws IOException, WriterException { QRCodeUtil.encode(jsonContent, paramDTO); File f = new File(qrcodeFile); Assert.assertTrue(f.exists()); }
|
### Question:
QRCodeUtil { public static String decode(BarcodeParamDTO paramDTO) { try { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(paramDTO.getFilepath())); LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); Result result = new MultiFormatReader().decode(bitmap, paramDTO.getDecodeHints()); return result.getText(); } catch (Exception e) { e.printStackTrace(); return null; } } static void encode(String content, BarcodeParamDTO paramDTO); static String decode(BarcodeParamDTO paramDTO); }### Answer:
@Test public void test02() { String expect = "{\"gender\":\"MALE\",\"name\":{\"last\":\"Zhang\",\"first\":\"Peng\"},\"email\":\"[email protected]\"}"; String content = QRCodeUtil.decode(paramDTO); Assert.assertEquals(expect, content); }
|
### Question:
VelocityUtil { public static String getMergeOutput(VelocityContext context, String templateName) { Template template = velocityEngine.getTemplate(templateName); StringWriter sw = new StringWriter(); template.merge(context, sw); String output = sw.toString(); try { sw.close(); } catch (IOException e) { e.printStackTrace(); } return output; } static String getMergeOutput(VelocityContext context, String templateName); }### Answer:
@Test public void test() { VelocityContext context = new VelocityContext(); context.put("name", "Victor Zhang"); context.put("project", "Velocity"); System.out.println(VelocityUtil.getMergeOutput(context, "template/hello.vm")); }
|
### Question:
StringUtils { public static String join(CharSequence delimiter, Iterable values) { StringBuilder sb = new StringBuilder(); Iterator<?> it = values.iterator(); if (it.hasNext()) { sb.append(it.next()); while (it.hasNext()) { sb.append(delimiter); sb.append(it.next()); } } return sb.toString(); } static String join(CharSequence delimiter, Iterable values); }### Answer:
@Test public void testJoin() throws Exception { String result = StringUtils.join(", ", asList(1, 2, 3, 4, 5)); Assert.assertEquals(result, "1, 2, 3, 4, 5"); }
|
### Question:
Characteristics { public boolean isLegacyDevice() { int hardwareLevel = cameraCharacteristics .get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); return hardwareLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void isLegacyDevice() throws Exception { given(cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)) .willReturn(CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); boolean isLegacyDevice = testee.isLegacyDevice(); assertTrue(isLegacyDevice); }
|
### Question:
Characteristics { public int getSensorOrientation() { return cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void sensorOrientation() throws Exception { given(cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)) .willReturn(90); int sensorOrientation = testee.getSensorOrientation(); assertEquals(90, sensorOrientation); }
|
### Question:
Characteristics { public int[] autoExposureModes() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES); } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void autoExposureModes() throws Exception { int[] availableExposures = { CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE, CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH, CameraMetadata.CONTROL_AE_MODE_OFF }; given(cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES)) .willReturn(availableExposures); int[] autoExposureModes = testee.autoExposureModes(); assertEquals(availableExposures, autoExposureModes); }
|
### Question:
Characteristics { public int[] autoFocusModes() { return cameraCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES); } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void autoFocusModes() throws Exception { int[] availableExposures = { CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO, CameraMetadata.CONTROL_AF_MODE_EDOF, CameraMetadata.CONTROL_AF_MODE_OFF }; given(cameraCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES)) .willReturn(availableExposures); int[] autoFocusModes = testee.autoFocusModes(); assertEquals(availableExposures, autoFocusModes); }
|
### Question:
CameraSelector { @NonNull public String findCameraId(LensPosition lensPosition) { try { return getCameraIdUnsafe(lensPosition); } catch (CameraAccessException e) { throw new CameraException(e); } } CameraSelector(android.hardware.camera2.CameraManager manager); @NonNull String findCameraId(LensPosition lensPosition); }### Answer:
@Test(expected = CameraException.class) public void cameraNotAvailable() throws Exception { given(manager.getCameraIdList()) .willThrow(new CameraAccessException(CAMERA_ERROR)); testee.findCameraId(LensPosition.EXTERNAL); }
@Test(expected = CameraException.class) public void noCameraFound() throws Exception { given(manager.getCameraIdList()) .willReturn(new String[]{"0"}); testee.findCameraId(LensPosition.EXTERNAL); }
@Test public void getFrontCamera() throws Exception { given(manager.getCameraIdList()) .willReturn(new String[]{"0", "1"}); String cameraId = testee.findCameraId(LensPosition.FRONT); assertEquals("1", cameraId); }
|
### Question:
OrientationManager implements OrientationOperator { public int getPhotoOrientation() { Characteristics characteristics = cameraConnection.getCharacteristics(); return OrientationUtils.computeImageOrientation( orientation, characteristics.getSensorOrientation(), characteristics.isFrontFacingLens() ); } OrientationManager(CameraConnection cameraConnection); @Override void setDisplayOrientation(int orientation); int getPhotoOrientation(); synchronized void addListener(Listener listener); }### Answer:
@Test public void back_landscape_0() throws Exception { givenSensor90Degrees(); givenLandscapeScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(0, orientation); }
@Test public void back_portrait_90() throws Exception { givenSensor90Degrees(); givenPortraitScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(270, orientation); }
@Test public void back_reverseLandscape_180() throws Exception { givenSensor90Degrees(); givenReverseLandscapeScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(180, orientation); }
@Test public void back_reversePortrait_270() throws Exception { givenSensor90Degrees(); givenReversePortraitScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(90, orientation); }
@Test public void front_reverseLandscape_0() throws Exception { givenFrontLens(); givenSensor90Degrees(); givenReverseLandscapeScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(0, orientation); }
@Test public void front_portrait_90() throws Exception { givenFrontLens(); givenSensor90Degrees(); givenPortraitScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(270, orientation); }
@Test public void front_landscape_180() throws Exception { givenFrontLens(); givenSensor90Degrees(); givenLandscapeScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(180, orientation); }
@Test public void front_reversePortrait_270() throws Exception { givenFrontLens(); givenSensor90Degrees(); givenReversePortraitScreen(); int orientation = testee.getPhotoOrientation(); assertEquals(90, orientation); }
|
### Question:
PendingResult { public <R> PendingResult<R> transform(@NonNull final Transformer<T, R> transformer) { FutureTask<R> transformTask = new FutureTask<>(new Callable<R>() { @Override public R call() throws Exception { return transformer.transform( future.get() ); } }); executor.execute(transformTask); return new PendingResult<>( transformTask, executor ); } PendingResult(Future<T> future,
Executor executor); static PendingResult<T> fromFuture(@NonNull Future<T> future); PendingResult<R> transform(@NonNull final Transformer<T, R> transformer); T await(); R adapt(@NonNull Adapter<T, R> adapter); void whenAvailable(@NonNull final Callback<T> callback); void whenDone(@NonNull final Callback<T> callback); }### Answer:
@Test public void transform() throws Exception { given(transformer.transform(RESULT)) .willReturn(123); Integer result = testee.transform(transformer) .await(); assertEquals( Integer.valueOf(123), result ); }
|
### Question:
RendererParametersProvider implements RendererParametersOperator { @Override public RendererParameters getRendererParameters() { return new RendererParameters( parametersProvider.getPreviewSize(), orientationManager.getPhotoOrientation() ); } RendererParametersProvider(ParametersProvider parametersProvider,
OrientationManager orientationManager); @Override RendererParameters getRendererParameters(); }### Answer:
@Test public void getParameters() throws Exception { Size size = new Size(1920, 1080); int sensorOrientation = 90; given(parametersProvider.getPreviewSize()) .willReturn(size); given(orientationManager.getPhotoOrientation()) .willReturn(sensorOrientation); RendererParameters rendererParameters = testee.getRendererParameters(); assertEquals( new RendererParameters( size, sensorOrientation ), rendererParameters ); }
|
### Question:
Request { static CaptureRequest create(CaptureRequestBuilder builder) throws CameraAccessException { return new Request( builder.cameraDevice, builder.requestTemplate, builder.surfaces, builder.shouldTriggerAutoFocus, builder.triggerPrecaptureExposure, builder.cancelPrecaptureExposure, builder.flash, builder.shouldSetExposureMode, builder.focus, builder.previewFpsRange, builder.sensorSensitivity, builder.jpegQuality ) .build(); } private Request(CameraDevice cameraDevice,
int requestTemplate,
List<Surface> surfaces,
boolean shouldTriggerAutoFocus,
boolean triggerPrecaptureExposure,
boolean cancelPrecaptureExposure,
Flash flash, boolean shouldSetExposureMode,
FocusMode focus,
Range<Integer> previewFpsRange,
Integer sensorSensitivity,
Integer jpegQuality); }### Answer:
@Test public void stillCapture_setCaptureIntent() throws Exception { CaptureRequestBuilder request = simpleRequest(); Request.create(request); verify(builder) .set(CaptureRequest.CONTROL_CAPTURE_INTENT, CameraMetadata.CONTROL_CAPTURE_INTENT_STILL_CAPTURE); verify(builder) .set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO); }
@Test public void stillCapture_notSetCaptureIntent() throws Exception { CaptureRequestBuilder request = CaptureRequestBuilder .create( cameraDevice, CameraDevice.TEMPLATE_PREVIEW ) .into(surface); Request.create(request); verify(builder, never()) .set(CaptureRequest.CONTROL_CAPTURE_INTENT, CameraMetadata.CONTROL_CAPTURE_INTENT_STILL_CAPTURE); verify(builder, never()) .set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO); }
|
### Question:
CaptureRequestBuilder { CaptureRequest build() throws CameraAccessException { validate(); return Request.create(this); } private CaptureRequestBuilder(CameraDevice cameraDevice, @RequestTemplate int requestTemplate); }### Answer:
@Test public void onlyMandatoryParameters() throws Exception { CaptureRequestBuilder builder = builderWithMandatoryArguments(); CaptureRequest result = builder.build(); assertNotNull(result); assertEquals(Collections.singletonList(surface), builder.surfaces); assertEquals(cameraDevice, builder.cameraDevice); assertEquals(CameraDevice.TEMPLATE_STILL_CAPTURE, builder.requestTemplate); }
|
### Question:
ParametersProvider implements ParametersOperator { public Flash getFlash() { return getSelectedParameters().getValue(FLASH); } @Override void updateParameters(Parameters selectedParameters); Flash getFlash(); FocusMode getFocus(); Size getStillCaptureSize(); Size getPreviewSize(); float getStillCaptureAspectRatio(); Range<Integer> getPreviewFpsRange(); Integer getSensorSensitivity(); Integer getJpegQuality(); }### Answer:
@Test public void getFlash() throws Exception { given(parameters.getValue(Parameters.Type.FLASH)) .willReturn(Flash.OFF); testee.updateParameters(parameters); Flash flash = testee.getFlash(); assertEquals(Flash.OFF, flash); }
|
### Question:
PendingResult { public <R> R adapt(@NonNull Adapter<T, R> adapter) { return adapter.adapt(future); } PendingResult(Future<T> future,
Executor executor); static PendingResult<T> fromFuture(@NonNull Future<T> future); PendingResult<R> transform(@NonNull final Transformer<T, R> transformer); T await(); R adapt(@NonNull Adapter<T, R> adapter); void whenAvailable(@NonNull final Callback<T> callback); void whenDone(@NonNull final Callback<T> callback); }### Answer:
@Test public void adapt() throws Exception { given(adapter.adapt(FUTURE)) .willReturn(123); int result = testee.adapt(adapter); verify(adapter).adapt(FUTURE); assertEquals(123, result); }
|
### Question:
ParametersProvider implements ParametersOperator { public FocusMode getFocus() { return getSelectedParameters().getValue(FOCUS_MODE); } @Override void updateParameters(Parameters selectedParameters); Flash getFlash(); FocusMode getFocus(); Size getStillCaptureSize(); Size getPreviewSize(); float getStillCaptureAspectRatio(); Range<Integer> getPreviewFpsRange(); Integer getSensorSensitivity(); Integer getJpegQuality(); }### Answer:
@Test public void getFocus() throws Exception { given(parameters.getValue(Parameters.Type.FOCUS_MODE)) .willReturn(FocusMode.CONTINUOUS_FOCUS); testee.updateParameters(parameters); FocusMode focusMode = testee.getFocus(); assertEquals(FocusMode.CONTINUOUS_FOCUS, focusMode); }
|
### Question:
ParametersProvider implements ParametersOperator { public Size getPreviewSize() { return getSelectedParameters().getValue(PREVIEW_SIZE); } @Override void updateParameters(Parameters selectedParameters); Flash getFlash(); FocusMode getFocus(); Size getStillCaptureSize(); Size getPreviewSize(); float getStillCaptureAspectRatio(); Range<Integer> getPreviewFpsRange(); Integer getSensorSensitivity(); Integer getJpegQuality(); }### Answer:
@Test public void getPreviewSize() throws Exception { given(parameters.getValue(Parameters.Type.PREVIEW_SIZE)) .willReturn(new Size(1920, 1080)); testee.updateParameters(parameters); Size previewSize = testee.getPreviewSize(); assertEquals(new Size(1920, 1080), previewSize); }
|
### Question:
OrientationUtils { public static int toClosestRightAngle(int degrees) { boolean roundUp = degrees % 90 > 45; int roundAppModifier = roundUp ? 1 : 0; return (((degrees / 90) + roundAppModifier) * 90) % 360; } static int toClosestRightAngle(int degrees); static int computeDisplayOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); static int computeImageOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); }### Answer:
@Test public void toClosestRightAngle_0() throws Exception { assertEquals( 0, OrientationUtils.toClosestRightAngle(5) ); }
@Test public void toClosestRightAngle_90() throws Exception { assertEquals( 90, OrientationUtils.toClosestRightAngle(60) ); }
@Test public void toClosestRightAngle_180() throws Exception { assertEquals( 180, OrientationUtils.toClosestRightAngle(190) ); }
@Test public void toClosestRightAngle_270() throws Exception { assertEquals( 270, OrientationUtils.toClosestRightAngle(269) ); }
@Test public void toClosestRightAngle_360() throws Exception { assertEquals( 0, OrientationUtils.toClosestRightAngle(359) ); }
|
### Question:
OrientationUtils { public static int computeDisplayOrientation(int screenRotationDegrees, int cameraRotationDegrees, boolean cameraIsMirrored) { int degrees = OrientationUtils.toClosestRightAngle(screenRotationDegrees); if (cameraIsMirrored) { degrees = (cameraRotationDegrees + degrees) % 360; degrees = (360 - degrees) % 360; } else { degrees = (cameraRotationDegrees - degrees + 360) % 360; } return degrees; } static int toClosestRightAngle(int degrees); static int computeDisplayOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); static int computeImageOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); }### Answer:
@Test public void computeDisplayOrientation_Phone_Portrait_FrontCamera() throws Exception { int screenOrientation = 0; int cameraOrientation = 270; int result = OrientationUtils.computeDisplayOrientation( screenOrientation, cameraOrientation, true ); assertEquals(90, result); }
@Test public void computeDisplayOrientation_Phone_Landscape_FrontCamera() throws Exception { int screenOrientation = 270; int cameraOrientation = 270; int result = OrientationUtils.computeDisplayOrientation( screenOrientation, cameraOrientation, true ); assertEquals(180, result); }
@Test public void computeDisplayOrientation_Phone_Portrait_BackCamera() throws Exception { int screenOrientation = 0; int cameraOrientation = 90; int result = OrientationUtils.computeDisplayOrientation( screenOrientation, cameraOrientation, false ); assertEquals(90, result); }
@Test public void computeDisplayOrientation_Phone_Landscape_BackCamera() throws Exception { int screenOrientation = 270; int cameraOrientation = 90; int result = OrientationUtils.computeDisplayOrientation( screenOrientation, cameraOrientation, false ); assertEquals(180, result); }
|
### Question:
PendingResult { public T await() throws ExecutionException, InterruptedException { return future.get(); } PendingResult(Future<T> future,
Executor executor); static PendingResult<T> fromFuture(@NonNull Future<T> future); PendingResult<R> transform(@NonNull final Transformer<T, R> transformer); T await(); R adapt(@NonNull Adapter<T, R> adapter); void whenAvailable(@NonNull final Callback<T> callback); void whenDone(@NonNull final Callback<T> callback); }### Answer:
@Test public void await() throws Exception { String result = testee.await(); assertEquals( RESULT, result ); }
|
### Question:
OrientationUtils { public static int computeImageOrientation(int screenRotationDegrees, int cameraRotationDegrees, boolean cameraIsMirrored) { int rotation; if (cameraIsMirrored) { rotation = -(screenRotationDegrees + cameraRotationDegrees); } else { rotation = screenRotationDegrees - cameraRotationDegrees; } return (rotation + 360 + 360) % 360; } static int toClosestRightAngle(int degrees); static int computeDisplayOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); static int computeImageOrientation(int screenRotationDegrees,
int cameraRotationDegrees,
boolean cameraIsMirrored); }### Answer:
@Test public void computeImageOrientation_Phone_Portrait_FrontCamera() throws Exception { int screenOrientation = 0; int cameraOrientation = 270; int result = OrientationUtils.computeImageOrientation( screenOrientation, cameraOrientation, true ); assertEquals(90, result); }
@Test public void computeImageOrientation_Phone_Landscape_FrontCamera() throws Exception { int screenOrientation = 270; int cameraOrientation = 270; int result = OrientationUtils.computeImageOrientation( screenOrientation, cameraOrientation, true ); assertEquals(180, result); }
@Test public void computeImageOrientation_Phone_Portrait_BackCamera() throws Exception { int screenOrientation = 0; int cameraOrientation = 90; int result = OrientationUtils.computeImageOrientation( screenOrientation, cameraOrientation, false ); assertEquals(270, result); }
@Test public void computeImageOrientation_Phone_Landscape_BackCamera() throws Exception { int screenOrientation = 270; int cameraOrientation = 90; int result = OrientationUtils.computeImageOrientation( screenOrientation, cameraOrientation, false ); assertEquals(180, result); }
|
### Question:
ParametersConverter { public CameraParametersDecorator toPlatformParameters(Parameters parameters, CameraParametersDecorator output) { for (Parameters.Type storedType : parameters.storedTypes()) { applyParameter( storedType, parameters, output ); } return output; } CameraParametersDecorator toPlatformParameters(Parameters parameters,
CameraParametersDecorator output); Parameters fromPlatformParameters(CameraParametersDecorator platformParameters); }### Answer:
@Test public void returnSameValue() throws Exception { Parameters input = new Parameters(); CameraParametersDecorator result = testee.toPlatformParameters( input, outputParameters ); assertSame( result, outputParameters ); }
@Test public void setFocusMode() throws Exception { Parameters input = new Parameters(); input.putValue( Parameters.Type.FOCUS_MODE, FocusMode.AUTO ); testee.toPlatformParameters( input, outputParameters ); verify(outputParameters).setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); }
@Test public void setFlash() throws Exception { Parameters input = new Parameters(); input.putValue( Parameters.Type.FLASH, Flash.TORCH ); testee.toPlatformParameters( input, outputParameters ); verify(outputParameters).setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); }
@Test public void setPictureSize() throws Exception { Parameters input = new Parameters(); input.putValue( Parameters.Type.PICTURE_SIZE, new Size(10, 20) ); testee.toPlatformParameters( input, outputParameters ); verify(outputParameters).setPictureSize(10, 20); }
@Test public void setPreviewSize() throws Exception { Parameters input = new Parameters(); input.putValue( Parameters.Type.PREVIEW_SIZE, new Size(10, 20) ); testee.toPlatformParameters( input, outputParameters ); verify(outputParameters).setPreviewSize(10, 20); }
|
### Question:
Fotoapparat { public void start() { ensureNotStarted(); started = true; startCamera(); configurePreviewStream(); updateOrientationRoutine.start(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void start() throws Exception { testee.start(); InOrder inOrder = inOrder( startCameraRoutine, updateOrientationRoutine, configurePreviewStreamRoutine ); inOrder.verify(startCameraRoutine).run(); inOrder.verify(configurePreviewStreamRoutine).run(); inOrder.verify(updateOrientationRoutine).start(); }
@Test(expected = IllegalStateException.class) public void start_SecondTime() throws Exception { testee.start(); testee.start(); }
|
### Question:
CameraParametersDecorator { @NonNull public Set<Integer> getSensorSensitivityValues() { String[] rawValues = extractRawCameraValues(RAW_ISO_SUPPORTED_VALUES_KEYS); return convertParamsToInts(rawValues); } CameraParametersDecorator(Camera.Parameters cameraParameters); Camera.Parameters asCameraParameters(); boolean isZoomSupported(); List<Size> getSupportedPreviewSizes(); List<Size> getSupportedPictureSizes(); List<String> getSupportedFlashModes(); List<String> getSupportedFocusModes(); List<int[]> getSupportedPreviewFpsRange(); String getFocusMode(); void setFocusMode(String focusMode); String getFlashMode(); void setFlashMode(String flash); Camera.Size getPictureSize(); Camera.Size getPreviewSize(); void setPreviewSize(int width, int height); void setPictureSize(int width, int height); void setPreviewFpsRange(int min, int max); @NonNull Set<Integer> getSensorSensitivityValues(); void setSensorSensitivityValue(int isoValue); int getJpegQuality(); void setJpegQuality(int quality); }### Answer:
@Test public void getSensorSensitivityValues_Available() throws Exception { given(parameters.get(anyString())) .willReturn("400,600,1200"); Set<Integer> isoValues = parametersProvider.getSensorSensitivityValues(); Assert.assertEquals( isoValues, asSet(400, 600, 1200) ); }
@Test public void getSensorSensitivityValues_NotAvailable() throws Exception { given(parameters.get(anyString())) .willReturn(null); Set<Integer> isoValues = parametersProvider.getSensorSensitivityValues(); Assert.assertEquals( isoValues, Collections.<Integer>emptySet() ); }
|
### Question:
CameraParametersDecorator { public void setSensorSensitivityValue(int isoValue) { String isoKey = findExistingKey(RAW_ISO_CURRENT_VALUE_KEYS); if (isoKey != null) { cameraParameters.set(isoKey, isoValue); } } CameraParametersDecorator(Camera.Parameters cameraParameters); Camera.Parameters asCameraParameters(); boolean isZoomSupported(); List<Size> getSupportedPreviewSizes(); List<Size> getSupportedPictureSizes(); List<String> getSupportedFlashModes(); List<String> getSupportedFocusModes(); List<int[]> getSupportedPreviewFpsRange(); String getFocusMode(); void setFocusMode(String focusMode); String getFlashMode(); void setFlashMode(String flash); Camera.Size getPictureSize(); Camera.Size getPreviewSize(); void setPreviewSize(int width, int height); void setPictureSize(int width, int height); void setPreviewFpsRange(int min, int max); @NonNull Set<Integer> getSensorSensitivityValues(); void setSensorSensitivityValue(int isoValue); int getJpegQuality(); void setJpegQuality(int quality); }### Answer:
@Test public void setSensorSensitivityValues_Available() throws Exception { given(parameters.get(anyString())) .willReturn("400"); parametersProvider.setSensorSensitivityValue(600); verify(parameters, times(1)).set(anyString(), anyInt()); }
@Test public void setSensorSensitivityValues_NotAvailable() throws Exception { given(parameters.get(anyString())) .willReturn(null); parametersProvider.setSensorSensitivityValue(600); verify(parameters, times(0)).set(anyString(), anyInt()); }
|
### Question:
FlashCapability { public static Flash toFlash(String code) { Flash flash = CODE_TO_FLASH.forward().get(code); if (flash == null) { return Flash.OFF; } return flash; } static Flash toFlash(String code); static String toCode(Flash flash); }### Answer:
@Test public void toFlash() throws Exception { Flash flash = FlashCapability.toFlash( Camera.Parameters.FLASH_MODE_AUTO ); assertEquals( Flash.AUTO, flash ); }
@Test public void toFlash_Unknown() throws Exception { Flash flash = FlashCapability.toFlash("whatever"); assertEquals( Flash.OFF, flash ); }
|
### Question:
FlashCapability { public static String toCode(Flash flash) { return CODE_TO_FLASH.reversed().get(flash); } static Flash toFlash(String code); static String toCode(Flash flash); }### Answer:
@Test public void toCode() throws Exception { String code = FlashCapability.toCode(Flash.AUTO); assertEquals( Camera.Parameters.FLASH_MODE_AUTO, code ); }
|
### Question:
SupressExceptionsParametersOperator implements ParametersOperator { @Override public void updateParameters(Parameters parameters) { try { wrapped.updateParameters(parameters); } catch (Exception e) { logger.log("Unable to set parameters: " + parameters); } } SupressExceptionsParametersOperator(ParametersOperator wrapped,
Logger logger); @Override void updateParameters(Parameters parameters); }### Answer:
@Test public void updateParameters() throws Exception { doThrow(new RuntimeException()) .when(wrapped) .updateParameters(parameters); testee.updateParameters(parameters); verify(wrapped).updateParameters(parameters); }
|
### Question:
SwitchOnFailureParametersOperator implements ParametersOperator { @Override public void updateParameters(Parameters parameters) { try { first.updateParameters(parameters); } catch (Exception e) { second.updateParameters(parameters); } } SwitchOnFailureParametersOperator(ParametersOperator first,
ParametersOperator second); @Override void updateParameters(Parameters parameters); }### Answer:
@Test public void firstSucceeds() throws Exception { testee.updateParameters(parameters); verify(first).updateParameters(parameters); verifyZeroInteractions(second); }
@Test public void firstFails() throws Exception { doThrow(new RuntimeException()) .when(first) .updateParameters(parameters); testee.updateParameters(parameters); verify(second).updateParameters(parameters); }
|
### Question:
SplitParametersOperator implements ParametersOperator { @Override public void updateParameters(Parameters parameters) { for (Parameters.Type type : parameters.storedTypes()) { wrapped.updateParameters( newParameters(type, parameters.getValue(type)) ); } } SplitParametersOperator(ParametersOperator wrapped); @Override void updateParameters(Parameters parameters); }### Answer:
@Test public void updateParameters() throws Exception { Parameters parameters = new Parameters(); parameters.putValue(Parameters.Type.PICTURE_SIZE, PICTURE_SIZE); parameters.putValue(Parameters.Type.PREVIEW_SIZE, PREVIEW_SIZE); testee.updateParameters(parameters); verify(wrapped).updateParameters( parametersWithJust(Parameters.Type.PICTURE_SIZE, PICTURE_SIZE) ); verify(wrapped).updateParameters( parametersWithJust(Parameters.Type.PREVIEW_SIZE, PREVIEW_SIZE) ); verifyNoMoreInteractions(wrapped); }
|
### Question:
FileLogger implements Logger { @Override public void log(String message) { try { ensureWriterInitialized(); writer.write(message + "\n"); writer.flush(); } catch (IOException e) { } } FileLogger(File file); @Override void log(String message); }### Answer:
@Test public void writeMessage() throws Exception { testee.log("message"); testee.log("message"); assertEquals( "message\nmessage\n", readFileToString(FILE, Charset.defaultCharset()) ); }
@Test public void ignoreExceptions() throws Exception { FileLogger logger = new FileLogger(new File("/")); logger.log("message"); }
|
### Question:
CompositeLogger implements Logger { @Override public void log(String message) { for (Logger logger : loggers) { logger.log(message); } } CompositeLogger(@NonNull List<Logger> loggers); @Override void log(String message); }### Answer:
@Test public void log() throws Exception { testee.log("message"); InOrder inOrder = inOrder(loggerA, loggerB); inOrder.verify(loggerA).log("message"); inOrder.verify(loggerB).log("message"); }
|
### Question:
FlashSelectors { public static SelectorFunction<Collection<Flash>, Flash> autoRedEye() { return flash(Flash.AUTO_RED_EYE); } static SelectorFunction<Collection<Flash>, Flash> off(); static SelectorFunction<Collection<Flash>, Flash> on(); static SelectorFunction<Collection<Flash>, Flash> autoFlash(); static SelectorFunction<Collection<Flash>, Flash> autoRedEye(); static SelectorFunction<Collection<Flash>, Flash> torch(); }### Answer:
@Test public void focusMode_Available() throws Exception { Set<Flash> availableModes = asSet( Flash.AUTO, Flash.AUTO_RED_EYE, Flash.OFF ); Flash result = FlashSelectors .autoRedEye() .select(availableModes); assertEquals( Flash.AUTO_RED_EYE, result ); }
@Test public void focusMode_NotAvailable() throws Exception { Set<Flash> availableModes = asSet( Flash.AUTO, Flash.OFF ); Flash result = FlashSelectors .autoRedEye() .select(availableModes); assertNull(result); }
|
### Question:
LensPositionSelectors { public static SelectorFunction<Collection<LensPosition>, LensPosition> front() { return lensPosition(LensPosition.FRONT); } static SelectorFunction<Collection<LensPosition>, LensPosition> front(); static SelectorFunction<Collection<LensPosition>, LensPosition> back(); static SelectorFunction<Collection<LensPosition>, LensPosition> external(); static SelectorFunction<Collection<LensPosition>, LensPosition> lensPosition(final LensPosition position); }### Answer:
@Test public void front_Available() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.BACK, LensPosition.FRONT, LensPosition.EXTERNAL ); LensPosition result = LensPositionSelectors .front() .select(availablePositions); assertEquals( LensPosition.FRONT, result ); }
@Test public void front_NotAvailable() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.BACK, LensPosition.EXTERNAL ); LensPosition result = LensPositionSelectors .front() .select(availablePositions); assertNull(result); }
|
### Question:
LensPositionSelectors { public static SelectorFunction<Collection<LensPosition>, LensPosition> back() { return lensPosition(LensPosition.BACK); } static SelectorFunction<Collection<LensPosition>, LensPosition> front(); static SelectorFunction<Collection<LensPosition>, LensPosition> back(); static SelectorFunction<Collection<LensPosition>, LensPosition> external(); static SelectorFunction<Collection<LensPosition>, LensPosition> lensPosition(final LensPosition position); }### Answer:
@Test public void back_Available() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.BACK, LensPosition.FRONT, LensPosition.EXTERNAL ); LensPosition result = LensPositionSelectors .back() .select(availablePositions); assertEquals( LensPosition.BACK, result ); }
@Test public void back_NotAvailable() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.FRONT, LensPosition.EXTERNAL ); LensPosition result = LensPositionSelectors .back() .select(availablePositions); assertNull(result); }
|
### Question:
Fotoapparat { public void stop() { ensureStarted(); started = false; updateOrientationRoutine.stop(); stopCamera(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void stop() throws Exception { testee.start(); testee.stop(); InOrder inOrder = inOrder( stopCameraRoutine, updateOrientationRoutine ); inOrder.verify(updateOrientationRoutine).stop(); inOrder.verify(stopCameraRoutine).run(); }
@Test(expected = IllegalStateException.class) public void stop_NotStarted() throws Exception { testee.stop(); }
|
### Question:
LensPositionSelectors { public static SelectorFunction<Collection<LensPosition>, LensPosition> external() { return lensPosition(LensPosition.EXTERNAL); } static SelectorFunction<Collection<LensPosition>, LensPosition> front(); static SelectorFunction<Collection<LensPosition>, LensPosition> back(); static SelectorFunction<Collection<LensPosition>, LensPosition> external(); static SelectorFunction<Collection<LensPosition>, LensPosition> lensPosition(final LensPosition position); }### Answer:
@Test public void external_Available() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.BACK, LensPosition.FRONT, LensPosition.EXTERNAL ); LensPosition result = LensPositionSelectors .external() .select(availablePositions); assertEquals( LensPosition.EXTERNAL, result ); }
@Test public void external_NotAvailable() throws Exception { List<LensPosition> availablePositions = asList( LensPosition.FRONT, LensPosition.BACK ); LensPosition result = LensPositionSelectors .external() .select(availablePositions); assertNull(result); }
|
### Question:
PreviewFpsRangeSelectors { public static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> fromExactFps(int fps) { return filtered(rangeWithHighestFps(), new ExactFpsRangePredicate(fps * FPS_RANGE_BOUNDS_SCALE)); } static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> fromExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> nearestToExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithHighestFps(); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithLowestFps(); }### Answer:
@Test public void fromExactFps_Available() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 24000), Ranges.continuousRange(30000, 30000), Ranges.continuousRange(40000, 40000) ); Range<Integer> result = PreviewFpsRangeSelectors .fromExactFps(30) .select(availableRanges); assertEquals( Ranges.continuousRange(30000, 30000), result ); }
@Test public void fromExactFps_NotAvailable() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 30000), Ranges.continuousRange(30000, 36000), Ranges.continuousRange(40000, 40000) ); Range<Integer> result = PreviewFpsRangeSelectors .fromExactFps(30) .select(availableRanges); assertNull(result); }
|
### Question:
PreviewFpsRangeSelectors { public static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> nearestToExactFps(int fps) { return firstAvailable(fromExactFps(fps), filtered(rangeWithHighestFps(), new InBoundsFpsRangePredicate(fps * FPS_RANGE_BOUNDS_SCALE))); } static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> fromExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> nearestToExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithHighestFps(); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithLowestFps(); }### Answer:
@Test public void nearestToExactFps_ExactAvailable() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 30000), Ranges.continuousRange(30000, 30000), Ranges.continuousRange(30000, 34000), Ranges.continuousRange(30000, 36000) ); Range<Integer> result = PreviewFpsRangeSelectors .nearestToExactFps(30) .select(availableRanges); assertEquals( Ranges.continuousRange(30000, 30000), result ); }
@Test public void nearestToExactFps_NoExactAvailable() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 30000), Ranges.continuousRange(30000, 34000), Ranges.continuousRange(30000, 36000) ); Range<Integer> result = PreviewFpsRangeSelectors .nearestToExactFps(30) .select(availableRanges); assertEquals( Ranges.continuousRange(30000, 36000), result ); }
|
### Question:
PreviewFpsRangeSelectors { public static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithHighestFps() { return new SelectorFunction<Collection<Range<Integer>>, Range<Integer>>() { @Override public Range<Integer> select(Collection<Range<Integer>> items) { if (items.isEmpty()) { return null; } return Collections.max(items, COMPARATOR_BY_BOUNDS); } }; } static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> fromExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> nearestToExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithHighestFps(); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithLowestFps(); }### Answer:
@Test public void rangeWithHighestFps() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 30000), Ranges.continuousRange(30000, 34000), Ranges.continuousRange(30000, 36000) ); Range<Integer> result = PreviewFpsRangeSelectors .rangeWithHighestFps() .select(availableRanges); assertEquals( Ranges.continuousRange(30000, 36000), result ); }
|
### Question:
PreviewFpsRangeSelectors { public static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithLowestFps() { return new SelectorFunction<Collection<Range<Integer>>, Range<Integer>>() { @Override public Range<Integer> select(Collection<Range<Integer>> items) { if (items.isEmpty()) { return null; } return Collections.min(items, COMPARATOR_BY_BOUNDS); } }; } static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> fromExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> nearestToExactFps(int fps); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithHighestFps(); static SelectorFunction<Collection<Range<Integer>>, Range<Integer>> rangeWithLowestFps(); }### Answer:
@Test public void rangeWithLowestFps() throws Exception { List<Range<Integer>> availableRanges = Arrays.<Range<Integer>>asList( Ranges.continuousRange(24000, 30000), Ranges.continuousRange(30000, 34000), Ranges.continuousRange(30000, 36000) ); Range<Integer> result = PreviewFpsRangeSelectors .rangeWithLowestFps() .select(availableRanges); assertEquals( Ranges.continuousRange(24000, 30000), result ); }
|
### Question:
Selectors { @SafeVarargs public static <Input, Output> SelectorFunction<Input, Output> firstAvailable(@NonNull final SelectorFunction<Input, Output> function, final SelectorFunction<Input, Output>... functions) { return new SelectorFunction<Input, Output>() { @SuppressWarnings("unchecked") @Override public Output select(Input input) { Output result = function.select(input); if (result != null) { return result; } for (SelectorFunction<Input, Output> selectorFunction : functions) { result = selectorFunction.select(input); if (result != null) { return result; } } return null; } }; } @SafeVarargs static SelectorFunction<Input, Output> firstAvailable(@NonNull final SelectorFunction<Input, Output> function,
final SelectorFunction<Input, Output>... functions); static SelectorFunction<Collection<T>, T> filtered(@NonNull final SelectorFunction<Collection<T>, T> selector,
@NonNull final Predicate<T> predicate); static SelectorFunction<Collection<T>, T> single(final T preference); static SelectorFunction<Input, Output> nothing(); }### Answer:
@Test public void firstAvailable() throws Exception { List<String> options = asList("B", "C"); given(functionA.select(options)) .willReturn(null); given(functionB.select(options)) .willReturn("B"); String result = Selectors .firstAvailable( functionA, functionB ) .select(options); assertEquals("B", result); }
|
### Question:
Selectors { public static <T> SelectorFunction<Collection<T>, T> filtered(@NonNull final SelectorFunction<Collection<T>, T> selector, @NonNull final Predicate<T> predicate) { return new SelectorFunction<Collection<T>, T>() { @Override public T select(Collection<T> items) { return selector.select( filteredItems(items, predicate) ); } }; } @SafeVarargs static SelectorFunction<Input, Output> firstAvailable(@NonNull final SelectorFunction<Input, Output> function,
final SelectorFunction<Input, Output>... functions); static SelectorFunction<Collection<T>, T> filtered(@NonNull final SelectorFunction<Collection<T>, T> selector,
@NonNull final Predicate<T> predicate); static SelectorFunction<Collection<T>, T> single(final T preference); static SelectorFunction<Input, Output> nothing(); }### Answer:
@Test public void filtered() throws Exception { SelectorFunction<Collection<String>, String> function = Selectors.filtered( functionA, new Predicate<String>() { @Override public boolean condition(@Nullable String value) { return value != null && value.startsWith("A"); } } ); given(functionA.select(ArgumentMatchers.<String>anyCollection())) .willReturn("A"); String result = function.select(asList("A", "B", "AB")); assertEquals("A", result); verify(functionA).select(asSet("A", "AB")); }
|
### Question:
Selectors { public static <T> SelectorFunction<Collection<T>, T> single(final T preference) { return new SelectorFunction<Collection<T>, T>() { @Override public T select(Collection<T> items) { return items.contains(preference) ? preference : null; } }; } @SafeVarargs static SelectorFunction<Input, Output> firstAvailable(@NonNull final SelectorFunction<Input, Output> function,
final SelectorFunction<Input, Output>... functions); static SelectorFunction<Collection<T>, T> filtered(@NonNull final SelectorFunction<Collection<T>, T> selector,
@NonNull final Predicate<T> predicate); static SelectorFunction<Collection<T>, T> single(final T preference); static SelectorFunction<Input, Output> nothing(); }### Answer:
@Test public void single() throws Exception { String result = Selectors .single("b") .select(asList( "a", "b", "c" )); assertEquals("b", result); }
@Test public void single_NotFound() throws Exception { String result = Selectors .single("b") .select(asList( "a", "c" )); assertEquals(null, result); }
|
### Question:
Selectors { public static <Input, Output> SelectorFunction<Input, Output> nothing() { return new SelectorFunction<Input, Output>() { @Override public Output select(Input input) { return null; } }; } @SafeVarargs static SelectorFunction<Input, Output> firstAvailable(@NonNull final SelectorFunction<Input, Output> function,
final SelectorFunction<Input, Output>... functions); static SelectorFunction<Collection<T>, T> filtered(@NonNull final SelectorFunction<Collection<T>, T> selector,
@NonNull final Predicate<T> predicate); static SelectorFunction<Collection<T>, T> single(final T preference); static SelectorFunction<Input, Output> nothing(); }### Answer:
@Test public void nothing() throws Exception { String result = Selectors.<Collection<String>, String>nothing() .select(asList("A", "B", "C")); assertNull(result); }
|
### Question:
AspectRatioSelectors { public static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector) { return aspectRatio(4f / 3f, selector); } static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio, SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio,
SelectorFunction<Collection<Size>, Size> selector); }### Answer:
@Test public void standardRatio() throws Exception { given(sizeSelector.select(ArgumentMatchers.<Size>anyCollection())) .willReturn(new Size(4, 3)); Size result = AspectRatioSelectors .standardRatio(sizeSelector) .select(asList( new Size(4, 3), new Size(8, 6), new Size(10, 10) )); assertEquals( new Size(4, 3), result ); verify(sizeSelector).select(asSet( new Size(4, 3), new Size(8, 6) )); }
@Test public void standardRatioWithTolerance() throws Exception { given(sizeSelector.select(ArgumentMatchers.<Size>anyCollection())) .willReturn(new Size(400, 300)); Size result = AspectRatioSelectors .standardRatio(sizeSelector, 0.1) .select(asList( new Size(400, 300), new Size(410, 300), new Size(800, 600), new Size(790, 600), new Size(100, 100), new Size(160, 90) )); assertEquals( new Size(400, 300), result ); verify(sizeSelector).select(asSet( new Size(400, 300), new Size(410, 300), new Size(800, 600), new Size(790, 600) )); }
|
### Question:
AspectRatioSelectors { public static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector) { return aspectRatio(16f / 9f, selector); } static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio, SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio,
SelectorFunction<Collection<Size>, Size> selector); }### Answer:
@Test public void wideRatio() throws Exception { given(sizeSelector.select(ArgumentMatchers.<Size>anyCollection())) .willReturn(new Size(16, 9)); Size result = AspectRatioSelectors .wideRatio(sizeSelector) .select(asList( new Size(16, 9), new Size(32, 18), new Size(10, 10) )); assertEquals( new Size(16, 9), result ); verify(sizeSelector).select(asSet( new Size(16, 9), new Size(32, 18) )); }
@Test public void wideRatioWithTolerance() throws Exception { given(sizeSelector.select(ArgumentMatchers.<Size>anyCollection())) .willReturn(new Size(16, 9)); Size result = AspectRatioSelectors .wideRatio(sizeSelector, 0.1) .select(asList( new Size(16, 9), new Size(16, 10), new Size(32, 18), new Size(32, 20), new Size(10, 10) )); assertEquals( new Size(16, 9), result ); verify(sizeSelector).select(asSet( new Size(16, 9), new Size(16, 10), new Size(32, 18), new Size(32, 20) )); }
|
### Question:
AspectRatioSelectors { public static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio, SelectorFunction<Collection<Size>, Size> selector, double tolerance) { return Selectors.filtered( selector, new AspectRatioPredicate(aspectRatio, tolerance) ); } static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> standardRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector); static SelectorFunction<Collection<Size>, Size> wideRatio(SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio, SelectorFunction<Collection<Size>, Size> selector, double tolerance); static SelectorFunction<Collection<Size>, Size> aspectRatio(float aspectRatio,
SelectorFunction<Collection<Size>, Size> selector); }### Answer:
@Test public void ratioWithTolerance() throws Exception { given(sizeSelector.select(ArgumentMatchers.<Size>anyCollection())) .willReturn(new Size(110, 100)); Size result = AspectRatioSelectors .aspectRatio(1.0f, sizeSelector, 0.1) .select(asList( new Size(16, 9), new Size(110, 100), new Size(105, 100), new Size(95, 100), new Size(90, 100), new Size(4, 3), new Size(20, 10) )); assertEquals( new Size(110, 100), result ); verify(sizeSelector).select(asSet( new Size(110, 100), new Size(105, 100), new Size(95, 100), new Size(90, 100) )); }
@Test public void ratioWithNegativeToleranceThrows() throws Exception { final double NEGATIVE_TOLERANCE = -0.1; final double ABOVE_RANGE_TOLERANCE = 1.1; try { AspectRatioSelectors .aspectRatio(1.0f, sizeSelector, NEGATIVE_TOLERANCE) .select(asList( new Size(16, 9), new Size(16, 10))); fail("Negative aspect ratio tolerance is illegal"); } catch (IllegalArgumentException ex) { } try { AspectRatioSelectors .aspectRatio(1.0f, sizeSelector, ABOVE_RANGE_TOLERANCE) .select(asList( new Size(16, 9), new Size(16, 10))); fail("Aspect ratio tolerance >1.0 is illegal"); } catch (IllegalArgumentException ex) { } }
|
### Question:
FocusModeSelectors { public static SelectorFunction<Collection<FocusMode>, FocusMode> continuousFocus() { return focusMode(FocusMode.CONTINUOUS_FOCUS); } static SelectorFunction<Collection<FocusMode>, FocusMode> fixed(); static SelectorFunction<Collection<FocusMode>, FocusMode> infinity(); static SelectorFunction<Collection<FocusMode>, FocusMode> macro(); static SelectorFunction<Collection<FocusMode>, FocusMode> autoFocus(); static SelectorFunction<Collection<FocusMode>, FocusMode> continuousFocus(); static SelectorFunction<Collection<FocusMode>, FocusMode> edof(); }### Answer:
@Test public void focusMode_Available() throws Exception { Set<FocusMode> availableModes = asSet( FocusMode.AUTO, FocusMode.CONTINUOUS_FOCUS, FocusMode.FIXED ); FocusMode result = FocusModeSelectors .continuousFocus() .select(availableModes); assertEquals( FocusMode.CONTINUOUS_FOCUS, result ); }
@Test public void focusMode_NotAvailable() throws Exception { Set<FocusMode> availableModes = asSet( FocusMode.AUTO, FocusMode.FIXED ); FocusMode result = FocusModeSelectors .continuousFocus() .select(availableModes); assertNull(result); }
|
### Question:
Fotoapparat { public CapabilitiesResult getCapabilities() { ensureStarted(); return capabilitiesProvider.getCapabilities(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void getCapabilities() throws Exception { given(capabilitiesProvider.getCapabilities()) .willReturn(CAPABILITIES_RESULT); testee.start(); CapabilitiesResult result = testee.getCapabilities(); assertEquals( CAPABILITIES_RESULT, result ); }
@Test(expected = IllegalStateException.class) public void getCapabilities_NotStartedYet() throws Exception { testee.getCapabilities(); }
|
### Question:
SizeSelectors { public static SelectorFunction<Collection<Size>, Size> biggestSize() { return new SelectorFunction<Collection<Size>, Size>() { @Override public Size select(Collection<Size> items) { if (items.isEmpty()) { return null; } return Collections.max(items, COMPARATOR_BY_AREA); } }; } static SelectorFunction<Collection<Size>, Size> biggestSize(); static SelectorFunction<Collection<Size>, Size> smallestSize(); }### Answer:
@Test public void biggestSize() throws Exception { List<Size> availableSizes = asList( new Size(4032, 3024), new Size(7680, 4320), new Size(1280, 720) ); Size result = SizeSelectors .biggestSize() .select(availableSizes); assertEquals( new Size(7680, 4320), result ); }
@Test public void bigestSize_EmptyList() throws Exception { Size result = SizeSelectors .biggestSize() .select(Collections.<Size>emptyList()); assertNull(result); }
|
### Question:
SizeSelectors { public static SelectorFunction<Collection<Size>, Size> smallestSize() { return new SelectorFunction<Collection<Size>, Size>() { @Override public Size select(Collection<Size> items) { if (items.isEmpty()) { return null; } return Collections.min(items, COMPARATOR_BY_AREA); } }; } static SelectorFunction<Collection<Size>, Size> biggestSize(); static SelectorFunction<Collection<Size>, Size> smallestSize(); }### Answer:
@Test public void smallestSize() throws Exception { List<Size> availableSizes = asList( new Size(4032, 3024), new Size(7680, 4320), new Size(1280, 720) ); Size result = SizeSelectors .smallestSize() .select(availableSizes); assertEquals( new Size(1280, 720), result ); }
@Test public void smallestSize_EmptyList() throws Exception { Size result = SizeSelectors .smallestSize() .select(Collections.<Size>emptyList()); assertNull(result); }
|
### Question:
ParametersFactory { public static Parameters selectPictureSize(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Collection<Size>, Size> selector) { return new Parameters().putValue( Parameters.Type.PICTURE_SIZE, selector.select( capabilities.supportedPictureSizes() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectPictureSize() throws Exception { Size size = new Size(100, 100); Parameters result = ParametersFactory.selectPictureSize(CAPABILITIES, selectFromCollection(size)); assertEquals( new Parameters().putValue(Parameters.Type.PICTURE_SIZE, size), result ); }
|
### Question:
ParametersFactory { public static Parameters selectPreviewSize(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Collection<Size>, Size> selector) { return new Parameters().putValue( Parameters.Type.PREVIEW_SIZE, selector.select( capabilities.supportedPreviewSizes() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectPreviewSize() throws Exception { Size size = new Size(100, 100); Parameters result = ParametersFactory.selectPreviewSize(CAPABILITIES, selectFromCollection(size)); assertEquals( new Parameters().putValue(Parameters.Type.PREVIEW_SIZE, size), result ); }
|
### Question:
ParametersFactory { public static Parameters selectFocusMode(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector) { return new Parameters().putValue( Parameters.Type.FOCUS_MODE, selector.select( capabilities.supportedFocusModes() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectFocusMode() throws Exception { FocusMode focusMode = FocusMode.AUTO; Parameters result = ParametersFactory.selectFocusMode(CAPABILITIES, selectFromCollection(focusMode)); assertEquals( new Parameters().putValue(Parameters.Type.FOCUS_MODE, focusMode), result ); }
|
### Question:
ParametersFactory { public static Parameters selectFlashMode(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Collection<Flash>, Flash> selector) { return new Parameters().putValue( Parameters.Type.FLASH, selector.select( capabilities.supportedFlashModes() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectFlashMode() throws Exception { Flash flash = Flash.AUTO; Parameters result = ParametersFactory.selectFlashMode(CAPABILITIES, selectFromCollection(flash)); assertEquals( new Parameters().putValue(Parameters.Type.FLASH, flash), result ); }
|
### Question:
ParametersFactory { public static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector) { return new Parameters().putValue( Parameters.Type.PREVIEW_FPS_RANGE, selector.select( capabilities.supportedPreviewFpsRanges() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectPreviewFpsRange() throws Exception { Range<Integer> range = Ranges.continuousRange(30000, 30000); Parameters result = ParametersFactory.selectPreviewFpsRange(CAPABILITIES, selectFromCollection(range)); assertEquals( new Parameters().putValue(Parameters.Type.PREVIEW_FPS_RANGE, range), result ); }
|
### Question:
Fotoapparat { public PhotoResult takePicture() { ensureStarted(); return takePictureRoutine.takePicture(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void takePicture() throws Exception { given(takePictureRoutine.takePicture()) .willReturn(PHOTO_RESULT); testee.start(); PhotoResult result = testee.takePicture(); assertEquals( PHOTO_RESULT, result ); }
@Test(expected = IllegalStateException.class) public void takePicture_NotStartedYet() throws Exception { testee.takePicture(); }
|
### Question:
ParametersFactory { public static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities, @NonNull SelectorFunction<Range<Integer>, Integer> selector) { return new Parameters().putValue( Parameters.Type.SENSOR_SENSITIVITY, selector.select( capabilities.supportedSensorSensitivityRange() ) ); } static Parameters selectPictureSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectPreviewSize(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Size>, Size> selector); static Parameters selectFocusMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); static Parameters selectFlashMode(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Flash>, Flash> selector); static Parameters selectPreviewFpsRange(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); static Parameters selectSensorSensitivity(@NonNull Capabilities capabilities,
@NonNull SelectorFunction<Range<Integer>, Integer> selector); static Parameters selectJpegQuality(@NonNull Integer jpegQuality); }### Answer:
@Test public void selectSensorSensitivity() throws Exception { Integer isoValue = 1200; Parameters result = ParametersFactory.selectSensorSensitivity(CAPABILITIES, TestSelectors.<Range<Integer>, Integer>select(isoValue)); assertEquals( new Parameters().putValue(Parameters.Type.SENSOR_SENSITIVITY, isoValue), result ); }
|
### Question:
InitialParametersProvider { static SelectorFunction<Collection<Size>, Size> validPreviewSizeSelector(Size photoSize, SelectorFunction<Collection<Size>, Size> original) { return Selectors .firstAvailable( previewWithSameAspectRatio(photoSize, original), original ); } InitialParametersProvider(CapabilitiesOperator capabilitiesOperator,
SelectorFunction<Collection<Size>, Size> photoSizeSelector,
SelectorFunction<Collection<Size>, Size> previewSizeSelector,
SelectorFunction<Collection<FocusMode>, FocusMode> focusModeSelector,
SelectorFunction<Collection<Flash>, Flash> flashSelector,
SelectorFunction<Collection<Range<Integer>>, Range<Integer>> previewFpsRangeSelector,
SelectorFunction<Range<Integer>, Integer> sensorSensitivitySelector,
Integer jpegQuality,
InitialParametersValidator parametersValidator); Parameters initialParameters(); }### Answer:
@Test public void validPreviewSizeSelector_WithValidAspectRatio() throws Exception { Size result = InitialParametersProvider .validPreviewSizeSelector( PHOTO_SIZE, selectFromCollection(PREVIEW_SIZE) ) .select(ALL_PREVIEW_SIZES); assertEquals( PREVIEW_SIZE, result ); }
@Test public void validPreviewSizeSelector_NoPreviewSizeWithSameAspectRatio() throws Exception { Size photoSize = new Size(10000, 100); Size result = InitialParametersProvider .validPreviewSizeSelector( photoSize, selectFromCollection(PREVIEW_SIZE) ) .select(ALL_PREVIEW_SIZES); assertEquals( PREVIEW_SIZE, result ); }
|
### Question:
InitialParametersProvider { public Parameters initialParameters() { Capabilities capabilities = capabilitiesOperator.getCapabilities(); Parameters parameters = combineParameters(asList( pictureSizeParameters(capabilities), previewSizeParameters(capabilities), focusModeParameters(capabilities), flashModeParameters(capabilities), previewFpsRange(capabilities), sensorSensitivity(capabilities), jpegQuality() )); parametersValidator.validate(parameters); return parameters; } InitialParametersProvider(CapabilitiesOperator capabilitiesOperator,
SelectorFunction<Collection<Size>, Size> photoSizeSelector,
SelectorFunction<Collection<Size>, Size> previewSizeSelector,
SelectorFunction<Collection<FocusMode>, FocusMode> focusModeSelector,
SelectorFunction<Collection<Flash>, Flash> flashSelector,
SelectorFunction<Collection<Range<Integer>>, Range<Integer>> previewFpsRangeSelector,
SelectorFunction<Range<Integer>, Integer> sensorSensitivitySelector,
Integer jpegQuality,
InitialParametersValidator parametersValidator); Parameters initialParameters(); }### Answer:
@Test public void initialParameters() throws Exception { given(capabilitiesOperator.getCapabilities()) .willReturn(new Capabilities( asSet(PHOTO_SIZE), ALL_PREVIEW_SIZES, asSet(FocusMode.AUTO), asSet(Flash.TORCH), PREVIEW_FPS_RANGES, SENSOR_SENSITIVITY_RANGE, true )); InitialParametersProvider testee = new InitialParametersProvider( capabilitiesOperator, SizeSelectors.biggestSize(), SizeSelectors.biggestSize(), autoFocus(), torch(), PreviewFpsRangeSelectors.rangeWithHighestFps(), SensorSensitivitySelectors.highestSensorSensitivity(), 95, initialParametersValidator ); Parameters parameters = testee.initialParameters(); assertEquals( new Parameters() .putValue( Parameters.Type.PICTURE_SIZE, PHOTO_SIZE ) .putValue( Parameters.Type.PREVIEW_SIZE, PREVIEW_SIZE ) .putValue( Parameters.Type.FOCUS_MODE, FocusMode.AUTO ) .putValue( Parameters.Type.FLASH, Flash.TORCH ) .putValue( Parameters.Type.PREVIEW_FPS_RANGE, PREVIEW_FPS_RANGE ) .putValue( Parameters.Type.SENSOR_SENSITIVITY, SENSOR_SENSITIVITY ) .putValue( Parameters.Type.JPEG_QUALITY, JPEG_QUALITY ), parameters ); verify(initialParametersValidator).validate(parameters); }
|
### Question:
InitialParametersValidator { void validate(Parameters parameters) { validateParameter(parameters, PICTURE_SIZE); validateParameter(parameters, PREVIEW_SIZE); validateParameter(parameters, FOCUS_MODE); validateParameter(parameters, FLASH); } }### Answer:
@Test(expected = IllegalArgumentException.class) public void noPictureSize() throws Exception { parameters.putValue(PICTURE_SIZE, null); testee.validate(parameters); }
@Test(expected = IllegalArgumentException.class) public void noPreviewSize() throws Exception { parameters.putValue(PREVIEW_SIZE, null); testee.validate(parameters); }
@Test(expected = IllegalArgumentException.class) public void noFocusMode() throws Exception { parameters.putValue(FOCUS_MODE, null); testee.validate(parameters); }
@Test(expected = IllegalArgumentException.class) public void noFlash() throws Exception { parameters.putValue(FLASH, null); testee.validate(parameters); }
|
### Question:
Size { public float getAspectRatio() { if (width == 0 || height == 0) { return Float.NaN; } return (float) width / height; } Size(int width, int height); float getAspectRatio(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); final int width; final int height; }### Answer:
@Test public void getAspectRatio() throws Exception { assertEquals( 2.5f, new Size(250, 100).getAspectRatio(), 1e-6 ); }
@Test public void getAspectRatio_EmptySize() throws Exception { assertEquals( Float.NaN, new Size(0, 0).getAspectRatio(), 1e-6 ); }
|
### Question:
BidirectionalHashMap { public Map<K, V> forward() { return Collections.unmodifiableMap(keyToValue); } BidirectionalHashMap(Map<K, V> keyToValue); Map<K, V> forward(); Map<V, K> reversed(); }### Answer:
@Test public void testForward() throws Exception { BidirectionalHashMap<Integer, String> testee = new BidirectionalHashMap<>(integerStringMap); assertEquals(integerStringMap, testee.forward()); }
|
### Question:
Size { @SuppressWarnings("SuspiciousNameCombination") public Size flip() { return new Size(height, width); } Size(int width, int height); float getAspectRatio(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @SuppressWarnings("SuspiciousNameCombination") Size flip(); final int width; final int height; }### Answer:
@Test public void flip() throws Exception { assertEquals( new Size(10, 20), new Size(20, 10).flip() ); }
|
### Question:
UpdateRequest { public static Builder builder() { return new Builder(); } private UpdateRequest(Builder builder); static Builder builder(); @Nullable
final SelectorFunction<Collection<Flash>, Flash> flashSelector; @Nullable
final SelectorFunction<Collection<FocusMode>, FocusMode> focusModeSelector; }### Answer:
@Test public void build() throws Exception { UpdateRequest updateRequest = UpdateRequest.builder() .flash(flashSelector) .focusMode(focusModeSelector) .build(); assertSame(flashSelector, updateRequest.flashSelector); assertSame(focusModeSelector, updateRequest.focusModeSelector); }
|
### Question:
Photo { public static Photo empty() { return new Photo(new byte[0], 0); } Photo(byte[] encodedImage,
int rotationDegrees); static Photo empty(); @Override boolean equals(Object o); @Override int hashCode(); final byte[] encodedImage; final int rotationDegrees; }### Answer:
@Test public void empty() throws Exception { Photo result = Photo.empty(); assertEquals( 0, result.encodedImage.length ); assertEquals( 0, result.rotationDegrees ); }
|
### Question:
Fotoapparat { public Fotoapparat autoFocus() { focus(); return this; } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void autoFocus() throws Exception { testee.start(); testee.autoFocus(); verify(autoFocusRoutine).autoFocus(); }
@Test(expected = IllegalStateException.class) public void autoFocus_NotStartedYet() throws Exception { testee.autoFocus(); }
|
### Question:
Fotoapparat { public PendingResult<FocusResult> focus() { ensureStarted(); return autoFocusRoutine.autoFocus(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void focus() throws Exception { given(autoFocusRoutine.autoFocus()) .willReturn(FOCUS_RESULT); testee.start(); PendingResult<FocusResult> result = testee.focus(); assertEquals( FOCUS_RESULT, result ); }
@Test(expected = IllegalStateException.class) public void focus_NotStartedYet() throws Exception { testee.focus(); }
|
### Question:
Fotoapparat { public static FotoapparatBuilder with(Context context) { if (context == null) { throw new IllegalStateException("Context is null."); } return new FotoapparatBuilder(context); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test(expected = IllegalStateException.class) public void ensureNonNullContext() throws Exception { Fotoapparat.with(null); }
|
### Question:
Fotoapparat { public boolean isAvailable() { return checkAvailabilityRoutine.isAvailable(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void isAvailable_Yes() throws Exception { given(checkAvailabilityRoutine.isAvailable()) .willReturn(true); boolean result = testee.isAvailable(); assertTrue(result); }
@Test public void isAvailable_No() throws Exception { given(checkAvailabilityRoutine.isAvailable()) .willReturn(false); boolean result = testee.isAvailable(); assertFalse(result); }
|
### Question:
Fotoapparat { public void updateParameters(@NonNull final UpdateRequest updateRequest) { ensureStarted(); executor.execute(new Runnable() { @Override public void run() { updateParametersRoutine.updateParameters(updateRequest); } }); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void updateParameters() throws Exception { UpdateRequest updateRequest = UpdateRequest.builder() .build(); testee.start(); testee.updateParameters(updateRequest); verify(updateParametersRoutine).updateParameters(updateRequest); }
@Test(expected = IllegalStateException.class) public void updateParameters_NotStartedYet() throws Exception { UpdateRequest updateRequest = UpdateRequest.builder() .build(); testee.updateParameters(updateRequest); }
|
### Question:
BidirectionalHashMap { public Map<V, K> reversed() { return Collections.unmodifiableMap(valueToKey); } BidirectionalHashMap(Map<K, V> keyToValue); Map<K, V> forward(); Map<V, K> reversed(); }### Answer:
@Test public void testReverse() throws Exception { HashMap<String, Integer> stringIntegerMap = new HashMap<>(3); stringIntegerMap.put("Hello", 1); stringIntegerMap.put("Hi", 3); stringIntegerMap.put("Hey!", 6); BidirectionalHashMap<Integer, String> testee = new BidirectionalHashMap<>(integerStringMap); assertEquals(stringIntegerMap, testee.reversed()); }
|
### Question:
Fotoapparat { public ParametersResult getCurrentParameters() { ensureStarted(); return currentParametersProvider.getParameters(); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void getCurrentParameters() throws Exception { given(currentParametersProvider.getParameters()) .willReturn(PARAMETERS_RESULT); testee.start(); ParametersResult retrievedParams = testee.getCurrentParameters(); assertEquals(PARAMETERS_RESULT, retrievedParams); }
@Test(expected = IllegalStateException.class) public void getCurrentParameters_NotStartedYet() throws Exception { testee.getCurrentParameters(); }
|
### Question:
Fotoapparat { public void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel) { ensureStarted(); executor.execute(new Runnable() { @Override public void run() { updateZoomLevelRoutine.updateZoomLevel(zoomLevel); } }); } Fotoapparat(StartCameraRoutine startCameraRoutine,
StopCameraRoutine stopCameraRoutine,
UpdateOrientationRoutine updateOrientationRoutine,
ConfigurePreviewStreamRoutine configurePreviewStreamRoutine,
CapabilitiesProvider capabilitiesProvider,
CurrentParametersProvider parametersProvider,
TakePictureRoutine takePictureRoutine,
AutoFocusRoutine autoFocusRoutine,
CheckAvailabilityRoutine checkAvailabilityRoutine,
UpdateParametersRoutine updateParametersRoutine,
UpdateZoomLevelRoutine updateZoomLevelRoutine,
Executor executor); static FotoapparatBuilder with(Context context); boolean isAvailable(); CapabilitiesResult getCapabilities(); ParametersResult getCurrentParameters(); PhotoResult takePicture(); Fotoapparat autoFocus(); PendingResult<FocusResult> focus(); void updateParameters(@NonNull final UpdateRequest updateRequest); void setZoom(@FloatRange(from = 0f, to = 1f) final float zoomLevel); void start(); void stop(); }### Answer:
@Test public void setZoom() throws Exception { testee.start(); testee.setZoom(0.5f); verify(updateZoomLevelRoutine).updateZoomLevel(0.5f); }
@Test(expected = IllegalStateException.class) public void setZoom_NotStartedYet() throws Exception { testee.setZoom(1f); }
|
### Question:
FotoapparatSwitcher { public void start() { fotoapparat.start(); started = true; } private FotoapparatSwitcher(@NonNull Fotoapparat fotoapparat); static FotoapparatSwitcher withDefault(@NonNull Fotoapparat fotoapparat); void start(); void stop(); void switchTo(@NonNull Fotoapparat fotoapparat); @NonNull Fotoapparat getCurrentFotoapparat(); }### Answer:
@Test public void start_Default() throws Exception { testee.start(); verify(fotoapparatA).start(); }
|
### Question:
FotoapparatSwitcher { public void stop() { fotoapparat.stop(); started = false; } private FotoapparatSwitcher(@NonNull Fotoapparat fotoapparat); static FotoapparatSwitcher withDefault(@NonNull Fotoapparat fotoapparat); void start(); void stop(); void switchTo(@NonNull Fotoapparat fotoapparat); @NonNull Fotoapparat getCurrentFotoapparat(); }### Answer:
@Test public void stop_Default() throws Exception { testee.stop(); verify(fotoapparatA).stop(); }
|
### Question:
FotoapparatSwitcher { @NonNull public Fotoapparat getCurrentFotoapparat() { return fotoapparat; } private FotoapparatSwitcher(@NonNull Fotoapparat fotoapparat); static FotoapparatSwitcher withDefault(@NonNull Fotoapparat fotoapparat); void start(); void stop(); void switchTo(@NonNull Fotoapparat fotoapparat); @NonNull Fotoapparat getCurrentFotoapparat(); }### Answer:
@Test public void getCurrentFotoapparat() throws Exception { Fotoapparat result = testee.getCurrentFotoapparat(); assertSame(fotoapparatA, result); }
|
### Question:
FotoapparatSwitcher { public void switchTo(@NonNull Fotoapparat fotoapparat) { if (started) { this.fotoapparat.stop(); fotoapparat.start(); } this.fotoapparat = fotoapparat; } private FotoapparatSwitcher(@NonNull Fotoapparat fotoapparat); static FotoapparatSwitcher withDefault(@NonNull Fotoapparat fotoapparat); void start(); void stop(); void switchTo(@NonNull Fotoapparat fotoapparat); @NonNull Fotoapparat getCurrentFotoapparat(); }### Answer:
@Test public void switchTo() throws Exception { testee.switchTo(fotoapparatB); Fotoapparat result = testee.getCurrentFotoapparat(); assertSame(fotoapparatB, result); verifyZeroInteractions(fotoapparatA); verifyZeroInteractions(fotoapparatB); }
|
### Question:
TakePictureRoutine { public PhotoResult takePicture() { TakePictureTask takePictureTask = new TakePictureTask(cameraDevice); cameraExecutor.execute(takePictureTask); return PhotoResult.fromFuture(takePictureTask); } TakePictureRoutine(CameraDevice cameraDevice,
Executor cameraExecutor); PhotoResult takePicture(); }### Answer:
@Test public void takePicture_EmptyRequest() throws Exception { PhotoResult result = testee.takePicture(); verify(executor).execute(isA(TakePictureTask.class)); assertNotNull(result); }
|
### Question:
TakePictureTask extends FutureTask<Photo> { private static FocusResult autoFocus(CameraDevice cameraDevice) { int focusAttempts = 0; FocusResult focusResult = FocusResult.none(); while (focusAttempts < MAX_FOCUS_ATTEMPTS && !focusResult.succeeded) { focusResult = cameraDevice.autoFocus(); focusAttempts++; } return focusResult; } TakePictureTask(final CameraDevice cameraDevice); }### Answer:
@Test public void noFocusAfter3Attempts_takePicture() throws Exception { given(cameraDevice.autoFocus()) .willReturn(new FocusResult(false, true)); Photo result = resultOf(testee); InOrder inOrder = inOrder(cameraDevice); inOrder.verify(cameraDevice, times(3)).autoFocus(); inOrder.verify(cameraDevice).takePicture(); inOrder.verify(cameraDevice).startPreview(); assertEquals(result, PHOTO); }
@Test public void exposureMeasurementRequired_takePhoto() throws Exception { given(cameraDevice.autoFocus()) .willReturn(new FocusResult(true, true)); Photo result = resultOf(testee); InOrder inOrder = inOrder(cameraDevice); inOrder.verify(cameraDevice).autoFocus(); inOrder.verify(cameraDevice).measureExposure(); inOrder.verify(cameraDevice).takePicture(); inOrder.verify(cameraDevice).startPreview(); assertEquals(result, PHOTO); }
@Test public void takePhoto() throws Exception { given(cameraDevice.autoFocus()) .willReturn(new FocusResult(true, false)); Photo result = resultOf(testee); InOrder inOrder = inOrder(cameraDevice); inOrder.verify(cameraDevice).autoFocus(); inOrder.verify(cameraDevice).takePicture(); inOrder.verify(cameraDevice).startPreview(); assertEquals(result, PHOTO); }
@Test public void doNotFocusInContinuousFocusMode() throws Exception { given(cameraDevice.getCurrentParameters()) .willReturn(PARAMETERS_WITH_CONTINUOUS_FOCUS); Photo result = resultOf(testee); verify(cameraDevice, never()).autoFocus(); assertEquals(result, PHOTO); }
@Test public void startPreviewFailed() throws Exception { given(cameraDevice.autoFocus()) .willReturn(new FocusResult(true, false)); doThrow(new CameraException("test")) .when(cameraDevice) .startPreview(); Photo result = resultOf(testee); verify(cameraDevice).startPreview(); assertEquals(result, PHOTO); }
|
### Question:
SaveToFileTransformer implements Transformer<Photo, Void> { @Override public Void transform(Photo input) { BufferedOutputStream outputStream = outputStream(); try { saveImage(input, outputStream); exifOrientationWriter.writeExifOrientation(file, input); } catch (IOException e) { throw new FileSaveException(e); } return null; } SaveToFileTransformer(File file,
ExifOrientationWriter exifOrientationWriter); static SaveToFileTransformer create(File file); @Override Void transform(Photo input); }### Answer:
@Test public void savePhoto() throws Exception { Photo photo = new Photo( new byte[]{1, 2, 3}, 0 ); testee.transform(photo); assertTrue(FILE.exists()); assertEquals( photo.encodedImage.length, FILE.length() ); verify(exifOrientationWriter).writeExifOrientation(FILE, photo); }
|
### Question:
StartCameraRoutine implements Runnable { @Override public void run() { try { tryToStartCamera(); } catch (CameraException e) { cameraErrorCallback.onError(e); } } StartCameraRoutine(CameraDevice cameraDevice,
CameraRenderer cameraRenderer,
ScaleType scaleType,
SelectorFunction<Collection<LensPosition>, LensPosition> lensPositionSelector,
ScreenOrientationProvider screenOrientationProvider,
InitialParametersProvider initialParametersProvider,
CameraErrorCallback cameraErrorCallback); @Override void run(); }### Answer:
@Test public void routine() throws Exception { StartCameraRoutine testee = new StartCameraRoutine( cameraDevice, cameraRenderer, ScaleType.CENTER_INSIDE, lensPositionSelector, screenOrientationProvider, initialParametersProvider, cameraErrorCallback ); List<LensPosition> availableLensPositions = asList( LensPosition.FRONT, LensPosition.BACK ); LensPosition preferredLensPosition = LensPosition.FRONT; ScaleType scaleType = ScaleType.CENTER_INSIDE; givenLensPositionsAvailable(availableLensPositions); givenPositionSelected(preferredLensPosition); givenScreenRotation(); givenInitialParametersAvailable(); testee.run(); InOrder inOrder = inOrder( cameraDevice, cameraRenderer, lensPositionSelector ); inOrder.verify(lensPositionSelector).select(availableLensPositions); inOrder.verify(cameraDevice).open(preferredLensPosition); inOrder.verify(cameraDevice).updateParameters(INITIAL_PARAMETERS); inOrder.verify(cameraDevice).setDisplayOrientation(SCREEN_ROTATION_DEGREES); inOrder.verify(cameraRenderer).setScaleType(scaleType); inOrder.verify(cameraRenderer).attachCamera(cameraDevice); inOrder.verify(cameraDevice).startPreview(); verifyZeroInteractions(cameraErrorCallback); }
@Test public void failedToOpenCamera() throws Exception { List<LensPosition> availableLensPositions = asList( LensPosition.FRONT, LensPosition.BACK ); LensPosition preferredLensPosition = LensPosition.FRONT; givenLensPositionsAvailable(availableLensPositions); givenPositionSelected(preferredLensPosition); doThrow(CAMERA_EXCEPTION) .when(cameraDevice) .open(preferredLensPosition); testee.run(); verify(cameraErrorCallback).onError(CAMERA_EXCEPTION); verify(cameraDevice).getAvailableLensPositions(); verify(cameraDevice).open(preferredLensPosition); verifyNoMoreInteractions(cameraDevice); }
|
### Question:
UpdateOrientationRoutine implements OrientationSensor.Listener { public void start() { orientationSensor.start(this); } UpdateOrientationRoutine(CameraDevice cameraDevice,
OrientationSensor orientationSensor,
Executor cameraExecutor,
Logger logger); void start(); void stop(); @Override void onOrientationChanged(final int degrees); }### Answer:
@Test public void start() throws Exception { testee.start(); verify(orientationSensor).start(testee); verifyZeroInteractions(logger); }
|
### Question:
UpdateOrientationRoutine implements OrientationSensor.Listener { public void stop() { orientationSensor.stop(); } UpdateOrientationRoutine(CameraDevice cameraDevice,
OrientationSensor orientationSensor,
Executor cameraExecutor,
Logger logger); void start(); void stop(); @Override void onOrientationChanged(final int degrees); }### Answer:
@Test public void stop() throws Exception { testee.stop(); verify(orientationSensor).stop(); verifyZeroInteractions(logger); }
|
### Question:
UpdateOrientationRoutine implements OrientationSensor.Listener { @Override public void onOrientationChanged(final int degrees) { cameraExecutor.execute(new Runnable() { @Override public void run() { try { cameraDevice.setDisplayOrientation(degrees); } catch (RuntimeException e) { logger.log("Failed to perform cameraDevice.setDisplayOrientation(" + degrees + ") e: " + e.getMessage()); } } }); } UpdateOrientationRoutine(CameraDevice cameraDevice,
OrientationSensor orientationSensor,
Executor cameraExecutor,
Logger logger); void start(); void stop(); @Override void onOrientationChanged(final int degrees); }### Answer:
@Test public void onOrientationChanged() throws Exception { testee.onOrientationChanged(90); verify(cameraDevice).setDisplayOrientation(90); verifyZeroInteractions(logger); }
@Test public void onOrientationChangedFailed() throws Exception { RuntimeException exception = new RuntimeException("test"); doThrow(exception) .when(cameraDevice) .setDisplayOrientation(anyInt()); testee.onOrientationChanged(90); verify(cameraDevice).setDisplayOrientation(90); verify(logger).log(anyString()); }
|
### Question:
SizeTransformers { public static Transformer<Size, Size> originalSize() { return new Transformer<Size, Size>() { @Override public Size transform(Size input) { return input; } }; } static Transformer<Size, Size> originalSize(); static Transformer<Size, Size> scaled(final float scaleFactor); }### Answer:
@Test public void originalSize() throws Exception { assertEquals( new Size(100, 200), SizeTransformers.originalSize().transform(new Size(100, 200)) ); }
|
### Question:
AutoFocusRoutine { public PendingResult<FocusResult> autoFocus() { AutoFocusTask autoFocusTask = new AutoFocusTask(cameraDevice); cameraExecutor.execute(autoFocusTask); return PendingResult.fromFuture(autoFocusTask); } AutoFocusRoutine(CameraDevice cameraDevice,
Executor cameraExecutor); PendingResult<FocusResult> autoFocus(); }### Answer:
@Test public void autoFocus() throws Exception { PendingResult<FocusResult> result = testee.autoFocus(); verify(executor).execute(isA(AutoFocusTask.class)); assertNotNull(result); }
|
### Question:
UpdateZoomLevelRoutine { public void updateZoomLevel(@FloatRange(from = 0f, to = 1f) float zoomLevel) { ensureInBounds(zoomLevel); if (cameraDevice.getCapabilities().isZoomSupported()) { cameraDevice.setZoom(zoomLevel); } } UpdateZoomLevelRoutine(CameraDevice cameraDevice); void updateZoomLevel(@FloatRange(from = 0f, to = 1f) float zoomLevel); }### Answer:
@SuppressWarnings("Range") @Test(expected = LevelOutOfRangeException.class) public void outOfRange_Higher() throws Exception { testee.updateZoomLevel(1.1f); }
@SuppressWarnings("Range") @Test(expected = LevelOutOfRangeException.class) public void outOfRange_Lower() throws Exception { testee.updateZoomLevel(-0.1f); }
@Test public void updateZoomLevel() throws Exception { givenZoomSupported(); testee.updateZoomLevel(0.5f); verify(cameraDevice).setZoom(0.5f); }
@Test public void zoomNotSupported() throws Exception { givenZoomNotSupported(); testee.updateZoomLevel(0.5f); verify(cameraDevice, never()).setZoom(anyFloat()); }
|
### Question:
StopCameraRoutine implements Runnable { @Override public void run() { cameraDevice.stopPreview(); cameraDevice.close(); } StopCameraRoutine(CameraDevice cameraDevice); @Override void run(); }### Answer:
@Test public void stop() throws Exception { testee.run(); InOrder inOrder = inOrder(cameraDevice); inOrder.verify(cameraDevice).stopPreview(); inOrder.verify(cameraDevice).close(); }
|
### Question:
ConfigurePreviewStreamRoutine implements Runnable { @Override public void run() { if (frameProcessor == null) { return; } PreviewStream previewStream = cameraDevice.getPreviewStream(); previewStream.addProcessor(frameProcessor); previewStream.start(); } ConfigurePreviewStreamRoutine(CameraDevice cameraDevice,
FrameProcessor frameProcessor); @Override void run(); }### Answer:
@Test public void configurePreview() throws Exception { testee.run(); InOrder inOrder = inOrder(previewStream); inOrder.verify(previewStream).addProcessor(frameProcessor); inOrder.verify(previewStream).start(); }
@Test public void noFrameProcessor() throws Exception { ConfigurePreviewStreamRoutine testee = new ConfigurePreviewStreamRoutine( cameraDevice, null ); testee.run(); verifyZeroInteractions(previewStream); }
|
### Question:
CheckAvailabilityRoutine { public boolean isAvailable() { return selectedLensPosition() != null; } CheckAvailabilityRoutine(CameraDevice cameraDevice,
SelectorFunction<Collection<LensPosition>, LensPosition> lensPositionSelector); boolean isAvailable(); }### Answer:
@Test public void available() throws Exception { givenLensPositionsAreReturned(); given(lensPositionSelector.select(LENS_POSITIONS)) .willReturn(LensPosition.FRONT); boolean result = testee.isAvailable(); assertTrue(result); }
@Test public void notAvailable() throws Exception { givenLensPositionsAreReturned(); given(lensPositionSelector.select(LENS_POSITIONS)) .willReturn(null); boolean result = testee.isAvailable(); assertFalse(result); }
|
### Question:
SizeTransformers { public static Transformer<Size, Size> scaled(final float scaleFactor) { return new Transformer<Size, Size>() { @Override public Size transform(Size input) { return new Size( (int) (input.width * scaleFactor), (int) (input.height * scaleFactor) ); } }; } static Transformer<Size, Size> originalSize(); static Transformer<Size, Size> scaled(final float scaleFactor); }### Answer:
@Test public void scaled() throws Exception { assertEquals( new Size(50, 100), SizeTransformers.scaled(0.5f).transform(new Size(100, 200)) ); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.