focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
protected final void ensureCapacity(final int index, final int length)
{
if (index < 0 || length < 0)
{
throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length);
}
final long resultingPosition = index + (long)length;
if (resulti... | @Test
void ensureCapacityThrowsIndexOutOfBoundsExceptionIfIndexIsNegative()
{
final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(1);
final IndexOutOfBoundsException exception =
assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(-3, 4));
... |
static String encodeString(Utf8String string) {
byte[] utfEncoded = string.getValue().getBytes(StandardCharsets.UTF_8);
return encodeDynamicBytes(new DynamicBytes(utfEncoded));
} | @Test
public void testUtf8String() {
Utf8String string = new Utf8String("Hello, world!");
assertEquals(
TypeEncoder.encodeString(string),
("000000000000000000000000000000000000000000000000000000000000000d"
+ "48656c6c6f2c20776f726c6421000000000... |
@Override
public CompletableFuture<Acknowledge> requestSlot(
final SlotID slotId,
final JobID jobId,
final AllocationID allocationId,
final ResourceProfile resourceProfile,
final String targetAddress,
final ResourceManagerId resourceManagerId,
... | @Test
void testJobLeaderDetection() throws Exception {
final TaskSlotTable<Task> taskSlotTable =
TaskSlotUtils.createTaskSlotTable(1, EXECUTOR_EXTENSION.getExecutor());
final JobLeaderService jobLeaderService =
new DefaultJobLeaderService(
unre... |
public static Serializable decode(final ByteBuf byteBuf) {
int valueType = byteBuf.readUnsignedByte() & 0xff;
StringBuilder result = new StringBuilder();
decodeValue(valueType, 1, byteBuf, result);
return result.toString();
} | @Test
void assertDecodeSmallJsonObjectWithUInt32() {
List<JsonEntry> jsonEntries = new LinkedList<>();
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT32, "key1", Integer.MAX_VALUE));
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT32, "key2", Integer.MIN_VALUE));
ByteBuf payload =... |
public static SessionWindows ofInactivityGapWithNoGrace(final Duration inactivityGap) {
return ofInactivityGapAndGrace(inactivityGap, ofMillis(NO_GRACE_PERIOD));
} | @Test
public void windowSizeMustNotBeZero() {
assertThrows(IllegalArgumentException.class, () -> SessionWindows.ofInactivityGapWithNoGrace(ofMillis(0)));
} |
@Nonnull
public static String fillLeft(int len, @Nonnull String pattern, @Nullable String string) {
StringBuilder sb = new StringBuilder(string == null ? "" : string);
while (sb.length() < len)
sb.insert(0, pattern);
return sb.toString();
} | @Test
void testFillLeft() {
assertEquals("aaab", StringUtil.fillLeft(4, "a", "b"));
assertEquals("aaaa", StringUtil.fillLeft(4, "a", null));
} |
@Override
public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) {
RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count);
return syncFuture(f);
} | @Test
public void testClusterGetKeysInSlot() {
connection.flushAll();
List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10);
assertThat(keys).isEmpty();
} |
@Override
public boolean isInSameDatabaseInstance(final ConnectionProperties connectionProps) {
return hostname.equals(connectionProps.getHostname()) && port == connectionProps.getPort();
} | @Test
void assertIsInSameDatabaseInstance() {
assertTrue(new StandardConnectionProperties("127.0.0.1", 9999, "foo", "foo")
.isInSameDatabaseInstance(new StandardConnectionProperties("127.0.0.1", 9999, "bar", "bar")));
} |
protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor c... | @Test
void testInterceptorsFromAnnotation2() {
final List<ClientInterceptor> beans =
assertDoesNotThrow(() -> this.postProcessor.interceptorsFromAnnotation(new GrpcClient() {
@Override
public Class<? extends Annotation> annotationType() {
... |
public static NamedFieldsMapping mapping( String[] actualFieldNames, String[] metaFieldNames ) {
LinkedHashMap<String, List<Integer>> metaNameToIndex = new LinkedHashMap<>();
List<Integer> unmatchedMetaFields = new ArrayList<>();
int[] actualToMetaFieldMapping = new int[ actualFieldNames == null ? 0 : actua... | @Test
public void mapping() {
NamedFieldsMapping mapping =
NamedFieldsMapping.mapping( new String[] { "FIRST", "SECOND", "THIRD" }, new String[] { "SECOND", "THIRD" } );
assertEquals( 0, mapping.fieldMetaIndex( 1 ) );
} |
public static Namespace of(String... levels) {
Preconditions.checkArgument(null != levels, "Cannot create Namespace from null array");
if (levels.length == 0) {
return empty();
}
for (String level : levels) {
Preconditions.checkNotNull(level, "Cannot create a namespace with a null level");
... | @Test
public void testDisallowsNamespaceWithNullByte() {
assertThatThrownBy(() -> Namespace.of("ac", "\u0000c", "b"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot create a namespace with the null-byte character");
assertThatThrownBy(() -> Namespace.of("ac", "c\0", "b"))
... |
public static InetSocketAddress getConnectAddress(Server server) {
return getConnectAddress(server.getListenerAddress());
} | @Test
public void testGetConnectAddress() throws IOException {
NetUtils.addStaticResolution("host", "127.0.0.1");
InetSocketAddress addr = NetUtils.createSocketAddrForHost("host", 1);
InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr);
assertEquals(addr.getHostName(), connectAddr.getHost... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
return super.read(file, status, callback);
}
catch(AccessDeniedException e) {
headers.clear();
return supe... | @Test
public void testReadConcurrency() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomS... |
@VisibleForTesting
static void computeAndSetAggregatedInstanceStatus(
WorkflowInstance currentInstance, WorkflowInstanceAggregatedInfo aggregated) {
if (!currentInstance.getStatus().isTerminal()
|| currentInstance.isFreshRun()
|| !currentInstance.getStatus().equals(WorkflowInstance.Status.SU... | @Test
public void testAggregatedInstanceStatusFromAggregatedV2() {
WorkflowInstance run1 =
getGenericWorkflowInstance(
2,
WorkflowInstance.Status.SUCCEEDED,
RunPolicy.RESTART_FROM_INCOMPLETE,
RestartPolicy.RESTART_FROM_INCOMPLETE);
WorkflowInstanceAggre... |
@Override
public String getURL( String hostname, String port, String databaseName ) {
String url = "jdbc:sqlserver://" + hostname + ":" + port + ";database=" + databaseName + ";encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
if ( getAttribute( IS_ALWAY... | @Test
public void testAlwaysEncryptionParameterIncludedInUrl() {
dbMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE );
dbMeta.addAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "true" );
dbMeta.addAttribute( CLIENT_ID, "dummy" );
dbMeta.addAttribute( CLIENT_SECRET_KEY, "xxxxx" );
String expectedUrl = ... |
@Override
protected ExecuteContext doBefore(ExecuteContext context) {
LogUtils.printHttpRequestBeforePoint(context);
Object[] arguments = context.getArguments();
AbstractClientHttpRequest request = (AbstractClientHttpRequest) arguments[0];
Optional<Object> httpRequest = ReflectUtils.... | @Test
public void test() {
// Test for normal conditions
AbstractClientHttpRequest request = new HttpComponentsClientHttpRequest(HttpMethod.GET, HELLO_URI,
HttpClientContext.create(), new DefaultDataBufferFactory());
arguments[0] = request;
ReflectUtils.setFieldValue(... |
public String get(String key) {
Supplier<String> supplier = evaluatedEntries.get(key);
return supplier != null
? supplier.get()
: null;
} | @Test
public void testNullValue() throws Throwable {
assertThat(context.get(PARAM_PROCESS))
.describedAs("Value of context element %s", PARAM_PROCESS)
.isNull();
} |
public static GeneratedResources getGeneratedResourcesObject(String generatedResourcesString) throws JsonProcessingException {
return objectMapper.readValue(generatedResourcesString, GeneratedResources.class);
} | @Test
void getGeneratedResourcesObjectFromJar() throws Exception {
ClassLoader originalClassLoader = addJarToClassLoader();
Optional<File> optionalIndexFile = getFileFromFileName("IndexFile.testb_json");
assertThat(optionalIndexFile).isNotNull().isPresent();
assertThat(optionalIndexF... |
public static TableSchema.Builder builderWithGivenSchema(TableSchema oriSchema) {
TableSchema.Builder builder = builderWithGivenColumns(oriSchema.getTableColumns());
// Copy watermark specification.
for (WatermarkSpec wms : oriSchema.getWatermarkSpecs()) {
builder.watermark(
... | @Test
void testBuilderWithGivenSchema() {
TableSchema oriSchema =
TableSchema.builder()
.field("a", DataTypes.INT().notNull())
.field("b", DataTypes.STRING())
.field("c", DataTypes.INT(), "a + 1")
... |
@Override
@MethodNotAvailable
public boolean evict(K key) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testEvict() {
adapter.evict(23);
} |
public static void setNamespaceDefaultId(String namespaceDefaultId) {
NamespaceUtil.namespaceDefaultId = namespaceDefaultId;
} | @Test
void testSetNamespaceDefaultId() {
NamespaceUtil.setNamespaceDefaultId("Deprecated");
assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId());
} |
@Override
public String getFileId(final Path file) throws BackgroundException {
if(StringUtils.isNotBlank(file.attributes().getFileId())) {
return file.attributes().getFileId();
}
if(file.isRoot()
|| new SimplePathPredicate(file).test(DriveHomeFinderService.MYDRIV... | @Test
public void testGetFileidSameName() throws Exception {
final String filename = new AlphanumericRandomStringService().random();
final Path test1 = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, filename, EnumSet.of(Path.Type.file));
final DriveFileIdProvider fileid = new DriveFileIdPro... |
public static Throwable stripException(
Throwable throwableToStrip, Class<? extends Throwable> typeToStrip) {
while (typeToStrip.isAssignableFrom(throwableToStrip.getClass())
&& throwableToStrip.getCause() != null) {
throwableToStrip = throwableToStrip.getCause();
... | @Test
void testExceptionStripping() {
final FlinkException expectedException = new FlinkException("test exception");
final Throwable strippedException =
ExceptionUtils.stripException(
new RuntimeException(new RuntimeException(expectedException)),
... |
public boolean removeWatchedAddresses(final List<Address> addresses) {
List<Script> scripts = new ArrayList<>();
for (Address address : addresses) {
Script script = ScriptBuilder.createOutputScript(address);
scripts.add(script);
}
return removeWatchedScripts(scr... | @Test
public void removeWatchedAddresses() {
List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, TESTNET);
addressesForRemoval.add(watchedAddress);
wallet.addWatched... |
@Override
public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException {
Collection<TableMetaData> tableMetaDataList = new LinkedList<>();
try (Connection connection = new MetaDataLoaderConnection(TypedSPILoader.getService(DatabaseType.class, "Oracle"), material.... | @Test
void assertLoadCondition1() throws SQLException {
DataSource dataSource = mockDataSource();
ResultSet resultSet = mockTableMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(ALL_TAB_COLUMNS_SQL_CONDITION1).executeQuery()).thenReturn(resultSet);
ResultSet inde... |
@Override
public void delete(InputWithExtractors nativeEntity) {
inputService.destroy(nativeEntity.input());
} | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void delete() throws NotFoundException {
final Input input = inputService.find("5acc84f84b900a4ff290d9a7");
final InputWithExtractors inputWithExtractors = InputWithExtractors.create(input);
assertThat(inputService.totalCount()).isEq... |
@Override
public boolean add(V value) {
lock.lock();
try {
checkComparator();
BinarySearchResult<V> res = binarySearch(value);
int index = 0;
if (res.getIndex() < 0) {
index = -(res.getIndex() + 1);
} else {
... | @Test
public void testIteratorNextNext() {
RPriorityQueue<String> list = redisson.getPriorityQueue("simple");
list.add("1");
list.add("4");
Iterator<String> iter = list.iterator();
Assertions.assertEquals("1", iter.next());
Assertions.assertEquals("4", iter.next());
... |
public static <K, V, R> Map<K, R> map(Map<K, V> map, BiFunction<K, V, R> biFunction) {
if (null == map || null == biFunction) {
return MapUtil.newHashMap();
}
return map.entrySet().stream().collect(CollectorUtil.toMap(Map.Entry::getKey, m -> biFunction.apply(m.getKey(), m.getValue()), (l, r) -> l));
} | @Test
public void mapTest() {
// Add test like a foreigner
final Map<Integer, String> adjectivesMap = MapUtil.<Integer, String>builder()
.put(0, "lovely")
.put(1, "friendly")
.put(2, "happily")
.build();
final Map<Integer, String> resultMap = MapUtil.map(adjectivesMap, (k, v) -> v + " " + People... |
@Override
public void report() {
try {
tryReport();
} catch (ConcurrentModificationException | NoSuchElementException ignored) {
// at tryReport() we don't synchronize while iterating over the various maps which might
// cause a
// ConcurrentModificati... | @Test
void testOnlyCounterRegistered() {
reporter.notifyOfAddedMetric(new SimpleCounter(), "metric", metricGroup);
reporter.report();
assertThat(testLoggerResource.getMessages())
.noneMatch(logOutput -> logOutput.contains("-- Meter"))
.noneMatch(logOutput ->... |
public RegistryBuilder port(Integer port) {
this.port = port;
return getThis();
} | @Test
void port() {
RegistryBuilder builder = new RegistryBuilder();
builder.port(8080);
Assertions.assertEquals(8080, builder.build().getPort());
} |
@Override
public Neighbor<double[], E>[] search(double[] q, int k) {
if (model == null) return super.search(q, k);
return search(q, k, 0.95, 100);
} | @Test
public void testRange() {
System.out.println("range");
int[] recall = new int[testx.length];
for (int i = 0; i < testx.length; i++) {
ArrayList<Neighbor<double[], double[]>> n1 = new ArrayList<>();
ArrayList<Neighbor<double[], double[]>> n2 = new ArrayList<>();... |
public static String getKeySchemaName(final String name) {
final String camelName = CaseFormat.UPPER_UNDERSCORE
.converterTo(CaseFormat.UPPER_CAMEL)
.convert(name);
return AvroProperties.AVRO_SCHEMA_NAMESPACE + "." + camelName + "Key";
} | @Test
public void shouldConvertNames() {
assertThat(AvroFormat.getKeySchemaName("foo"), is("io.confluent.ksql.avro_schemas.FooKey"));
assertThat(AvroFormat.getKeySchemaName("Foo"), is("io.confluent.ksql.avro_schemas.FooKey"));
assertThat(AvroFormat.getKeySchemaName("FOO"), is("io.confluent.ksql.avro_schem... |
Object[] findValues(int ordinal) {
return getAllValues(ordinal, type, 0);
} | @Test
public void testSetIntegerReference() throws Exception {
SetType setType = new SetType();
setType.intValues = new HashSet<>(Arrays.asList(1, 2, 3));
objectMapper.add(setType);
StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine);
FieldPath fiel... |
public BlobOperationResponse deleteContainer(final Exchange exchange) {
final BlobRequestConditions blobRequestConditions = configurationProxy.getBlobRequestConditions(exchange);
final Duration timeout = configurationProxy.getTimeout(exchange);
final BlobExchangeHeaders blobExchangeHeaders
... | @Test
void testDeleteContainer() {
when(client.deleteContainer(any(), any())).thenReturn(deleteContainerMock());
final BlobContainerOperations blobContainerOperations = new BlobContainerOperations(configuration, client);
final BlobOperationResponse response = blobContainerOperations.deleteC... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseLiteralStepParameterWithStepId() {
StringParameter bar = StringParameter.builder().name("bar").value("test ${step1__foo}").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.singletonMap("foo", StringParame... |
private void sendResponse(Response response) {
try {
((GrpcConnection) this.currentConnection).sendResponse(response);
} catch (Exception e) {
LOGGER.error("[{}]Error to send ack response, ackId->{}", this.currentConnection.getConnectionId(),
response.getReque... | @Test
void testBindRequestStreamOnNextParseException()
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection... |
private void checkDropMaterializedView(String mvName, OlapTable olapTable)
throws DdlException, MetaNotFoundException {
Preconditions.checkState(olapTable.getState() == OlapTableState.NORMAL, olapTable.getState().name());
if (mvName.equals(olapTable.getName())) {
throw new DdlExc... | @Test
public void testCheckDropMaterializedView(@Injectable OlapTable olapTable, @Injectable Partition partition,
@Injectable MaterializedIndex materializedIndex,
@Injectable Database db) {
String mvName = "mv_1";
... |
@Override
public List<TableIdentifier> listTables(Namespace namespace) {
SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace);
Preconditions.checkArgument(
scope.type() == SnowflakeIdentifier.Type.SCHEMA,
"listTables must be at SCHEMA level; got %s from namespace %s",
... | @Test
public void testListTablesWithinDB() {
String dbName = "DB_1";
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> catalog.listTables(Namespace.of(dbName)))
.withMessageContaining("listTables must be at SCHEMA level");
} |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetPartialGenericBiFunction() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericBiFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getSchemaFromType(genericType);
// Then:
assertTh... |
Flux<DataEntityList> export(KafkaCluster cluster) {
String clusterOddrn = Oddrn.clusterOddrn(cluster);
Statistics stats = statisticsCache.get(cluster);
return Flux.fromIterable(stats.getTopicDescriptions().keySet())
.filter(topicFilter)
.flatMap(topic -> createTopicDataEntity(cluster, topic,... | @Test
void doesNotExportTopicsWhichDontFitFiltrationRule() {
when(schemaRegistryClientMock.getSubjectVersion(anyString(), anyString(), anyBoolean()))
.thenReturn(Mono.error(WebClientResponseException.create(404, "NF", new HttpHeaders(), null, null, null)));
stats = Statistics.empty()
.toBuilde... |
@Override
public Class<? extends StorageBuilder> builder() {
return MinStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), SMALL_VALUE);
function.calculate();
StorageBuilder<MinFunction> storageBuilder = function.builder().newInstance();
final Has... |
@VisibleForTesting
static int findEndPosition(int startPosition, int endPosition, BiPredicate<Integer, Integer> comparator)
{
checkArgument(startPosition >= 0, "startPosition must be greater or equal than zero: %s", startPosition);
checkArgument(startPosition < endPosition, "startPosition (%s) m... | @Test
public void testFindEndPosition()
{
assertFindEndPosition("0", 1);
assertFindEndPosition("11", 2);
assertFindEndPosition("1111111111", 10);
assertFindEndPosition("01", 1);
assertFindEndPosition("011", 1);
assertFindEndPosition("0111", 1);
assertFind... |
public void updateTopicConfig(final TopicConfig topicConfig) {
updateSingleTopicConfigWithoutPersist(topicConfig);
this.persist(topicConfig.getTopicName(), topicConfig);
} | @Test
public void testNormalUpdateUnchangeableKeyOnUpdating() {
String topic = "exist-topic";
supportAttributes(asList(
new EnumAttribute("enum.key", true, newHashSet("enum-1", "enum-2", "enum-3"), "enum-1"),
new BooleanAttribute("bool.key", true, false),
... |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeWithIncludeFailsOnDuplicateRegularColumn() {
Schema sourceSchema = Schema.newBuilder().column("one", DataTypes.INT()).build();
List<SqlNode> derivedColumns =
Arrays.asList(
regularColumn("two", DataTypes.INT()),
regular... |
@Description("greedily removes occurrences of a pattern in a string")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("varchar(x)")
public static Slice replace(@SqlType("varchar(x)") Slice str, @SqlType("varchar(y)") Slice search)
{
return replace(str, search, Slices.EMPTY_SLICE);
... | @Test
public void testReplace()
{
assertFunction("REPLACE('aaa', 'a', 'aa')", createVarcharType(11), "aaaaaa");
assertFunction("REPLACE('abcdefabcdef', 'cd', 'XX')", createVarcharType(38), "abXXefabXXef");
assertFunction("REPLACE('abcdefabcdef', 'cd')", createVarcharType(12), "abefabef")... |
public static void adjustImageConfigForTopo(Map<String, Object> conf, Map<String, Object> topoConf, String topoId)
throws InvalidTopologyException {
//don't need sanity check here as we assume it's already done during daemon startup
List<String> allowedImages = getAllowedImages(conf, false);
... | @Test
public void adjustImageConfigForTopoNotInAllowedList() {
String image1 = "storm/rhel7:dev_test";
String image2 = "storm/rhel7:dev_current";
Map<String, Object> conf = new HashMap<>();
List<String> allowedImages = new ArrayList<>();
allowedImages.add(image1);
co... |
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) {
invokeCompletedOffsetCommitCallbacks();
if (offsets.isEmpty()) {
// We guarantee that the callbacks for all commitAsync() will be invoked when
// commitSync() completes, even if the u... | @Test
public void testCommitOffsetSyncWithoutFutureGetsCompleted() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
assertFalse(coordinator.commitOffsetsSync(singletonMap(t1p, new OffsetAndMetadata(100L)), ... |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/export/by-query", produces = MediaType.APPLICATION_OCTET_STREAM)
@Operation(
tags = {"Flows"},
summary = "Export flows as a ZIP archive of yaml sources."
)
public HttpResponse<byte[]> exportByQuery(
@Parameter(description = "A string filt... | @Test
void exportByQuery() throws IOException {
byte[] zip = client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/export/by-query?namespace=io.kestra.tests"),
Argument.of(byte[].class));
File file = File.createTempFile("flows", ".zip");
Files.write(file.toPath(), zip);
... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void returnOnErrorUsingMaybe() throws InterruptedException {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
given(helloWorldService.returnHelloWorld())
.willThrow(new HelloWorldException());
Maybe.fromCallable(helloWorldServic... |
@GetMapping("")
public ShenyuAdminResult queryApis(final String apiPath, final Integer state,
final String tagId,
@NotNull final Integer currentPage,
@NotNull final Integer pageSize) {
Common... | @Test
public void testQueryApis() throws Exception {
final PageParameter pageParameter = new PageParameter();
List<ApiVO> apiVOS = new ArrayList<>();
apiVOS.add(apiVO);
final CommonPager<ApiVO> commonPager = new CommonPager<>();
commonPager.setPage(pageParameter);
com... |
public Result checkConnectionToPackage(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_CHECK_PACKAGE_CONNECTION, new Def... | @Test
public void shouldTalkToPluginToCheckPackageConnectionFailure() throws Exception {
String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," +
"\"package-configuration\":{\"key-three\":{\"value\":\"value-... |
@Override
@SuppressWarnings("unchecked")
public AccessToken load(String token) {
DBObject query = new BasicDBObject();
query.put(AccessTokenImpl.TOKEN, cipher.encrypt(token));
final List<DBObject> objects = query(AccessTokenImpl.class, query);
if (objects.isEmpty()) {
... | @Test
@MongoDBFixtures("accessTokensSingleToken.json")
public void testLoadSingleToken() throws Exception {
final AccessToken accessToken = accessTokenService.load("foobar");
assertNotNull("Matching token should have been returned", accessToken);
assertEquals("foobar", accessToken.getTok... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_map_of_non_serializable_value_with_null_value() {
Map<String, NonSerializableObject> original = new LinkedHashMap<>();
original.put("null", null);
original.put("key", new NonSerializableObject("value"));
Object cloned = serializer.clone(original);
... |
void serialize(OutputStream out, TransportSecurityOptions options) {
try {
mapper.writerWithDefaultPrettyPrinter().writeValue(out, toTransportSecurityOptionsEntity(options));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | @Test
void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
... |
@Nonnull
public static <T> Traverser<T> traverseSpliterator(@Nonnull Spliterator<T> spliterator) {
return new SpliteratorTraverser<>(spliterator);
} | @Test(expected = NullPointerException.class)
public void when_traverseSpliteratorWithNull_then_failure() {
Traverser<Integer> trav = traverseSpliterator(Stream.of(1, null).spliterator());
trav.next();
trav.next();
} |
@Override
public String fetchArtifactMessage(ArtifactStore artifactStore, Configuration configuration, Map<String, Object> metadata, String agentWorkingDirectory) {
final Map<String, Object> map = new HashMap<>();
map.put("store_configuration", artifactStore.getConfigurationAsMap(true));
map... | @Test
public void fetchArtifactMessage_shouldSerializeToJson() {
final ArtifactMessageConverterV2 converter = new ArtifactMessageConverterV2();
final ArtifactStore artifactStore = new ArtifactStore("s3-store", "pluginId", create("Foo", false, "Bar"));
final Map<String, Object> metadata = Map... |
public static StrimziPodSet createPodSet(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
ResourceTemplate template,
int replicas,
Map<String, String> annotations,
Labels selectorLabels,
... | @Test
public void testCreateStrimziPodSetWithTemplate() {
List<Integer> podIds = new ArrayList<>();
StrimziPodSet sps = WorkloadUtils.createPodSet(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
new ResourceTemplateBuilder(... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthSendTransaction() throws Exception {
web3j.ethSendTransaction(
new Transaction(
"0xb60e8dd61c5d32be8058bb8eb970870f07233155",
BigInteger.ONE,
Numeric.toBigInt("0x9... |
@Override
public void publish(ScannerReportWriter writer) {
ScannerReport.Component.Builder projectBuilder = prepareProjectBuilder();
ScannerReport.Component.Builder fileBuilder = ScannerReport.Component.newBuilder();
for (DefaultInputFile file : inputComponentStore.allFilesToPublish()) {
projectBu... | @Test
public void publish_project_with_links() throws Exception {
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setProperty(CoreProper... |
static void execute(String... args) throws Exception {
if (args.length != 5 && args.length != 6) {
throw new TerseException("USAGE: java " + EndToEndLatency.class.getName()
+ " broker_list topic num_messages producer_acks message_size_bytes [optional] properties_file");
}... | @Test
public void shouldFailWhenSuppliedUnexpectedArgs() {
String[] args = new String[] {"localhost:9092", "test", "10000", "1", "200", "propsfile.properties", "random"};
assertThrows(TerseException.class, () -> EndToEndLatency.execute(args));
} |
@Override
public void removeService(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);
synchronized (this) {
if (isServiceInUse(uid)) {
final String error = String.format(MSG_SERVICE, uid, ERR_IN_USE);
throw new IllegalStateEx... | @Test(expected = IllegalArgumentException.class)
public void testRemoveServiceWithNull() {
target.removeService(null);
} |
public Map<String, Map<String, Object>> getPropertyMetadataAndValuesAsMap() {
Map<String, Map<String, Object>> configMap = new HashMap<>();
for (ConfigurationProperty property : this) {
Map<String, Object> mapValue = new HashMap<>();
mapValue.put("isSecure", property.isSecure());... | @Test
void shouldReturnConfigWithMetadataAsMap() throws CryptoException {
ConfigurationProperty configurationProperty1 = ConfigurationPropertyMother.create("property1", false, "value");
ConfigurationProperty configurationProperty2 = ConfigurationPropertyMother.create("property2", false, null);
... |
public static byte[] getValue(byte[] raw) {
try (final Asn1InputStream is = new Asn1InputStream(raw)) {
is.readTag();
return is.read(is.readLength());
}
} | @Test
public void getValueShouldSkipExtendedTagAndLength() {
assertArrayEquals(new byte[] { 0x31 }, Asn1Utils.getValue(new byte[] { 0x7f, 0x01, 1, 0x31}));
} |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void retryOnResultUsingFlowable() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);... |
public <V> V retryCallable(
Callable<V> callable, Set<Class<? extends Exception>> exceptionsToIntercept) {
return RetryHelper.runWithRetries(
callable,
getRetrySettings(),
getExceptionHandlerForExceptions(exceptionsToIntercept),
NanoClock.getDefaultClock());
} | @Test(expected = RetryHelperException.class)
public void testRetryCallable_ThrowsRetryHelperExceptionOnUnspecifiedException() {
Callable<Integer> incrementingFunction =
() -> {
throw new DoNotIgnoreException();
};
retryCallableManager.retryCallable(incrementingFunction, ImmutableSet.... |
@Override
protected void set(String key, String value) {
localProperties.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
} | @Test
public void set_will_throw_NPE_if_key_is_null() {
assertThatThrownBy(() -> underTest.set(null, ""))
.isInstanceOf(NullPointerException.class)
.hasMessage("key can't be null");
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definitio... | @Test
void invokeListParamReturnNull() {
FunctionTestUtil.assertResultNull(allFunction.invoke(Arrays.asList(Boolean.TRUE, null, Boolean.TRUE)));
} |
@Override
@PublicAPI(usage = ACCESS)
public boolean isAnnotatedWith(Class<? extends Annotation> annotationType) {
return packageInfo.map(it -> it.isAnnotatedWith(annotationType)).orElse(false);
} | @Test
public void test_isAnnotatedWith_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class)).isTrue();
assertT... |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseCl... | @Test
void getExceptionWithMessageAndNestedException() {
final FailedState failedState = new FailedState("JobRunr message", new CustomException("custom exception message", new CustomException()));
assertThat(failedState.getException())
.isInstanceOf(CustomException.class)
... |
@Override
public Num calculate(BarSeries series, Position position) {
int beginIndex = position.getEntry().getIndex();
int endIndex = series.getEndIndex();
return criterion.calculate(series, createEnterAndHoldTrade(series, beginIndex, endIndex));
} | @Test
public void calculateOnlyWithLossPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series),
Trade.buyAt(2, series), Trade.sellAt(5, series));... |
@Override
public OAuth2AccessTokenDO removeAccessToken(String accessToken) {
// 删除访问令牌
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenMapper.selectByAccessToken(accessToken);
if (accessTokenDO == null) {
return null;
}
oauth2AccessTokenMapper.deleteById(acce... | @Test
public void testRemoveAccessToken_null() {
// 调用,并断言
assertNull(oauth2TokenService.removeAccessToken(randomString()));
} |
public static String version() {
return IcebergBuild.version();
} | @Test
public void testGetVersion() {
String version = IcebergSinkConfig.version();
assertThat(version).isNotNull();
} |
Future<Boolean> canRoll(int podId) {
LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId);
return canRollBroker(descriptions, podId);
} | @Test
public void testCanRollThrowsTimeoutExceptionWhenTopicsListThrowsException(VertxTestContext context) {
KSB ksb = new KSB()
.addNewTopic("A", false)
.addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
.addNewPartition(0)
... |
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be null");
if (dataTable.isEmpty()) {... | @Test
void to_map_of_entry_to_row__throws_exception__more_values_then_keys() {
DataTable table = parse("",
"| code | 29.993333 | -90.258056 |",
"| KSFO | 37.618889 | -122.375 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KJFK | 40.639722 | -73.778889 |");
... |
public RelDataType createRelDataTypeFromSchema(Schema schema) {
Builder builder = new Builder(this);
boolean enableNullHandling = schema.isEnableColumnBasedNullHandling();
for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) {
builder.add(entry.getKey(), toRelDataType(entry.g... | @Test(dataProvider = "relDataTypeConversion")
public void testNullableScalarTypes(FieldSpec.DataType dataType, RelDataType scalarType, boolean columnNullMode) {
TypeFactory typeFactory = new TypeFactory();
Schema testSchema = new Schema.SchemaBuilder()
.addDimensionField("col", dataType, field -> fiel... |
@CanIgnoreReturnValue
public final Ordered containsExactly() {
return containsExactlyEntriesIn(ImmutableMap.of());
} | @Test
public void containsExactlyEmpty_fails() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
expectFailureWhenTestingThat(actual).containsExactly();
assertFailureKeys("expected to be empty", "but was");
} |
@Override
public Progress getProgress() {
// If current tracking range is no longer growable, get progress as a normal range.
if (range.getTo() != Long.MAX_VALUE || range.getTo() == range.getFrom()) {
return super.getProgress();
}
// Convert to BigDecimal in computation to prevent overflow, whi... | @Test
public void testProgressAfterFinished() throws Exception {
SimpleEstimator simpleEstimator = new SimpleEstimator();
GrowableOffsetRangeTracker tracker = new GrowableOffsetRangeTracker(10L, simpleEstimator);
assertFalse(tracker.tryClaim(Long.MAX_VALUE));
tracker.checkDone();
simpleEstimator.s... |
public static String getStackTracker( Throwable e ) {
return getClassicStackTrace( e );
} | @Test
public void testStackTracker() {
assertTrue( Const.getStackTracker( new Exception() ).contains( getClass().getName() + ".testStackTracker("
+ getClass().getSimpleName() + ".java:" ) );
} |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeAlterSystemProperty() {
Assert.assertEquals("ALTER SYSTEM 'ksql.persistent.prefix'='[string]';",
anon.anonymize("ALTER SYSTEM 'ksql.persistent.prefix'='test';"));
} |
public List<CommentSimpleResponse> findAllWithPaging(final Long boardId, final Long memberId, final Long commentId, final int pageSize) {
return jpaQueryFactory.select(constructor(CommentSimpleResponse.class,
comment.id,
comment.content,
me... | @Test
void no_offset_페이징_두번째_조회() {
// given
for (long i = 1L; i <= 20L; i++) {
commentRepository.save(Comment.builder()
.id(i)
.boardId(board.getId())
.content("comment")
.writerId(member.getId())
... |
public String getAndFormatStatsFor(final String topic, final boolean isError) {
return format(
getStatsFor(topic, isError),
isError ? "last-failed" : "last-message");
} | @Test
public void shouldKeepWorkingWhenDuplicateTopicConsumerIsRemoved() {
final MetricCollectors metricCollectors = new MetricCollectors();
final ConsumerCollector collector1 = new ConsumerCollector();
collector1.configure(
ImmutableMap.of(
ConsumerConfig.GROUP_ID_CONFIG, "stream-thr... |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testNotEqualsOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder.startNot().equals("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
Not expected = (Not) Expressions.not(Expressions.equal("salary", 3000L));
Not... |
@Nonnull
public Vertex localParallelism(int localParallelism) {
throwIfLocked();
this.localParallelism = checkLocalParallelism(localParallelism);
return this;
} | @Test
public void when_badLocalParallelism_then_error() {
v = new Vertex("v", NoopP::new);
v.localParallelism(4);
v.localParallelism(-1); // this is good
Assert.assertThrows(IllegalArgumentException.class, () -> v.localParallelism(-5)); // this is not good
} |
public static void main(String[] args) {
LOGGER.info("The knight receives an enchanted sword.");
var enchantedSword = new Sword(new SoulEatingEnchantment());
enchantedSword.wield();
enchantedSword.swing();
enchantedSword.unwield();
LOGGER.info("The valkyrie receives an enchanted hammer.");
... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static VerificationMode times(final int count) {
checkArgument(count >= 0, "Times count must not be less than zero");
return new TimesVerification(count);
} | @Test
public void should_verify_expected_request_and_log_at_same_time_for_https() throws Exception {
final HttpServer server = httpsServer(port(), DEFAULT_CERTIFICATE, hit, log());
server.get(by(uri("/foo"))).response("bar");
running(server, () -> assertThat(helper.get(remoteHttpsUrl("/foo"... |
@Override
public void recordMisses(int count) {
missCount.inc(count);
} | @Test
public void miss() {
stats.recordMisses(2);
assertThat(registry.counter(PREFIX + ".misses").getCount()).isEqualTo(2);
} |
public Optional<T> owned() {
return isOwned ? Optional.of(value) : Optional.empty();
} | @Test
void testOwnedReferenceReturnsSomeOwned() {
final String value = "foobar";
final Reference<String> owned = Reference.owned(value);
assertThat(owned.owned()).hasValue(value);
} |
protected Triple<MessageExt, String, Boolean> getMessageFromRemote(String topic, long offset, int queueId, String brokerName) {
return getMessageFromRemoteAsync(topic, offset, queueId, brokerName).join();
} | @Test
public void getMessageFromRemoteTest() {
Assertions.assertThatCode(() -> escapeBridge.getMessageFromRemote(TEST_TOPIC, 1, DEFAULT_QUEUE_ID, BROKER_NAME)).doesNotThrowAnyException();
} |
@Override
public boolean isValid(final String object,
final ConstraintValidatorContext constraintContext) {
if (object == null) {
return true;
}
final int lengthInBytes = object.getBytes(StandardCharsets.UTF_8).length;
return lengthInBytes >= t... | @Test
void nullObjectIsValid() {
assertThat(toTest.isValid(null, null)).isTrue();
} |
Flux<Post> allPosts() {
return client.get()
.uri("/posts")
.accept(MediaType.APPLICATION_JSON)
.exchangeToFlux(response -> response.bodyToFlux(Post.class));
} | @SneakyThrows
@Test
public void testGetAllPosts() {
var data = List.of(
new Post(UUID.randomUUID(), "title1", "content1", Status.DRAFT, LocalDateTime.now()),
new Post(UUID.randomUUID(), "title2", "content2", Status.PUBLISHED, LocalDateTime.now())
);
stubFo... |
public boolean fileIsInAllowedPath(Path path) {
if (allowedPaths.isEmpty()) {
return true;
}
final Path realFilePath = resolveRealPath(path);
if (realFilePath == null) {
return false;
}
for (Path allowedPath : allowedPaths) {
final Pat... | @Test
public void permittedPathDoesNotExist() throws IOException {
final Path permittedPath = Paths.get("non-existent-file-path");
final Path filePath = permittedTempDir.newFile(FILE).toPath();
pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.singleton(permittedPath))... |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testEmptyMetricUpdates() throws IOException {
Job modelJob = new Job();
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job = mock(DataflowPipelineJob.class);
DataflowPipelineOptions options = mock(DataflowPipelineOptions.class);
when(options.isStreaming(... |
public EdgeIteratorState copyEdge(int edge, boolean reuseGeometry) {
EdgeIteratorStateImpl edgeState = (EdgeIteratorStateImpl) getEdgeIteratorState(edge, Integer.MIN_VALUE);
EdgeIteratorStateImpl newEdge = (EdgeIteratorStateImpl) edge(edgeState.getBaseNode(), edgeState.getAdjNode())
.set... | @Test
public void copyEdge() {
BaseGraph graph = createGHStorage();
EnumEncodedValue<RoadClass> rcEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class);
EdgeIteratorState edge1 = graph.edge(3, 5).set(rcEnc, RoadClass.LIVING_STREET);
EdgeIteratorState edge2 = graph... |
public static boolean validatePlugin(PluginLookup.PluginType type, Class<?> pluginClass) {
switch (type) {
case INPUT:
return containsAllMethods(inputMethods, pluginClass.getMethods());
case FILTER:
return containsAllMethods(filterMethods, pluginClass.getM... | @Test
public void testValidInputPlugin() {
Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.INPUT, Stdin.class));
Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.INPUT, Generator.class));
} |
@Override
public ProcNodeInterface lookup(String dbIdStr) throws AnalysisException {
long dbId = -1L;
try {
dbId = Long.valueOf(dbIdStr);
} catch (NumberFormatException e) {
throw new AnalysisException("Invalid db id format: " + dbIdStr);
}
if (global... | @Test(expected = AnalysisException.class)
public void testLookupInvalid() throws AnalysisException {
new StatisticProcDir(GlobalStateMgr.getCurrentState()).lookup("12345");
} |
public static ScanReport fromJson(String json) {
return JsonUtil.parse(json, ScanReportParser::fromJson);
} | @Test
public void missingFields() {
assertThatThrownBy(() -> ScanReportParser.fromJson("{}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing string: table-name");
assertThatThrownBy(() -> ScanReportParser.fromJson("{\"table-name\":\"roundTripTableName\"}"))
... |
public static List<TypedExpression> coerceCorrectConstructorArguments(
final Class<?> type,
List<TypedExpression> arguments,
List<Integer> emptyCollectionArgumentsIndexes) {
Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from t... | @Test
public void coerceCorrectConstructorArgumentsEmptyCollectionIndexesBiggerThanArguments() {
Assertions.assertThatThrownBy(
() -> MethodResolutionUtils.coerceCorrectConstructorArguments(
Person.class,
Collections.emp... |
private PaginatedList<ViewDTO> searchPaginated(SearchUser searchUser,
SearchQuery query,
Predicate<ViewDTO> filter,
SortOrder order,
... | @Test
public void searchPaginated() {
final ImmutableMap<String, SearchQueryField> searchFieldMapping = ImmutableMap.<String, SearchQueryField>builder()
.put("id", SearchQueryField.create(ViewDTO.FIELD_ID))
.put("title", SearchQueryField.create(ViewDTO.FIELD_TITLE))
... |
@Override
public T next() {
return buffer.poll();
} | @Test
public void testEmptyCollectorReturnsNull() {
BufferingCollector<Integer> collector = new BufferingCollector<>();
Assert.assertNull("Empty collector did not return null", collector.next());
} |
public String get(MetaDataKey key) {
return metadata.get(key.getName());
} | @Test
public void testAutoBuild() throws Exception {
try (MockedStatic<AmazonInfoUtils> mockUtils = mockStatic(AmazonInfoUtils.class)) {
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.