focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static String generateClassName(final OpenAPI document) {
final Info info = document.getInfo();
if (info == null) {
return DEFAULT_CLASS_NAME;
}
final String title = info.getTitle();
if (title == null) {
return DEFAULT_CLASS_NAME;
}
final... | @Test
public void shouldGenerateClassNameFromTitle() {
final OpenAPI openapi = new OpenAPI();
final Info info = new Info();
info.setTitle("Example API");
openapi.setInfo(info);
assertThat(RestDslSourceCodeGenerator.generateClassName(openapi)).isEqualTo("ExampleAPI");
} |
public static BigDecimal roundHalfEven(Number number, int scale) {
return roundHalfEven(toBigDecimal(number), scale);
} | @Test
public void roundHalfEvenTest() {
String roundStr = NumberUtil.roundHalfEven(4.245, 2).toString();
assertEquals(roundStr, "4.24");
roundStr = NumberUtil.roundHalfEven(4.2450, 2).toString();
assertEquals(roundStr, "4.24");
roundStr = NumberUtil.roundHalfEven(4.2451, 2).toString();
assertEquals(roundSt... |
public boolean matches(String text) {
if (text == null) {
return false;
}
if (this.regex) {
final Pattern rx;
if (this.caseSensitive) {
rx = Pattern.compile(this.value);
} else {
rx = Pattern.compile(this.value, Patt... | @Test
public void testMatches() {
String text = "Simple";
PropertyType instance = new PropertyType();
instance.setValue("simple");
assertTrue(instance.matches(text));
instance.setCaseSensitive(true);
assertFalse(instance.matches(text));
instance.setValue("s.... |
public final synchronized List<E> getAllAddOns() {
Logger.d(mTag, "getAllAddOns has %d add on for %s", mAddOns.size(), getClass().getName());
if (mAddOns.size() == 0) {
loadAddOns();
}
Logger.d(
mTag, "getAllAddOns will return %d add on for %s", mAddOns.size(), getClass().getName());
r... | @Test(expected = UnsupportedOperationException.class)
public void testGetAllAddOnsReturnsUnmodifiableList() throws Exception {
TestableAddOnsFactory factory = new TestableAddOnsFactory(true);
List<TestAddOn> list = factory.getAllAddOns();
list.remove(0);
} |
public static void writeFixedLengthBytesFromStart(byte[] data, int length, ByteArrayOutputStream out) {
writeFixedLengthBytes(data, 0, length, out);
} | @Test
public void testWriteFixedLengthBytesFromStart() {
ByteHelper.writeFixedLengthBytesFromStart(null, 0, null);
} |
@Override
public boolean contains(Object o) {
for (M member : members) {
if (selector.select(member) && o.equals(member)) {
return true;
}
}
return false;
} | @Test
public void testDoesNotContainThisMemberWhenDataMembersSelected() {
Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, DATA_MEMBER_SELECTOR);
assertFalse(collection.contains(thisMember));
} |
static int internalEncodeLogHeader(
final MutableDirectBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final NanoClock nanoClock)
{
if (captureLength < 0 || captureLength > length || captureLength > MAX_CAPTURE_LENGTH)
{
... | @Test
void encodeLogHeaderThrowsIllegalArgumentExceptionIfCaptureLengthIsNegative()
{
assertThrows(IllegalArgumentException.class,
() -> internalEncodeLogHeader(buffer, 0, -1, Integer.MAX_VALUE, () -> 0));
} |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
if (!joinKey.isForeignKey()) {
ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient());
}
final JoinerFactory joinerFactory = new JoinerFactory(
buildContext,
this,
... | @Test
public void shouldPerformStreamToStreamRightJoin() {
// Given:
setupStream(left, leftSchemaKStream);
setupStream(right, rightSchemaKStream);
final JoinNode joinNode =
new JoinNode(nodeId, RIGHT, joinKey, true, left, right, WITHIN_EXPRESSION, "KAFKA");
// When:
joinNode.buildStr... |
void setFieldInSObject( SObject sobjPass, XmlObject element ) {
Iterator<XmlObject> children = element.getChildren();
String name = element.getName().getLocalPart();
if ( !children.hasNext() ) {
sobjPass.setSObjectField( name, element.getValue() );
} else {
SObject child = new SObject();
... | @Test
public void testSetFieldInSObjectForeignKey() throws Exception {
SalesforceUpsert salesforceUpsert =
new SalesforceUpsert( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans );
SObject sobjPass = new SObject();
XmlObject parentObject = new XmlObject();
String parentParam = "... |
@Override
public Integer doCall() throws Exception {
JsonObject pluginConfig = loadConfig();
JsonObject plugins = pluginConfig.getMap("plugins");
Optional<PluginType> camelPlugin = PluginType.findByName(name);
if (camelPlugin.isPresent()) {
if (command == null) {
... | @Test
public void shouldUseArtifactIdAndVersion() throws Exception {
PluginAdd command = new PluginAdd(new CamelJBangMain().withPrinter(printer));
command.name = "foo-plugin";
command.command = "foo";
command.groupId = "org.foo";
command.artifactId = "foo-bar";
comman... |
public static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups) {
int errorCount = 0;
List<ConfigInfo> configInfoList = new LinkedList<>();
Map<String, ConfigValue> configValueMap = new HashMap<>();
for (C... | @Test
public void testGenerateResultWithConfigValuesAllUsingConfigKeysAndWithNoErrors() {
String name = "com.acme.connector.MyConnector";
Map<String, ConfigDef.ConfigKey> keys = new HashMap<>();
addConfigKey(keys, "config.a1", null);
addConfigKey(keys, "config.b1", "group B");
... |
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch)
{
trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch);
} | @Test
public void testRecordRefArrayTrim() throws CloneNotSupportedException
{
TyperefTest test = new TyperefTest();
RecordBarArrayArray recordBarArrayArray = new RecordBarArrayArray();
RecordBarArray recordBarArray = new RecordBarArray();
RecordBar recordBar = new RecordBar();
recordBar.setLo... |
public ShareFetchContext newContext(String groupId, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData,
List<TopicIdPartition> toForget, ShareRequestMetadata reqMetadata, Boolean isAcknowledgeDataPresent) {
ShareFetchContext context;
// Top... | @Test
public void testNewContextReturnsFinalContextError() {
Time time = new MockTime();
ShareSessionCache cache = new ShareSessionCache(10, 1000);
SharePartitionManager sharePartitionManager = SharePartitionManagerBuilder.builder()
.withCache(cache).withTime(time).build();
... |
@Override
public void includePattern(String[] regexp) {
if (regexp != null && regexp.length > 0) {
INCPTRN = regexp;
this.PTRNFILTER = true;
// now we create the compiled pattern and
// add it to the arraylist
for (String includePattern : INCPTRN) ... | @Test
public void testIncludePattern() {
testf.includePattern(PATTERNS);
for (TestData td : TESTDATA) {
String theFile = td.file;
boolean expect = td.inclpatt;
assertPrimitiveEquals(!expect, testf.isFiltered(theFile, null));
String line = testf.filter... |
public static SslContextFactory.Server createSslContextFactory(String sslProviderString,
PulsarSslFactory pulsarSslFactory,
boolean requireTrustedClientCertOnConnect,
... | @Test(expectedExceptions = SSLHandshakeException.class)
public void testJettyTlsServerInvalidTlsProtocol() throws Exception {
@Cleanup("stop")
Server server = new Server();
List<ServerConnector> connectors = new ArrayList<>();
PulsarSslConfiguration sslConfiguration = PulsarSslConfig... |
@Override
public Map<K, V> loadAll(Collection<K> keys) {
long startNanos = Timer.nanos();
try {
return delegate.loadAll(keys);
} finally {
loadAllProbe.recordValue(Timer.nanosElapsed(startNanos));
}
} | @Test
public void loadAll() {
Collection<String> keys = asList("key1", "key2");
Map<String, String> values = new HashMap<>();
values.put("key1", "value1");
values.put("key2", "value2");
when(delegate.loadAll(keys)).thenReturn(values);
Map<String, String> result = ca... |
@JsonProperty
public URI getUri()
{
return uri;
} | @Test
public void testQueryWithTableNameNeedingURLEncodeInSplits()
throws URISyntaxException
{
Instant now = LocalDateTime.of(2019, 10, 2, 7, 26, 56, 0).toInstant(UTC);
PrometheusConnectorConfig config = getCommonConfig(prometheusHttpServer.resolve("/prometheus-data/prom-metrics-non-... |
public void retain(IndexSet indexSet, IndexLifetimeConfig config, RetentionExecutor.RetentionAction action, String actionName) {
final Map<String, Set<String>> deflectorIndices = indexSet.getAllIndexAliases();
// Account for DST and time zones in determining age
final DateTime now = clock.nowUT... | @Test
public void retainTimeBasedNothing() {
underTest.retain(indexSet, getIndexLifetimeConfig(20, 30), action, "action");
verify(action, times(0)).retain(any(), any());
} |
public AdditionalServletWithClassLoader load(
AdditionalServletMetadata metadata, String narExtractionDirectory) throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
.narFile(narFi... | @Test(expectedExceptions = IOException.class)
public void testLoadEventListenerWithBlankListenerClass() throws Exception {
AdditionalServletDefinition def = new AdditionalServletDefinition();
def.setDescription("test-proxy-listener");
String archivePath = "/path/to/proxy/listener/nar";
... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
TbMsgMetaData metaDataCopy = msg.getMetaData().copy();
String data = msg.getData();
boolean msgChanged = false;
switch (renameIn) {
case METADATA:
... | @Test
void givenMsgDataNotJSONObject_whenOnMsg_thenVerifyOutput() throws Exception {
TbMsg msg = getTbMsg(deviceId, TbMsg.EMPTY_JSON_ARRAY);
node.onMsg(ctx, msg);
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ctx, times(1)).tellSuccess(newMsgCapto... |
static Set<Dependency> tryCreateFromAccess(JavaAccess<?> access) {
JavaClass originOwner = access.getOriginOwner();
JavaClass targetOwner = access.getTargetOwner();
ImmutableSet.Builder<Dependency> dependencies = ImmutableSet.<Dependency>builder()
.addAll(createComponentTypeDepen... | @Test
public void convert_dependency_from_access() {
JavaMethodCall call = simulateCall().from(getClass(), "toString").to(Object.class, "toString");
Dependency dependency = getOnlyElement(Dependency.tryCreateFromAccess(call));
assertThatConversionOf(dependency)
.satisfiesSt... |
public static Matcher<HttpRequest> methodEquals(String method) {
if (method == null) throw new NullPointerException("method == null");
if (method.isEmpty()) throw new NullPointerException("method is empty");
return new MethodEquals(method);
} | @Test void methodEquals_matched() {
when(httpRequest.method()).thenReturn("GET");
assertThat(methodEquals("GET").matches(httpRequest)).isTrue();
} |
@Override
public void run() {
boolean isNeedFlush = false;
boolean sqlShowEnabled = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps().getValue(ConfigurationPropertyKey.SQL_SHOW);
try {
if (sqlShowEnabled) {
fillLogMDC();... | @Test
void assertRunWithOOMError() throws BackendConnectionException, SQLException {
doThrow(OutOfMemoryError.class).when(commandExecutor).execute();
when(engine.getCodecEngine().createPacketPayload(message, StandardCharsets.UTF_8)).thenReturn(payload);
when(engine.getCommandExecuteEngine().... |
@Override
public ValidationResult validate(RuleBuilderStep step) {
final RuleFragment ruleFragment = actions.get(step.function());
FunctionDescriptor<?> functionDescriptor = ruleFragment.descriptor();
String functionName = functionDescriptor.name();
if (functionName.equals(SetField.... | @Test
void validateOtherFunctionsAreSkipped() {
HashMap<String, Object> parameters = new HashMap<>();
parameters.put(FIELD_PARAM, WITH_SPACES);
RuleBuilderStep randomOtherFunction = RuleBuilderStep
.builder()
.parameters(parameters)
.function(V... |
public static RocksDbIndexedTimeOrderedWindowBytesStoreSupplier create(final String name,
final Duration retentionPeriod,
final Duration windowSize,
... | @Test
public void shouldThrowIfWindowSizeIsNegative() {
final Exception e = assertThrows(IllegalArgumentException.class, () -> RocksDbIndexedTimeOrderedWindowBytesStoreSupplier.create("anyName", ofMillis(0L), ofMillis(-1L), false, false));
assertEquals("windowSize cannot be negative", e.getMessage()... |
@Override
public int getClusterSize()
{
return networkRetry.run("fetchClusterSize", this::fetchClusterSize);
} | @Test
public void testNodeResource()
{
assertEquals(client.getClusterSize(), 0);
} |
public static <T extends Throwable> void checkNotEmpty(final String value, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (Strings.isNullOrEmpty(value)) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckNotEmptyWithStringToNotThrowException() {
assertDoesNotThrow(() -> ShardingSpherePreconditions.checkNotEmpty("foo", SQLException::new));
} |
public EnumSet<CreateFlag> createFlag() {
String cf = "";
if (param(CreateFlagParam.NAME) != null) {
QueryStringDecoder decoder = new QueryStringDecoder(
param(CreateFlagParam.NAME),
StandardCharsets.UTF_8);
cf = decoder.path();
}
return new CreateFlagParam(cf).getValue()... | @Test
public void testCreateFlag() {
final String path = "/test1?createflag=append,sync_block";
Configuration conf = new Configuration();
QueryStringDecoder decoder = new QueryStringDecoder(
WebHdfsHandler.WEBHDFS_PREFIX + path);
ParameterParser testParser = new ParameterParser(decoder, conf);... |
@Override
public V pollLast(long timeout, TimeUnit unit) throws InterruptedException {
return commandExecutor.getInterrupted(pollLastAsync(timeout, unit));
} | @Test
public void testPollLast() throws InterruptedException {
RBlockingDeque<Integer> queue1 = redisson.getPriorityBlockingDeque("queue1");
queue1.add(3);
queue1.add(1);
queue1.add(2);
assertThat(queue1.pollLast(2, TimeUnit.SECONDS)).isEqualTo(3);
assertThat(queue1.... |
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) {
KafkaMetadataState currentState = metadataState;
metadataState = switch (currentState) {
case KRaft -> onKRaft(kafkaStatus);
case ZooKeeper -> onZooKeeper(kafkaStatus);
case KRaftMigration -... | @Test
public void testFromZookeeperToKRaftMigration() {
// test with no metadata state set
Kafka kafka = new KafkaBuilder(KAFKA)
.editMetadata()
.addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "migration")
.endMetadata()
.build... |
public boolean isAtLeast(final KsqlVersion version) {
if (versionType == version.versionType) {
return isAtLeastVersion(this, version.majorVersion, version.minorVersion);
}
if (versionType == VersionType.KSQLDB_STANDALONE) {
final KsqlVersion otherStandalone = versionMapping.get(version);
... | @Test
public void shouldCompareCpVersionToStandaloneVersionIsAtLeast() {
// known mappings
assertThat(new KsqlVersion("6.0.").isAtLeast(new KsqlVersion("0.10.")), is(true));
assertThat(new KsqlVersion("0.10.").isAtLeast(new KsqlVersion("6.0.")), is(true));
assertThat(new KsqlVersion("6.1.").isAtLeast... |
public static String formatTimer(long timerInSeconds) {
final long min = TimeUnit.SECONDS.toMinutes(timerInSeconds);
final long sec = TimeUnit.SECONDS.toSeconds(timerInSeconds - TimeUnit.MINUTES.toSeconds(min));
return String.format("%02d:%02d", min, sec);
} | @Test
public void testFormatTimer() {
assertEquals("10:00", formatTimer(600));
assertEquals("00:00", formatTimer(0));
assertEquals("00:45", formatTimer(45));
assertEquals("02:45", formatTimer(165));
assertEquals("30:33", formatTimer(1833));
} |
@Override
public void validateTransientQuery(
final SessionConfig config,
final ExecutionPlan executionPlan,
final Collection<QueryMetadata> runningQueries
) {
validateCacheBytesUsage(
runningQueries.stream()
.filter(q -> q instanceof TransientQueryMetadata)
.co... | @Test
public void shouldIgnoreBufferCacheLimitIfNotSetForTransientQueries() {
// Given:
final SessionConfig config = configWithLimits(100000000000L, OptionalLong.empty());
// When/Then (no throw)
queryValidator.validateTransientQuery(config, plan, queries);
} |
@Override
public ReservationSubmissionResponse submitReservation(
ReservationSubmissionRequest request) throws YarnException, IOException {
if (request == null || request.getReservationId() == null
|| request.getReservationDefinition() == null || request.getQueue() == null) {
routerMetrics.in... | @Test
public void testSubmitReservation() throws Exception {
LOG.info("Test FederationClientInterceptor : SubmitReservation request.");
// get new reservationId
GetNewReservationRequest request = GetNewReservationRequest.newInstance();
GetNewReservationResponse response = interceptor.getNewReservatio... |
@Override
public List<SensitiveWordDO> getSensitiveWordList() {
return sensitiveWordMapper.selectList();
} | @Test
public void testGetSensitiveWordList() {
// mock 数据
SensitiveWordDO sensitiveWord01 = randomPojo(SensitiveWordDO.class);
sensitiveWordMapper.insert(sensitiveWord01);
SensitiveWordDO sensitiveWord02 = randomPojo(SensitiveWordDO.class);
sensitiveWordMapper.insert(sensitiv... |
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName)
throws Exception {
Message in = exchange.getIn();
MetricsTimerAction action = endpoint.getAction();
MetricsTimerAction finalAction = in.getHeader(HEADER_TI... | @Test
public void testProcessStartWithOverride() throws Exception {
when(endpoint.getAction()).thenReturn(MetricsTimerAction.start);
when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class))
.thenReturn(MetricsTimerAction.stop);
when(exchange... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testCorrectHandlingOfOutOfOrderResponses() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(producerId, Errors.NONE)... |
@Beta
public static Application fromBuilder(Builder builder) throws Exception {
return builder.build();
} | @Test
void renderer() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.renderer("mock", MockRenderer.class))))
) {
... |
@Override
public void updateDataSourceConfig(DataSourceConfigSaveReqVO updateReqVO) {
// 校验存在
validateDataSourceConfigExists(updateReqVO.getId());
DataSourceConfigDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceConfigDO.class);
validateConnectionOK(updateObj);
// 更新
... | @Test
public void testUpdateDataSourceConfig_notExists() {
// 准备参数
DataSourceConfigSaveReqVO reqVO = randomPojo(DataSourceConfigSaveReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> dataSourceConfigService.updateDataSourceConfig(reqVO), DATA_SOURCE_CONFIG_NOT_EXISTS);
} |
static Expression createIntervalsExpression(List<Interval> intervals) {
ExpressionStmt arraysAsListStmt = CommonCodegenUtils.createArraysAsListExpression();
MethodCallExpr arraysCallExpression = arraysAsListStmt.getExpression().asMethodCallExpr();
NodeList<Expression> arguments = new NodeList<>(... | @Test
void createIntervalsExpression() {
List<Interval> intervals = IntStream.range(0, 3)
.mapToObj(i -> {
int leftMargin = new Random().nextInt(40);
int rightMargin = leftMargin + 13;
return new Interval(leftMargin, rightMargin);
... |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
public void when_schemaHasUnsupportedType_then_fieldResolutionFails() {
List<Schema> unsupportedSchemaTypes = List.of(
Schema.create(Schema.Type.BYTES),
SchemaBuilder.array().items(Schema.create(Schema.Type.INT)),
SchemaBuilder.map().values(Schema.create... |
public XmlConfiguration(final LoggerContext loggerContext, final ConfigurationSource configSource) {
super(loggerContext, configSource);
} | @Test
public void testXmlConfiguration() throws IOException {
Path path = getConfigPath().resolve("log4j2-test.xml");
try (InputStream is = Files.newInputStream(path)) {
ConfigurationSource configurationSource = new ConfigurationSource(is, path.toFile());
LoggerContext context = new Log... |
@Deprecated
public static StreamException buildStreamException(RestLiResponseException restLiResponseException, StreamDataCodec codec)
{
RestLiResponse restLiResponse = restLiResponseException.getRestLiResponse();
StreamResponseBuilder responseBuilder = new StreamResponseBuilder()
.setHeaders(restLi... | @Test
public void testContentTypeHeaderForStreamException()
{
RestLiResponseException restLiResponseException = new RestLiResponseException(
new RuntimeException("this is a test"),
new RestLiResponse.Builder()
.status(HttpStatus.S_500_INTERNAL_SERVER_ERROR)
.entity(new Te... |
public static <T> RemoteIterator<T> remoteIteratorFromArray(T[] array) {
return new WrappedJavaIterator<>(Arrays.stream(array).iterator());
} | @Test
public void testIterateArray() throws Throwable {
verifyInvoked(remoteIteratorFromArray(DATA), DATA.length,
(s) -> LOG.info(s));
} |
public void patchCommentById(
final Long memberId,
final Long commentId,
final CommentPatchRequest request
) {
Comment comment = findComment(commentId);
comment.update(request.comment(), memberId);
} | @Test
void 댓글을_수정한다() {
// given
Comment saved = commentRepository.save(댓글_생성());
String text = "edit";
CommentPatchRequest req = new CommentPatchRequest(text);
// when
commentService.patchCommentById(1L, 1L, req);
// then
assertThat(saved.getContent... |
@Override
public Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain,
final SelectorData selector, final RuleData rule) {
ICache cache = CacheUtils.getCache();
if (Objects.nonNull(cache)) {
return cache.getData(CacheUtils.d... | @Test
public void pluginTest() {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("localhost").build());
final CachePlugin cachePlugin = new CachePlugin();
final ShenyuPluginChain shenyuPluginChain = mock(ShenyuPluginChain.class);
final RuleData ruleD... |
@Override
public boolean isTrusted(Address address) {
if (address == null) {
return false;
}
if (trustedInterfaces.isEmpty()) {
return true;
}
String host = address.getHost();
if (matchAnyInterface(host, trustedInterfaces)) {
retur... | @Test
public void givenNoInterfaceIsConfigured_whenMessageArrives_thenTrust() throws UnknownHostException {
AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(emptySet(), logger);
Address address = createAddress("127.0.0.1");
assertTrue(joinMessageTrustChecker.isTrusted(addr... |
@SuppressWarnings("unchecked")
public <IN, OUT> AvroDatumConverter<IN, OUT> create(Class<IN> inputClass) {
boolean isMapOnly = ((JobConf) getConf()).getNumReduceTasks() == 0;
if (AvroKey.class.isAssignableFrom(inputClass)) {
Schema schema;
if (isMapOnly) {
schema = AvroJob.getMapOutputKeyS... | @Test
void convertByteWritable() {
AvroDatumConverter<ByteWritable, GenericFixed> converter = mFactory.create(ByteWritable.class);
assertEquals(42, converter.convert(new ByteWritable((byte) 42)).bytes()[0]);
} |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testListOffsetNoUpdateMissingEpoch() {
buildFetcher();
// Set up metadata with no leader epoch
subscriptions.assignFromUser(singleton(tp0));
MetadataResponse metadataWithNoLeaderEpochs = RequestTestUtils.metadataUpdateWithIds(
"kafka-cluster", 1, Co... |
void put(String key, SelType obj) {
symtab.put(key, obj);
} | @Test
public void put() {
state.put("foo", SelString.of("bar"));
SelType res = state.get("foo");
assertEquals("STRING: bar", res.type() + ": " + res);
} |
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < 1) {
return;
}
// read one byte to guess protocol
final int magic = in.getByte(in.readerIndex());
ChannelPipeline p = ctx.pipelin... | @Test
void testDecodeTelnet() throws Exception {
ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'A'});
ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class);
ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class);
Mockito.when(context.pipeline()).thenRet... |
@Override
public @Nullable V put(K key, V value) {
return put(key, value, expiry(), /* onlyIfAbsent */ false);
} | @Test(dataProvider = "caches")
@CacheSpec(compute = Compute.SYNC, population = Population.EMPTY,
initialCapacity = InitialCapacity.FULL, expireAfterWrite = Expire.ONE_MINUTE)
public void put_expireTolerance_expireAfterWrite(
BoundedLocalCache<Int, Int> cache, CacheContext context) {
boolean mayCheck... |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test
public void saveNewClient_noOfflineAccess() {
ClientDetailsEntity client = new ClientDetailsEntity();
client = service.saveNewClient(client);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(client.getScope().contains(SystemScopeService.OFFLINE_A... |
@Override
public RouteContext createRouteContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database,
final BroadcastRule rule, final ConfigurationProperties props, final ConnectionContext connectionContext) {
... | @Test
void assertCreateBroadcastRouteContextWithMultiDataSource() throws SQLException {
BroadcastRuleConfiguration currentConfig = mock(BroadcastRuleConfiguration.class);
when(currentConfig.getTables()).thenReturn(Collections.singleton("t_order"));
BroadcastRule broadcastRule = new Broadcast... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetArraySchemaFromListClassVariadic() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("listType", List.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getVarArgsSchemaFromType(type);
assertThat(schema, instanceOf(Arr... |
public static <T extends Comparable<? super T>> T max(T[] numberArray) {
return max(numberArray, null);
} | @Test
public void maxTest() {
int max = ArrayUtil.max(1, 2, 13, 4, 5);
assertEquals(13, max);
long maxLong = ArrayUtil.max(1L, 2L, 13L, 4L, 5L);
assertEquals(13, maxLong);
double maxDouble = ArrayUtil.max(1D, 2.4D, 13.0D, 4.55D, 5D);
assertEquals(13.0, maxDouble, 0);
BigDecimal one = new BigDecimal("1... |
public static boolean isStorageSpaceError(final Throwable error)
{
Throwable cause = error;
while (null != cause)
{
if (cause instanceof IOException)
{
final String msg = cause.getMessage();
if ("No space left on device".equals(msg) || ... | @Test
void isStorageSpaceErrorReturnsFalseIfNotIOException()
{
assertFalse(isStorageSpaceError(new IllegalArgumentException("No space left on device")));
} |
@Description("Returns TRUE if this Geometry has no anomalous geometric points, such as self intersection or self tangency")
@ScalarFunction("ST_IsSimple")
@SqlType(BOOLEAN)
public static boolean stIsSimple(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
try {
return deserialize(input).is... | @Test
public void testSTIsSimple()
{
assertSimpleGeometry("POINT (1.5 2.5)");
assertSimpleGeometry("MULTIPOINT (1 2, 2 4, 3 6, 4 8)");
assertNotSimpleGeometry("MULTIPOINT (1 2, 2 4, 3 6, 1 2)");
assertSimpleGeometry("LINESTRING (8 4, 5 7)");
assertSimpleGeometry("LINESTRI... |
@Override
public InetSocketAddress getLocalAddress() {
return client.getLocalAddress();
} | @Test
void test_multi_share_connect() {
// here a three shared connection is established between a consumer process and a provider process.
final int shareConnectionNum = 3;
init(0, shareConnectionNum);
List<ReferenceCountExchangeClient> helloReferenceClientList = getReferenceClien... |
@Override
public void removeRule(final RuleData ruleData) {
Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData)));
} | @Test
public void removeSelectorTest() {
modifyResponsePluginDataHandler.removeRule(ruleData);
ModifyResponseRuleHandle modifyResponseRuleHandle = ModifyResponsePluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(ruleData));
assertNull(modifyResponseRuleHandle);
... |
public void add(TProtocol p) {
events.addLast(p);
} | @Test
public void testSet() throws TException {
final Set<String> names = new HashSet<String>();
names.add("John");
names.add("Jack");
final TestNameSet o = new TestNameSet("name", names);
validate(o);
} |
@Override
protected String ruleHandler() {
return "";
} | @Test
public void testRuleHandler() {
assertEquals(StringUtils.EMPTY, shenyuClientRegisterGrpcService.ruleHandler());
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCombinationActivity(CombinationActivityUpdateReqVO updateReqVO) {
// 校验存在
CombinationActivityDO activityDO = validateCombinationActivityExists(updateReqVO.getId());
// 校验状态
if (ObjectUtil.equal(activityDO.g... | @Test
public void testUpdateCombinationActivity_notExists() {
// 准备参数
CombinationActivityUpdateReqVO reqVO = randomPojo(CombinationActivityUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> combinationActivityService.updateCombinationActivity(reqVO), COMBINATION_ACTIVITY_... |
@Override
public Set<IndexRange> indexRangesForStreamsInTimeRange(Set<String> streamIds, TimeRange timeRange) {
return indexLookup.indexRangesForStreamsInTimeRange(streamIds, timeRange);
} | @Test
public void testExplain() {
when(indexLookup.indexRangesForStreamsInTimeRange(anySet(), any())).thenAnswer(a -> {
if (a.getArgument(1, TimeRange.class).getFrom().getYear() < 2024) {
return Set.of(
MongoIndexRange.create("graylog_0", nowUTC(), nowUTC(... |
@Udf(description = "Returns the cosine of an INT value")
public Double cos(
@UdfParameter(
value = "value",
description = "The value in radians to get the cosine of."
) final Integer value
) {
return cos(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleNegative() {
assertThat(udf.cos(-0.43), closeTo(0.9089657496748851, 0.000000000000001));
assertThat(udf.cos(-Math.PI), closeTo(-1.0, 0.000000000000001));
assertThat(udf.cos(-2 * Math.PI), closeTo(1.0, 0.000000000000001));
assertThat(udf.cos(-6), closeTo(0.960170286650366,... |
static <T extends Type> String encodeDynamicArray(DynamicArray<T> value) {
int size = value.getValue().size();
String encodedLength = encode(new Uint(BigInteger.valueOf(size)));
String valuesOffsets = encodeArrayValuesOffsets(value);
String encodedValues = encodeArrayValues(value);
... | @Test
public void testDynamicArrayOfDynamicArraysOfStaticStructs() {
DynamicArray<DynamicArray<Bar>> array =
new DynamicArray(
DynamicArray.class,
Arrays.asList(
new DynamicArray(
... |
public List<PlainAccessConfig> getPlainAccessConfigs() {
return plainAccessConfigs;
} | @Test
public void testGetPlainAccessConfigsWhenNull() {
AclConfig aclConfig = new AclConfig();
Assert.assertNull("The plainAccessConfigs should return null", aclConfig.getPlainAccessConfigs());
} |
@Override
public String addResourceReference(String key,
SharedCacheResourceReference ref) {
String interned = intern(key);
synchronized (interned) {
SharedCacheResource resource = cachedResources.get(interned);
if (resource == null) { // it's not mapped
return null;
}
re... | @Test
void testAddResourceRefNonExistentResource() throws Exception {
startEmptyStore();
String key = "key1";
ApplicationId id = createAppId(1, 1L);
// try adding an app id without adding the key first
assertNull(store.addResourceReference(key,
new SharedCacheResourceReference(id, "user"))... |
@Override
public void close() throws IllegalStateException {
try {
session.close();
} catch (UncheckedOrtException e) {
throw new IllegalStateException("Failed to close ONNX session", e);
} catch (IllegalStateException e) {
throw new IllegalStateException(... | @Test
public void testLoggingMessages() throws IOException {
assumeTrue(OnnxRuntime.isRuntimeAvailable());
Logger logger = Logger.getLogger(OnnxEvaluator.class.getName());
CustomLogHandler logHandler = new CustomLogHandler();
logger.addHandler(logHandler);
var runtime = new O... |
public static KiePMMLRegressionTable getRegressionTable(final RegressionTable regressionTable,
final RegressionCompilationDTO compilationDTO) {
logger.trace("getRegressionTable {}", regressionTable);
final Map<String, SerializableFunction<Doub... | @Test
void getRegressionTable() {
regressionTable = getRegressionTable(3.5, "professional");
RegressionModel regressionModel = new RegressionModel();
regressionModel.setNormalizationMethod(RegressionModel.NormalizationMethod.CAUCHIT);
regressionModel.addRegressionTables(regressionTab... |
@Override
public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) {
if (ER_PARSE_ERROR == ex.getErrorCode()) {
return Optional.empty();
}
if (sqlStatement instanceof SelectStatement) {
return createQueryResult((SelectS... | @Test
void assertGetSaneQueryResultForShowOtherStatement() {
Optional<ExecuteResult> actual = new MySQLDialectSaneQueryResultEngine().getSaneQueryResult(new MySQLShowOtherStatement(), new SQLException(""));
assertTrue(actual.isPresent());
assertThat(actual.get(), instanceOf(RawMemoryQueryRes... |
@Override
public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
WebhookDelivery.Builder builder = new WebhookDelivery.Builder();
long startedAt = system.now();
builder
.setAt(startedAt)
.setPayload(payload)
.setWebhook(webhook);
try {
HttpUrl url = HttpUrl.par... | @Test
public void post_payload_to_http_server() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40),
"my-webhook", server.url("/ping").toString(), null);
server.enqueue(new MockResponse().setBody("pong").setResponseCode(201));
WebhookDel... |
public static String hashSecretContent(Secret secret) {
if (secret == null) {
throw new RuntimeException("Secret not found");
}
if (secret.getData() == null || secret.getData().isEmpty()) {
throw new RuntimeException("Empty secret");
}
St... | @Test
public void testHashSecretContentWithNoData() {
Secret secret = new SecretBuilder().build();
RuntimeException ex = assertThrows(RuntimeException.class, () -> ReconcilerUtils.hashSecretContent(secret));
assertThat(ex.getMessage(), is("Empty secret"));
} |
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) getBeanFactory().getBean(name);
} | @Test
public void getBeanWithTypeReferenceTest() {
Map<String, Object> mapBean = SpringUtil.getBean(new TypeReference<Map<String, Object>>() {});
assertNotNull(mapBean);
assertEquals("value1", mapBean.get("key1"));
assertEquals("value2", mapBean.get("key2"));
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefin... | @Test
public void testConvertBlob() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("blob")
.dataType("blob")
.length(2147483647L)
... |
@Override
public void onDiscoveredSplits(Collection<IcebergSourceSplit> splits) {
addSplits(splits);
} | @Test
public void testMultipleFilesInASplit() throws Exception {
SplitAssigner assigner = splitAssigner();
assigner.onDiscoveredSplits(
SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 4, 2));
assertGetNext(assigner, GetSplitResult.Status.AVAILABLE);
assertSnapshot(assigner,... |
public static StreamingService getService(final int serviceId) throws ExtractionException {
return ServiceList.all().stream()
.filter(service -> service.getServiceId() == serviceId)
.findFirst()
.orElseThrow(() -> new ExtractionException(
"... | @Test
public void getServiceWithId() throws Exception {
assertEquals(NewPipe.getService(YouTube.getServiceId()), YouTube);
} |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String targetObjectId = reader.readLine();
String methodName = reader.readLine();
List<Object> arguments = getArguments(reader);
ReturnObject returnObject = invokeMethod(metho... | @Test
public void testReflectionException() {
String inputCommand = "z:java.lang.String\nvalueOf2\ni123\ne\n";
try {
command.execute("c", new BufferedReader(new StringReader(inputCommand)), writer);
assertTrue(sWriter.toString().startsWith("!xspy4j.Py4JException: "));
} catch (Exception e) {
e.printStac... |
public IndexEntry lookupIndex(final long logIndex) {
mapInIfNecessary();
this.readLock.lock();
try {
final ByteBuffer byteBuffer = sliceByteBuffer();
final int slot = (int) (logIndex - this.header.getFirstLogIndex());
if (slot < 0) {
return Ind... | @Test
public void testLooUp() {
testAppendIndex();
final IndexEntry entry0 = this.offsetIndex.lookupIndex(appendEntry0.getOffset());
assertEquals(appendEntry0.getOffset(), entry0.getOffset());
final IndexEntry entry1 = this.offsetIndex.lookupIndex(appendEntry1.getOffset());
... |
@POST
@ApiOperation(value = "Retrieve the field list of a given set of streams")
@NoAuditEvent("This is not changing any data")
public Set<MappedFieldTypeDTO> byStreams(@ApiParam(name = "JSON body", required = true)
@Valid @NotNull FieldTypesForStreamsRequest req... | @Test
public void byStreamReturnsTypesFromMappedFieldTypesService() {
final SearchUser searchUser = TestSearchUser.builder()
.allowStream("2323")
.allowStream("4242")
.build();
final MappedFieldTypesService fieldTypesService = (streamIds, timeRange) ... |
public static WindowBytesStoreSupplier persistentWindowStore(final String name,
final Duration retentionPeriod,
final Duration windowSize,
... | @Test
public void shouldThrowIfIPersistentWindowStoreIfWindowSizeIsNegative() {
final Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentWindowStore("anyName", ofMillis(0L), ofMillis(-1L), false));
assertEquals("windowSize cannot be negative", e.getMessage());
} |
static Schema sortKeySchema(Schema schema, SortOrder sortOrder) {
List<SortField> sortFields = sortOrder.fields();
int size = sortFields.size();
List<Types.NestedField> transformedFields = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < size; ++i) {
int sourceFieldId = sortFields.get(i).... | @Test
public void testResultSchema() {
Schema schema =
new Schema(
Types.NestedField.required(1, "id", Types.StringType.get()),
Types.NestedField.required(2, "ratio", Types.DoubleType.get()),
Types.NestedField.optional(
3,
"user",
... |
@Override
public void updateDependencyTree(int childStreamId, int parentStreamId, short weight, boolean exclusive) {
// It is assumed there are all validated at a higher level. For example in the Http2FrameReader.
assert weight >= MIN_WEIGHT && weight <= MAX_WEIGHT : "Invalid weight";
assert... | @Test
public void invalidWeightTooBigThrows() {
assertThrows(AssertionError.class, new Executable() {
@Override
public void execute() throws Throwable {
controller.updateDependencyTree(STREAM_A, STREAM_D, (short) (MAX_WEIGHT + 1), true);
}
});
... |
@Override
public boolean validate(String metricKey) {
Metric metric = metricByKey.get(metricKey);
if (metric == null) {
if (!alreadyLoggedMetricKeys.contains(metricKey)) {
LOG.debug("The metric '{}' is ignored and should not be send in the batch report", metricKey);
alreadyLoggedMetricKe... | @Test
public void not_generate_new_log_when_validating_twice_the_same_metric() {
when(scannerMetrics.getMetrics()).thenReturn(Collections.emptySet());
ReportMetricValidator validator = new ReportMetricValidatorImpl(scannerMetrics);
assertThat(validator.validate(METRIC_KEY)).isFalse();
assertThat(logT... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testSpdyWindowUpdateFrame() throws Exception {
short type = 9;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE +... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
final boolean satisfied = rule1.isSatisfied(index, tradingRecord) || rule2.isSatisfied(index, tradingRecord);
traceIsSatisfied(index, satisfied);
return satisfied;
} | @Test
public void isSatisfied() {
assertTrue(satisfiedRule.or(BooleanRule.FALSE).isSatisfied(0));
assertTrue(BooleanRule.FALSE.or(satisfiedRule).isSatisfied(0));
assertFalse(unsatisfiedRule.or(BooleanRule.FALSE).isSatisfied(0));
assertFalse(BooleanRule.FALSE.or(unsatisfiedRule).isSat... |
@Override
@Nonnull
public List<Sdk> selectSdks(Configuration configuration, UsesSdk usesSdk) {
Config config = configuration.get(Config.class);
Set<Sdk> sdks = new TreeSet<>(configuredSdks(config, usesSdk));
if (enabledSdks != null) {
sdks = Sets.intersection(sdks, enabledSdks);
}
return L... | @Test
public void withTargetSdkGreaterThanMaxSdk_shouldThrowError() throws Exception {
when(usesSdk.getMaxSdkVersion()).thenReturn(21);
when(usesSdk.getTargetSdkVersion()).thenReturn(22);
try {
sdkPicker.selectSdks(buildConfig(new Config.Builder()), usesSdk);
fail();
} catch (IllegalArgume... |
@Nullable
public static EpoxyModel<?> getModelFromPayload(List<Object> payloads, long modelId) {
if (payloads.isEmpty()) {
return null;
}
for (Object payload : payloads) {
DiffPayload diffPayload = (DiffPayload) payload;
if (diffPayload.singleModel != null) {
if (diffPayload.si... | @Test
public void getSingleModelFromPayload() {
TestModel model = new TestModel();
List<Object> payloads = payloadsWithChangedModels(model);
EpoxyModel<?> modelFromPayload = getModelFromPayload(payloads, model.id());
assertEquals(model, modelFromPayload);
} |
public String getServiceAccount() {
return flinkConfig.get(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT);
} | @Test
void testGetServiceAccount() {
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT, "flink");
assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink");
} |
public static ModelReference resolveToModelReference(
String paramName, Optional<String> id, Optional<String> url, Optional<String> path, Set<String> requiredTags, DeployState state) {
if (id.isEmpty()) return createModelReference(Optional.empty(), url, path, state);
else if (state.isHosted(... | @Test
void throws_on_known_model_with_missing_tags() {
var state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true)).build();
var e = assertThrows(IllegalArgumentException.class, () ->
ModelIdResolver.resolveToModelReference(
"par... |
public FEELFnResult<List> invoke(@ParameterName( "list" ) List list, @ParameterName( "position" ) BigDecimal position, @ParameterName( "newItem" ) Object newItem) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
... | @Test
void invokeListPositionNull() {
FunctionTestUtil.assertResultError(insertBeforeFunction.invoke(null, null, new Object()),
InvalidParametersEvent.class);
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetUncleByBlockNumberAndIndex() throws Exception {
web3j.ethGetUncleByBlockNumberAndIndex(
DefaultBlockParameter.valueOf(Numeric.toBigInt("0x29c")), BigInteger.ZERO)
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"metho... |
public FrameworkErrorCode getErrcode() {
return errcode;
} | @Test
public void testGetErrcode() {
Throwable throwable = Assertions.assertThrows(FrameworkException.class, () -> {
message.print4();
});
assertThat(throwable).hasMessage(FrameworkErrorCode.UnknownAppError.getErrMessage());
assertThat(((FrameworkException)throwable).getE... |
@Override
public BrokerResponse executeQuery(String brokerAddress, String query)
throws PinotClientException {
try {
return executeQueryAsync(brokerAddress, query).get(_brokerReadTimeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new PinotClientException(e);
}
} | @Test
public void invalidJsonResponseTriggersPinotClientException() {
_responseJson = "{";
JsonAsyncHttpPinotClientTransportFactory factory = new JsonAsyncHttpPinotClientTransportFactory();
JsonAsyncHttpPinotClientTransport transport = (JsonAsyncHttpPinotClientTransport) factory.buildTransport();
try ... |
@Override
public int ncol() {
return n;
} | @Test
public void testNcols() {
System.out.println("ncol");
assertEquals(3, sparse.ncol());
} |
@Override
public void resetToCheckpoint(long checkpointId, @Nullable byte[] checkpointData)
throws Exception {
// the first time this method is called is early during execution graph construction,
// before the main thread executor is set. hence this conditional check.
if (mainTh... | @Test
void restoreOpensGatewayEvents() throws Exception {
final EventReceivingTasks tasks = EventReceivingTasks.createForRunningTasks();
final OperatorCoordinatorHolder holder =
createCoordinatorHolder(tasks, TestingOperatorCoordinator::new);
triggerAndCompleteCheckpoint(hol... |
@Override
public void deprecated(String message, Object... params) {
logger.warn(message, params);
} | @Test
public void testDeprecationLoggerWriteOut_root() throws IOException {
final DefaultDeprecationLogger deprecationLogger = new DefaultDeprecationLogger(LogManager.getLogger("test"));
// Exercise
deprecationLogger.deprecated("Simple deprecation message");
String logs = LogTestUt... |
public Object evaluate(final ProcessingDTO processingDTO,
final List<Object> paramValues) {
final List<KiePMMLNameValue> kiePMMLNameValues = new ArrayList<>();
if (parameterFields != null) {
if (paramValues == null || paramValues.size() < parameterFields.size()) {
... | @Test
void evaluateFromApply() {
// <DefineFunction name="CUSTOM_FUNCTION" optype="continuous" dataType="double">
// <ParameterField name="PARAM_1"/>
// <ParameterField field="PARAM_2"/>
// <Apply function="/">
// <FieldRef>PARAM_1</FieldRef>
// ... |
public Order status(StatusEnum status) {
this.status = status;
return this;
} | @Test
public void statusTest() {
// TODO: test status
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.