focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static void onFail(final ServerMemberManager manager, final Member member) {
// To avoid null pointer judgments, pass in one NONE_EXCEPTION
onFail(manager, member, ExceptionUtil.NONE_EXCEPTION);
} | @Test
void testMemberOnFailWhenReachMaxFailAccessCnt() {
final Member remote = buildMember();
mockMemberAddressInfos.add(remote.getAddress());
remote.setState(NodeState.SUSPICIOUS);
remote.setFailAccessCnt(2);
MemberUtil.onFail(memberManager, remote);
assertEquals(3, ... |
public static PathOutputCommitter createCommitter(Path outputPath,
TaskAttemptContext context) throws IOException {
return getCommitterFactory(outputPath,
context.getConfiguration())
.createOutputCommitter(outputPath, context);
} | @Test
public void testNamedCommitterNullPath() throws Throwable {
Configuration conf = new Configuration();
// set up for the schema factory
conf.set(COMMITTER_FACTORY_CLASS, NAMED_COMMITTER_FACTORY);
conf.set(NAMED_COMMITTER_CLASS, SimpleCommitter.class.getName());
SimpleCommitter sc = createCom... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void strips_line_filters_from_feature_paths_and_put_them_among_line_filters() {
RuntimeOptions options = parser
.parse("somewhere_else.feature:3")
.build();
assertAll(
() -> assertThat(options.getFeaturePaths(), contains(new File("somewhere_else.fea... |
@Override
public void validateDeleteGroup() throws ApiException {
switch (currentState()) {
case DEAD:
throw new GroupIdNotFoundException(String.format("Group %s is in dead state.", groupId));
case STABLE:
case PREPARING_REBALANCE:
case COMPLET... | @Test
public void testValidateDeleteGroup() {
group.transitionTo(PREPARING_REBALANCE);
assertThrows(GroupNotEmptyException.class, group::validateDeleteGroup);
group.transitionTo(COMPLETING_REBALANCE);
assertThrows(GroupNotEmptyException.class, group::validateDeleteGroup);
gro... |
public static PostgreSQLCommandPacket newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLPacketPayload payload) {
if (!PostgreSQLCommandPacketType.isExtendedProtocolPacketType(commandPacketType)) {
payload.getByteBuf().skipBytes(1);
return getPostgreSQLComma... | @Test
void assertNewInstanceWithBindComPacket() {
assertThat(PostgreSQLCommandPacketFactory.newInstance(PostgreSQLCommandPacketType.BIND_COMMAND, payload), instanceOf(PostgreSQLAggregatedCommandPacket.class));
} |
public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long... | @Test
void testGenerateSimpleFileWithZST() throws IOException {
String inputPath = "no.jsonl";
ClientParameters params1 = createParameters(inputPath, "output.json", "text", "nb", "nb", "true").build();
// Throws exception when outputfile does not have .zst extension when using zst compress... |
public ConsumerBuilderImpl(PulsarClientImpl client, Schema<T> schema) {
this(client, new ConsumerConfigurationData<T>(), schema);
} | @Test
public void testConsumerBuilderImpl() throws PulsarClientException {
Consumer consumer = mock(Consumer.class);
when(consumerBuilderImpl.subscribeAsync())
.thenReturn(CompletableFuture.completedFuture(consumer));
assertNotNull(consumerBuilderImpl.topic(TOPIC_NAME).subscr... |
private Pair<LogicalSchema, List<SelectExpression>> build(
final MetaStore metaStore
) {
final LogicalSchema parentSchema = getSource().getSchema();
final Optional<LogicalSchema> targetSchema = getTargetSchema(metaStore);
final List<SelectExpression> selectExpressions = SelectionUtil
.build... | @Test
public void shouldNotThrowOnSyntheticKeyColumnInProjection() {
// Given:
clearInvocations(source);
final UnqualifiedColumnReferenceExp syntheticKeyRef =
new UnqualifiedColumnReferenceExp(ColumnName.of("ROWKEY"));
selects = ImmutableList.of(new SingleColumn(syntheticKeyRef, Optional.of(... |
public Protocol forName(final String identifier) {
return this.forName(identifier, null);
} | @Test
public void testOverrideBundledProtocols() {
final TestProtocol baseProtocol = new TestProtocol(Scheme.http) {
@Override
public String getProvider() {
return "test-provider1";
}
@Override
public boolean isBundled() {
... |
String messageFromFile(Locale locale, String filename, String relatedProperty) {
String result = null;
String bundleBase = propertyToBundles.get(relatedProperty);
if (bundleBase == null) {
// this property has no translation
return null;
}
String filePath = bundleBase.replace('.', '/');... | @Test
public void return_null_if_rule_not_internationalized() {
String html = underTest.messageFromFile(Locale.ENGLISH, "UnknownRule.html", "foo.rule1.name");
assertThat(html).isNull();
} |
@Override
public void createFunction(SqlInvokedFunction function, boolean replace)
{
checkCatalog(function);
checkFunctionLanguageSupported(function);
checkArgument(!function.hasVersion(), "function '%s' is already versioned", function);
QualifiedObjectName functionName = functi... | @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Function name exceeds max length of 256.*")
public void testFunctionNameTooLong()
{
QualifiedObjectName functionName = QualifiedObjectName.valueOf(TEST_CATALOG, TEST_SCHEMA, dummyString(257));
createFunction(cre... |
public static URI parse(String gluePath) {
requireNonNull(gluePath, "gluePath may not be null");
if (gluePath.isEmpty()) {
return rootPackageUri();
}
// Legacy from the Cucumber Eclipse plugin
// Older versions of Cucumber allowed it.
if (CLASSPATH_SCHEME_PRE... | @Test
void can_parse_package_form() {
URI uri = GluePath.parse("com.example.app");
assertAll(
() -> assertThat(uri.getScheme(), is("classpath")),
() -> assertThat(uri.getSchemeSpecificPart(), is("/com/example/app")));
} |
@Override
public void doBeforeRequest(String remoteAddr, RemotingCommand request) {
if (StringUtils.isNotEmpty(clientConfig.getNamespaceV2())) {
request.addExtField(MixAll.RPC_REQUEST_HEADER_NAMESPACED_FIELD, "true");
request.addExtField(MixAll.RPC_REQUEST_HEADER_NAMESPACE_FIELD, cli... | @Test
public void testDoBeforeRequestWithNamespace() {
clientConfig = new ClientConfig();
clientConfig.setNamespaceV2(namespace);
namespaceRpcHook = new NamespaceRpcHook(clientConfig);
PullMessageRequestHeader pullMessageRequestHeader = new PullMessageRequestHeader();
Remotin... |
public static Map<String, Map<String, InetSocketAddress>>
getNNServiceRpcAddressesForCluster(Configuration conf) throws IOException {
// Use default address as fall back
String defaultAddress;
try {
defaultAddress = NetUtils.getHostPortString(
DFSUtilClient.getNNAddress(conf));
} cat... | @Test
public void testErrorMessageForInvalidNameservice() throws Exception {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1, ns2");
String expectedErrorMessage = "Incorrect configuration: namenode address "
+ DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY + "... |
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
} | @Test
public void testWrite() throws IOException {
CallCountOutputStream fsCount = new CallCountOutputStream();
FilterOutputStream fs = new FilterOutputStream(fsCount);
CallCountOutputStream osCount = new CallCountOutputStream();
UnownedOutputStream os = new UnownedOutputStream(osCount);
byte[] d... |
public Map<String, List<TopicPartitionInfo>> getTopicPartitionInfo(final Set<String> topics) {
log.debug("Starting to describe topics {} in partition assignor.", topics);
long currentWallClockMs = time.milliseconds();
final long deadlineMs = currentWallClockMs + retryTimeoutMs;
final S... | @Test
public void shouldReturnCorrectPartitionInfo() {
final TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, broker1, singleReplica, Collections.emptyList());
mockAdminClient.addTopic(
false,
topic1,
Collections.singletonList(topicPartitionInfo),... |
@Override
public Instant deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
if (!(json instanceof JsonPrimitive))
throw new JsonParseException("The instant should be a string value");
else {
Instant time = deserializeToIns... | @Test
public void testDeserialize() {
assertEquals(
LocalDateTime.of(2017, 6, 8, 4, 26, 33)
.atOffset(ZoneOffset.UTC).toInstant(),
InstantTypeAdapter.deserializeToInstant("2017-06-08T04:26:33+0000"));
assertEquals(
LocalDateTim... |
@Override
public SchemaResult getKeySchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true);
} | @Test
public void shouldReturnErrorFromGetKeySchemaIfSchemaIsNotInExpectedFormat() {
// Given:
when(parsedSchema.schemaType()).thenReturn(ProtobufSchema.TYPE);
// When:
final SchemaResult result = supplier.getKeySchema(Optional.of(TOPIC_NAME),
Optional.empty(), expectedFormat, SerdeFeatures.o... |
public static String validateClaimNameOverride(String name, String value) throws ValidateException {
return validateString(name, value);
} | @Test
public void testValidateClaimNameOverride() {
String expected = "email";
String actual = ClaimValidationUtils.validateClaimNameOverride("sub", String.format(" %s ", expected));
assertEquals(expected, actual);
} |
public boolean isSystemInitiatedRun() {
return !initiator.getType().isRestartable();
} | @Test
public void testIsSystemInitiatedRun() {
RunRequest runRequest =
RunRequest.builder()
.currentPolicy(RunPolicy.START_FRESH_NEW_RUN)
.requester(User.create("tester"))
.build();
Assert.assertFalse(runRequest.isSystemInitiatedRun());
runRequest =
Run... |
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
} | @Test
public void testIsInfoEnabled() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.getName()).thenReturn("foo");
when(mockLogger.isInfoEnabled()).thenReturn(true);
InternalLogger logger = new Slf4JLogger(mockLogger);
assertTrue(logger.isInfoEnabled());
... |
public static <T> PrefetchableIterable<T> limit(Iterable<T> iterable, int limit) {
PrefetchableIterable<T> prefetchableIterable = maybePrefetchable(iterable);
return new Default<T>() {
@Override
public PrefetchableIterator<T> createIterator() {
return new PrefetchableIterator<T>() {
... | @Test
public void testLimit() {
verifyIterable(PrefetchableIterables.limit(PrefetchableIterables.fromArray(), 0));
verifyIterable(PrefetchableIterables.limit(PrefetchableIterables.fromArray(), 1));
verifyIterable(PrefetchableIterables.limit(PrefetchableIterables.fromArray("A", "B", "C"), 0));
verifyIt... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertArray() {
BasicTypeDefine typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("_bool")
.dataType("_bool")
.build();
Column column = PostgresTypeCo... |
@Override
public String getPort() {
final int port = Integer.parseInt(Optional.ofNullable(super.getPort()).orElseGet(() -> "-1"));
final int mergedPort = port <= 0 ? PortUtils.findPort(getContext().getAutowireCapableBeanFactory()) : port;
return String.valueOf(mergedPort);
} | @Test
public void testGetPort() {
String port = eventListener.getPort();
assertNotNull(port);
assertEquals(port, "8080");
} |
@Override
public String getWelcomeMessage(User user) {
if (UserGroup.isPaid(user)) {
return "You're amazing " + user + ". Thanks for paying for this awesome software.";
}
return "I suppose you can use this software.";
} | @Test
void testGetWelcomeMessageForPaidUser() {
final var welcomeMessage = service.getWelcomeMessage(paidUser);
final var expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software.";
assertEquals(expected, welcomeMessage);
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void booleanToJson() {
JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.BOOLEAN_SCHEMA, true));
validateEnvelope(converted);
assertEquals(parse("{ \"type\": \"boolean\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
ass... |
@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() {
List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10);
assertThat(keys).isEmpty();
} |
public static Properties parseKeyValueArgs(List<String> args) {
return parseKeyValueArgs(args, true);
} | @Test
public void testParseEmptyArgWithNoDelimiter() {
List<String> argArray = Arrays.asList("my.empty.property");
assertThrows(IllegalArgumentException.class, () -> CommandLineUtils.parseKeyValueArgs(argArray, false));
} |
public synchronized V get(final K key, final Supplier<V> valueSupplier, final Consumer<V> expireCallback) {
final var value = cache.get(key);
if (value != null) {
value.updateDeadline();
return value.value;
}
final var newValue = new ExpirableValue<>(valueSupplie... | @Test
public void testConcurrentUpdate() throws Exception {
final var cache = new SimpleCache<Integer, Integer>(executor, 10000L, 10000L);
final var pool = Executors.newFixedThreadPool(2);
final var latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
final var va... |
long count() {
return collection().count();
} | @Test
@MongoDBFixtures("singleDashboard.json")
public void testCountSingleDashboard() throws Exception {
assertEquals(1, this.dashboardService.count());
} |
@Override
public void beforeComponent(Component component) {
if (FILE.equals(component.getType())) {
anticipatedTransitions = anticipatedTransitionRepository.getAnticipatedTransitionByComponent(component);
} else {
anticipatedTransitions = Collections.emptyList();
}
} | @Test
public void givenAFileComponent_theRepositoryIsHitForFetchingAnticipatedTransitions() {
Component component = getComponent(Component.Type.FILE);
when(anticipatedTransitionRepository.getAnticipatedTransitionByComponent(component)).thenReturn(Collections.emptyList());
underTest.beforeComponent(compon... |
public int getMfgReserved() {
return mDataFields.get(0).intValue();
} | @Test
public void testRecognizeBeacon() {
byte[] bytes = hexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.fromScanData(bytes, -55, null, 123456L);
assertEquals("manData shoul... |
@Override
public List<String> getBrokers() {
return _allBrokerListRef.get();
} | @Test
public void testGetBrokers() {
assertEquals(_dynamicBrokerSelectorUnderTest.getBrokers(), ImmutableList.of("broker1"));
} |
@Produces
@DefaultBean
@Singleton
public JobScheduler jobScheduler(StorageProvider storageProvider) {
if (jobRunrBuildTimeConfiguration.jobScheduler().enabled()) {
final JobDetailsGenerator jobDetailsGenerator = newInstance(jobRunrRuntimeConfiguration.jobScheduler().jobDetailsGenerator()... | @Test
void jobSchedulerIsNotSetupWhenConfigured() {
when(jobSchedulerBuildTimeConfiguration.enabled()).thenReturn(false);
assertThat(jobRunrProducer.jobScheduler(storageProvider)).isNull();
} |
public int getNumber1()
{
checkAvailable(1);
int value = needle.get(needle.position()) & 0xff;
forward(1);
return value;
} | @Test(expected = IllegalArgumentException.class)
public void testGetIncorrectByte()
{
ZFrame frame = new ZFrame(new byte[0]);
ZNeedle needle = new ZNeedle(frame);
needle.getNumber1();
} |
@Override
public EntityExcerpt createExcerpt(DataAdapterDto dataAdapterDto) {
return EntityExcerpt.builder()
.id(ModelId.of(dataAdapterDto.id()))
.type(ModelTypes.LOOKUP_ADAPTER_V1)
.title(dataAdapterDto.title())
.build();
} | @Test
public void createExcerpt() {
final DataAdapterDto dataAdapterDto = DataAdapterDto.builder()
.id("1234567890")
.name("data-adapter-name")
.title("Data Adapter Title")
.description("Data Adapter Description")
.config(new Fa... |
public static boolean needsQuoting(byte[] data, int off, int len) {
for(int i=off; i< off+len; ++i) {
switch(data[i]) {
case '&':
case '<':
case '>':
case '\'':
case '"':
return true;
default:
break;
}
}
return false;
} | @Test public void testNeedsQuoting() throws Exception {
assertTrue(HtmlQuoting.needsQuoting("abcde>"));
assertTrue(HtmlQuoting.needsQuoting("<abcde"));
assertTrue(HtmlQuoting.needsQuoting("abc'de"));
assertTrue(HtmlQuoting.needsQuoting("abcde\""));
assertTrue(HtmlQuoting.needsQuoting("&"));
asse... |
public static void validateCardSecurityVsCardAccess(SecurityInfos cardSecurity, int caKeyReference, int paceVersion,
int taVersion) {
Assert.notNull(cardSecurity, "cardSecurity may not be null");
if (caKeyReference != cardSecurity.getCaKeyId() || ... | @Test
public void validateCardSecurityVsCardAccessPaceFail() {
ClientException thrown = assertThrows(ClientException.class, () -> CardValidations.validateCardSecurityVsCardAccess(efCardSecurity, 1, 2, 1));
assertEquals("The card info and the card security do not match.", thrown.getMessage());
} |
public Result resolve(List<PluginDescriptor> plugins) {
// create graphs
dependenciesGraph = new DirectedGraph<>();
dependentsGraph = new DirectedGraph<>();
// populate graphs
Map<String, PluginDescriptor> pluginByIds = new HashMap<>();
for (PluginDescriptor plugin : plu... | @Test
void cyclicDependencies() {
PluginDescriptor pd1 = new DefaultPluginDescriptor()
.setPluginId("p1")
.setPluginVersion("0.0.0")
.setDependencies("p2");
PluginDescriptor pd2 = new DefaultPluginDescriptor()
.setPluginId("p2")
.setPlugin... |
@Override
public ReleaseId getParentReleaseId() {
return parentReleaseId;
} | @Test
public void getParentReleaseIdNull() {
final MavenSession mavenSession = mockMavenSession(false);
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
assertThat(pomModel.getParentReleaseId()).isNull();
} |
static String determineFullyQualifiedClassName(Path baseDir, String basePackageName, Path classFile) {
String subpackageName = determineSubpackageName(baseDir, classFile);
String simpleClassName = determineSimpleClassName(classFile);
return of(basePackageName, subpackageName, simpleClassName)
... | @Test
void determineFullyQualifiedClassNameFromComPackage() {
Path baseDir = Paths.get("path", "to", "com");
String basePackageName = "com";
Path classFile = Paths.get("path", "to", "com", "example", "app", "App.class");
String fqn = ClasspathSupport.determineFullyQualifiedClassName(... |
@Override
public boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionState) {
return state.tryCall(
StateWithExecutionGraph.class,
stateWithExecutionGraph ->
stateWithExecutionGraph.updateTaskExecutionStat... | @Test
void testExceptionHistoryWithTaskFailure() throws Exception {
final Exception expectedException = new Exception("Expected Local Exception");
BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic =
(scheduler, attemptIds) -> {
final ExecutionAttem... |
public static NetFlowV9Packet parsePacket(ByteBuf bb, NetFlowV9FieldTypeRegistry typeRegistry) {
return parsePacket(bb, typeRegistry, Maps.newHashMap(), null);
} | @Test
public void testParse() throws IOException {
final byte[] b1 = Resources.toByteArray(Resources.getResource("netflow-data/netflow-v9-2-1.dat"));
final byte[] b2 = Resources.toByteArray(Resources.getResource("netflow-data/netflow-v9-2-2.dat"));
final byte[] b3 = Resources.toByteArray(Res... |
private static double[] parseThresholds(String ns, Configuration conf,
int numLevels) {
int[] percentages = conf.getInts(ns + "." +
IPC_FCQ_DECAYSCHEDULER_THRESHOLDS_KEY);
if (percentages.length == 0) {
percentages = conf.getInts(ns + "." + IPC_DECAYSCHEDULER_THRESHOLDS_KEY);
if (perc... | @Test
@SuppressWarnings("deprecation")
public void testParseThresholds() {
// Defaults vary by number of queues
Configuration conf = new Configuration();
scheduler = new DecayRpcScheduler(1, "ipc.5", conf);
assertEqualDecimalArrays(new double[]{}, scheduler.getThresholds());
scheduler = new Dec... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the TIMESTAMP value."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.")
public Timestamp parseTimestamp(
@UdfParameter(
descrip... | @Test
public void shouldWorkWithManyDifferentFormatters() {
IntStream.range(0, 10_000)
.parallel()
.forEach(idx -> {
try {
final String sourceDate = "2018-12-01 10:12:13.456X" + idx;
final String pattern = "yyyy-MM-dd HH:mm:ss.SSS'X" + idx + "'";
final... |
protected String messageToString(Message message) {
switch (message.getMessageType()) {
case SYSTEM:
return message.getContent();
case USER:
return humanPrompt + message.getContent();
case ASSISTANT:
return assistantPrompt + mes... | @Test
public void testSingleUserMessage() {
Message userMessage = new UserMessage("User message");
String expected = "User message";
Assert.assertEquals(expected, converter.messageToString(userMessage));
} |
@Override
public void finish()
{
close();
} | @Test
public void testFinish()
throws Exception
{
SourceOperator operator = createExchangeOperator();
operator.addSplit(new ScheduledSplit(0, operator.getSourceId(), newRemoteSplit(TASK_1_ID)));
operator.addSplit(new ScheduledSplit(1, operator.getSourceId(), newRemoteSplit(T... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDecimal() {
Column column =
PhysicalColumn.builder().name("test").dataType(new DecimalType(0, 0)).build();
BasicTypeDefine typeDefine = XuguTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName()... |
@Override
public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) {
ParamCheckResponse paramCheckResponse = new ParamCheckResponse();
if (paramInfos == null) {
paramCheckResponse.setSuccess(true);
return paramCheckResponse;
}
for (ParamInfo pa... | @Test
void testCheckParamInfoForDataId() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
// Max Length
String dataId = buildStringLength(257);
paramInfo.setDataId(dataId);
ParamCheckRespo... |
@Override
protected void refresh(final List<PluginData> data) {
pluginDataSubscriber.refreshPluginDataAll();
if (CollectionUtils.isEmpty(data)) {
LOG.info("clear all plugin data cache");
return;
}
data.forEach(pluginDataSubscriber::onSubscribe);
} | @Test
public void testRefreshCoverage() {
final PluginDataRefresh pluginDataRefresh = mockPluginDataRefresh;
PluginData selectorData = new PluginData();
List<PluginData> selectorDataList = new ArrayList<>();
pluginDataRefresh.refresh(selectorDataList);
selectorDataList.add(se... |
public MediaType getContentType() {
Optional<MediaType> optionalType = toContentType(Files.getFileExtension(filename));
Optional<Charset> targetCharset = toCharset(optionalType.orElse(null));
MediaType type = optionalType.orElse(DEFAULT_CONTENT_TYPE_WITH_CHARSET);
if (targetCharset.isPr... | @Test
public void should_get_default_type_from_unknown_name() {
FileContentType contentType = new FileContentType("UNKNOWN_FILE");
assertThat(contentType.getContentType(), is(MediaType.PLAIN_TEXT_UTF_8));
} |
public static GroupByParams build(
final LogicalSchema sourceSchema,
final List<CompiledExpression> groupBys,
final ProcessingLogger logger
) {
if (groupBys.isEmpty()) {
throw new IllegalArgumentException("No GROUP BY groupBys");
}
final Grouper grouper = buildGrouper(sourceSchema... | @Test(expected = IllegalArgumentException.class)
public void shouldThrowOnEmptyParam() {
GroupByParamsV1Factory
.build(SOURCE_SCHEMA, Collections.emptyList(), logger);
} |
public void appendDocument(PDDocument destination, PDDocument source) throws IOException
{
if (source.getDocument().isClosed())
{
throw new IOException("Error: source PDF is closed.");
}
if (destination.getDocument().isClosed())
{
throw new IOException... | @Test
void testMergeBogusStructParents1() throws IOException
{
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
try (PDDocument src = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4408.pdf"));
PDDocument dst = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4408.pdf")))
... |
@Override
public <T> TransformEvaluator<T> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
@SuppressWarnings({"cast", "unchecked", "rawtypes"})
TransformEvaluator<T> evaluator = createEvaluator((AppliedPTransform) application);
return evaluator;
} | @Test
public void testInMemoryEvaluator() throws Exception {
PCollection<String> input = p.apply(Create.of("foo", "bar"));
PCollectionView<Iterable<String>> pCollectionView = input.apply(View.asIterable());
PCollection<Iterable<String>> concat =
input
.apply(WithKeys.of((Void) null))
... |
@Override
public void validate(String name, String value) throws ParameterException {
URL serverUrl;
try {
serverUrl = new URL(value);
} catch (MalformedURLException e) {
throw new ParameterException(name + " is not a valid url");
}
if (!List.of("http... | @Test
void shouldValidateByParsingUrl() {
assertThatCode(() -> new ServerUrlValidator().validate("foo", "bad-url"))
.isOfAnyClassIn(ParameterException.class)
.hasMessageContaining("is not a valid url");
} |
@Override
public ParDoFn create(
PipelineOptions options,
CloudObject cloudUserFn,
List<SideInputInfo> sideInputInfos,
TupleTag<?> mainOutputTag,
Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices,
DataflowExecutionContext<?> executionContext,
DataflowOperationContext... | @Test
public void testCreateSimpleParDoFn() throws Exception {
// A serialized DoFn
String stringFieldValue = "some state";
long longFieldValue = 42L;
TestDoFn fn = new TestDoFn(stringFieldValue, longFieldValue);
String serializedFn =
StringUtils.byteArrayToJsonString(
Serializ... |
public static SerializableFunction<Row, TableRow> toTableRow() {
return ROW_TO_TABLE_ROW;
} | @Test
public void testToTableRow_array() {
TableRow row = toTableRow().apply(ARRAY_ROW);
assertThat(row, hasEntry("ids", Arrays.asList("123", "124")));
assertThat(row.size(), equalTo(1));
} |
@Override
public Runnable get() {
if (currentRunnable == null && currentStep != null) {
currentRunnable = createRunnable(currentStep, state);
}
return currentRunnable;
} | @Test
public void step_supplier_finishes() throws Exception {
HazelcastInstance node = createHazelcastInstance(getConfig());
Data data = Accessors.getSerializationService(node).toData("data");
MapOperation operation = new SetOperation("map", data, data);
operation.setNodeEngine(Acces... |
public static void checkDataSourceConnection(HikariDataSource ds) {
java.sql.Connection connection = null;
try {
connection = ds.getConnection();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
... | @Test
void testCheckConnectionNormal() throws SQLException {
HikariDataSource ds = mock(HikariDataSource.class);
Connection connection = mock(Connection.class);
when(ds.getConnection()).thenReturn(connection);
ConnectionCheckUtil.checkDataSourceConnection(ds);
verify(ds).getC... |
@Override
public void deleteCouponTemplate(Long id) {
// 校验存在
validateCouponTemplateExists(id);
// 删除
couponTemplateMapper.deleteById(id);
} | @Test
public void testDeleteCouponTemplate_success() {
// mock 数据
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class);
couponTemplateMapper.insert(dbCouponTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbCouponTemplate.getId();
// 调用
coup... |
@ConstantFunction(name = "milliseconds_sub", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true)
public static ConstantOperator millisecondsSub(ConstantOperator date, ConstantOperator millisecond) {
return ConstantOperator.createDatetimeOrNull(date.getDatetime().minus(millisecond.getInt()... | @Test
public void millisecondsSub() {
assertEquals("2015-03-23T09:23:54.990",
ScalarOperatorFunctions.millisecondsSub(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
@Override
public void e(String tag, String message, Object... args) {
Log.e(tag, formatString(message, args));
} | @Test
public void errorLoggedCorrectly() {
String expectedMessage = "Hello World";
logger.e(tag, "Hello %s", "World");
assertLogged(ERROR, tag, expectedMessage, null);
} |
public static String getJobFile(Configuration conf, String user,
org.apache.hadoop.mapreduce.JobID jobId) {
Path jobFile = new Path(MRApps.getStagingAreaDir(conf, user),
jobId.toString() + Path.SEPARATOR + MRJobConfig.JOB_CONF_FILE);
return jobFile.toString();
} | @Test
@Timeout(120000)
public void testGetJobFileWithUser() {
Configuration conf = new Configuration();
conf.set(MRJobConfig.MR_AM_STAGING_DIR, "/my/path/to/staging");
String jobFile = MRApps.getJobFile(conf, "dummy-user",
new JobID("dummy-job", 12345));
assertNotNull(jobFile, "getJobFile re... |
public RowMetaInterface getQueryFieldsFromDatabaseMetaData() throws Exception {
return this.getQueryFieldsFromDatabaseMetaData( null );
} | @Test
public void testGetQueryFieldsFromDatabaseMetaData() throws Exception {
DatabaseMeta meta = mock( DatabaseMeta.class );
DatabaseMetaData dbMetaData = mock( DatabaseMetaData.class );
Connection conn = mockConnection( dbMetaData );
ResultSet rs = mock( ResultSet.class );
String columnName = "y... |
public ReferenceConfig<GenericService> get(final String path) {
try {
return cache.get(path);
} catch (ExecutionException e) {
throw new ShenyuException(e.getCause());
}
} | @Test
public void testGet() {
assertNotNull(this.apacheDubboConfigCache.get("/test"));
} |
public static JavaToSqlTypeConverter javaToSqlConverter() {
return JAVA_TO_SQL_CONVERTER;
} | @Test
public void shouldGetSqlTypeForAllJavaTypes() {
SQL_TO_JAVA.inverse().forEach((java, sqlType) -> {
assertThat(javaToSqlConverter().toSqlType(java), is(sqlType));
});
} |
public Point getMinimum() {
int minx = Integer.MAX_VALUE, miny = Integer.MAX_VALUE;
for ( int i = 0; i < nrSteps(); i++ ) {
StepMeta stepMeta = getStep( i );
Point loc = stepMeta.getLocation();
if ( loc.x < minx ) {
minx = loc.x;
}
if ( loc.y < miny ) {
miny = loc.y... | @Test
public void testGetMinimum() {
final Point minimalCanvasPoint = new Point( 0, 0 );
//for test goal should content coordinate more than NotePadMetaPoint
final Point stepPoint = new Point( 500, 500 );
//empty Trans return 0 coordinate point
Point point = transMeta.getMinimum();
assertEqu... |
@Override
public int hashCode()
{
return super.hashCode() * 31 + (_entity == null ? 0 : _entity.hashCode());
} | @Test
public void testHashCode()
{
IdEntityResponse<Long, AnyRecord> longIdEntityResponse1 = new IdEntityResponse<>(1L, new AnyRecord());
IdEntityResponse<Long, AnyRecord> longIdEntityResponse2 = new IdEntityResponse<>(1L, new AnyRecord());
IdEntityResponse<Long, AnyRecord> nullLongResponse = new IdEnti... |
public static boolean shouldLoadInIsolation(String name) {
return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches());
} | @Test
public void testAllowedFileConnectors() {
List<String> jsonConverterClasses = Arrays.asList(
"org.apache.kafka.connect.file.",
"org.apache.kafka.connect.file.FileStreamSinkConnector",
"org.apache.kafka.connect.file.FileStreamSinkTask",
"org.apache.kafka.... |
@Override
public void lock() {
try {
lockInterruptibly(-1, null);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testLockUnlock() {
Lock lock = redisson.getSpinLock("lock1");
lock.lock();
lock.unlock();
lock.lock();
lock.unlock();
} |
@Override
public boolean dataDefinitionCausesTransactionCommit() {
return false;
} | @Test
void assertDataDefinitionCausesTransactionCommit() {
assertFalse(metaData.dataDefinitionCausesTransactionCommit());
} |
public @CheckForNull V start() throws Exception {
V result = null;
int currentAttempt = 0;
boolean success = false;
while (currentAttempt < attempts && !success) {
currentAttempt++;
try {
if (LOGGER.isLoggable(Level.INFO)) {
LO... | @Test
public void failedActionWithAllowedExceptionByInheritanceTest() throws Exception {
final int ATTEMPTS = 1;
final String ACTION = "print";
RingBufferLogHandler handler = new RingBufferLogHandler(20);
Logger.getLogger(Retrier.class.getName()).addHandler(handler);
// Set... |
public static <T> Mono<Long> writeAll(Writer writer, Flux<T> values) throws IOException {
return writeAll(DEFAULT_OBJECT_MAPPER, writer, values);
} | @Test
void writeAll_fromSingleValuedSource() throws IOException {
final Path outputTempFilePath = createTempFile();
final List<SimpleEntry> inputValues = List.of(new SimpleEntry(1, "value1"));
final Long outputCount = FileSerde.writeAll(Files.newBufferedWriter(outputTempFilePath), Flux.from... |
public static boolean isMatch(String regex, CharSequence content) {
if (content == null) {
// 提供null的字符串为不匹配
return false;
}
if (StrUtil.isEmpty(regex)) {
// 正则不存在则为全匹配
return true;
}
// Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Pattern pattern = PatternPool.get(regex, Pa... | @Test
public void matchTest(){
final boolean match = ReUtil.isMatch(
"(.+?)省(.+?)市(.+?)区", "广东省深圳市南山区");
Console.log(match);
} |
@Nonnull
public static <V> Set<V> findDuplicates(@Nonnull final Collection<V>... collections)
{
final Set<V> merged = new HashSet<>();
final Set<V> duplicates = new HashSet<>();
for (Collection<V> collection : collections) {
for (V o : collection) {
if (!merge... | @Test
public void testSingleCollectionWithDuplicates() throws Exception
{
// Setup test fixture.
final List<String> input = Arrays.asList("a", "DUPLICATE", "c", "DUPLICATE");
// Execute system under test.
@SuppressWarnings("unchecked")
final Set<String> result = Collecti... |
public BundleProcessor getProcessor(
BeamFnApi.ProcessBundleDescriptor descriptor,
List<RemoteInputDestination> remoteInputDesinations) {
checkState(
!descriptor.hasStateApiServiceDescriptor(),
"The %s cannot support a %s containing a state %s.",
BundleProcessor.class.getSimpleNa... | @Test
public void testBundleCheckpointCallback() throws Exception {
BeamFnDataOutboundAggregator mockInputSender = mock(BeamFnDataOutboundAggregator.class);
CompletableFuture<InstructionResponse> processBundleResponseFuture = new CompletableFuture<>();
when(fnApiControlClient.handle(any(BeamFnApi.Instruc... |
public void addHandler(int startAddress, int endAddress, EH handler) {
TryBounds<EH> bounds = getBoundingRanges(startAddress, endAddress);
MutableTryBlock<EH> startBlock = bounds.start;
MutableTryBlock<EH> endBlock = bounds.end;
int previousEnd = startAddress;
MutableTryBlock<E... | @Test
public void testHandlerMerge_DifferentAddress() {
TryListBuilder tlb = new TryListBuilder();
tlb.addHandler(5, 10, new ImmutableExceptionHandler("LException1;", 5));
tlb.addHandler(0, 15, new ImmutableExceptionHandler("LException1;", 6));
// no exception should be thrown...
... |
@JsonProperty("streamsProperties")
public Map<String, Object> getConfigOverrides() {
return PropertiesUtil.coerceTypes(configOverrides, false);
} | @Test
public void shouldHandleNullPropertyValue() {
// Given:
final KsqlRequest request = new KsqlRequest(
"sql",
Collections.singletonMap(
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"
),
SOME_REQUEST_PROPS,
null
);
// When:
final Map<Str... |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void nonTruthErrorFactValue() {
Object unused = expectFailureWhenTestingThat(new AssertionError()).factValue("foo");
assertFailureKeys("expected a failure thrown by Truth's failure API", "but was");
} |
@Override
public void handshakeFailed(Event event, Throwable throwable) {
log.log(Level.FINE, throwable, () -> "Ssl handshake failed: " + throwable.getMessage());
String metricName = SslHandshakeFailure.fromSslHandshakeException((SSLHandshakeException) throwable)
.map(SslHandshakeFai... | @Test
void does_not_include_client_ip_dimension_present_when_peer_unavailable() {
listener.handshakeFailed(handshakeEvent(false), new SSLHandshakeException("Empty server certificate chain"));
verify(metrics).createContext(eq(Map.of("serverName", "connector", "serverPort", 1234)));
} |
@Override
public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
AuthPaginationHelper<RoleInfo> helper = createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM (SELECT DISTINCT role FROM roles) roles WHERE ";
String sqlFetchRows = "SELECT role,userna... | @Test
void testGetRoles() {
Page<RoleInfo> roles = externalRolePersistService.getRoles(1, 10);
assertNotNull(roles);
} |
public static Read read() {
return new Read(null, "", new Scan());
} | @Test
public void testReadingWithSplits() throws Exception {
final String table = tmpTable.getName();
final int numRows = 1500;
final int numRegions = 4;
final long bytesPerRow = 100L;
createAndWriteData(table, numRows);
HBaseIO.Read read = HBaseIO.read().withConfiguration(conf).withTableId(t... |
@Override
public boolean canHandleReturnType(Class<?> returnType) {
return rxSupportedTypes.stream().anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Single.class)).isTrue();
assertThat(rxJava3TimeLimiterAspectExt.canHandleReturnType(Observable.class)).isTrue(... |
public static MetricRegistry getDefault() {
MetricRegistry metricRegistry = tryGetDefault();
if (metricRegistry == null) {
throw new IllegalStateException("Default registry name has not been set.");
}
return metricRegistry;
} | @Test
public void errorsWhenDefaultUnset() {
exception.expect(IllegalStateException.class);
exception.expectMessage("Default registry name has not been set.");
SharedMetricRegistries.getDefault();
} |
void triggerEvent(final DiscordGameEventType eventType)
{
final Optional<EventWithTime> foundEvent = events.stream().filter(e -> e.type == eventType).findFirst();
final EventWithTime event;
if (foundEvent.isPresent())
{
event = foundEvent.get();
}
else
{
event = new EventWithTime(eventType);
ev... | @Test
public void testAreaChange()
{
when(discordConfig.elapsedTimeType()).thenReturn(DiscordConfig.ElapsedTimeType.TOTAL);
// Start with state of IN_GAME
ArgumentCaptor<DiscordPresence> captor = ArgumentCaptor.forClass(DiscordPresence.class);
discordState.triggerEvent(DiscordGameEventType.IN_GAME);
verify... |
public Option<Dataset<Row>> loadAsDataset(SparkSession spark, List<CloudObjectMetadata> cloudObjectMetadata,
String fileFormat, Option<SchemaProvider> schemaProviderOption, int numPartitions) {
if (LOG.isDebugEnabled()) {
LOG.debug("Extracted distinct files " + clou... | @Test
public void filesFromMetadataRead() {
CloudObjectsSelectorCommon cloudObjectsSelectorCommon = new CloudObjectsSelectorCommon(new TypedProperties());
List<CloudObjectMetadata> input = Collections.singletonList(new CloudObjectMetadata("src/test/resources/data/partitioned/country=US/state=CA/data.json", 1)... |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
int date = payload.getByteBuf().readUnsignedMediumLE();
int year = date / 16 / 32;
int month = date / 32 % 16;
int day = date % 32;
return 0 == date ? MySQLTimeValueUt... | @Test
void assertReadNullDate() {
when(payload.getByteBuf()).thenReturn(byteBuf);
when(byteBuf.readUnsignedMediumLE()).thenReturn(0);
assertThat(new MySQLDateBinlogProtocolValue().read(columnDef, payload), is(MySQLTimeValueUtils.ZERO_OF_DATE));
} |
public boolean isAbsolute() {
final int start = hasWindowsDrive(uri.getPath(), true) ? 3 : 0;
return uri.getPath().startsWith(SEPARATOR, start);
} | @Test
void testIsAbsolute() {
// UNIX
Path p = new Path("/my/abs/path");
assertThat(p.isAbsolute()).isTrue();
p = new Path("/");
assertThat(p.isAbsolute()).isTrue();
p = new Path("./my/rel/path");
assertThat(p.isAbsolute()).isFalse();
p = new Path... |
@VisibleForTesting
static Path resolveEntropy(Path path, EntropyInjectingFileSystem efs, boolean injectEntropy)
throws IOException {
final String entropyInjectionKey = efs.getEntropyInjectionKey();
if (entropyInjectionKey == null) {
return path;
} else {
... | @Test
void testFullUriMatching() throws Exception {
EntropyInjectingFileSystem efs = new TestEntropyInjectingFs("s0mek3y", "12345678");
Path path = new Path("s3://hugo@myawesomehost:55522/path/s0mek3y/the/file");
assertThat(EntropyInjector.resolveEntropy(path, efs, true))
.i... |
public PullResult getHalfMessage(int queueId, long offset, int nums) {
String group = TransactionalMessageUtil.buildConsumerGroup();
String topic = TransactionalMessageUtil.buildHalfTopic();
SubscriptionData sub = new SubscriptionData(topic, "*");
return getMessage(group, topic, queueId,... | @Test
public void testGetHalfMessage() {
when(messageStore.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))).thenReturn(createGetMessageResult(GetMessageStatus.NO_MESSAGE_IN_QUEUE));
PullResult result = transactionBridge.getHalfMess... |
protected List<DeviceId> getDeviceAndPopulatePowerMap(JsonNode connectivityReply,
Map<DeviceId, Double> deviceAtoBPowerMap,
Map<DeviceId, Double> deviceBtoAPowerMap,
... | @Test
public void testgetDevicePowerMap() throws IOException {
Map<DeviceId, Double> deviceAtoBPowerMap = new HashMap<>();
Map<DeviceId, Double> deviceBtoAPowerMap = new HashMap<>();
manager.getDeviceAndPopulatePowerMap(reply, deviceAtoBPowerMap, deviceBtoAPowerMap, "second");
assert... |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithDelimiterAndEnclosureNullMultiCharRemoveEnclosure() {
String mask = "Hello%s world";
String[] chunks = {"Hello", " world"};
String stringToSplit = String.format( mask, DELIMITER2 );
String[] result = Const.splitString( stringToSplit, DELIMITER2, null, true );
... |
@Override
public ManageSnapshots replaceBranch(String name, long snapshotId) {
updateSnapshotReferencesOperation().replaceBranch(name, snapshotId);
return this;
} | @TestTemplate
public void testReplaceBranch() {
table.newAppend().appendFile(FILE_A).set("wap.id", "123").stageOnly().commit();
Snapshot firstSnapshot = Iterables.getOnlyElement(table.snapshots());
table.manageSnapshots().createBranch("branch1", firstSnapshot.snapshotId()).commit();
table.newAppend().... |
static BayeuxClient createClient(final SalesforceComponent component, final SalesforceSession session)
throws SalesforceException {
// use default Jetty client from SalesforceComponent, it's shared by all consumers
final SalesforceHttpClient httpClient = component.getConfig().getHttpClient()... | @Test
public void shouldLoginWhenAccessTokenIsNullAndLazyLoginIsFalse() throws SalesforceException {
final SalesforceHttpClient httpClient = mock(SalesforceHttpClient.class);
httpClient.setTimeout(0L);
final SalesforceEndpointConfig endpointConfig = new SalesforceEndpointConfig();
e... |
@Override public final String path() {
return delegate.getRequestURI();
} | @Test void path_doesntCrashOnNullUrl() {
assertThat(wrapper.path())
.isNull();
} |
public byte[] loadContent() {
Collection<String> lines = Arrays.asList(urlLoader.load(url.getConfigurationSubject(), url.getQueryProps()).split(System.lineSeparator()));
return URLArgumentLineRender.render(lines, URLArgumentPlaceholderTypeFactory.valueOf(url.getQueryProps()));
} | @Test
void assertLoadContent() {
final String lineSeparator = System.lineSeparator();
String content = "foo_driver_fixture_db=2" + lineSeparator + "storage_unit_count=2" + lineSeparator;
ShardingSphereURLLoader urlLoader = mock(ShardingSphereURLLoader.class);
when(urlLoader.load(any(... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testNoOperation() throws Exception {
// Test MapTaskExecutor without a single operation.
ExecutionStateTracker stateTracker = ExecutionStateTracker.newForTest();
try (IntrinsicMapTaskExecutor executor =
IntrinsicMapTaskExecutor.withSharedCounterSet(
new ArrayList<Oper... |
public ChannelUriStringBuilder linger(final Long lingerNs)
{
if (null != lingerNs && lingerNs < 0)
{
throw new IllegalArgumentException("linger value cannot be negative: " + lingerNs);
}
this.linger = lingerNs;
return this;
} | @Test
void shouldCopyLingerTimeoutFromChannelUriHumanForm()
{
final ChannelUriStringBuilder builder = new ChannelUriStringBuilder();
builder.linger(ChannelUri.parse("aeron:ipc?linger=7200s"));
assertEquals(TimeUnit.HOURS.toNanos(2), builder.linger());
} |
@SuppressWarnings("unchecked")
public static <T> TypeInformation<T> convert(String jsonSchema) {
Preconditions.checkNotNull(jsonSchema, "JSON schema");
final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper();
mapper.getFactory()
.enable(JsonParser.Feature.ALLOW_... | @Test
void testMissingProperties() {
final TypeInformation<?> result = JsonRowSchemaConverter.convert("{ type: 'object' }");
assertThat(result).isEqualTo(Types.ROW());
} |
public synchronized void scheduleRequest(DataSize maxResponseSize)
{
if (closed || (future != null) || scheduled) {
return;
}
scheduled = true;
// start before scheduling to include error delay
backoff.startRequest();
long delayNanos = backoff.getBackoff... | @Test
public void testExceptionFromResponseHandler()
throws Exception
{
DataSize expectedMaxSize = new DataSize(10, Unit.MEGABYTE);
TestingTicker ticker = new TestingTicker();
AtomicReference<Duration> tickerIncrement = new AtomicReference<>(new Duration(0, TimeUnit.SECONDS))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.