method2testcases
stringlengths 118
3.08k
|
---|
### Question:
EncodeUtils { public static byte[] longToByteArray(long longValue) { ByteBuffer longToByteBuffer = ByteBuffer.allocate(Long.BYTES); longToByteBuffer.putLong(longValue); return longToByteBuffer.array(); } private EncodeUtils(); static byte[] longToByteArray(long longValue); static long byteArrayToLong(byte[] byteArray); }### Answer:
@Test public void longToByteArrayTest() { long value = 1234L; byte[] byteValue = EncodeUtils.longToByteArray(value); assertEquals(8, byteValue.length); assertEquals(-46, byteValue[7]); assertEquals(4, byteValue[6]); } |
### Question:
EncodeUtils { public static long byteArrayToLong(byte[] byteArray) { ByteBuffer byteToLongBuffer = ByteBuffer.allocate(Long.BYTES); byte[] storageBytes = {0,0,0,0,0,0,0,0}; int differenceInSize = storageBytes.length - byteArray.length; for(int i = byteArray.length-1; i >= 0; i--) { if(differenceInSize + i >= 0) storageBytes[differenceInSize + i] = byteArray[i]; } byteToLongBuffer.put(storageBytes); byteToLongBuffer.flip(); return byteToLongBuffer.getLong(); } private EncodeUtils(); static byte[] longToByteArray(long longValue); static long byteArrayToLong(byte[] byteArray); }### Answer:
@Test public void byteArrayToLongTest() { byte[] byteArr = {0,0,0,0,73,-106,2,-46}; long value = EncodeUtils.byteArrayToLong(byteArr); assertEquals(1234567890, value); byte[] byteArr2 = {-24,106,4,-97}; long value2 = EncodeUtils.byteArrayToLong(byteArr2); assertEquals(3899262111L, value2); byte[] byteArr3 = {124,0,0,12,-45,76,-8,-96,1}; long value3 = EncodeUtils.byteArrayToLong(byteArr3); assertEquals(14101668995073L, value3); } |
### Question:
MatrixResponse { public MatrixResponseInfo getResponseInformation() { return responseInformation; } MatrixResponse(MatrixResult result, MatrixRequest request); MatrixResponseInfo getResponseInformation(); MatrixResult getMatrixResult(); MatrixRequest getMatrixRequest(); }### Answer:
@Test public void getResponseInformation() { Assert.assertEquals(MatrixResponseInfo.class, bareMatrixResponse.responseInformation.getClass()); Assert.assertNotNull(bareMatrixResponse.responseInformation); } |
### Question:
JSONBasedIndividualMatrixResponse { List<JSON2DDestinations> constructDestinations(MatrixResult matrixResult) { List<JSON2DDestinations> destinations = new ArrayList<>(); for (ResolvedLocation location : matrixResult.getDestinations()) { if (location != null) destinations.add(new JSON2DDestinations(location, includeResolveLocations)); else destinations.add(null); } return destinations; } JSONBasedIndividualMatrixResponse(MatrixRequest request); }### Answer:
@Test public void constructDestinations() { List<JSON2DDestinations> json2DDestinations = jsonBasedIndividualMatrixResponse.constructDestinations(matrixResult); Assert.assertEquals(1, json2DDestinations.size()); Assert.assertEquals("foo", json2DDestinations.get(0).name); Assert.assertEquals(new Coordinate(8.681495, 49.41461, Double.NaN), json2DDestinations.get(0).location); Double[] location = json2DDestinations.get(0).getLocation(); Assert.assertEquals(2, location.length); Assert.assertEquals(0, location[0].compareTo(8.681495)); Assert.assertEquals(0, location[1].compareTo(49.41461)); } |
### Question:
JSONBasedIndividualMatrixResponse { List<JSON2DSources> constructSources(MatrixResult matrixResult) { List<JSON2DSources> sources = new ArrayList<>(); for (ResolvedLocation location : matrixResult.getSources()) { if (location != null) sources.add(new JSON2DSources(location, includeResolveLocations)); else sources.add(null); } return sources; } JSONBasedIndividualMatrixResponse(MatrixRequest request); }### Answer:
@Test public void constructSources() { List<JSON2DSources> json2DSources = jsonBasedIndividualMatrixResponse.constructSources(matrixResult); Assert.assertEquals(1, json2DSources.size()); Assert.assertEquals("foo", json2DSources.get(0).name); Assert.assertEquals(new Coordinate(8.681495, 49.41461, Double.NaN), json2DSources.get(0).location); Double[] location = json2DSources.get(0).getLocation(); Assert.assertEquals(2, location.length); Assert.assertEquals(0, location[0].compareTo(8.681495)); Assert.assertEquals(0, location[1].compareTo(49.41461)); } |
### Question:
JSONMatrixResponse extends MatrixResponse { @JsonProperty("metadata") @ApiModelProperty("Information about the service and request") public MatrixResponseInfo getInfo() { return responseInformation; } JSONMatrixResponse(MatrixResult result, MatrixRequest request); @JsonProperty("matrix") @JsonUnwrapped JSONIndividualMatrixResponse getMatrix(); @JsonProperty("metadata") @ApiModelProperty("Information about the service and request") MatrixResponseInfo getInfo(); }### Answer:
@Test public void getInfo() { Assert.assertEquals(MatrixResponseInfo.class, jsonMatrixDurationsResponse.getInfo().getClass()); Assert.assertNotNull(jsonMatrixDurationsResponse.getInfo().getEngineInfo()); Assert.assertNotNull(jsonMatrixDurationsResponse.getInfo().getAttribution()); Assert.assertNotNull(jsonMatrixDurationsResponse.getInfo().getRequest()); Assert.assertNotNull(jsonMatrixDurationsResponse.getInfo().getService()); Assert.assertTrue(jsonMatrixDurationsResponse.getInfo().getTimeStamp() > 0); } |
### Question:
JSONLocation { public Double getSnappedDistance() { return FormatUtility.roundToDecimals(snappedDistance, SNAPPED_DISTANCE_DECIMAL_PLACES); } JSONLocation(ResolvedLocation location, boolean includeResolveLocations); Double getSnappedDistance(); Double[] getLocation(); }### Answer:
@Test public void getSnapped_distance() { Assert.assertEquals("foo", jsonLocationWithLocation.name); Assert.assertEquals(new Double(0.0), jsonLocationWithLocation.getSnappedDistance()); } |
### Question:
JSONLocation { public Double[] getLocation() { return new Double[0]; } JSONLocation(ResolvedLocation location, boolean includeResolveLocations); Double getSnappedDistance(); Double[] getLocation(); }### Answer:
@Test public void getLocation() { Assert.assertEquals(new Coordinate(8.681495, 49.41461, Double.NaN), jsonLocationWithLocation.location); Assert.assertArrayEquals(new Double[0], jsonLocationWithLocation.getLocation()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public Double[][] getDistances() { return distances; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void getDistances() { Assert.assertNull(durationsMatrixResponse.getDistances()); Assert.assertArrayEquals(new Double[]{0.0, 1.0, 2.0}, distancesMatrixResponse.getDistances()[0]); Assert.assertArrayEquals(new Double[]{3.0,4.0,5.0}, combinedMatrixResponse.getDistances()[1]); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public void setDistances(Double[][] distances) { this.distances = distances; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void setDistances() { distancesMatrixResponse.setDistances(new Double[][]{{1.0, 2.0, 3.0},{1.0, 2.0, 3.0},{1.0, 2.0, 3.0}}); Assert.assertEquals(3, distancesMatrixResponse.getDistances().length); Assert.assertArrayEquals(new Double[]{1.0, 2.0, 3.0}, distancesMatrixResponse.getDistances()[0]); Assert.assertNull(durationsMatrixResponse.getDistances()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public Double[][] getDurations() { return durations; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void getDurations() { Assert.assertEquals(3, durationsMatrixResponse.getDurations().length); Assert.assertArrayEquals(new Double[]{0.0, 1.0, 2.0}, durationsMatrixResponse.getDurations()[0]); Assert.assertNull(distancesMatrixResponse.getDurations()); Assert.assertArrayEquals(new Double[]{3.0,4.0,5.0}, combinedMatrixResponse.getDurations()[1]); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public void setDurations(Double[][] durations) { this.durations = durations; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void setDurations() { durationsMatrixResponse.setDurations(new Double[][]{{1.0, 2.0, 3.0},{1.0, 2.0, 3.0},{1.0, 2.0, 3.0}}); Assert.assertEquals(3, durationsMatrixResponse.getDurations().length); Assert.assertArrayEquals(new Double[]{1.0, 2.0, 3.0}, durationsMatrixResponse.getDurations()[0]); Assert.assertNull(distancesMatrixResponse.getDurations()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public List<JSON2DDestinations> getDestinations() { return destinations; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void getDestinations() { Assert.assertEquals(3, distancesMatrixResponse.getDestinations().size()); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, distancesMatrixResponse.getDestinations().get(0).getLocation()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public void setDestinations(List<JSON2DDestinations> destinations) { this.destinations = destinations; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void setDestinations() { Coordinate coordinate = new Coordinate(9.681495, 50.41461); ResolvedLocation resolvedLocation = new ResolvedLocation(coordinate, "foo", 0.0); List<JSON2DDestinations> json2DDestinations = new ArrayList<>(); JSON2DDestinations json2DDestination = new JSON2DDestinations(resolvedLocation, false); json2DDestinations.add(json2DDestination); durationsMatrixResponse.setDestinations(json2DDestinations); distancesMatrixResponse.setDestinations(json2DDestinations); Assert.assertEquals(1, durationsMatrixResponse.getDestinations().size()); Assert.assertArrayEquals(new Double[]{9.681495, 50.41461}, durationsMatrixResponse.getDestinations().get(0).getLocation()); Assert.assertEquals(1, distancesMatrixResponse.getDestinations().size()); Assert.assertArrayEquals(new Double[]{9.681495, 50.41461}, distancesMatrixResponse.getDestinations().get(0).getLocation()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public List<JSON2DSources> getSources() { return sources; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void getSources() { Assert.assertEquals(3, durationsMatrixResponse.getSources().size()); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, durationsMatrixResponse.getSources().get(0).getLocation()); } |
### Question:
JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixResponse { public void setSources(List<JSON2DSources> sources) { this.sources = sources; } JSONIndividualMatrixResponse(MatrixResult result, MatrixRequest request); Double[][] getDurations(); List<JSON2DDestinations> getDestinations(); List<JSON2DSources> getSources(); Double[][] getDistances(); void setDistances(Double[][] distances); void setDurations(Double[][] durations); void setDestinations(List<JSON2DDestinations> destinations); void setSources(List<JSON2DSources> sources); }### Answer:
@Test public void setSources() { Coordinate coordinate = new Coordinate(9.681495, 50.41461); ResolvedLocation resolvedLocation = new ResolvedLocation(coordinate, "foo", 0.0); List<JSON2DSources> json2DSources = new ArrayList<>(); JSON2DSources json2DSource = new JSON2DSources(resolvedLocation, false); json2DSources.add(json2DSource); durationsMatrixResponse.setSources(json2DSources); distancesMatrixResponse.setSources(json2DSources); Assert.assertEquals(1, durationsMatrixResponse.getSources().size()); Assert.assertArrayEquals(new Double[]{9.681495, 50.41461}, durationsMatrixResponse.getSources().get(0).getLocation()); Assert.assertEquals(1, distancesMatrixResponse.getSources().size()); Assert.assertArrayEquals(new Double[]{9.681495, 50.41461}, distancesMatrixResponse.getSources().get(0).getLocation()); } |
### Question:
JSON2DDestinations extends JSONLocation { @Override public Double[] getLocation() { Double[] location2D = new Double[2]; location2D[0] = FormatUtility.roundToDecimals(location.x, COORDINATE_DECIMAL_PLACES); location2D[1] = FormatUtility.roundToDecimals(location.y, COORDINATE_DECIMAL_PLACES); return location2D; } JSON2DDestinations(ResolvedLocation destination, boolean includeResolveLocations); @Override Double[] getLocation(); }### Answer:
@Test public void getLocation() { JSON2DDestinations json2DDestinationsWithLocation = new JSON2DDestinations(resolvedLocation, true); JSON2DDestinations json2DDestinationsWoLocation = new JSON2DDestinations(resolvedLocation, false); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, json2DDestinationsWithLocation.getLocation()); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, json2DDestinationsWoLocation.getLocation()); } |
### Question:
JSON2DSources extends JSONLocation { @Override public Double[] getLocation() { Double[] location2D = new Double[2]; location2D[0] = FormatUtility.roundToDecimals(location.x, COORDINATE_DECIMAL_PLACES); location2D[1] = FormatUtility.roundToDecimals(location.y, COORDINATE_DECIMAL_PLACES); return location2D; } JSON2DSources(ResolvedLocation source, boolean includeResolveLocations); @Override Double[] getLocation(); }### Answer:
@Test public void getLocation() { JSON2DSources json2DSourcesWithLocation = new JSON2DSources(resolvedLocation, true); JSON2DSources json2DSourcesWoLocation = new JSON2DSources(resolvedLocation, false); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, json2DSourcesWithLocation.getLocation()); Assert.assertArrayEquals(new Double[]{8.681495, 49.41461}, json2DSourcesWoLocation.getLocation()); } |
### Question:
MatrixResponseInfo { public String getAttribution() { return attribution; } MatrixResponseInfo(MatrixRequest request); void setGraphDate(String graphDate); String getAttribution(); String getOsmFileMD5Hash(); String getService(); long getTimeStamp(); MatrixRequest getRequest(); EngineInfo getEngineInfo(); }### Answer:
@Test public void getAttributionTest() { Assert.assertEquals(MatrixResponseInfo.class, responseInformation.getClass()); Assert.assertEquals(String.class, responseInformation.getAttribution().getClass()); } |
### Question:
MatrixResponseInfo { public String getService() { return service; } MatrixResponseInfo(MatrixRequest request); void setGraphDate(String graphDate); String getAttribution(); String getOsmFileMD5Hash(); String getService(); long getTimeStamp(); MatrixRequest getRequest(); EngineInfo getEngineInfo(); }### Answer:
@Test public void getServiceTest() { Assert.assertEquals("matrix", responseInformation.getService()); } |
### Question:
MatrixResponseInfo { public long getTimeStamp() { return timeStamp; } MatrixResponseInfo(MatrixRequest request); void setGraphDate(String graphDate); String getAttribution(); String getOsmFileMD5Hash(); String getService(); long getTimeStamp(); MatrixRequest getRequest(); EngineInfo getEngineInfo(); }### Answer:
@Test public void getTimeStampTest() { Assert.assertTrue(Long.toString(responseInformation.getTimeStamp()).length() > 0); } |
### Question:
MatrixResponseInfo { public MatrixRequest getRequest() { return request; } MatrixResponseInfo(MatrixRequest request); void setGraphDate(String graphDate); String getAttribution(); String getOsmFileMD5Hash(); String getService(); long getTimeStamp(); MatrixRequest getRequest(); EngineInfo getEngineInfo(); }### Answer:
@Test public void getRequestTest() { Assert.assertEquals(bareMatrixRequest, responseInformation.getRequest()); } |
### Question:
MatrixResponseInfo { public EngineInfo getEngineInfo() { return engineInfo; } MatrixResponseInfo(MatrixRequest request); void setGraphDate(String graphDate); String getAttribution(); String getOsmFileMD5Hash(); String getService(); long getTimeStamp(); MatrixRequest getRequest(); EngineInfo getEngineInfo(); }### Answer:
@Test public void getEngineInfoTest() { Assert.assertNotNull(responseInformation.getEngineInfo()); } |
### Question:
IsochronesResponse { public IsochronesResponseInfo getResponseInformation() { return responseInformation; } IsochronesResponse(IsochronesRequest request); IsochronesResponseInfo getResponseInformation(); BoundingBox getBbox(); }### Answer:
@Test public void getResponseInformation() { } |
### Question:
Auth implements AuthDistribution { @Override public Promise<Void> signOut() { return FuturePromise.when(new Consumer<FuturePromise<Void>>() { @Override public void accept(FuturePromise<Void> promise) { try { FirebaseAuth.getInstance().signOut(); promise.doComplete(null); } catch (Exception e) { promise.doFail(e); } } }); } @Override GdxFirebaseUser getCurrentUser(); @Override Promise<GdxFirebaseUser> createUserWithEmailAndPassword(String email, char[] password); @Override Promise<GdxFirebaseUser> signInWithEmailAndPassword(String email, char[] password); @Override Promise<GdxFirebaseUser> signInWithToken(String token); @Override Promise<GdxFirebaseUser> signInAnonymously(); @Override Promise<Void> signOut(); @Override Promise<Void> sendPasswordResetEmail(final String email); }### Answer:
@Test public void signOut() { Auth auth = new Auth(); Consumer consumer = Mockito.mock(Consumer.class); auth.signOut().then(consumer); PowerMockito.verifyStatic(FirebaseAuth.class, VerificationModeFactory.times(1)); FirebaseAuth.getInstance(); Mockito.verify(firebaseAuth, VerificationModeFactory.times(1)).signOut(); Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.any()); }
@Test public void signOut_fail() { Auth auth = new Auth(); BiConsumer biConsumer = Mockito.mock(BiConsumer.class); Mockito.doThrow(new RuntimeException()).when(firebaseAuth).signOut(); auth.signOut().fail(biConsumer); PowerMockito.verifyStatic(FirebaseAuth.class, VerificationModeFactory.times(1)); FirebaseAuth.getInstance(); Mockito.verify(firebaseAuth, VerificationModeFactory.times(1)).signOut(); Mockito.verify(biConsumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(String.class), Mockito.any(Exception.class)); } |
### Question:
ProviderQueryFiltering extends SortingFilteringProvider<Query, ResolverQueryFilter, ResolverQueryOrderBy> { @Override public ResolverQueryFilter createFilterResolver() { return new ResolverQueryFilter(); } @Override ResolverQueryFilter createFilterResolver(); @Override ResolverQueryOrderBy createOrderByResolver(); }### Answer:
@Test public void createFilterResolver() { ProviderQueryFiltering provider = new ProviderQueryFiltering(); Object result = provider.createFilterResolver(); Assert.assertNotNull(result); } |
### Question:
ProviderQueryFiltering extends SortingFilteringProvider<Query, ResolverQueryFilter, ResolverQueryOrderBy> { @Override public ResolverQueryOrderBy createOrderByResolver() { return new ResolverQueryOrderBy(); } @Override ResolverQueryFilter createFilterResolver(); @Override ResolverQueryOrderBy createOrderByResolver(); }### Answer:
@Test public void createOrderByResolver() { ProviderQueryFiltering provider = new ProviderQueryFiltering(); Object result = provider.createOrderByResolver(); Assert.assertNotNull(result); } |
### Question:
QueryCompletionListener implements DatabaseReference.CompletionListener { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (promise == null) return; if (databaseError != null) { promise.doFail(databaseError.toException()); } else { promise.doComplete(null); } } QueryCompletionListener(FuturePromise promise); @Override void onComplete(DatabaseError databaseError, DatabaseReference databaseReference); }### Answer:
@Test public void onComplete_withoutError() { DatabaseError databaseError = null; DatabaseReference databaseReference = Mockito.mock(DatabaseReference.class); FuturePromise promise = Mockito.spy(FuturePromise.class); QueryCompletionListener listener = new QueryCompletionListener(promise); listener.onComplete(databaseError, databaseReference); Mockito.verify(promise, VerificationModeFactory.times(1)).doComplete(Mockito.any()); }
@Test public void onComplete_error() { DatabaseError databaseError = Mockito.mock(DatabaseError.class); DatabaseReference databaseReference = Mockito.mock(DatabaseReference.class); FuturePromise promise = Mockito.spy(FuturePromise.class); promise.silentFail(); QueryCompletionListener listener = new QueryCompletionListener(promise); listener.onComplete(databaseError, databaseReference); Mockito.verify(promise, VerificationModeFactory.times(1)).doFail(Mockito.nullable(Exception.class)); } |
### Question:
ResolverDataSnapshotList { @SuppressWarnings("unchecked") static List resolve(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() == null) { throw new IllegalStateException(); } List result = new ArrayList<>(); Iterable<DataSnapshot> dataSnapshots; for (Object o : dataSnapshot.getChildren()) { if (o instanceof DataSnapshot) { result.add(((DataSnapshot) o).getValue()); } else { result.add(o); } } return result; } private ResolverDataSnapshotList(); }### Answer:
@Test public void resolve() { DataSnapshot dataSnapshot = Mockito.mock(DataSnapshot.class); DataSnapshot dataSnapshot2 = Mockito.mock(DataSnapshot.class); DataSnapshot dataSnapshot3 = Mockito.mock(DataSnapshot.class); ArrayList list = new ArrayList(); list.add(dataSnapshot2); list.add(dataSnapshot3); Mockito.when(dataSnapshot.getChildren()).thenReturn(list); Mockito.when(dataSnapshot.getValue()).thenReturn(list); List result = ResolverDataSnapshotList.resolve(dataSnapshot); Assert.assertEquals(2, result.size()); Mockito.verify(dataSnapshot2, VerificationModeFactory.times(1)).getValue(); Mockito.verify(dataSnapshot3, VerificationModeFactory.times(1)).getValue(); } |
### Question:
ResolverDataSnapshotList { static boolean shouldResolveOrderBy(Class<?> dataType, DataSnapshot dataSnapshot) { return (ClassReflection.isAssignableFrom(List.class, dataType) || ClassReflection.isAssignableFrom(Map.class, dataType)) && dataSnapshot.getChildrenCount() > 0; } private ResolverDataSnapshotList(); }### Answer:
@Test public void shouldResolveOrderBy() { Class dataType = List.class; DataSnapshot dataSnapshot = Mockito.mock(DataSnapshot.class); Mockito.when(dataSnapshot.getChildrenCount()).thenReturn(1L); boolean should = ResolverDataSnapshotList.shouldResolveOrderBy(dataType, dataSnapshot); Assert.assertTrue(should); }
@Test public void shouldResolveOrderBy3() { Class dataType = String.class; DataSnapshot dataSnapshot = Mockito.mock(DataSnapshot.class); Mockito.when(dataSnapshot.getChildrenCount()).thenReturn(1L); boolean should = ResolverDataSnapshotList.shouldResolveOrderBy(dataType, dataSnapshot); Assert.assertFalse(should); }
@Test public void shouldResolveOrderBy4() { Class dataType = String.class; DataSnapshot dataSnapshot = Mockito.mock(DataSnapshot.class); Mockito.when(dataSnapshot.getChildrenCount()).thenReturn(0L); boolean should = ResolverDataSnapshotList.shouldResolveOrderBy(dataType, dataSnapshot); Assert.assertFalse(should); } |
### Question:
QueryOnDataChange extends AndroidDatabaseQuery<R> { @Override protected ArgumentsValidator createArgumentsValidator() { return new OnDataValidator(); } QueryOnDataChange(Database databaseDistribution, String databasePath); }### Answer:
@Test public void createArgumentsValidator() { Database databaseDistribution = Mockito.mock(Database.class); QueryOnDataChange queryOnDataChange = new QueryOnDataChange(databaseDistribution, "/test"); ArgumentsValidator argumentsValidator = queryOnDataChange.createArgumentsValidator(); Assert.assertNotNull(argumentsValidator); Assert.assertTrue(argumentsValidator instanceof OnDataValidator); } |
### Question:
QueryOnDataChange extends AndroidDatabaseQuery<R> { @Override @SuppressWarnings("unchecked") protected R run() { SnapshotValueListener dataChangeListener = new SnapshotValueListener((Class) arguments.get(0), (ConverterPromise) promise); filtersProvider.applyFiltering().addValueEventListener(dataChangeListener); ((FutureListenerPromise) promise).onCancel(new CancelListenerAction(dataChangeListener, query)); return null; } QueryOnDataChange(Database databaseDistribution, String databasePath); }### Answer:
@Test public void run() { final Database databaseDistribution = Mockito.spy(Database.class); final DatabaseReference databaseReference = Mockito.mock(DatabaseReference.class); Mockito.when(firebaseDatabase.getReference(Mockito.anyString())).thenReturn(databaseReference); Mockito.when(databaseDistribution.inReference(Mockito.anyString())).thenCallRealMethod(); final QueryOnDataChange queryOnDataChange = new QueryOnDataChange(databaseDistribution, "/test"); final ConverterPromise promise = Mockito.spy(ConverterPromise.class); databaseDistribution.inReference("/test"); queryOnDataChange.with(promise).withArgs(Map.class).execute(); Mockito.verify(databaseReference, VerificationModeFactory.times(1)).addValueEventListener(Mockito.any(ValueEventListener.class)); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public ListenerPromise<ConnectionStatus> onConnect() { return FutureListenerPromise.whenListener(new Consumer<FutureListenerPromise<ConnectionStatus>>() { @Override public void accept(FutureListenerPromise<ConnectionStatus> promise) { new QueryConnectionStatus(Database.this, getDatabasePath()) .with(promise) .execute(); } }); } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void onConnect() throws Exception { PowerMockito.mockStatic(QueryConnectionStatus.class); Database database = new Database(); QueryConnectionStatus query = Mockito.spy(new QueryConnectionStatus(database, "/test")); PowerMockito.whenNew(QueryConnectionStatus.class).withAnyArguments().thenReturn(query); when(query.withArgs(Mockito.any())).thenReturn(query); database.onConnect().subscribe(); PowerMockito.verifyNew(QueryConnectionStatus.class); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public DatabaseDistribution inReference(String databasePath) { databaseReference = FirebaseDatabase.getInstance().getReference(databasePath); this.databasePath = databasePath; return this; } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void inReference() { Database database = Mockito.spy(new Database()); database.inReference("test"); DatabaseReference reference = Whitebox.getInternalState(database, "databaseReference"); String path = Whitebox.getInternalState(database, "databasePath"); Assert.assertEquals("test", path); Assert.assertNotNull(reference); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override @SuppressWarnings("unchecked") public <V> DatabaseDistribution filter(FilterType filterType, V... filterArguments) { filters.add(new Filter(filterType, filterArguments)); return this; } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void filter() { Database database = new Database(); database.filter(FilterType.LIMIT_FIRST, 2) .filter(FilterType.EQUAL_TO, 3); Assert.assertEquals(FilterType.LIMIT_FIRST, ((Array<Filter>) Whitebox.getInternalState(database, "filters")).get(0).getFilterType()); Assert.assertEquals(FilterType.EQUAL_TO, ((Array<Filter>) Whitebox.getInternalState(database, "filters")).get(1).getFilterType()); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public DatabaseDistribution orderBy(OrderByMode orderByMode, String argument) { orderByClause = new OrderByClause(orderByMode, argument); return this; } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void orderBy() { Database database = new Database(); database.orderBy(OrderByMode.ORDER_BY_KEY, "test"); Assert.assertEquals(OrderByMode.ORDER_BY_KEY, ((OrderByClause) Whitebox.getInternalState(database, "orderByClause")).getOrderByMode()); Assert.assertEquals("test", ((OrderByClause) Whitebox.getInternalState(database, "orderByClause")).getArgument()); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public DatabaseDistribution push() { databaseReference = databaseReference().push(); databasePath = databasePath + "/" + databaseReference.getKey(); return this; } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void push() { Database database = new Database(); when(databaseReference.push()).thenReturn(databaseReference); database.inReference("/test").push(); Mockito.verify(databaseReference, VerificationModeFactory.times(1)).push(); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public Promise<Void> removeValue() { checkDatabaseReference(); return FuturePromise.when(new DatabaseConsumer<FuturePromise<Void>>(this) { @Override public void accept(FuturePromise<Void> voidFuturePromise) { new QueryRemoveValue(Database.this, getDatabasePath()) .with(voidFuturePromise) .execute(); } }); } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void removeValue() throws Exception { PowerMockito.mockStatic(QueryRemoveValue.class); Database database = new Database(); QueryRemoveValue query = PowerMockito.mock(QueryRemoveValue.class); PowerMockito.whenNew(QueryRemoveValue.class).withAnyArguments().thenReturn(query); when(query.withArgs(Mockito.any())).thenReturn(query); Promise promise = Mockito.spy(database.inReference("/test").removeValue()); PowerMockito.verifyNew(QueryRemoveValue.class); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public void setPersistenceEnabled(boolean enabled) { FirebaseDatabase.getInstance().setPersistenceEnabled(enabled); } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void setPersistenceEnabled() { Database database = new Database(); database.setPersistenceEnabled(true); Mockito.verify(firebaseDatabase, VerificationModeFactory.times(1)).setPersistenceEnabled(Mockito.eq(true)); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public void keepSynced(boolean synced) { databaseReference().keepSynced(synced); } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void keepSynced() { Database database = new Database(); database.inReference("/test").keepSynced(true); Mockito.verify(databaseReference, VerificationModeFactory.times(1)).keepSynced(Mockito.eq(true)); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { DatabaseReference databaseReference() { checkDatabaseReference(); return databaseReference; } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test(expected = DatabaseReferenceNotSetException.class) public void databaseReference() { Database database = new Database(); database.keepSynced(true); Assert.fail(); } |
### Question:
Database implements DatabaseDistribution, QueryProvider { @Override public void terminateOperation() { databaseReference = null; databasePath = null; orderByClause = null; filters.clear(); } Database(); @Override ListenerPromise<ConnectionStatus> onConnect(); @Override DatabaseDistribution inReference(String databasePath); @Override Promise<Void> setValue(final Object value); @Override @SuppressWarnings("unchecked") Promise<E> readValue(final Class<T> dataType); @Override @SuppressWarnings("unchecked") ListenerPromise<R> onDataChange(final Class<T> dataType); @Override ListenerPromise<R> onChildChange(final Class<T> dataType, final ChildEventType... eventsType); @Override @SuppressWarnings("unchecked") DatabaseDistribution filter(FilterType filterType, V... filterArguments); @Override DatabaseDistribution orderBy(OrderByMode orderByMode, String argument); @Override DatabaseDistribution orderBy(OrderByMode orderByMode); @Override DatabaseDistribution push(); @Override Promise<Void> removeValue(); @Override Promise<Void> updateChildren(final Map<String, Object> data); @Override @SuppressWarnings("unchecked") Promise<Void> transaction(final Class<T> dataType, final Function<R, R> transaction); @Override void setPersistenceEnabled(boolean enabled); @Override void keepSynced(boolean synced); @Override String getReferencePath(); @Override Array<Filter> getFilters(); @Override OrderByClause getOrderByClause(); @Override void terminateOperation(); }### Answer:
@Test public void terminateOperation() { Database database = new Database(); database.inReference("test").filter(FilterType.LIMIT_FIRST, 2).orderBy(OrderByMode.ORDER_BY_KEY, "test"); database.terminateOperation(); Assert.assertNull(Whitebox.getInternalState(database, "databaseReference")); Assert.assertNull(Whitebox.getInternalState(database, "databasePath")); Assert.assertNull(Whitebox.getInternalState(database, "orderByClause")); Assert.assertEquals(0, ((Array) Whitebox.getInternalState(database, "filters")).size); } |
### Question:
TransactionHandler implements Transaction.Handler { @Override @SuppressWarnings("unchecked") public Transaction.Result doTransaction(MutableData mutableData) { try { if (mutableData.getValue() == null) { mutableData.setValue(transactionFunction.apply((R) DefaultTypeRecognizer.getDefaultValue(dataType))); return Transaction.success(mutableData); } MapConversion mapConversionAnnotation = null; R transactionData; if (promise.getThenConsumer() != null) { mapConversionAnnotation = AnnotationFinder.getMethodAnnotation(MapConversion.class, promise.getThenConsumer()); } if (mapConversionAnnotation != null) { transactionData = (R) mutableData.getValue(mapConversionAnnotation.value()); } else { transactionData = (R) mutableData.getValue(); } mutableData.setValue(transactionFunction.apply(transactionData)); return Transaction.success(mutableData); } catch (Exception e) { GdxFIRLogger.error(TRANSACTION_ERROR, e); return Transaction.abort(); } } TransactionHandler(Class<?> dataType, Function<R, R> transactionFunction, FuturePromise<Void> promise); @Override @SuppressWarnings("unchecked") Transaction.Result doTransaction(MutableData mutableData); @Override void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot); }### Answer:
@Test public void doTransaction() { Function transactionFunction = Mockito.mock(Function.class); FuturePromise promise = Mockito.mock(FuturePromise.class); TransactionHandler transactionHandler = new TransactionHandler(Long.class, transactionFunction, promise); MutableData mutableData = Mockito.mock(MutableData.class); Mockito.when(mutableData.getValue()).thenReturn("test_value"); transactionHandler.doTransaction(mutableData); PowerMockito.verifyStatic(Transaction.class, VerificationModeFactory.times(1)); Transaction.success(Mockito.nullable(MutableData.class)); } |
### Question:
App implements AppDistribution { @Override public void configure() { } @Override void configure(); }### Answer:
@Test public void configure() { GdxFIRApp.instance().configure(); } |
### Question:
Analytics implements AnalyticsDistribution { @Override public void setScreen(final String name, final Class<?> screenClass) { ((AndroidApplication) Gdx.app).runOnUiThread(new Runnable() { @Override public void run() { FirebaseAnalytics.getInstance((AndroidApplication) Gdx.app).setCurrentScreen((AndroidApplication) Gdx.app, name, screenClass.getSimpleName()); } }); } @Override void logEvent(String name, Map<String, String> params); @Override void setScreen(final String name, final Class<?> screenClass); @Override void setUserProperty(String name, String value); @Override void setUserId(String id); }### Answer:
@Test public void setScreen() { Analytics analytics = new Analytics(); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { ((Runnable) invocation.getArgument(0)).run(); return null; } }).when(((AndroidApplication) Gdx.app)).runOnUiThread(Mockito.any(Runnable.class)); analytics.setScreen("test", AnalyticsTest.class); PowerMockito.verifyStatic(FirebaseAnalytics.class, VerificationModeFactory.times(1)); FirebaseAnalytics.getInstance((Context) Gdx.app); Mockito.verify(firebaseAnalytics, VerificationModeFactory.times(1)) .setCurrentScreen(Mockito.eq((Activity) Gdx.app), Mockito.eq("test"), Mockito.eq(AnalyticsTest.class.getSimpleName())); Mockito.verifyNoMoreInteractions(firebaseAnalytics); } |
### Question:
Analytics implements AnalyticsDistribution { @Override public void setUserProperty(String name, String value) { FirebaseAnalytics.getInstance((AndroidApplication) Gdx.app).setUserProperty(name, value); } @Override void logEvent(String name, Map<String, String> params); @Override void setScreen(final String name, final Class<?> screenClass); @Override void setUserProperty(String name, String value); @Override void setUserId(String id); }### Answer:
@Test public void setUserProperty() { Analytics analytics = new Analytics(); analytics.setUserProperty("test_name", "test_value"); PowerMockito.verifyStatic(FirebaseAnalytics.class, VerificationModeFactory.times(1)); FirebaseAnalytics.getInstance((Context) Gdx.app); Mockito.verify(firebaseAnalytics, VerificationModeFactory.times(1)) .setUserProperty(Mockito.eq("test_name"), Mockito.eq("test_value")); Mockito.verifyNoMoreInteractions(firebaseAnalytics); } |
### Question:
Analytics implements AnalyticsDistribution { @Override public void setUserId(String id) { FirebaseAnalytics.getInstance((AndroidApplication) Gdx.app).setUserId(id); } @Override void logEvent(String name, Map<String, String> params); @Override void setScreen(final String name, final Class<?> screenClass); @Override void setUserProperty(String name, String value); @Override void setUserId(String id); }### Answer:
@Test public void setUserId() { Analytics analytics = new Analytics(); analytics.setUserId("test"); PowerMockito.verifyStatic(FirebaseAnalytics.class, VerificationModeFactory.times(1)); FirebaseAnalytics.getInstance((Context) Gdx.app); Mockito.verify(firebaseAnalytics, VerificationModeFactory.times(1)) .setUserId(Mockito.eq("test")); Mockito.verifyNoMoreInteractions(firebaseAnalytics); } |
### Question:
Storage implements StorageDistribution { @Override public StorageDistribution inBucket(String url) { firebaseStorage = FirebaseStorage.getInstance(url); return this; } @Override Promise<FileMetadata> upload(final String path, final FileHandle file); @Override Promise<FileMetadata> upload(final String path, final byte[] data); @Override Promise<byte[]> download(final String path, final long bytesLimit); @Override Promise<FileHandle> download(final String path, final FileHandle targetFile); @Override Promise<Void> delete(final String path); @Override StorageDistribution inBucket(String url); }### Answer:
@Test public void inBucket() { Storage storage = new Storage(); storage.inBucket("test"); PowerMockito.verifyStatic(FirebaseStorage.class, VerificationModeFactory.times(1)); FirebaseStorage.getInstance(Mockito.eq("test")); } |
### Question:
Crash implements CrashDistribution { @Override public void initialize() { initializeOnce(); } @Override void log(String message); @Override void initialize(); }### Answer:
@Test public void initialize() { PowerMockito.mockStatic(Crashlytics.class); PowerMockito.mockStatic(Fabric.class); Crash crash = new Crash(); crash.initialize(); crash.initialize(); crash.initialize(); PowerMockito.verifyStatic(Fabric.class, VerificationModeFactory.times(1)); Fabric.with(Mockito.any(AndroidApplication.class), Mockito.any(Crashlytics.class)); PowerMockito.verifyNoMoreInteractions(Fabric.class); } |
### Question:
Crash implements CrashDistribution { @Override public void log(String message) { initializeOnce(); Crashlytics.log(message); } @Override void log(String message); @Override void initialize(); }### Answer:
@Test public void log() { PowerMockito.mockStatic(Crashlytics.class); PowerMockito.mockStatic(Fabric.class); Crash crash = new Crash(); crash.log("abc"); PowerMockito.verifyStatic(Crashlytics.class, VerificationModeFactory.times(1)); Crashlytics.log("abc"); PowerMockito.verifyNoMoreInteractions(Crashlytics.class); } |
### Question:
User implements AuthUserDistribution { @Override public Promise<Void> delete() { if (FirebaseAuth.getInstance().getCurrentUser() == null) { throw new IllegalStateException(); } return FuturePromise.when(new VoidPromiseConsumer<>(FirebaseAuth.getInstance().getCurrentUser().delete())); } @Override Promise<GdxFirebaseUser> updateEmail(String newEmail); @Override Promise<GdxFirebaseUser> sendEmailVerification(); @Override Promise<GdxFirebaseUser> updatePassword(char[] newPassword); @Override Promise<Void> delete(); @Override Promise<GdxFirebaseUser> reload(); }### Answer:
@Test(expected = IllegalStateException.class) public void delete_noUser() { User user = new User(); user.delete(); Assert.fail(); }
@Test public void delete() { User user = new User(); FirebaseUser firebaseUser = Mockito.mock(FirebaseUser.class); Consumer consumer = Mockito.mock(Consumer.class); Mockito.when(firebaseAuth.getCurrentUser()).thenReturn(firebaseUser); Mockito.when(task.isSuccessful()).thenReturn(true); Mockito.when(firebaseUser.delete()).thenReturn(task); user.delete().then(consumer); Mockito.verify(firebaseUser, VerificationModeFactory.times(1)).delete(); Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.any()); }
@Test public void delete_fail() { User user = new User(); FirebaseUser firebaseUser = Mockito.mock(FirebaseUser.class); BiConsumer consumer = Mockito.mock(BiConsumer.class); Mockito.when(firebaseAuth.getCurrentUser()).thenReturn(firebaseUser); Mockito.when(task.isSuccessful()).thenReturn(false); Mockito.when(firebaseUser.delete()).thenReturn(task); user.delete().fail(consumer); Mockito.verify(firebaseUser, VerificationModeFactory.times(1)).delete(); Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(String.class), Mockito.nullable(Exception.class)); } |
### Question:
User implements AuthUserDistribution { @Override public Promise<GdxFirebaseUser> reload() { if (FirebaseAuth.getInstance().getCurrentUser() == null) { throw new IllegalStateException(); } return FuturePromise.when(new AuthPromiseConsumer<>(FirebaseAuth.getInstance().getCurrentUser().reload())); } @Override Promise<GdxFirebaseUser> updateEmail(String newEmail); @Override Promise<GdxFirebaseUser> sendEmailVerification(); @Override Promise<GdxFirebaseUser> updatePassword(char[] newPassword); @Override Promise<Void> delete(); @Override Promise<GdxFirebaseUser> reload(); }### Answer:
@Test public void reload() { User user = new User(); FirebaseUser firebaseUser = Mockito.mock(FirebaseUser.class); Mockito.when(firebaseAuth.getCurrentUser()).thenReturn(firebaseUser); Mockito.when(task.isSuccessful()).thenReturn(true); Mockito.when(firebaseUser.reload()).thenReturn(task); user.reload(); Mockito.verify(firebaseUser, VerificationModeFactory.times(1)).reload(); }
@Test public void reload_fail() { User user = new User(); FirebaseUser firebaseUser = Mockito.mock(FirebaseUser.class); Mockito.when(firebaseAuth.getCurrentUser()).thenReturn(firebaseUser); Mockito.when(task.isSuccessful()).thenReturn(false); Mockito.when(firebaseUser.reload()).thenReturn(task); user.reload(); Mockito.verify(firebaseUser, VerificationModeFactory.times(1)).reload(); } |
### Question:
AuthPromiseConsumer implements Consumer<FuturePromise<GdxFirebaseUser>> { @Override public void accept(final FuturePromise<GdxFirebaseUser> promise) { if (task != null) { task.addOnCompleteListener(new OnCompleteListener<T>() { @Override public void onComplete(@NonNull Task<T> task) { if (task.isSuccessful()) { promise.doComplete(GdxFIRAuth.instance().getCurrentUser()); } else { promise.doFail(task.getException() != null ? task.getException().getLocalizedMessage() : "Authorization fail", task.getException()); } } }); } } AuthPromiseConsumer(Task<T> task); @Override void accept(final FuturePromise<GdxFirebaseUser> promise); }### Answer:
@Test public void accept() { Mockito.when(task.isSuccessful()).thenReturn(true); FuturePromise promise = Mockito.spy(FuturePromise.empty()); promise.then(Mockito.mock(Consumer.class)).silentFail(); AuthPromiseConsumer authPromiseConsumer = new AuthPromiseConsumer(task); authPromiseConsumer.accept(promise); Mockito.verify(promise, VerificationModeFactory.atLeast(1)).doComplete(Mockito.any()); }
@Test public void accept_fail() { Mockito.when(task.isSuccessful()).thenReturn(false); FuturePromise promise = Mockito.spy(FuturePromise.empty()); promise.then(Mockito.mock(Consumer.class)).silentFail(); AuthPromiseConsumer authPromiseConsumer = new AuthPromiseConsumer(task); authPromiseConsumer.accept(promise); Mockito.verify(promise, VerificationModeFactory.times(1)).doFail(Mockito.nullable(String.class), Mockito.nullable(Exception.class)); } |
### Question:
GoogleAuth implements GoogleAuthDistribution { @Override public Promise<GdxFirebaseUser> signIn() { return FuturePromise.when(new Consumer<FuturePromise<GdxFirebaseUser>>() { @Override public void accept(FuturePromise<GdxFirebaseUser> gdxFirebaseUserFuturePromise) { GoogleSignInOptions gso = GoogleSignInOptionsFactory.factory(); ((AndroidApplication) Gdx.app).addAndroidEventListener(new GoogleSignInListener(gdxFirebaseUserFuturePromise)); ((AndroidApplication) Gdx.app).startActivityForResult( GoogleSignIn.getClient((AndroidApplication) Gdx.app, gso).getSignInIntent(), Const.GOOGLE_SIGN_IN); } }); } @Override Promise<GdxFirebaseUser> signIn(); @Override Promise<Void> signOut(); @Override Promise<Void> revokeAccess(); }### Answer:
@Test public void signIn() { GoogleAuth googleAuth = new GoogleAuth(); googleAuth.signIn().subscribe(); Mockito.verify(((AndroidApplication) Gdx.app), VerificationModeFactory.times(1)).startActivityForResult(Mockito.nullable(Intent.class), Mockito.anyInt()); PowerMockito.verifyStatic(GoogleSignIn.class, VerificationModeFactory.times(1)); GoogleSignIn.getClient((Activity) Mockito.refEq(Gdx.app), Mockito.any(GoogleSignInOptions.class)); } |
### Question:
StringResource { static String getStringResourceByName(String name) { int id = ((AndroidApplication) Gdx.app).getResources().getIdentifier(name, "string", ((AndroidApplication) Gdx.app).getPackageName()); return ((AndroidApplication) Gdx.app).getResources().getString(id); } private StringResource(); }### Answer:
@Test public void getStringResourceByName() { Resources resources = Mockito.mock(Resources.class); String name = "test"; Mockito.when(((AndroidApplication) Gdx.app).getResources()).thenReturn(resources); Mockito.when(resources.getString(Mockito.anyInt())).thenReturn("test_return"); String result = StringResource.getStringResourceByName(name); Assert.assertEquals("test_return", result); } |
### Question:
ProtoFileHandler { public void handle(FileDescriptorProto protoFile) throws IOException { String javaPackage = inferJavaPackage(protoFile); boolean multipleFiles = protoFile.getOptions().getJavaMultipleFiles(); String outerClassName = null; if (!multipleFiles) { if (protoFile.getOptions().hasJavaOuterClassname()) { outerClassName = protoFile.getOptions().getJavaOuterClassname(); } else { outerClassName = inferOuterClassName(protoFile); } } ProtoServiceHandler serviceHandler = new ProtoServiceHandler(javaPackage, types, multipleFiles, outerClassName, protoFile.getPackage(), output); for (ServiceDescriptorProto service : protoFile.getServiceList()) { serviceHandler.handle(service); } } ProtoFileHandler(TypeMap types, OutputStream output); void handle(FileDescriptorProto protoFile); }### Answer:
@Test public void testHandle() throws IOException { Descriptors.Descriptor personDescriptor = Person.getDescriptor(); FileDescriptorProto protoFile = personDescriptor.getFile().toProto(); TypeMap types = TypeMap.of(protoFile); ProtoFileHandler fileHandler = new ProtoFileHandler(types, new ByteArrayOutputStream()); fileHandler.handle(protoFile); } |
### Question:
JavaType { @Override public String toString() { return DOT.join(javaPackage, enclosingClass, className); } JavaType(@Nullable String javaPackage, @Nullable String enclosingClass, String className); @Override String toString(); }### Answer:
@Test public void testNullPackage() { JavaType type = new JavaType(null, "B", "C"); Assert.assertEquals("B.C", type.toString()); }
@Test public void testNullEnclosingClass() { JavaType type = new JavaType("a", null, "C"); Assert.assertEquals("a.C", type.toString()); } |
### Question:
LoginPresenter extends BasePresenter<Contract.View> implements Contract.Presenter { @Override public boolean isLogined() { return KeyManager.getToken() != null; } LoginPresenter(Contract.View view); @Override void attachView(); @Override boolean isLogined(); @Override void onLoginButtonClicked(String id, String password); }### Answer:
@Test public void isLogined_LoginedStatusTest() { KeyManager.clear(); KeyManager.putToken(TEST_LOGIN_KEY); Assert.assertEquals( true, presenter.isLogined() ); }
@Test public void isLogined_NotLoginedStatusTest() { KeyManager.clear(); Assert.assertEquals( false, presenter.isLogined() ); } |
### Question:
LoginPresenter extends BasePresenter<Contract.View> implements Contract.Presenter { @Override public void onLoginButtonClicked(String id, String password) { if (isUserInputVaild(id, password) == false) { view.showInputInvaildToast(); return; } requestLogin(id, password); } LoginPresenter(Contract.View view); @Override void attachView(); @Override boolean isLogined(); @Override void onLoginButtonClicked(String id, String password); }### Answer:
@Test public void onLoginButtonClick_EmptyIdTest() { presenter.onLoginButtonClicked( null, TEST_ACCOUNT_PW ); verify(view).showInputInvaildToast(); }
@Test public void onLoginButtonClick_EmptyPwTest() { presenter.onLoginButtonClicked( TEST_ACCOUNT_ID, null ); verify(view).showInputInvaildToast(); }
@Test public void onLoginButtonClick_EmptyIdPwTest() { presenter.onLoginButtonClicked( null, null ); verify(view).showInputInvaildToast(); }
@Test public void onLoginButtonClick_DismatchIdPwTest() { presenter.onLoginButtonClicked( TEST_ACCOUNT_ID, TEST_ACCOUNT_PW ); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } |
### Question:
ResourceBundleService extends TranslationService { @Override public String translate(String key) { return rb.getString(key); } ResourceBundleService(ResourceBundle rb); void changeLocale(ResourceBundle newValue); @Override String translate(String key); }### Answer:
@Test public void translateTest() { ResourceBundleService rbs = new ResourceBundleService(rbEN); Assert.assertEquals("Test Form", rbs.translate("form_title")); try { rbs.translate("non_existing"); fail(); } catch (MissingResourceException ignored) {} } |
### Question:
IntegerRangeValidator extends CustomValidator<Integer> { public static IntegerRangeValidator between(int min, int max, String errorMessage) { if (min > max) { throw new IllegalArgumentException("Minimum must not be larger than maximum."); } return new IntegerRangeValidator(min, max, errorMessage); } private IntegerRangeValidator(int min, int max, String errorMessage); static IntegerRangeValidator between(int min, int max, String errorMessage); static IntegerRangeValidator atLeast(int min, String errorMessage); static IntegerRangeValidator upTo(int max, String errorMessage); static IntegerRangeValidator exactly(int value, String errorMessage); }### Answer:
@Test public void betweenTest() { IntegerRangeValidator i = IntegerRangeValidator.between(10, 20, "test"); Assert.assertTrue(i.validate(14).getResult()); Assert.assertFalse(i.validate(21).getResult()); Assert.assertTrue(i.validate(20).getResult()); Assert.assertTrue(i.validate(10).getResult()); try { IntegerRangeValidator i2 = IntegerRangeValidator.between(20, 10, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { IntegerRangeValidator i2 = IntegerRangeValidator.between(10, 10, "test"); } catch (IllegalArgumentException ignored) { fail(); } } |
### Question:
IntegerRangeValidator extends CustomValidator<Integer> { public static IntegerRangeValidator atLeast(int min, String errorMessage) { return new IntegerRangeValidator(min, Integer.MAX_VALUE, errorMessage); } private IntegerRangeValidator(int min, int max, String errorMessage); static IntegerRangeValidator between(int min, int max, String errorMessage); static IntegerRangeValidator atLeast(int min, String errorMessage); static IntegerRangeValidator upTo(int max, String errorMessage); static IntegerRangeValidator exactly(int value, String errorMessage); }### Answer:
@Test public void atLeastTest() { IntegerRangeValidator i = IntegerRangeValidator.atLeast(10, "test"); Assert.assertTrue(i.validate(14).getResult()); Assert.assertFalse(i.validate(-139).getResult()); Assert.assertTrue(i.validate(10).getResult()); Assert.assertFalse(i.validate(9).getResult()); Assert.assertTrue(i.validate(Integer.MAX_VALUE).getResult()); } |
### Question:
IntegerRangeValidator extends CustomValidator<Integer> { public static IntegerRangeValidator upTo(int max, String errorMessage) { return new IntegerRangeValidator(Integer.MIN_VALUE, max, errorMessage); } private IntegerRangeValidator(int min, int max, String errorMessage); static IntegerRangeValidator between(int min, int max, String errorMessage); static IntegerRangeValidator atLeast(int min, String errorMessage); static IntegerRangeValidator upTo(int max, String errorMessage); static IntegerRangeValidator exactly(int value, String errorMessage); }### Answer:
@Test public void upToTest() { IntegerRangeValidator i = IntegerRangeValidator.upTo(10, "test"); Assert.assertFalse(i.validate(14).getResult()); Assert.assertFalse(i.validate(21).getResult()); Assert.assertTrue(i.validate(10).getResult()); Assert.assertFalse(i.validate(11).getResult()); Assert.assertTrue(i.validate(Integer.MIN_VALUE).getResult()); } |
### Question:
IntegerRangeValidator extends CustomValidator<Integer> { public static IntegerRangeValidator exactly(int value, String errorMessage) { return new IntegerRangeValidator(value, value, errorMessage); } private IntegerRangeValidator(int min, int max, String errorMessage); static IntegerRangeValidator between(int min, int max, String errorMessage); static IntegerRangeValidator atLeast(int min, String errorMessage); static IntegerRangeValidator upTo(int max, String errorMessage); static IntegerRangeValidator exactly(int value, String errorMessage); }### Answer:
@Test public void exactlyTest() { IntegerRangeValidator i = IntegerRangeValidator.exactly(10, "test"); Assert.assertFalse(i.validate(11).getResult()); Assert.assertFalse(i.validate(9).getResult()); Assert.assertTrue(i.validate(10).getResult()); Assert.assertFalse(i.validate(Integer.MIN_VALUE).getResult()); } |
### Question:
StringLengthValidator extends CustomValidator<String> { public static StringLengthValidator between(int min, int max, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } else if (min > max) { throw new IllegalArgumentException("Minimum must not be larger than maximum."); } return new StringLengthValidator(min, max, errorMessage); } private StringLengthValidator(int min, int max, String errorMessage); static StringLengthValidator between(int min, int max, String errorMessage); static StringLengthValidator atLeast(int min, String errorMessage); static StringLengthValidator upTo(int max, String errorMessage); static StringLengthValidator exactly(int value, String errorMessage); }### Answer:
@Test public void betweenTest() { StringLengthValidator s = StringLengthValidator.between(10, 20, "test"); Assert.assertTrue(s.validate("abcdefghijklmno").getResult()); Assert.assertFalse(s.validate("abcde").getResult()); Assert.assertTrue(s.validate(" ").getResult()); Assert.assertTrue(s.validate("梢äöä1ö3ä±æ#¢æ±“{").getResult()); try { StringLengthValidator s2 = StringLengthValidator.between(-10, 2, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { StringLengthValidator s3 = StringLengthValidator.between(0, 0, "test"); } catch (IllegalArgumentException e) { fail(); } try { StringLengthValidator s4 = StringLengthValidator.between(10, 1, "test"); fail(); } catch (IllegalArgumentException ignored) {} } |
### Question:
StringLengthValidator extends CustomValidator<String> { public static StringLengthValidator atLeast(int min, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } return new StringLengthValidator(min, Integer.MAX_VALUE, errorMessage); } private StringLengthValidator(int min, int max, String errorMessage); static StringLengthValidator between(int min, int max, String errorMessage); static StringLengthValidator atLeast(int min, String errorMessage); static StringLengthValidator upTo(int max, String errorMessage); static StringLengthValidator exactly(int value, String errorMessage); }### Answer:
@Test public void atLeastTest() { StringLengthValidator s = StringLengthValidator.atLeast(5, "test"); Assert.assertTrue(s.validate("gosjrgohgsr").getResult()); Assert.assertFalse(s.validate(" ").getResult()); Assert.assertFalse(s.validate("ae").getResult()); Assert.assertTrue(s.validate("¶æ¢¶ππ§±#").getResult()); try { StringLengthValidator s2 = StringLengthValidator.atLeast(-10, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { StringLengthValidator s3 = StringLengthValidator.atLeast(0, "test"); } catch (IllegalArgumentException e) { fail(); } } |
### Question:
StringLengthValidator extends CustomValidator<String> { public static StringLengthValidator upTo(int max, String errorMessage) { return new StringLengthValidator(0, max, errorMessage); } private StringLengthValidator(int min, int max, String errorMessage); static StringLengthValidator between(int min, int max, String errorMessage); static StringLengthValidator atLeast(int min, String errorMessage); static StringLengthValidator upTo(int max, String errorMessage); static StringLengthValidator exactly(int value, String errorMessage); }### Answer:
@Test public void upToTest() { StringLengthValidator s = StringLengthValidator.upTo(5, "test"); Assert.assertFalse(s.validate("gosjrgohgsr").getResult()); Assert.assertTrue(s.validate(" ").getResult()); Assert.assertTrue(s.validate("ae").getResult()); Assert.assertFalse(s.validate("¶æ¢¶ππ§±#").getResult()); } |
### Question:
StringLengthValidator extends CustomValidator<String> { public static StringLengthValidator exactly(int value, String errorMessage) { return new StringLengthValidator(value, value, errorMessage); } private StringLengthValidator(int min, int max, String errorMessage); static StringLengthValidator between(int min, int max, String errorMessage); static StringLengthValidator atLeast(int min, String errorMessage); static StringLengthValidator upTo(int max, String errorMessage); static StringLengthValidator exactly(int value, String errorMessage); }### Answer:
@Test public void exactlyTest() { StringLengthValidator s = StringLengthValidator.exactly(3, "test"); Assert.assertFalse(s.validate("gfyf").getResult()); Assert.assertTrue(s.validate(" ").getResult()); Assert.assertTrue(s.validate("aee").getResult()); Assert.assertFalse(s.validate("ee").getResult()); } |
### Question:
ResourceBundleService extends TranslationService { public void changeLocale(ResourceBundle newValue) { if (newValue.equals(rb)) { return; } rb = newValue; notifyListeners(); } ResourceBundleService(ResourceBundle rb); void changeLocale(ResourceBundle newValue); @Override String translate(String key); }### Answer:
@Test public void changeLocaleTest() { ResourceBundleService rbs = new ResourceBundleService(rbEN); final int[] calls = new int[] { 0 }; Runnable r = () -> calls[0] += 1; rbs.addListener(r); rbs.changeLocale(rbDE); Assert.assertEquals(1, calls[0]); rbs.changeLocale(rbDE); Assert.assertEquals(1, calls[0]); rbs.removeListener(r); } |
### Question:
Section extends Group { public Section collapse(boolean newValue) { collapsed.setValue(newValue); return this; } private Section(Element... elements); static Section of(Element... elements); Section title(String newValue); Section collapse(boolean newValue); BooleanProperty collapsedProperty(); boolean isCollapsed(); String getTitle(); StringProperty titleProperty(); Section collapsible(boolean newValue); boolean isCollapsible(); BooleanProperty collapsibleProperty(); }### Answer:
@Test public void collapseTest() { Section s = Section.of(); final int[] changes = { 0 }; s.collapsedProperty().addListener((observable, oldValue, newValue) -> changes[0] += 1); s.collapse(true); s.collapse(false); Assert.assertEquals(2, changes[0]); Assert.assertFalse(s.isCollapsed()); } |
### Question:
DoubleRangeValidator extends CustomValidator<Double> { public static DoubleRangeValidator between(double min, double max, String errorMessage) { if (min > max) { throw new IllegalArgumentException("Minimum must not be larger than maximum."); } return new DoubleRangeValidator(min, max, errorMessage); } private DoubleRangeValidator(double min, double max, String errorMessage); static DoubleRangeValidator between(double min, double max, String errorMessage); static DoubleRangeValidator atLeast(double min, String errorMessage); static DoubleRangeValidator upTo(double max, String errorMessage); static DoubleRangeValidator exactly(double value, String errorMessage); }### Answer:
@Test public void betweenTest() { DoubleRangeValidator i = DoubleRangeValidator.between(3.5, 12.1351, "test"); Assert.assertTrue(i.validate(11.5).getResult()); Assert.assertTrue(i.validate(3.50000001).getResult()); Assert.assertFalse(i.validate(12.13511).getResult()); Assert.assertFalse(i.validate(3.4999999).getResult()); try { DoubleRangeValidator i2 = DoubleRangeValidator.between(10.0, 5.3, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { DoubleRangeValidator i2 = DoubleRangeValidator.between(5.5, 5.5, "test"); } catch (IllegalArgumentException ignored) { fail(); } } |
### Question:
DoubleRangeValidator extends CustomValidator<Double> { public static DoubleRangeValidator atLeast(double min, String errorMessage) { return new DoubleRangeValidator(min, Double.MAX_VALUE, errorMessage); } private DoubleRangeValidator(double min, double max, String errorMessage); static DoubleRangeValidator between(double min, double max, String errorMessage); static DoubleRangeValidator atLeast(double min, String errorMessage); static DoubleRangeValidator upTo(double max, String errorMessage); static DoubleRangeValidator exactly(double value, String errorMessage); }### Answer:
@Test public void atLeastTest() { DoubleRangeValidator i = DoubleRangeValidator.atLeast(5.12351, "test"); Assert.assertTrue(i.validate(6234.1).getResult()); Assert.assertFalse(i.validate(1.31).getResult()); Assert.assertTrue(i.validate(5.12351).getResult()); Assert.assertFalse(i.validate(5.1235).getResult()); Assert.assertTrue(i.validate(Double.MAX_VALUE).getResult()); } |
### Question:
DoubleRangeValidator extends CustomValidator<Double> { public static DoubleRangeValidator upTo(double max, String errorMessage) { return new DoubleRangeValidator(Double.MIN_VALUE, max, errorMessage); } private DoubleRangeValidator(double min, double max, String errorMessage); static DoubleRangeValidator between(double min, double max, String errorMessage); static DoubleRangeValidator atLeast(double min, String errorMessage); static DoubleRangeValidator upTo(double max, String errorMessage); static DoubleRangeValidator exactly(double value, String errorMessage); }### Answer:
@Test public void upToTest() { DoubleRangeValidator i = DoubleRangeValidator.upTo(3.14, "test"); Assert.assertFalse(i.validate(-1.14).getResult()); Assert.assertFalse(i.validate(5.13).getResult()); Assert.assertTrue(i.validate(3.14).getResult()); Assert.assertFalse(i.validate(3.141).getResult()); Assert.assertTrue(i.validate(Double.MIN_VALUE).getResult()); } |
### Question:
DoubleRangeValidator extends CustomValidator<Double> { public static DoubleRangeValidator exactly(double value, String errorMessage) { return new DoubleRangeValidator(value, value, errorMessage); } private DoubleRangeValidator(double min, double max, String errorMessage); static DoubleRangeValidator between(double min, double max, String errorMessage); static DoubleRangeValidator atLeast(double min, String errorMessage); static DoubleRangeValidator upTo(double max, String errorMessage); static DoubleRangeValidator exactly(double value, String errorMessage); }### Answer:
@Test public void exactlyTest() { DoubleRangeValidator i = DoubleRangeValidator.exactly(3.14, "test"); Assert.assertFalse(i.validate(-3.4).getResult()); Assert.assertFalse(i.validate(3.145).getResult()); Assert.assertTrue(i.validate(3.14).getResult()); Assert.assertFalse(i.validate(3.0).getResult()); Assert.assertFalse(i.validate(Double.MIN_VALUE).getResult()); } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> between(int min, int max, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } else if (min > max) { throw new IllegalArgumentException("Minimum must not be larger than maximum."); } return new SelectionLengthValidator<>(min, max, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void betweenTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.between(1, 3, "test"); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3, 4, 5)).getResult()); try { SelectionLengthValidator s2 = SelectionLengthValidator.between(-10, 2, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { SelectionLengthValidator s3 = SelectionLengthValidator.between(0, 0, "test"); } catch (IllegalArgumentException e) { fail(); } try { SelectionLengthValidator s4 = SelectionLengthValidator.between(10, 1, "test"); fail(); } catch (IllegalArgumentException ignored) {} } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> atLeast(int min, String errorMessage) { if (min < 0) { throw new IllegalArgumentException("Minimum string length cannot be negative."); } return new SelectionLengthValidator<>(min, Integer.MAX_VALUE, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void atLeastTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.atLeast(2, "test"); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 4)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); try { SelectionLengthValidator s2 = SelectionLengthValidator.atLeast(-10, "test"); fail(); } catch (IllegalArgumentException ignored) {} try { SelectionLengthValidator s3 = SelectionLengthValidator.atLeast(0, "test"); } catch (IllegalArgumentException e) { fail(); } } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> upTo(int max, String errorMessage) { return new SelectionLengthValidator<>(0, max, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void upToTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.upTo(2, "test"); Assert.assertFalse(s.validate(FXCollections.observableArrayList(3, 5, 1)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3, 5, 14)).getResult()); } |
### Question:
SelectionLengthValidator extends CustomValidator<ObservableList<E>> { public static <T> SelectionLengthValidator<T> exactly(int value, String errorMessage) { return new SelectionLengthValidator<>(value, value, errorMessage); } private SelectionLengthValidator(int min, int max, String errorMessage); static SelectionLengthValidator<T> between(int min, int max, String errorMessage); static SelectionLengthValidator<T> atLeast(int min, String errorMessage); static SelectionLengthValidator<T> upTo(int max, String errorMessage); static SelectionLengthValidator<T> exactly(int value, String errorMessage); }### Answer:
@Test public void exactlyTest() { SelectionLengthValidator<Integer> s = SelectionLengthValidator.exactly(2, "test"); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1, 2, 3)).getResult()); Assert.assertTrue(s.validate(FXCollections.observableArrayList(1, 2)).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList()).getResult()); Assert.assertFalse(s.validate(FXCollections.observableArrayList(1)).getResult()); } |
### Question:
StructuredArrayOfAtomicLong extends StructuredArray<AtomicLong> { public static StructuredArrayOfAtomicLong newInstance(final long length) { return StructuredArray.newInstance(StructuredArrayOfAtomicLong.class, AtomicLong.class, length); } static StructuredArrayOfAtomicLong newInstance(final long length); AtomicLong get(long index); }### Answer:
@Test public void shouldInitializeToCorrectValues() { final long length = 1444; final StructuredArrayOfAtomicLong array = StructuredArrayOfAtomicLong.newInstance(length); initSumValues(array); assertCorrectVariableInitialisation(length, array); } |
### Question:
SignatureMethodsHMAC256Impl implements SignatureMethod<SymmetricKeyImpl, SymmetricKeyImpl> { @Override public String calculate(String header, String payload, SymmetricKeyImpl signingKey) { StringBuilder sb = new StringBuilder(); sb.append(header).append(".").append(payload); String stringToSign = sb.toString(); byte[] bytes = stringToSign.getBytes(); try { Mac mac = Mac.getInstance("HMACSHA256"); mac.init(new SecretKeySpec(signingKey.getKey(), mac.getAlgorithm())); mac.update(bytes); bytes = mac.doFinal(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } return TokenDecoder.base64Encode(bytes); } @Override String calculate(String header, String payload, SymmetricKeyImpl signingKey); @Override boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey); @Override String getAlgorithm(); }### Answer:
@Test public void testCalculate() { assertEquals("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", sHmacImpl.calculate(TokenDecoder.base64Encode(hs256), TokenDecoder.base64Encode(payload), key)); } |
### Question:
OAuthASResponse extends OAuthResponse { public static OAuthTokenResponseBuilder tokenResponse(int code) { return new OAuthTokenResponseBuilder(code); } protected OAuthASResponse(String uri, int responseStatus); static OAuthAuthorizationResponseBuilder authorizationResponse(HttpServletRequest request,int code); static OAuthTokenResponseBuilder tokenResponse(int code); }### Answer:
@Test public void testTokenResponse() throws Exception { OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token") .setTokenType("bearer").setExpiresIn("200").setRefreshToken("refresh_token2") .buildBodyMessage(); String body = oAuthResponse.getBody(); assertEquals( "access_token=access_token&refresh_token=refresh_token2&token_type=bearer&expires_in=200", body); }
@Test public void testTokenResponseAdditionalParam() throws Exception { OAuthResponse oAuthResponse = OAuthASResponse.tokenResponse(200).setAccessToken("access_token") .setTokenType("bearer").setExpiresIn("200").setRefreshToken("refresh_token2").setParam("some_param", "new_param") .buildBodyMessage(); String body = oAuthResponse.getBody(); assertEquals( "access_token=access_token&refresh_token=refresh_token2&some_param=new_param&token_type=bearer&expires_in=200", body); } |
### Question:
TokenValidator extends AbstractValidator<HttpServletRequest> { @Override public void validateMethod(HttpServletRequest request) throws OAuthProblemException { String method = request.getMethod(); if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) { throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) .description("Method not correct."); } } TokenValidator(); @Override void validateMethod(HttpServletRequest request); @Override void validateContentType(HttpServletRequest request); }### Answer:
@Test public void testValidateMethod() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.GET); replay(request); TokenValidator validator = new TokenValidator(); validator.validateMethod(request); verify(request); reset(request); request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.POST); replay(request); validator = new TokenValidator(); validator.validateMethod(request); verify(request); reset(request); request = createStrictMock(HttpServletRequest.class); expect(request.getMethod()).andStubReturn(OAuth.HttpMethod.DELETE); replay(request); validator = new TokenValidator(); try { validator.validateMethod(request); Assert.fail("Expected validation exception"); } catch (OAuthProblemException e) { } verify(request); } |
### Question:
OAuthResponse implements OAuthMessage { public static OAuthErrorResponseBuilder errorResponse(int code) { return new OAuthErrorResponseBuilder(code); } protected OAuthResponse(String uri, int responseStatus); static OAuthResponseBuilder status(int code); static OAuthErrorResponseBuilder errorResponse(int code); @Override String getLocationUri(); @Override void setLocationUri(String uri); @Override String getBody(); @Override void setBody(String body); @Override String getHeader(String name); @Override Map<String, String> getHeaders(); @Override void setHeaders(Map<String, String> headers); int getResponseStatus(); @Override void addHeader(String name, String header); }### Answer:
@Test public void testErrorResponse() throws Exception { OAuthResponse oAuthResponse = OAuthResponse.errorResponse(400) .setError("error") .setRealm("album") .setState("ok") .setErrorDescription("error_description") .setErrorUri("http: .setParam("param", "value") .buildJSONMessage(); String body = oAuthResponse.getBody(); assertEquals( "{\"param\":\"value\",\"error_description\":\"error_description\",\"realm\":\"album\",\"state\":\"ok\",\"error\":\"error\",\"error_uri\":\"http: body); } |
### Question:
AbstractValidator implements OAuthValidator<T> { @Override public void validateContentType(T request) throws OAuthProblemException { String contentType = request.getContentType(); final String expectedContentType = OAuth.ContentType.URL_ENCODED; if (!OAuthUtils.hasContentType(contentType, expectedContentType)) { throw OAuthUtils.handleBadContentTypeException(expectedContentType); } } @Override void validateMethod(T request); @Override void validateContentType(T request); @Override void validateRequiredParameters(T request); @Override void validateOptionalParameters(T request); @Override void validateNotAllowedParameters(T request); @Override void validateClientAuthenticationCredentials(T request); @Override void performAllValidations(T request); }### Answer:
@Test public void testValidateContentType() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn(OAuth.ContentType.URL_ENCODED); replay(request); AbstractValidator validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); reset(request); expect(request.getContentType()).andStubReturn(OAuth.ContentType.URL_ENCODED + ";utf-8"); replay(request); validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); }
@Test(expected = OAuthProblemException.class) public void testInvalidContentType() throws Exception { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getContentType()).andStubReturn(OAuth.ContentType.JSON); replay(request); AbstractValidator validator = new AbstractValidatorImpl(); validator.validateContentType(request); verify(request); } |
### Question:
SignatureMethodsHMAC256Impl implements SignatureMethod<SymmetricKeyImpl, SymmetricKeyImpl> { @Override public boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey) { String signed = calculate(header, payload, verifyingKey); return signed.equals(signature); } @Override String calculate(String header, String payload, SymmetricKeyImpl signingKey); @Override boolean verify(String signature, String header, String payload, SymmetricKeyImpl verifyingKey); @Override String getAlgorithm(); }### Answer:
@Test public void testVerify() { String accessToken = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; String jwt[] = accessToken.split("\\."); assertTrue(sHmacImpl.verify(jwt[2], jwt[0], jwt[1], key)); } |
### Question:
JSONUtils { public static String buildJSON(Map<String, Object> params) { final StringWriter stringWriter = new StringWriter(); final JsonGenerator generator = GENERATOR_FACTORY.createGenerator(stringWriter); generator.writeStartObject(); for (Map.Entry<String, Object> param : params.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (key != null && value != null) { if (value instanceof Boolean) { generator.write(key, (Boolean) value); } else if (value instanceof Double) { generator.write(key, (Double) value); } else if (value instanceof Integer) { generator.write(key, (Integer) value); } else if (value instanceof BigDecimal) { generator.write(key, (BigDecimal) value); } else if (value instanceof BigInteger) { generator.write(key, (BigInteger) value); } else if (value instanceof Long) { generator.write(key, (Long) value); } else if (value instanceof String) { String string = (String) value; if (!string.isEmpty()) { generator.write(key, string); } } else if (value.getClass().isArray()) { generator.writeStartArray(key); for (int i = 0; i < Array.getLength(value); i++) { witeItem(generator, Array.get(value, i)); } generator.writeEnd(); } else if (value instanceof Collection) { generator.writeStartArray(key); Collection<?> collection = (Collection<?>) value; for (Object item : collection) { witeItem(generator, item); } generator.writeEnd(); } } } generator.writeEnd().close(); return stringWriter.toString(); } static String buildJSON(Map<String, Object> params); static Map<String, Object> parseJSON(String jsonBody); }### Answer:
@Test public void testBuildJSON() throws Exception { Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuthError.OAUTH_ERROR, OAuthError.TokenResponse.INVALID_REQUEST); String json = JSONUtils.buildJSON(params); assertEquals("{\"error\":\"invalid_request\"}", json); } |
### Question:
JSONUtils { public static Map<String, Object> parseJSON(String jsonBody) { final Map<String, Object> params = new HashMap<String, Object>(); StringReader reader = new StringReader(jsonBody); JsonReader jsonReader = Json.createReader(reader); JsonStructure structure = jsonReader.read(); if (structure == null || structure instanceof JsonArray) { throw new IllegalArgumentException(format("String '%s' is not a valid JSON object representation", jsonBody)); } JsonObject object = (JsonObject) structure; for (Entry<String, JsonValue> entry : object.entrySet()) { String key = entry.getKey(); if (key != null && !key.isEmpty()) { JsonValue jsonValue = entry.getValue(); if (jsonValue != null) { Object value = toJavaObject(jsonValue); params.put(key, value); } } } jsonReader.close(); return params; } static String buildJSON(Map<String, Object> params); static Map<String, Object> parseJSON(String jsonBody); }### Answer:
@Test public void testParseJson() throws Exception { Map<String, Object> jsonParams = new HashMap<String, Object>(); jsonParams.put("author", "John B. Smith"); jsonParams.put("year", "2000"); String s = JSONUtils.buildJSON(jsonParams); Map<String, Object> map = JSONUtils.parseJSON(s); assertEquals("John B. Smith", map.get("author")); assertEquals("2000", map.get("year")); } |
### Question:
OAuthUtils { public static String saveStreamAsString(InputStream is) throws IOException { return toString(is, ENCODING); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testSaveStreamAsString() throws Exception { String sampleTest = "It is raining again today"; InputStream is = new ByteArrayInputStream(sampleTest.getBytes("UTF-8")); assertEquals(sampleTest, OAuthUtils.saveStreamAsString(is)); } |
### Question:
OAuthUtils { public static OAuthProblemException handleOAuthProblemException(String message) { return OAuthProblemException.error(OAuthError.TokenResponse.INVALID_REQUEST) .description(message); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testHandleOAuthProblemException() throws Exception { OAuthProblemException exception = OAuthUtils.handleOAuthProblemException("missing parameter"); assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, exception.getError()); assertEquals("missing parameter", exception.getDescription()); } |
### Question:
OAuthUtils { public static <T> T instantiateClass(Class<T> clazz) throws OAuthSystemException { return instantiateClassWithParameters(clazz, null, null); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testInstantiateClass() throws Exception { StringBuilder builder = OAuthUtils.instantiateClass(StringBuilder.class); assertNotNull(builder); } |
### Question:
OAuthUtils { private static boolean isEmpty(Set<String> missingParams) { if (missingParams == null || missingParams.size() == 0) { return true; } return false; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testIsEmpty() throws Exception { Boolean trueExpected = OAuthUtils.isEmpty(""); Boolean trueExpected2 = OAuthUtils.isEmpty(null); Boolean falseExpected = OAuthUtils.isEmpty("."); assertEquals(true, trueExpected); assertEquals(true, trueExpected2); assertEquals(false, falseExpected); } |
### Question:
OAuthUtils { public static String getAuthzMethod(String header) { if (header != null) { Matcher m = OAUTH_HEADER.matcher(header); if (m.matches()) { return m.group(1); } } return null; } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testGetAuthzMethod() throws Exception { String authzMethod = OAuthUtils.getAuthzMethod("Basic dXNlcjpwYXNzd29yZA=="); assertEquals("Basic", authzMethod); } |
### Question:
OAuthUtils { public static String encodeScopes(Set<String> s) { StringBuffer scopes = new StringBuffer(); for (String scope : s) { scopes.append(scope).append(" "); } return scopes.toString().trim(); } static String format(
final Collection<? extends Map.Entry<String, Object>> parameters,
final String encoding); static String saveStreamAsString(InputStream is); static String toString(
final InputStream is, final String defaultCharset); static OAuthProblemException handleOAuthProblemException(String message); static OAuthProblemException handleMissingParameters(Set<String> missingParams); static OAuthProblemException handleBadContentTypeException(String expectedContentType); static OAuthProblemException handleNotAllowedParametersOAuthException(
List<String> notAllowedParams); static Map<String, Object> decodeForm(String form); static boolean isFormEncoded(String contentType); static String decodePercent(String s); static String percentEncode(String s); static T instantiateClass(Class<T> clazz); static T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes,
Object[] paramValues); static String getAuthHeaderField(String authHeader); static Map<String, String> decodeOAuthHeader(String header); static String[] decodeClientAuthenticationHeader(String authenticationHeader); static String encodeOAuthHeader(Map<String, Object> entries); static String encodeAuthorizationBearerHeader(Map<String, Object> entries); static boolean isEmpty(String value); static boolean hasEmptyValues(String[] array); static String getAuthzMethod(String header); static Set<String> decodeScopes(String s); static String encodeScopes(Set<String> s); static boolean isMultipart(HttpServletRequest request); static boolean hasContentType(String requestContentType, String requiredContentType); static final String AUTH_SCHEME; static final String MULTIPART; }### Answer:
@Test public void testEncodeScopes() throws Exception { Set<String> actual = new HashSet<String>(); actual.add("photo"); actual.add("birth_date"); String actualString = OAuthUtils.encodeScopes(actual); assertEquals("birth_date photo", actualString); } |
### Question:
JSONBodyParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String json = null; try { json = JSONUtils.buildJSON(params); message.setBody(json); return message; } catch (Throwable e) { throw new OAuthSystemException(e); } } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new JSONBodyParametersApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String msgBody = message.getBody(); Map<String, Object> map = JSONUtils.parseJSON(msgBody); assertEquals(3600L, map.get(OAuth.OAUTH_EXPIRES_IN)); assertEquals("token_authz", map.get(OAuth.OAUTH_ACCESS_TOKEN)); assertEquals("code_", map.get(OAuth.OAUTH_CODE)); assertEquals("read", map.get(OAuth.OAUTH_SCOPE)); assertEquals("state", map.get(OAuth.OAUTH_STATE)); assertNull(map.get("empty_param")); assertNull(map.get("null_param")); assertNull(map.get("")); assertNull(map.get(null)); } |
### Question:
BodyURLEncodedParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String body = OAuthUtils.format(params.entrySet(), "UTF-8"); message.setBody(body); return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new BodyURLEncodedParametersApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String body = message.getBody(); Assert.assertTrue(body.contains("3600")); Assert.assertTrue(body.contains("token_authz")); Assert.assertTrue(body.contains("code_")); Assert.assertTrue(body.contains("read")); Assert.assertTrue(body.contains("state")); Assert.assertFalse(body.contains("empty_param")); Assert.assertFalse(body.contains("null_param")); } |
### Question:
WWWAuthHeaderParametersApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException { String header = OAuthUtils.encodeOAuthHeader(params); message.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, header); return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { Map<String, Object> params = new HashMap<String, Object>(); params.put("error", "invalid_token"); params.put("error_uri", "http: params.put("scope", "s1 s2 s3"); params.put("empty_param", ""); params.put("null_param", null); params.put("", "some_value"); params.put(null, "some_value"); OAuthResponse res = OAuthResponse.status(200).location("").buildQueryMessage(); OAuthParametersApplier applier = new WWWAuthHeaderParametersApplier(); res = (OAuthResponse)applier.applyOAuthParameters(res, params); assertNotNull(res); String header = res.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE); assertNotNull(header); assertEquals(OAuth.OAUTH_HEADER_NAME + " scope=\"s1 s2 s3\",error=\"invalid_token\",error_uri=\"http: header); } |
### Question:
QueryParameterApplier implements OAuthParametersApplier { public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) { String messageUrl = message.getLocationUri(); if (messageUrl != null) { boolean containsQuestionMark = messageUrl.contains("?"); StringBuffer url = new StringBuffer(messageUrl); StringBuffer query = new StringBuffer(OAuthUtils.format(params.entrySet(), "UTF-8")); if (!OAuthUtils.isEmpty(query.toString())) { if (containsQuestionMark) { url.append("&").append(query); } else { url.append("?").append(query); } } message.setLocationUri(url.toString()); } return message; } OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params); }### Answer:
@Test public void testApplyOAuthParameters() throws Exception { OAuthParametersApplier app = new QueryParameterApplier(); Map<String, Object> params = new HashMap<String, Object>(); params.put(OAuth.OAUTH_EXPIRES_IN, 3600l); params.put(OAuth.OAUTH_ACCESS_TOKEN, "token_authz"); params.put(OAuth.OAUTH_CODE, "code_"); params.put(OAuth.OAUTH_SCOPE, "read"); params.put(OAuth.OAUTH_STATE, "state"); params.put("empty_param", ""); params.put("null_param", null); OAuthMessage message = new DummyOAuthMessage("http: app.applyOAuthParameters(message, params); String locationURI = message.getLocationUri(); Assert.assertTrue(locationURI.contains("3600")); Assert.assertTrue(locationURI.contains("token_authz")); Assert.assertTrue(locationURI.contains("code_")); Assert.assertTrue(locationURI.contains("read")); Assert.assertTrue(locationURI.contains("state")); Assert.assertTrue(!locationURI.contains("empty_param")); Assert.assertTrue(!locationURI.contains("null_param")); } |
### Question:
OAuthResourceResponse extends OAuthClientResponse { public InputStream getBodyAsInputStream() { if (bodyRetrieved && inputStream == null) { throw new IllegalStateException("Cannot call getBodyAsInputStream() after getBody()"); } bodyRetrieved = true; return inputStream; } OAuthResourceResponse(); String getBody(); int getResponseCode(); String getContentType(); Map<String, List<String>> getHeaders(); InputStream getBodyAsInputStream(); }### Answer:
@Test public void allowBinaryResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(BINARY); final byte[] bytes = IOUtils.toByteArray(resp.getBodyAsInputStream()); assertArrayEquals(BINARY, bytes); }
@Test public void allowStringAsBinaryResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(STRING_BYTES); final byte[] bytes = IOUtils.toByteArray(resp.getBodyAsInputStream()); assertArrayEquals(STRING_BYTES, bytes); } |
### Question:
OAuthResourceResponse extends OAuthClientResponse { public String getBody() { if (bodyRetrieved && body == null) { throw new IllegalStateException("Cannot call getBody() after getBodyAsInputStream()"); } if (body == null) { try { body = OAuthUtils.saveStreamAsString(getBodyAsInputStream()); inputStream = null; } catch (IOException e) { LOG.error("Failed to convert InputStream to String", e); } } return body; } OAuthResourceResponse(); String getBody(); int getResponseCode(); String getContentType(); Map<String, List<String>> getHeaders(); InputStream getBodyAsInputStream(); }### Answer:
@Test public void allowStringResponseBody() throws OAuthProblemException, OAuthSystemException, IOException { final OAuthResourceResponse resp = createBinaryResponse(STRING_BYTES); assertEquals("getBody() should return correct string", STRING, resp.getBody()); } |
### Question:
OAuthClientResponseFactory { public static OAuthClientResponse createGitHubTokenResponse(String body, String contentType, int responseCode) throws OAuthProblemException { GitHubTokenResponse resp = new GitHubTokenResponse(); resp.init(body, contentType, responseCode); return resp; } static OAuthClientResponse createGitHubTokenResponse(String body, String contentType,
int responseCode); static OAuthClientResponse createJSONTokenResponse(String body, String contentType,
int responseCode); static T createCustomResponse(String body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); static T createCustomResponse(InputStream body, String contentType,
int responseCode,
Map<String, List<String>> headers,
Class<T> clazz); }### Answer:
@Test public void testCreateGitHubTokenResponse() throws Exception { OAuthClientResponse gitHubTokenResponse = OAuthClientResponseFactory .createGitHubTokenResponse("access_token=123", OAuth.ContentType.URL_ENCODED, 200); assertNotNull(gitHubTokenResponse); } |
Subsets and Splits