focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
String delete() {
return delete;
} | @Test
public void testDeleteIsEscaped() {
Queries queries = new Queries(mappingEscape, idColumnEscape, columnMetadataEscape);
String result = queries.delete();
assertEquals("DELETE FROM \"my\"\"mapping\" WHERE \"i\"\"d\" = ?", result);
} |
@VisibleForTesting
static boolean validate(TableConfig tableConfig, String taskType) {
String tableNameWithType = tableConfig.getTableName();
if (REFRESH.equalsIgnoreCase(IngestionConfigUtils.getBatchSegmentIngestionType(tableConfig))) {
LOGGER.warn("Skip generating task: {} for non-APPEND table: {}, RE... | @Test
public void testValidateIfMergeRollupCanBeEnabledOrNot() {
TableConfig tableConfig =
new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).setTimeColumnName(TIME_COLUMN_NAME)
.build();
assertTrue(MergeRollupTaskGenerator.validate(tableConfig, MinionConstants.MergeRol... |
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) {
if (operation.getOperationResponseHandler() != null) {
throw new IllegalArgumentException("Operation must not have a response handler set");
}
if (!operation.returnsResponse())... | @Test
public void executeLocallyRetriesWhenPartitionIsMigrating() throws InterruptedException {
final HazelcastInstance instance = createHazelcastInstance(smallInstanceConfig());
final NodeEngineImpl nodeEngineImpl = getNodeEngineImpl(instance);
final InternalPartitionService partitionServic... |
public OffsetRange[] getNextOffsetRanges(Option<String> lastCheckpointStr, long sourceLimit, HoodieIngestionMetrics metrics) {
// Come up with final set of OffsetRanges to read (account for new partitions, limit number of events)
long maxEventsToReadFromKafka = getLongWithAltKeys(props, KafkaSourceConfig.MAX_EV... | @Test
public void testGetNextOffsetRangesFromLatest() {
HoodieTestDataGenerator dataGenerator = new HoodieTestDataGenerator();
testUtils.createTopic(testTopicName, 1);
testUtils.sendMessages(testTopicName, Helpers.jsonifyRecords(dataGenerator.generateInserts("000", 1000)));
KafkaOffsetGen kafkaOffsetG... |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamMa... | @Test
public void testWorkflowParamSanity() {
Map<String, ParamDefinition> params = new LinkedHashMap<>();
RunRequest request =
RunRequest.builder()
.initiator(new ManualInitiator())
.currentPolicy(RunPolicy.START_FRESH_NEW_RUN)
.runParams(params)
.build... |
@Deprecated
@Override
public ProducerBuilder<T> maxPendingMessagesAcrossPartitions(int maxPendingMessagesAcrossPartitions) {
conf.setMaxPendingMessagesAcrossPartitions(maxPendingMessagesAcrossPartitions);
return this;
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testProducerBuilderImplWhenMaxPendingMessagesAcrossPartitionsPropertyIsInvalid() {
producerBuilderImpl.maxPendingMessagesAcrossPartitions(-1);
} |
@Override
public Long createSensitiveWord(SensitiveWordSaveVO createReqVO) {
// 校验唯一性
validateSensitiveWordNameUnique(null, createReqVO.getName());
// 插入
SensitiveWordDO sensitiveWord = BeanUtils.toBean(createReqVO, SensitiveWordDO.class);
sensitiveWordMapper.insert(sensitiv... | @Test
public void testCreateSensitiveWord_success() {
// 准备参数
SensitiveWordSaveVO reqVO = randomPojo(SensitiveWordSaveVO.class)
.setId(null); // 防止 id 被赋值
// 调用
Long sensitiveWordId = sensitiveWordService.createSensitiveWord(reqVO);
// 断言
assertNotNul... |
public static Comparator<Descriptor> getPrimitiveComparator(
boolean compressInt, boolean compressLong) {
if (!compressInt && !compressLong) {
return PRIMITIVE_COMPARATOR;
}
return (d1, d2) -> {
Class<?> t1 = TypeUtils.unwrap(d1.getRawType());
Class<?> t2 = TypeUtils.unwrap(d2.getRaw... | @Test
public void testPrimitiveCompressedComparator() {
List<Descriptor> descriptors = new ArrayList<>();
int index = 0;
for (Class<?> aClass : Primitives.allPrimitiveTypes()) {
descriptors.add(new Descriptor(TypeRef.of(aClass), "f" + index++, -1, "TestClass"));
}
Collections.shuffle(descrip... |
public Node chooseRandomWithStorageType(final String scope,
final Collection<Node> excludedNodes, StorageType type) {
netlock.readLock().lock();
try {
if (scope.startsWith("~")) {
return chooseRandomWithStorageType(
NodeBase.ROOT, scope.substring(1), excludedNodes, type);
}... | @Test
public void testNonExistingNode() throws Exception {
Node n;
n = CLUSTER.chooseRandomWithStorageType(
"/l100", null, null, StorageType.DISK);
assertNull(n);
n = CLUSTER.chooseRandomWithStorageType(
"/l100/d100", null, null, StorageType.DISK);
assertNull(n);
n = CLUSTER.ch... |
@Override
public Properties info(RedisClusterNode node) {
Map<String, String> info = execute(node, RedisCommands.INFO_ALL);
Properties result = new Properties();
for (Entry<String, String> entry : info.entrySet()) {
result.setProperty(entry.getKey(), entry.getValue());
}
... | @Test
public void testInfo() {
RedisClusterNode master = getFirstMaster();
Properties info = connection.info(master);
assertThat(info.size()).isGreaterThan(10);
} |
public static boolean isDecimal(final Schema schema) {
return schema.type() == Type.BYTES
&& Decimal.LOGICAL_NAME.equals(schema.name());
} | @Test
public void shouldNotCheckSchemaForNonDecimals() {
// Given:
final Schema notDecimal = Schema.OPTIONAL_STRING_SCHEMA;
// Then:
assertThat("String should not be decimal schema", !DecimalUtil.isDecimal(notDecimal));
} |
@VisibleForTesting
DictTypeDO validateDictTypeExists(Long id) {
if (id == null) {
return null;
}
DictTypeDO dictType = dictTypeMapper.selectById(id);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
return dictType;
} | @Test
public void testValidateDictDataExists_notExists() {
assertServiceException(() -> dictTypeService.validateDictTypeExists(randomLongId()), DICT_TYPE_NOT_EXISTS);
} |
@VisibleForTesting
protected RMAdminRequestInterceptor createRequestInterceptorChain() {
Configuration conf = getConfig();
return RouterServerUtil.createRequestInterceptorChain(conf,
YarnConfiguration.ROUTER_RMADMIN_INTERCEPTOR_CLASS_PIPELINE,
YarnConfiguration.DEFAULT_ROUTER_RMADMIN_INTERCEPT... | @Test
public void testRequestInterceptorChainCreation() throws Exception {
RMAdminRequestInterceptor root =
super.getRouterRMAdminService().createRequestInterceptorChain();
int index = 0;
while (root != null) {
// The current pipeline is:
// PassThroughRMAdminRequestInterceptor - index... |
@Override
public boolean hasNext() {
while (innerIter == null || !innerIter.hasNext()) {
if (!outerIter.hasNext()) {
return false;
}
StateDescriptor<?, ?> descriptor = outerIter.next();
Stream<K> stream = backend.getKeys(descriptor.getName(), ... | @Test
public void testIteratorPullsSingleKeyFromAllDescriptors() throws AssertionError {
CountingKeysKeyedStateBackend keyedStateBackend =
createCountingKeysKeyedStateBackend(100_000_000);
MultiStateKeyIterator<Integer> testedIterator =
new MultiStateKeyIterator<>(des... |
void activate(long newNextWriteOffset) {
if (active()) {
throw new RuntimeException("Can't activate already active OffsetControlManager.");
}
if (newNextWriteOffset < 0) {
throw new RuntimeException("Invalid negative newNextWriteOffset " +
newNextWrite... | @Test
public void testActivateFailsIfNewNextWriteOffsetIsNegative() {
OffsetControlManager offsetControl = new OffsetControlManager.Builder().build();
assertEquals("Invalid negative newNextWriteOffset -2.",
assertThrows(RuntimeException.class,
() -> offsetControl.activate... |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingInsertJsonRowToDataChangeRecord() {
final DataChangeRecord dataChangeRecord =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"transactionId",
false,
"1",
"tableName",
... |
@Override
public Result apply(PathData item, int depth) throws IOException {
String name = getPath(item).getName();
if (!caseSensitive) {
name = StringUtils.toLowerCase(name);
}
if (globPattern.matches(name)) {
return Result.PASS;
} else {
return Result.FAIL;
}
} | @Test
public void applyGlobMixedCase() throws IOException {
setup("n*e");
PathData item = new PathData("/directory/path/NaMe", mockFs.getConf());
assertEquals(Result.FAIL, name.apply(item, -1));
} |
static KiePMMLDefineFunction getKiePMMLDefineFunction(final DefineFunction defineFunction) {
final List<KiePMMLParameterField> kiePMMLParameterFields =
getKiePMMLParameterFields(defineFunction.getParameterFields());
DATA_TYPE dataType = defineFunction.getDataType() != null ?
... | @Test
void getKiePMMLDefineFunction() {
final String functionName = "functionName";
final DefineFunction toConvert = getDefineFunction(functionName);
KiePMMLDefineFunction retrieved = KiePMMLDefineFunctionInstanceFactory.getKiePMMLDefineFunction(toConvert);
commonVerifyKiePMMLDefineF... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testKerberosConfConfigMap() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final ConfigMap resultConfigMap =
(C... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testNot() {
Expression expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.NOT,
Expressions.$("field1").isEqual(Expressions.lit(1))));
Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.conve... |
public static String removeLeadingSlashes(String path) {
return SLASH_PREFIX_PATTERN.matcher(path).replaceFirst("");
} | @Test
public void removeLeadingSlashes_whenSingleLeadingSlash_removesLeadingSlashes() {
assertThat(removeLeadingSlashes("/a/b/c/")).isEqualTo("a/b/c/");
} |
@Override
public void updateProgress(TReportExecStatusParams params) {
writeLock();
try {
super.updateProgress(params);
if (!loadingStatus.getLoadStatistic().getLoadFinish()) {
if (this.loadType == TLoadJobType.INSERT_QUERY) {
if (loadingSt... | @Test
public void testUpdateProgress(@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database database,
@Injectable Table table) throws MetaNotFoundException {
new Expectations() {
{
globalStateMgr.getDb(any... |
public Flow injectDefaults(Flow flow, Execution execution) {
try {
return this.injectDefaults(flow);
} catch (Exception e) {
RunContextLogger
.logEntries(
Execution.loggingEventFromException(e),
LogEntry.of(execution)
... | @Test
void alias() {
DefaultTester task = DefaultTester.builder()
.id("test")
.type(DefaultTester.class.getName())
.set(666)
.build();
Flow flow = Flow.builder()
.tasks(Collections.singletonList(task))
.pluginDefaults(List.of(
... |
@Converter(fallback = true)
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
if (NodeInfo.class.isAssignableFrom(value.getClass())) {
// use a fallback type converter so we can convert the embedded body if the value is NodeInfo
... | @Test
public void convertSubNodeToDocument() throws XPathExpressionException {
evaluator.setNamespaceContext(NS_CONTEXT);
Object nodeObj = evaluator.evaluate("/ns1:a/ns1:b", doc, XPathConstants.NODE);
assertNotNull(nodeObj);
Document document = context.getTypeConverter().convertTo(Do... |
@Override
public void validateJoinRequest(JoinMessage joinMessage) {
// check joining member's major.minor version is same as current cluster version's major.minor numbers
MemberVersion memberVersion = joinMessage.getMemberVersion();
Version clusterVersion = node.getClusterService().getClust... | @Test
public void test_joinRequestAllowed_whenSameVersion() {
JoinRequest joinRequest = new JoinRequest(Packet.VERSION, buildNumber, nodeVersion, joinAddress, newUnsecureUUID(),
false, null, null, null, null, null);
nodeExtension.validateJoinRequest(joinRequest);
} |
public abstract long observeWm(int queueIndex, long wmValue); | @Test
public void when_i1_active_i2_idle_then_wmForwardedImmediately() {
assertEquals(Long.MIN_VALUE, wc.observeWm(0, 100));
assertEquals(100, wc.observeWm(1, IDLE_MESSAGE.timestamp()));
} |
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
@Operation(
summary = "Send a message",
description = """
Deliver a message to a single recipient. May be authenticated or unauthenticated; if unauthenticated... | @Test
void testMultiDeviceNotUrgent() throws Exception {
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", MULTI_DEVICE_UUID))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.... |
@Override
public CompletableFuture<SubscriptionData> querySubscriptionByConsumer(String address,
QuerySubscriptionByConsumerRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<SubscriptionData> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.cre... | @Test
public void assertQuerySubscriptionByConsumerWithError() {
setResponseError();
QuerySubscriptionByConsumerRequestHeader requestHeader = mock(QuerySubscriptionByConsumerRequestHeader.class);
CompletableFuture<SubscriptionData> actual = mqClientAdminImpl.querySubscriptionByConsumer(defau... |
static boolean isFormFile(final String pathName) {
return pathName.endsWith("frm");
} | @Test
public void testIsFormFile() {
assertThat(KieModuleMetaDataImpl.isFormFile("abc.frm")).isTrue();
assertThat(KieModuleMetaDataImpl.isFormFile("abc.form")).isFalse();
} |
public String getServiceName() {
return serviceName;
} | @Test
public void getServiceName() {
final ServiceStats serviceStats = new ServiceStats(serviceName);
Assert.assertEquals(serviceStats.getServiceName(), serviceName);
} |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test
public void testLiteral() {
String noSubst = "hello world";
String result = OptionHelper.substVars(noSubst, context);
assertEquals(noSubst, result);
} |
@JsonIgnore
public WorkflowInstance.Status getRunStatus() {
if (runtimeOverview == null || runtimeOverview.getRunStatus() == null) {
return status;
}
return runtimeOverview.getRunStatus();
} | @Test
public void testRunStatus() throws Exception {
WorkflowInstance instance =
loadObject(
"fixtures/instances/sample-workflow-instance-succeeded.json", WorkflowInstance.class);
assertEquals(WorkflowInstance.Status.SUCCEEDED, instance.getStatus());
assertEquals(WorkflowInstance.Statu... |
@Override
void decode(ByteBufAllocator alloc, ByteBuf headerBlock, SpdyHeadersFrame frame) throws Exception {
int len = setInput(headerBlock);
int numBytes;
do {
numBytes = decompress(alloc, frame);
} while (numBytes > 0);
// z_stream has an internal 64-bit hold... | @Test
public void testHeaderBlockInvalidDeflateBlock() throws Exception {
final ByteBuf headerBlock = Unpooled.buffer(11);
headerBlock.writeBytes(zlibHeader);
headerBlock.writeByte(0); // Non-compressed block
headerBlock.writeByte(0x00); // little-endian length (0)
headerBloc... |
@Override
public <OUT> ProcessConfigurableAndGlobalStream<OUT> process(
OneInputStreamProcessFunction<T, OUT> processFunction) {
validateStates(
processFunction.usesStates(),
new HashSet<>(
Collections.singletonList(StateDeclaration.Redistr... | @Test
void testStateErrorWithTwoOutputStream() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
GlobalStreamImpl<Integer> stream =
new GlobalStreamImpl<>(env, new TestingTransformation<>("t1", Types.INT, 1));
assertThatThrownBy(
... |
public String toJSON() {
return JSON.toJSON(this);
} | @Test
public void testWriteUnionInfo() throws Exception {
StructType st = new StructType(new LinkedList<ThriftField>(), null);
assertEquals(
("{\n"
+ " \"id\" : \"STRUCT\",\n"
+ " \"children\" : [ ],\n"
+ " \"structOrUnionType\" : \"STRUCT\",\n"
... |
@Override
public ExecuteContext doBefore(ExecuteContext context) {
final Object url = context.getArguments()[0];
final Map<String, String> parameters = getParameters(url);
final String application = parameters.get(CommonConst.DUBBO_APPLICATION);
final String interfaceName = parameter... | @Test
public void doBefore() throws Exception {
String interfaceName = "io.sermant.test";
String application = "test";
String protocol = "dubbo";
String host = "localhost";
int port = 8080;
final ClusterInterceptor clusterInterceptor = new ClusterInterceptor();
... |
@Override
public void writeFloat(final float v) throws IOException {
ensureAvailable(FLOAT_SIZE_IN_BYTES);
MEM.putFloat(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v);
pos += FLOAT_SIZE_IN_BYTES;
} | @Test
public void testWriteFloatV() throws Exception {
float expected = 1.1f;
out.writeFloat(expected);
int val = Bits.readInt(out.buffer, 0, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
float actual = Float.intBitsToFloat(val);
assertEquals(expected, actual, 0);
} |
@GetMapping("/apps/search/by-appid-or-name")
public PageDTO<App> search(@RequestParam(value = "query", required = false) String query, Pageable pageable) {
if (StringUtils.isEmpty(query)) {
return appService.findAll(pageable);
}
//search app
PageDTO<App> appPageDTO = appService.searchByAppIdOrA... | @Test
public void testSearchApp() {
String query = "timeout";
PageRequest request = PageRequest.of(0, 20);
PageDTO<App> apps = genPageApp(10, request, 100);
when(appService.searchByAppIdOrAppName(query, request)).thenReturn(apps);
searchController.search(query, request);
verify(appService,... |
public RegistryBuilder extraKeys(String extraKeys) {
this.extraKeys = extraKeys;
return getThis();
} | @Test
void extraKeys() {
RegistryBuilder builder = new RegistryBuilder();
builder.extraKeys("extraKeys");
Assertions.assertEquals("extraKeys", builder.build().getExtraKeys());
} |
@SafeVarargs
static <T> List<T> ordered(Collection<T> items, Class<? extends T>... order) {
List<T> ordered = new ArrayList<>(items);
ordered.sort(Comparator.comparingInt(item -> {
int best = order.length;
for (int i = 0; i < order.length; i++) {
if ( order[... | @Test
void testSorting() {
class A { @Override public String toString() { return getClass().getSimpleName(); } }
class B extends A { }
class C extends B { }
class D extends B { }
A a = new A(), b = new B(), c = new C(), d = new D(), e = new D() { @Override public String toSt... |
public static FuryBuilder builder() {
return new FuryBuilder();
} | @Test(dataProvider = "crossLanguageReferenceTrackingConfig")
public void primitivesTest(boolean referenceTracking, Language language) {
Fury fury1 =
Fury.builder()
.withLanguage(language)
.withRefTracking(referenceTracking)
.requireClassRegistration(false)
.... |
@Override
public Member getMember() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetMember() {
batchIMapEvent.getMember();
} |
public synchronized void write(Mutation tableRecord) throws IllegalStateException {
write(ImmutableList.of(tableRecord));
} | @Test
public void testWriteSingleRecordShouldWorkWhenSpannerWriteSucceeds()
throws ExecutionException, InterruptedException {
// arrange
prepareTable();
when(spanner.getDatabaseClient(any()).write(any())).thenReturn(Timestamp.now());
Mutation testMutation =
Mutation.newInsertOrUpdateBuil... |
public static String format(Date date) {
return formatter().format0(checkNotNull(date, "date"));
} | @Test
public void testFormat() {
assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", format(DATE));
} |
@Override
public YamlTableDataConsistencyCheckResult swapToYamlConfiguration(final TableDataConsistencyCheckResult data) {
YamlTableDataConsistencyCheckResult result = new YamlTableDataConsistencyCheckResult();
if (data.isIgnored()) {
result.setIgnoredType(data.getIgnoredType().name());
... | @Test
void assertSwapToYamlConfigurationWithTableDataConsistencyCheckResultMatched() {
TableDataConsistencyCheckResult data = new TableDataConsistencyCheckResult(true);
YamlTableDataConsistencyCheckResult result = yamlTableDataConsistencyCheckResultSwapper.swapToYamlConfiguration(data);
asse... |
@Override
public DataTableType dataTableType() {
return dataTableType;
} | @Test
void can_define_table_entry_transformer_with_empty_pattern() throws NoSuchMethodException {
Method method = JavaDataTableTypeDefinitionTest.class.getMethod("converts_table_entry_to_string", Map.class);
JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, lookup,
... |
public static Caffeine<Object, Object> newBuilder() {
return new Caffeine<>();
} | @Test
public void nullParameters() {
var npeTester = new NullPointerTester();
npeTester.testAllPublicInstanceMethods(Caffeine.newBuilder());
} |
@Override
public ShenyuContext decorator(final ShenyuContext shenyuContext, final MetaData metaData) {
shenyuContext.setModule(metaData.getAppName());
shenyuContext.setMethod(metaData.getServiceName());
shenyuContext.setContextPath(metaData.getContextPath());
shenyuContext.setRpcType... | @Test
public void testDecorator() {
MetaData metaData = new MetaData();
metaData.setAppName("grpc");
metaData.setServiceName("echo");
metaData.setRpcType(PluginEnum.GRPC.getName());
metaData.setContextPath("/grpc");
final ShenyuContext shenyuContext = grpcShenyuContex... |
public static ExecutableStage forGrpcPortRead(
QueryablePipeline pipeline,
PipelineNode.PCollectionNode inputPCollection,
Set<PipelineNode.PTransformNode> initialNodes) {
checkArgument(
!initialNodes.isEmpty(),
"%s must contain at least one %s.",
GreedyStageFuser.class.getS... | @Test
public void materializesWithDifferentEnvConsumer() {
// (impulse.out) -> parDo -> parDo.out -> window -> window.out
// Fuses into
// (impulse.out) -> parDo -> (parDo.out)
// (parDo.out) -> window -> window.out
Environment env = Environments.createDockerEnvironment("common");
PTransform p... |
public UserTokenDto setTokenHash(String tokenHash) {
this.tokenHash = checkTokenHash(tokenHash);
return this;
} | @Test
void fail_if_token_hash_is_longer_than_255_characters() {
assertThatThrownBy(() -> new UserTokenDto().setTokenHash(randomAlphabetic(256)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Token hash length (256) is longer than the maximum authorized (255)");
} |
@VisibleForTesting
public RequestInterceptorChainWrapper getInterceptorChain()
throws IOException {
String user = UserGroupInformation.getCurrentUser().getUserName();
RequestInterceptorChainWrapper chain = userPipelineMap.get(user);
if (chain != null && chain.getRootInterceptor() != null) {
re... | @Test
public void testRMAdminPipelineConcurrent() throws InterruptedException {
final String user = "test1";
/*
* ClientTestThread is a thread to simulate a client request to get a
* RMAdminRequestInterceptor for the user.
*/
class ClientTestThread extends Thread {
private RMAdminReq... |
public static List<Uuid> toList(Uuid[] array) {
if (array == null) return null;
List<Uuid> list = new ArrayList<>(array.length);
list.addAll(Arrays.asList(array));
return list;
} | @Test
void testToList() {
assertNull(Uuid.toList(null));
assertEquals(
Arrays.asList(
Uuid.ZERO_UUID, Uuid.fromString("UXyU9i5ARn6W00ON2taeWA")
),
Uuid.toList(new Uuid[]{
Uuid.ZERO_UUID, Uuid.fromString("UXyU9i5A... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void deleteWebhook() {
BaseResponse response = bot.execute(new DeleteWebhook().dropPendingUpdates(true));
assertTrue(response.isOk());
} |
@Override
public void abort() {
// Signal the read loop to abort on the next record and async abort any iterators.
// TODO: Also interrupt the execution thread.
for (Operation op : operations) {
Preconditions.checkState(op instanceof ReadOperation || op instanceof ReceivingOperation);
if (op i... | @Test
public void testAbort() throws Exception {
// Operation must be an instance of ReadOperation or ReceivingOperation per preconditions
// in MapTaskExecutor.
ReadOperation o1 = Mockito.mock(ReadOperation.class);
ReadOperation o2 = Mockito.mock(ReadOperation.class);
ExecutionStateTracker state... |
static void createUploadDir(
final Path uploadDir, final Logger log, final boolean initialCreation)
throws IOException {
if (!Files.exists(uploadDir)) {
if (initialCreation) {
log.info("Upload directory {} does not exist. ", uploadDir);
} else {
... | @Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser")
@Test
void testCreateUploadDirFails(@TempDir File file) throws Exception {
assertThat(file.setWritable(false));
final Path testUploadDir = file.toPath().resolve("testUploadDir");
assertThat(Files.exists(testUploadD... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
AvroSchema schema = message.getExchange().getProperty(SchemaHelper.CONTENT_SCHEMA, AvroSchema.class);
if (schema == null) {
throw new CamelExecutionException("Missing proper avro schema for data type ... | @Test
void shouldHandleJsonNode() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
AvroSchema avroSchema = getSchema();
exchange.setProperty(SchemaHelper.CONTENT_SCHEMA, avroSchema);
exchange.getMessage().setBody(Json.mapper().readerFor(JsonNode.class).readV... |
public static void debug(final Logger logger, final String format, final Supplier<Object> supplier) {
if (logger.isDebugEnabled()) {
logger.debug(format, supplier.get());
}
} | @Test
public void testAtLeastOnceDebugWithFormat() {
when(logger.isDebugEnabled()).thenReturn(true);
LogUtils.debug(logger, "testDebug: {}", supplier);
verify(supplier, atLeastOnce()).get();
} |
public void setHeader(String name, String value) {
parent.headers().put(name, value);
} | @Test
void testSetHeader() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
DiscFilterResponse response = new DiscFilterResponse(httpResp)... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void should_support_deprecated_props_with_multi_values() {
Settings settings = new MapSettings(definitions);
settings.setProperty("new_multi_values", new String[]{" A ", " B "});
assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[]{"A", "B"});
assertThat(settings... |
@Override
public TransformResultMetadata getResultMetadata() {
return _resultMetadata;
} | @Test
public void testIntersectIndices() {
ExpressionContext expression = RequestContextUtils.getExpression(
String.format("intersect_indices(%s, %s)", INT_MONO_INCREASING_MV_1, INT_MONO_INCREASING_MV_2));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
... |
public final void doesNotContainEntry(@Nullable Object key, @Nullable Object value) {
checkNoNeedToDisplayBothValues("entrySet()")
.that(checkNotNull(actual).entrySet())
.doesNotContain(immutableEntry(key, value));
} | @Test
public void doesNotContainEntryFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).doesNotContainEntry("kurt", "kluever");
assertFailureKeys("value of", "expected not to contain", "but was");
assertFailureValue("value of", "m... |
@Override
protected void processOptions(LinkedList<String> args) throws IOException {
CommandFormat cf =
new CommandFormat(1, Integer.MAX_VALUE, OPTION_FOLLOW_LINK,
OPTION_FOLLOW_ARG_LINK, null);
cf.parse(args);
if (cf.getOpt(OPTION_FOLLOW_LINK)) {
getOptions().setFollowLink(tru... | @Test
public void processOptionsUnknown() throws IOException {
Find find = new Find();
find.setConf(conf);
String args = "path -unknown";
try {
find.processOptions(getArgs(args));
fail("Unknown expression not caught");
} catch (IOException e) {
}
} |
@Override
void toHtml() throws IOException {
writeHtmlHeader();
htmlCoreReport.toHtml();
writeHtmlFooter();
} | @Test
public void testJob() throws IOException, SchedulerException {
// job quartz
initJobGlobalListener();
getJobCounter().clear();
//Grab the Scheduler instance from the Factory
final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
try {
// and start it off
scheduler.start();
... |
@Override
public int hashCode() {
return System.identityHashCode(this);
} | @Test
public void identity() {
assertEquals(a, a);
assertNotEquals(a, b);
assertNotEquals(a.hashCode(), b.hashCode());
} |
public StateStore getStore() {
return store;
} | @Test
public void shouldGetTimestampedStore() {
givenWrapperWithTimestampedStore();
assertThat(wrapper.getStore(), equalTo(timestampedStore));
} |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testCopyStrategy() {
DistCpOptions options = OptionsParser.parse(new String[] {
"-strategy",
"dynamic",
"-f",
"hdfs://localhost:8020/source/first",
"hdfs://localhost:8020/target/"});
assertThat(options.getCopyStrategy()).isEqualTo("dynamic");
opti... |
public Counter counter(String name) {
return getOrAdd(name, MetricBuilder.COUNTERS);
} | @Test
public void accessingACustomCounterRegistersAndReusesTheCounter() {
final MetricRegistry.MetricSupplier<Counter> supplier = () -> counter;
final Counter counter1 = registry.counter("thing", supplier);
final Counter counter2 = registry.counter("thing", supplier);
assertThat(cou... |
BrokerResponse getQueueResponse(String queueName) throws IOException {
String queryUrl = getQueueEndpoint(messageVpn, queueName);
HttpResponse response = executeGet(new GenericUrl(baseUrl + queryUrl));
return BrokerResponse.fromHttpResponse(response);
} | @Test
public void testExecuteWithUnauthorized() throws IOException {
// Making it a final array, so that we can reference it from within the MockHttpTransport
// instance
final int[] requestCounter = {0};
MockHttpTransport transport =
new MockHttpTransport() {
@Override
pub... |
@Override
public WindowStore<K, V> build() {
if (storeSupplier.retainDuplicates() && enableCaching) {
log.warn("Disabling caching for {} since store was configured to retain duplicates", storeSupplier.name());
enableCaching = false;
}
return new MeteredWindowStore<>(... | @Test
public void shouldHaveChangeLoggingStoreByDefault() {
setUp();
final WindowStore<String, String> store = builder.build();
final StateStore next = ((WrappedStateStore) store).wrapped();
assertThat(next, instanceOf(ChangeLoggingWindowBytesStore.class));
} |
@Override
public void clear() {
items.clear();
} | @Test
public void testClear() throws Exception {
//Test set emptying
assertTrue("The set should be initialized empty.", set.isEmpty());
set.clear();
assertTrue("Clear should have no effect on an empty set.", set.isEmpty());
fillSet(10, set);
assertFalse("The set shoul... |
@Override
public String getFileId(final DriveItem.Metadata metadata) {
final ItemReference parent = metadata.getParentReference();
if(metadata.getRemoteItem() != null) {
final DriveItem.Metadata remoteMetadata = metadata.getRemoteItem();
final ItemReference remoteParent = rem... | @Test
public void testRealBusinessFileIdResponseSharedWithMe() throws Exception {
final DriveItem.Metadata metadata;
try (final InputStream test = getClass().getResourceAsStream("/RealBusinessFileIdResponseSharedWithMe.json")) {
final InputStreamReader reader = new InputStreamReader(test... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void getChatMembersCount() {
GetChatMembersCountResponse response = bot.execute(new GetChatMembersCount(chatId));
assertEquals(2, response.count());
} |
public String getNamespace() {
return namespace;
} | @Test
void getNamespace() {
ConfigurationChangeEvent event = new ConfigurationChangeEvent();
event.setNamespace("namespace");
Assertions.assertEquals("namespace", event.getNamespace());
} |
@Override
public Map<String, StepTransition> translate(WorkflowInstance workflowInstance) {
WorkflowInstance instance = objectMapper.convertValue(workflowInstance, WorkflowInstance.class);
if (instance.getRunConfig() != null) {
if (instance.getRunConfig().getPolicy() == RunPolicy.RESTART_FROM_INCOMPLET... | @Test
public void testTranslateForRestartFromBeginning() {
instance.getRunConfig().setPolicy(RunPolicy.RESTART_FROM_BEGINNING);
Map<String, StepTransition> dag = translator.translate(instance);
Assert.assertEquals(
new HashSet<>(Arrays.asList("job1", "job.2", "job3", "job4")), dag.keySet());
} |
@Override public SpanCustomizer name(String name) {
return tracer.currentSpanCustomizer().name(name);
} | @Test void name() {
span.start();
try (SpanInScope scope = tracing.tracer().withSpanInScope(span)) {
spanCustomizer.name("newname");
}
span.flush();
assertThat(spans).extracting(MutableSpan::name)
.containsExactly("newname");
} |
@Override
public MetadataNode child(String name) {
String value = image.data().get(name);
if (value == null) return null;
return new MetadataNode() {
@Override
public boolean isDirectory() {
return false;
}
@Override
... | @Test
public void testUnknownChild() {
assertNull(NODE.child("also.non.secret"));
} |
@Override
public String toString() {
return "Service{" + "name='" + name + '\'' + ", protectThreshold=" + protectThreshold + ", appName='" + appName
+ '\'' + ", groupName='" + groupName + '\'' + ", metadata=" + metadata + '}';
} | @Test
void testToString() {
Service service = new Service("service");
service.setGroupName("group");
service.setAppName("app");
service.setProtectThreshold(1.0f);
service.setMetadata(Collections.singletonMap("a", "b"));
assertEquals("Service{name='service', protectThr... |
protected String host(Reconciliation reconciliation, String podName) {
return DnsNameGenerator.podDnsName(reconciliation.namespace(), KafkaResources.zookeeperHeadlessServiceName(reconciliation.name()), podName);
} | @Test
public void testGetHostReturnsCorrectHostForGivenPod() {
assertThat(new ZookeeperLeaderFinder(vertx, this::backoff).host(new Reconciliation("test", "Kafka", "myproject", "my-cluster"), KafkaResources.zookeeperPodName("my-cluster", 3)),
is("my-cluster-zookeeper-3.my-cluster-zookeeper-no... |
@Override
public void onDeserializationFailure(
final String source,
final String changelog,
final byte[] data
) {
// NOTE: this only happens for values, we should never auto-register key schemas
final String sourceSubject = KsqlConstants.getSRSubject(source, false);
final String chang... | @Test
public void shouldNotRegisterFailedIdTwice() throws IOException, RestClientException {
// Given:
when(srClient.getSchemaBySubjectAndId(KsqlConstants.getSRSubject(SOURCE, false), ID)).thenReturn(schema);
when(srClient.register(KsqlConstants.getSRSubject(CHANGELOG, false), schema)).thenThrow(new KsqlE... |
public static <T> Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress) {
return DiffUtils.diff(original, revised, DEFAULT_DIFF.create(), progress);
} | @Test
public void testDiff_Change() {
final List<String> changeTest_from = Arrays.asList("aaa", "bbb", "ccc");
final List<String> changeTest_to = Arrays.asList("aaa", "zzz", "ccc");
final Patch<String> patch = DiffUtils.diff(changeTest_from, changeTest_to);
assertNotNull(patch);
... |
public Blade listen() {
return listen(BladeConst.DEFAULT_SERVER_PORT);
} | @Test
public void testListen() throws Exception {
Blade blade = Blade.create();
blade.listen(9001).start().await();
try {
int code = Unirest.get("http://127.0.0.1:9001").asString().getStatus();
assertEquals(404, code);
} finally {
blade.stop();
... |
public OpenTelemetry getOpenTelemetry() {
return openTelemetrySdkReference.get();
} | @Test
public void testMetricCardinalityIsSet() {
var prometheusExporterPort = 9464;
@Cleanup
var ots = OpenTelemetryService.builder()
.builderCustomizer(getBuilderCustomizer(null,
Map.of(OpenTelemetryService.OTEL_SDK_DISABLED_KEY, "false",
... |
@Override
public List<ImportValidationFeedback> verifyRule( Object subject ) {
List<ImportValidationFeedback> feedback = new ArrayList<>();
if ( !isEnabled() || !( subject instanceof TransMeta ) ) {
return feedback;
}
TransMeta transMeta = (TransMeta) subject;
String description = transMe... | @Test
public void testVerifyRule_NotTransMetaParameter_EnabledRule() {
TransformationHasDescriptionImportRule importRule = getImportRule( 10, true );
List<ImportValidationFeedback> feedbackList = importRule.verifyRule( "" );
assertNotNull( feedbackList );
assertTrue( feedbackList.isEmpty() );
} |
public Meter meter() {
return meter;
} | @Test
public void testConstruction() {
final Meter m1 = new TestMeter();
final MeterOperation op = new MeterOperation(m1, MeterOperation.Type.ADD);
assertThat(op.meter(), is(m1));
} |
public static Find find(String regex) {
return find(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testFind() {
PCollection<String> output =
p.apply(Create.of("aj", "xj", "yj", "zj")).apply(Regex.find("[xyz]"));
PAssert.that(output).containsInAnyOrder("x", "y", "z");
p.run();
} |
@Override
public InputFile toInputFile() {
return new OSSInputFile(client(), uri(), aliyunProperties(), metrics());
} | @Test
public void testToInputFile() throws IOException {
int dataSize = 1024 * 10;
byte[] data = randomData(dataSize);
OutputFile out =
new OSSOutputFile(ossClient, randomURI(), aliyunProperties, MetricsContext.nullMetrics());
try (OutputStream os = out.create();
InputStream is = new ... |
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) {
return null;
}
BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification);
StringBuilder message = new StringBuilder("The ... | @Test
public void notification_contains_count_of_new_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.new... |
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {... | @Test
public void testExecute() {
UpdateOrderConfCommand cmd = new UpdateOrderConfCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-t unit-test", "-v default-broker:8", "-m post"};
final CommandLine commandLine =
... |
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"})
public static boolean isScalablePushQuery(
final Statement statement,
final KsqlExecutionContext ksqlEngine,
final KsqlConfig ksqlConfig,
final Map<String, Object> overrides
) {
if (!isPushV2Enabled(ksqlConfig, ov... | @Test
public void isScalablePushQuery_false_configNotLatest() {
try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) {
// When:
expectIsSPQ(ColumnName.of("foo"), columnExtractor);
when(ksqlConfig.getKsqlStreamConfigProp(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG))
... |
public int month() {
return getField(DateField.MONTH);
} | @Test
public void monthTest() {
//noinspection ConstantConditions
int month = DateUtil.parse("2017-07-01").month();
assertEquals(6, month);
} |
public static Thread daemonThread(Runnable r, Class<?> context, String description) {
return daemonThread(r, "hollow", context, description);
} | @Test
public void described_customPlatform() {
Thread thread = daemonThread(() -> {}, "solid", getClass(), "howdy");
assertEquals("solid | ThreadsTest | howdy", thread.getName());
assertTrue(thread.isDaemon());
} |
SourceRecord convertRecord(ConsumerRecord<byte[], byte[]> record) {
String targetTopic = formatRemoteTopic(record.topic());
Headers headers = convertHeaders(record);
return new SourceRecord(
MirrorUtils.wrapPartition(new TopicPartition(record.topic(), record.partition()), sourceC... | @Test
public void testSerde() {
byte[] key = new byte[]{'a', 'b', 'c', 'd', 'e'};
byte[] value = new byte[]{'f', 'g', 'h', 'i', 'j', 'k'};
Headers headers = new RecordHeaders();
headers.add("header1", new byte[]{'l', 'm', 'n', 'o'});
headers.add("header2", new byte[]{'p', 'q'... |
public String toServiceString() {
return buildString(true, false, true, true);
} | @Test
void testToServiceString() {
URL url = URL.valueOf(
"zookeeper://10.20.130.230:4444/org.apache.dubbo.metadata.report.MetadataReport?version=1.0.0&application=vic&group=aaa");
assertEquals(
"zookeeper://10.20.130.230:4444/aaa/org.apache.dubbo.metadata.report.Meta... |
@Override
public int compareTo(LeanHit o) {
int res = (sortData != null)
? compareData(sortData, o.sortData)
: Double.compare(o.relevance, relevance);
return (res != 0) ? res : compareData(gid, o.gid);
} | @Test
void testOrderingByRelevance() {
assertEquals(0, new LeanHit(gidA, 0, 0, 1).compareTo(new LeanHit(gidA, 0, 0, 1)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 1),
new LeanHit(gidA, 0, 0, 0),
new LeanHit(gidA, 0, 0, -1));
} |
public static String serialize(Object obj) throws JsonProcessingException {
return MAPPER.writeValueAsString(obj);
} | @Test
void serializeHistogram() throws JsonProcessingException {
DHistogram h =
new DHistogram(new TestHistogram(), METRIC, HOST, tags, () -> MOCKED_SYSTEM_MILLIS);
DSeries series = new DSeries();
h.addTo(series);
assertSerialization(
DatadogHttpClie... |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testDateRange() throws ParseException {
Assertions.assertThat(parser.parse("otherDate:[now-3d TO now-4d]").terms())
.hasSize(2)
.extracting(ParsedTerm::value)
.contains("now-3d", "now-4d");
Assertions.assertThat(parser.parse("otherDate:[200... |
@Override
public OUT extract(Tuple in) {
return in.getField(fieldId);
} | @Test
void testSingleFieldExtraction() throws InstantiationException, IllegalAccessException {
// extract single fields
for (int i = 0; i < Tuple.MAX_ARITY; i++) {
Tuple current = (Tuple) CLASSES[i].newInstance();
for (int j = 0; j < i; j++) {
current.setField... |
@Override
protected TableRecords getUndoRows() {
return sqlUndoLog.getBeforeImage();
} | @Test
public void getUndoRows() {
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
} |
@VisibleForTesting
static EntryFilterDefinition getEntryFilterDefinition(NarClassLoader ncl) throws IOException {
String configStr;
try {
configStr = ncl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yaml");
} catch (NoSuchFileException e) {
configStr = ncl.g... | @Test
public void testReadYamlFile() throws IOException {
try (NarClassLoader cl = mock(NarClassLoader.class)) {
when(cl.getServiceDefinition(ENTRY_FILTER_DEFINITION_FILE + ".yaml"))
.thenThrow(new NoSuchFileException(""));
try {
EntryFilterProvide... |
Mono<ImmutableMap<String, String>> resolve(List<SchemaReference> refs) {
return resolveReferences(refs, new Resolving(ImmutableMap.of(), ImmutableSet.of()))
.map(Resolving::resolved);
} | @Test
void resolvesRefsUsingSrClient() {
mockSrCall("sub1", 1,
new SchemaSubject()
.schema("schema1"));
mockSrCall("sub2", 1,
new SchemaSubject()
.schema("schema2")
.references(
List.of(
new SchemaReference().name("ref2_1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.