focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T> Window<T> into(WindowFn<? super T, ?> fn) {
try {
fn.windowCoder().verifyDeterministic();
} catch (NonDeterministicException e) {
throw new IllegalArgumentException("Window coders must be deterministic.", e);
}
return Window.<T>configure().withWindowFn(fn);
} | @Test
@Category(ValidatesRunner.class)
public void testTimestampCombinerDefault() {
pipeline.enableAbandonedNodeEnforcement(true);
pipeline
.apply(
Create.timestamped(
TimestampedValue.of(KV.of(0, "hello"), new Instant(0)),
TimestampedValue.of(KV.of(0, "g... |
@Override
public boolean revokeToken(String clientId, String accessToken) {
// 先查询,保证 clientId 时匹配的
OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken);
if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) {
retur... | @Test
public void testRevokeToken_clientIdError() {
// 准备参数
String clientId = randomString();
String accessToken = randomString();
// mock 方法
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class);
when(oauth2TokenService.getAccessToken(eq(accessTok... |
@Override
public Output run(RunContext runContext) throws Exception {
String taskSpec = runContext.render(this.spec);
try {
Task task = OBJECT_MAPPER.readValue(taskSpec, Task.class);
if (task instanceof TemplatedTask) {
throw new IllegalArgumentException("The ... | @Test
void templatedType() throws Exception {
RunContext runContext = runContextFactory.of(Map.of("type", "io.kestra.plugin.core.debug.Return"));
TemplatedTask templatedTask = TemplatedTask.builder()
.id("template")
.type(TemplatedTask.class.getName())
.spec("""
... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_and_aggregate_duplicated_lines_when_only_some_lines_have_changesets() {
// 2 new duplicated lines in each, since only the first 2 lines are new
addDuplicatedBlock(FILE_1_REF, 2);
addDuplicatedBlock(FILE_3_REF, 10);
addDuplicatedBlock(FILE_4_REF, 12);
setFirstTwoLinesAsNew... |
@Override
public String generateSqlType(Dialect dialect) {
switch (dialect.getId()) {
case MsSql.ID:
return format("NVARCHAR (%d)", columnSize);
case Oracle.ID:
return format("VARCHAR2 (%d%s)", columnSize, ignoreOracleUnit ? "" : " CHAR");
default:
return format("VARCHAR ... | @Test
public void generate_sql_type() {
VarcharColumnDef def = new VarcharColumnDef.Builder()
.setColumnName("issues")
.setLimit(10)
.setIsNullable(true)
.build();
assertThat(def.generateSqlType(new H2())).isEqualTo("VARCHAR (10)");
assertThat(def.generateSqlType(new PostgreSql())... |
public ChmDirectoryListingSet getChmDirList() {
return chmDirList;
} | @Test
public void testGetChmDirList() {
assertNotNull(chmExtractor.getChmDirList());
} |
@JsonProperty
public SchemaTableName getSchemaTableName()
{
return schemaTableName;
} | @Test
public void testRoundTrip()
{
MongoTableHandle expected = new MongoTableHandle(new SchemaTableName("schema", "table"));
String json = codec.toJson(expected);
MongoTableHandle actual = codec.fromJson(json);
assertEquals(actual.getSchemaTableName(), expected.getSchemaTableN... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testPartitionedIsNull() throws Exception {
createPartitionedTable(spark, tableName, "truncate(4, data)");
SparkScanBuilder builder = scanBuilder();
TruncateFunction.TruncateString function = new TruncateFunction.TruncateString();
UserDefinedScalarFunc udf = toUDF(function, ... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testHsOverallNoPb_NoPb()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Floor 5 time: <col=ff0000>3:56</col>. Personal best: 3:05<br>Overall time: <col=ff0000>9:14</col>. Personal best: 7:49<br>", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
verify(configManag... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STAT... | @Test
public void testComplexNR() throws ScanException {
List<Token> tl = new TokenStream("%d{1234} [%34.-67toto] %n").tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(Token.PERCENT_TOKEN);
witness.add(new Token(Token.SIMPLE_KEYWORD, "d"));
List<String> o... |
public List<String> build() {
checkState(!columnDefs.isEmpty() || !pkColumnDefs.isEmpty(), "at least one column must be specified");
return Stream.concat(of(createTableStatement()), createOracleAutoIncrementStatements())
.toList();
} | @Test
public void build_throws_ISE_if_no_column_has_been_set() {
assertThatThrownBy(() -> underTest.build())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("at least one column must be specified");
} |
@Override
public Map<String, Collection<String>> getSystemDatabaseSchemaMap() {
return SYSTEM_DATABASE_SCHEMA_MAP;
} | @Test
void assertGetSystemDatabases() {
assertTrue(systemDatabase.getSystemDatabaseSchemaMap().containsKey("postgres"));
} |
@Override
public int hashCode() {
return key.hashCode();
} | @Test
public void hashcode_uses_only_key() {
int expected = new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT).hashCode();
assertThat(new MetricImpl(SOME_UUID, SOME_KEY, "some other name", Metric.MetricType.FLOAT).hashCode()).isEqualTo(expected);
assertThat(new MetricImpl(SOME_UUID, ... |
@Override
public int hashCode() {
int result = Objects.hashCode(cpuCores);
result = 31 * result + Objects.hashCode(taskHeapMemory);
result = 31 * result + Objects.hashCode(taskOffHeapMemory);
result = 31 * result + Objects.hashCode(managedMemory);
result = 31 * result + exten... | @Test
void testHashCode() {
ResourceSpec rs1 = ResourceSpec.newBuilder(1.0, 100).build();
ResourceSpec rs2 = ResourceSpec.newBuilder(1.0, 100).build();
assertThat(rs2).hasSameHashCodeAs(rs1);
ResourceSpec rs3 =
ResourceSpec.newBuilder(1.0, 100)
... |
@Override
public SymbolTable getRequestSymbolTable(URI requestUri)
{
// If the URI prefix doesn't match, return null.
if (!requestUri.toString().startsWith(_uriPrefix))
{
return null;
}
String serviceName = LoadBalancerUtil.getServiceNameFromUri(requestUri);
// First check the cache.
... | @Test
public void testGetRemoteRequestSymbolTableFetch404Error()
{
RestResponseBuilder builder = new RestResponseBuilder();
builder.setStatus(404);
Assert.assertNull(_provider.getRequestSymbolTable(URI.create("d2://serviceName")));
// Subsequent fetch should not trigger network fetch and get the t... |
private IcebergUUIDObjectInspector() {
super(TypeInfoFactory.stringTypeInfo);
} | @Test
public void testIcebergUUIDObjectInspector() {
IcebergUUIDObjectInspector oi = IcebergUUIDObjectInspector.get();
Assert.assertEquals(ObjectInspector.Category.PRIMITIVE, oi.getCategory());
Assert.assertEquals(PrimitiveObjectInspector.PrimitiveCategory.STRING, oi.getPrimitiveCategory());
Assert.... |
@Override
public int compareTo(Tag tag) {
int keyResult = this.key.compareTo(tag.key);
if (keyResult != 0) {
return keyResult;
}
return this.value.compareTo(tag.value);
} | @Test
public void compareToTest() {
Tag tag1 = new Tag(KEY, VALUE);
Tag tag2 = new Tag(KEY, VALUE);
Tag tag3 = new Tag(KEY, KEY);
Tag tag4 = new Tag(VALUE, VALUE);
Assert.assertTrue(tag1.compareTo(tag2) == 0);
Assert.assertTrue(tag1.compareTo(tag3) < 0);
Asse... |
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 testIllegalSpdySynStreamFrameStreamId() throws Exception {
short type = 1;
byte flags = 0;
int length = 10;
int streamId = 0; // invalid stream identifier
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte priority = (byte) (RANDOM.nextIn... |
@Override
public void getBytes(int index, byte[] dst) {
getBytes(index, dst, 0, dst.length);
} | @Test
void getDirectByteBufferBoundaryCheck() {
Assertions.assertThrows(
IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocateDirect(0)));
} |
public List<DBObject> getIndexInfo() {
return delegate.listIndexes(DBObject.class).into(new ArrayList<>());
} | @Test
void getIndexInfo() {
final var collection = jacksonCollection("simple", Simple.class);
collection.createIndex(new BasicDBObject("name", 1));
collection.createIndex(new BasicDBObject("_id", 1).append("name", 1));
assertThat(collection.getIndexInfo()).containsExactlyInAnyOrder(... |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definitio... | @Test
void invokeArrayParamNull() {
FunctionTestUtil.assertResultError(allFunction.invoke((Object[]) null), InvalidParametersEvent.class);
} |
@SuppressWarnings("checkstyle:trailingcomment")
public long footprint() {
return
INT_SIZE_IN_BYTES * hashes.length // size of hashes array
+ REFERENCE_COST_IN_BYTES * table.length // size of table array
+ REFERENCE_COST_IN_BYTES // reference to hashes array
... | @Test
public void testFootprintReflectsCapacityIncrease() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
final long originalFootprint = set.footprint();
populateSet(set, 10);
final long footprintAfterCapacityIncrease = set.footprint();
assertTrue(footprintAfterCapacit... |
protected void waitForRunning(long interval) {
if (hasNotified.compareAndSet(true, false)) {
this.onWaitEnd();
return;
}
//entry to wait
waitPoint.reset();
try {
waitPoint.await(interval, TimeUnit.MILLISECONDS);
} catch (InterruptedEx... | @Test
public void testWaitForRunning() {
ServiceThread testServiceThread = startTestServiceThread();
// test waitForRunning
testServiceThread.waitForRunning(1000);
assertEquals(false, testServiceThread.hasNotified.get());
assertEquals(1, testServiceThread.waitPoint.getCount()... |
public static String repeat(char value, int n) {
return new String(new char[n]).replace("\0", String.valueOf(value));
} | @Test
public void testRepeat() {
assertEquals(repeat('0', 0), (""));
assertEquals(repeat('1', 3), ("111"));
} |
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
OptionParser optionParser = new OptionParser();
OptionSet optionSet = optionParser.parse(args.toArray(new String[0]));
List<String> nargs = (List<String>) optionSet.nonOptionArguments();
... | @Test
void basic() throws Exception {
final List<Integer> inputSizes = IntStream.range(0, 20).boxed().collect(Collectors.toList());
for (Integer inputSize : inputSizes) {
File inputFile = generateData(inputSize);
List<String> args = Collections.singletonList(inputFile.getAbsolutePath());
fin... |
public static int validateToken(CharSequence token) {
if (token instanceof AsciiString) {
return validateAsciiStringToken((AsciiString) token);
}
return validateCharSequenceToken(token);
} | @DisabledForJreRange(max = JRE.JAVA_17) // This test is much too slow on older Java versions.
@Test
void headerNameValidationMustRejectAllNamesRejectedByOldAlgorithm() throws Exception {
byte[] array = new byte[4];
final ByteBuffer buffer = ByteBuffer.wrap(array);
final AsciiString ascii... |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void testCompositePattern() {
pl.setPattern("%-56(%d %lo{20}) - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message
String regex = ISO_REGEX + " c.q.l.c.p.ConverterTest -... |
@GetMapping("/search")
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE)
public List<String> searchUsersLikeUsername(@RequestParam String username) {
return userDetailsService.findUserLikeUsername(username);
} | @Test
void testSearchUsersLikeUsername() {
List<String> test = new ArrayList<>(1);
when(userDetailsService.findUserLikeUsername(anyString())).thenReturn(test);
List<String> list = userController.searchUsersLikeUsername("nacos");
assertEquals(test, list);
} |
TreePSet<E> underlying() {
return underlying;
} | @Test
public void testUnderlying() {
assertSame(SINGLETON_SET, new PCollectionsImmutableNavigableSet<>(SINGLETON_SET).underlying());
} |
public final HttpClient cookie(Cookie cookie) {
Objects.requireNonNull(cookie, "cookie");
if (!cookie.value().isEmpty()) {
HttpClient dup = duplicate();
HttpHeaders headers = configuration().headers.copy();
headers.add(HttpHeaderNames.COOKIE, dup.configuration().cookieEncoder.encode(cookie));
dup.config... | @Test
@SuppressWarnings({"CollectionUndefinedEquality", "deprecation"})
void testCookie() {
disposableServer =
createServer()
.host("localhost")
.route(r -> r.get("/201",
(req, res) -> res.addHeader("test",
req.c... |
@Override
public void broadcastRecord(ByteBuffer record) throws IOException {
broadcast(record, Buffer.DataType.DATA_BUFFER);
} | @Test
void testMetricsUpdateForBroadcastOnlyResultPartition() throws Exception {
BufferPool bufferPool = globalPool.createBufferPool(3, 3);
try (HsResultPartition partition = createHsResultPartition(2, bufferPool, true)) {
partition.broadcastRecord(ByteBuffer.allocate(bufferSize));
... |
public HazelcastMemberBuilder setProcessId(ProcessId p) {
if (p == ProcessId.ELASTICSEARCH) {
throw new IllegalArgumentException("Hazelcast must not be enabled on Elasticsearch node");
}
this.processId = p;
return this;
} | @Test
public void fail_if_elasticsearch_process() {
var builder = new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP);
assertThatThrownBy(() -> builder.setProcessId(ProcessId.ELASTICSEARCH))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Hazelcast must not be enabled on Elasticsea... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void twilightForestOptiFineIncompatible() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/mod/twilightforest_optifine_incompatibility.txt")),
CrashReportAnalyzer.Rule.TWILIGHT_FOREST_OP... |
public PluginRuntime addInfo(String name, Object value) {
infoList.add(new Info(name, value));
return this;
} | @Test
public void test() {
PluginRuntime runtime = new PluginRuntime("test");
Assert.assertEquals("test", runtime.getPluginId());
Assert.assertTrue(runtime.getInfoList().isEmpty());
runtime.addInfo("item", "item");
PluginRuntime.Info info = runtime.getInfoList().get(0);
... |
@Override
public int hashCode() {
return label.hashCode();
} | @Test
void requireThatHashCodeIsImplemented() {
assertEquals(new RangePartition("foo=0-9").hashCode(), new RangePartition("foo=0-9").hashCode());
} |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldThrowWhenSubscribedToAPatternWithDifferentResetPolicies() {
builder.stream(Pattern.compile("some-regex"), Consumed.with(AutoOffsetReset.EARLIEST));
builder.stream(Pattern.compile("some-regex"), Consumed.with(AutoOffsetReset.LATEST));
assertThrows(TopologyException.cla... |
public int getLockRetryInterval() {
return lockRetryInterval;
} | @Test
public void testGetLockRetryInterval() {
GlobalLockConfig config = new GlobalLockConfig();
config.setLockRetryInterval(1000);
assertEquals(1000, config.getLockRetryInterval());
} |
@Udf(description = "Returns the correctly rounded positive square root of a DOUBLE value")
public Double sqrt(
@UdfParameter(
value = "value",
description = "The value to get the square root of."
) final Integer value
) {
return sqrt(value == null ? null : value.doubleValue());
... | @Test
public void shouldHandleNegative() {
assertThat(Double.isNaN(udf.sqrt(-6.0)), is(true));
} |
@Override
@Transactional(rollbackFor = Exception.class)
@LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_CREATE_SUB_TYPE, bizNo = "{{#role.id}}",
success = SYSTEM_ROLE_CREATE_SUCCESS)
public Long createRole(RoleSaveReqVO createReqVO, Integer type) {
// 1. 校验角色
validateRo... | @Test
public void testCreateRole() {
// 准备参数
RoleSaveReqVO reqVO = randomPojo(RoleSaveReqVO.class)
.setId(null); // 防止 id 被赋值
// 调用
Long roleId = roleService.createRole(reqVO, null);
// 断言
RoleDO roleDO = roleMapper.selectById(roleId);
assertP... |
protected final void ensureCapacity(final int index, final int length)
{
if (index < 0 || length < 0)
{
throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length);
}
final long resultingPosition = index + (long)length;
final int c... | @Test
void ensureCapacityThrowsIndexOutOfBoundsExceptionIfLengthIsNegative()
{
final ExpandableDirectByteBuffer buffer = new ExpandableDirectByteBuffer(1);
final IndexOutOfBoundsException exception =
assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(8, ... |
public Optional<Column> findValueColumn(final ColumnName columnName) {
return findColumnMatching(withNamespace(VALUE).and(withName(columnName)));
} | @Test
public void shouldNotGetMetaColumnFromValue() {
assertThat(SOME_SCHEMA.findValueColumn(ROWTIME_NAME), is(Optional.empty()));
assertThat(SOME_SCHEMA.findValueColumn(ROWPARTITION_NAME), is(Optional.empty()));
assertThat(SOME_SCHEMA.findValueColumn(ROWOFFSET_NAME), is(Optional.empty()));
} |
public List<String> getAllAclFiles(String path) {
if (!new File(path).exists()) {
log.info("The default acl dir {} is not exist", path);
return new ArrayList<>();
}
List<String> allAclFileFullPath = new ArrayList<>();
File file = new File(path);
File[] fil... | @Test
public void getAllAclFilesTest() {
final List<String> notExistList = plainPermissionManager.getAllAclFiles("aa/bb");
Assertions.assertThat(notExistList).isEmpty();
final List<String> files = plainPermissionManager.getAllAclFiles(confHome.getAbsolutePath());
Assertions.assertTha... |
@Override
protected long getSleepTime() {
int count = getAttemptCount();
if (count >= 30) {
// current logic overflows at 30, so set value to max
return mMaxSleepMs;
} else {
// use randomness to avoid contention between many operations using the same retry policy
int sleepMs =
... | @Test
public void largeRetriesProducePositiveTime() {
int max = 1000;
MockExponentialBackoffRetry backoff =
new MockExponentialBackoffRetry(50, Integer.MAX_VALUE, max);
for (int i = 0; i < max; i++) {
backoff.setRetryCount(i);
long time = backoff.getSleepTime();
assertTrue("Time ... |
@Override
public OutputStream getOutputStream(boolean append) throws AccessDeniedException {
final NSURL resolved;
try {
resolved = this.lock(this.exists());
if(null == resolved) {
return super.getOutputStream(append);
}
}
catch(Loc... | @Test
public void testWriteExistingFile() throws Exception {
final FinderLocal file = new FinderLocal(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
new DefaultLocalTouchFeature().touch(file);
final OutputStream out = file.getOutputStream(false);
... |
protected static boolean isMissingKey( final String string ) {
return string == null || ( string.trim().startsWith( "!" ) && string.trim().endsWith( "!" )
&& !string.trim().equals( "!" ) );
} | @Test
public void isMissingKey() {
Assert.assertTrue( GlobalMessageUtil.isMissingKey( null ) );
Assert.assertFalse( GlobalMessageUtil.isMissingKey( "" ) );
Assert.assertFalse( GlobalMessageUtil.isMissingKey( " " ) );
Assert.assertTrue( GlobalMessageUtil.isMissingKey( "!foo!" ) );
Assert.assertTrue... |
@Override
public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig)
throws Exception {
return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig);
} | @Test
void testMinimizedDefinition() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(Paths.get(resource.toURI()), new Co... |
public static List<AuthMethodConfig> parse(final String methods, final Map<String, String> replacements) {
try {
if (methods == null || methods.isEmpty()) {
return Collections.emptyList();
}
final List<AuthMethodConfig> ret = new ArrayList<AuthMethodConfig>();... | @Test
public void testPEMEncoded() throws Exception {
String pemOrig = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClH5+52mqHLdChbOfzuyue5FSDl2n1mOkpMlF1676NT79AScHVMi1Io"
+ "hWkuSe3W+oPLE+GAwyyr0DyolUmTkrhrMID6LamgmH8IzhOeyaxDOjwbCIUeGM1V9Qht+nTneRMhGa/oL687XioZiE1Ev52D8kMa"
+ "K... |
@GetMapping("/config")
public Result<ConfigInfo> getConfig(ConfigInfo configInfo) {
if (StringUtils.isEmpty(configInfo.getGroup()) || StringUtils.isEmpty(configInfo.getKey())) {
return new Result<>(ResultCodeType.MISS_PARAM.getCode(), ResultCodeType.MISS_PARAM.getMessage());
}
re... | @Test
public void getConfig() {
Result<ConfigInfo> result = configController.getConfig(configInfo);
Assert.assertTrue(result.isSuccess());
Assert.assertNotNull(result.getData());
ConfigInfo info = result.getData();
Assert.assertEquals(info.getKey(), KEY);
Assert.asser... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testChemistry1()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_AMULET_OF_CHEMISTRY_1, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_AMULET_OF_CHEMISTRY... |
static GlobalPhaseSetup maybeMakeSetup(RankProfilesConfig.Rankprofile rp, RankProfilesEvaluator modelEvaluator) {
var model = modelEvaluator.modelForRankProfile(rp.name());
Map<String, RankProfilesConfig.Rankprofile.Normalizer> availableNormalizers = new HashMap<>();
for (var n : rp.normalizer()... | @Test void mediumAdvancedSetup() {
RankProfilesConfig rpCfg = readConfig("medium");
assertEquals(1, rpCfg.rankprofile().size());
RankProfilesEvaluator rpEvaluator = createEvaluator(rpCfg);
var setup = GlobalPhaseSetup.maybeMakeSetup(rpCfg.rankprofile().get(0), rpEvaluator);
asser... |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void literalVariableLiteral() throws ScanException {
Tokenizer tokenizer = new Tokenizer("a${b}c");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.LITERAL, "a");
witness.next = new Node(Node.Type.VARIABLE, new Node(Node.... |
@Override
public CheckResult runCheck() {
try {
// Create an absolute range from the relative range to make sure it doesn't change during the two
// search requests. (count and find messages)
// This is needed because the RelativeRange computes the range from NOW on every... | @Test
public void testRunCheckMoreNegative() throws Exception {
final MessageCountAlertCondition.ThresholdType type = MessageCountAlertCondition.ThresholdType.MORE;
final MessageCountAlertCondition messageCountAlertCondition = getConditionWithParameters(type, threshold);
searchCountShouldR... |
static ImmutableList<PushImageStep> makeListForManifestList(
BuildContext buildContext,
ProgressEventDispatcher.Factory progressEventDispatcherFactory,
RegistryClient registryClient,
ManifestTemplate manifestList,
boolean manifestListAlreadyExists)
throws IOException {
Set<String... | @Test
public void testMakeListForManifestList() throws IOException, RegistryException {
List<PushImageStep> pushImageStepList =
PushImageStep.makeListForManifestList(
buildContext, progressDispatcherFactory, registryClient, manifestList, false);
assertThat(pushImageStepList).hasSize(2);
... |
public static int getMaxMagicOffset() {
return maxMagicOffset;
} | @Test
public void getMaxMagicOffset() throws Exception {
} |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsMissingRequiredSignature() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2);
Callback<Void> taskConfigCb = mock(Callback.class);
herder.putTaskConfigs(CONN1, TASK_CONFIGS, taskConfigCb, null);
ArgumentCaptor<Throwable> erro... |
@Override
public void completeRequest() {
} | @Test
public void completeRequest() {
final InstanceStats stats = new InstanceStats();
stats.completeRequest();
Assert.assertEquals(stats.getActiveRequests(), 0);
} |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void emptyRelativeTemplate() {
String template = "/";
UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8);
assertThat(uriTemplate.expand(Collections.emptyMap())).isEqualToIgnoringCase("/");
} |
public String migrate(String oldJSON, int targetVersion) {
LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON);
Chainr transform = getTransformerFor(targetVersion);
Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion));
... | @Test
void migrateV2ToV3_shouldAddArtifactOriginOnAllFetchTasks() {
ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother();
String oldJSON = documentMother.v2WithFetchTask();
String newJson = documentMother.v3WithFetchTask();
String transformedJSON = migrator.migra... |
public PrimitiveValue minValue()
{
return minValue;
} | @Test
void shouldReturnCorrectMinValueWhenSpecified() throws Exception
{
final String minVal = "10";
final String testXmlString =
"<types>" +
" <type name=\"testTypeInt8MinValue\" primitiveType=\"int8\" minValue=\"" + minVal + "\"/>" +
"</types>";
... |
public static String mkString(Collection<?> collection, String sep) {
return mkString(collection, "", sep, "");
} | @Test
public void testMkString() {
assertEquals("1, 2, 3, 4",
CollectionUtil.mkString(List.of(1, 2, 3, 4), ", "));
} |
public void add(final T node) {
if ( this.firstNode == null ) {
this.firstNode = node;
this.lastNode = node;
} else {
this.lastNode.setNext( node );
node.setPrevious( this.lastNode );
this.lastNode = node;
}
this.size++;
} | @Test
public void testAdd() {
this.list.add( this.node1 );
assertThat(this.node1.getPrevious()).as("Node1 previous should be null").isNull();
assertThat(this.node1.getNext()).as("Node1 next should be null").isNull();
assertThat(this.node1).as("First node should be node1").isSameAs(th... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test
public void testSiblingsOnResourceRequestBodyMultiple() {
Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true));
OpenAPI openAPI = reader.read(SiblingsResourceRequestBodyMultiple.class);
String yaml = "openapi: 3.1.0\n" +
"paths:... |
int run() {
final Map<String, String> configProps = options.getConfigFile()
.map(Ksql::loadProperties)
.orElseGet(Collections::emptyMap);
final Map<String, String> sessionVariables = options.getVariables();
try (KsqlRestClient restClient = buildClient(configProps)) {
try (Cli cli = c... | @Test
public void shouldStripSslConfigFromConfigFileWhenMakingLocalProperties() throws Exception {
// Given:
givenConfigFile(
"ssl.truststore.location=some/path" + System.lineSeparator()
+ "ssl.truststore.password=letmein" + System.lineSeparator()
+ "some.other.setting=value"
... |
@Override
public void onMultiTapEnded() {
mParentListener.listener().onMultiTapEnded();
} | @Test
public void testOnMultiTapEnded() {
mUnderTest.onMultiTapEnded();
final InOrder inOrder = Mockito.inOrder(mMockParentListener, mMockKeyboardDismissAction);
inOrder.verify(mMockParentListener).onMultiTapEnded();
inOrder.verifyNoMoreInteractions();
} |
@Override
public HttpResponse send(HttpRequest httpRequest) throws IOException {
return send(httpRequest, null);
} | @Test
public void send_whenNoUserAgentInRequest_setsCorrectUserAgentHeader() throws IOException {
mockWebServer.setDispatcher(new UserAgentTestDispatcher());
mockWebServer.start();
HttpResponse response =
httpClient.send(
get(mockWebServer.url(UserAgentTestDispatcher.USERAGENT_TEST_PA... |
@Nullable
@VisibleForTesting
static List<String> computeEntrypoint(
RawConfiguration rawConfiguration,
ProjectProperties projectProperties,
JibContainerBuilder jibContainerBuilder)
throws MainClassInferenceException, InvalidAppRootException, IOException,
InvalidContainerizingModeEx... | @Test
public void testComputeEntrypoint_default()
throws MainClassInferenceException, InvalidAppRootException, IOException,
InvalidContainerizingModeException {
assertThat(
PluginConfigurationProcessor.computeEntrypoint(
rawConfiguration, projectProperties, jibContainer... |
public static Set<String> getSegmentNamesForTable(String tableNameWithType, long startTimestamp, long endTimestamp,
boolean excludeOverlapping, URI controllerBaseURI, @Nullable AuthProvider authProvider)
throws Exception {
String rawTableName = TableNameBuilder.extractRawTableName(tableNameWithType);
... | @Test
public void testNonExistentSegments()
throws Exception {
Assert.assertEquals(
SegmentConversionUtils.getSegmentNamesForTable(TEST_TABLE_WITHOUT_TYPE + "_" + TEST_TABLE_TYPE,
FileUploadDownloadClient.getURI(TEST_SCHEME, TEST_HOST, TEST_PORT), null),
ImmutableSet.of(TEST_TABLE_SE... |
@Override
public Mono<DeleteUsernameLinkResponse> deleteUsernameLink(final DeleteUsernameLinkRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountId... | @Test
void deleteUsernameLink() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
assertDoesNotThrow(
() -> authenticatedServiceStub().deleteUsernameLin... |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);
assert shenyuContext != null;
ContextMappingRuleHandle ruleHan... | @Test
public void executeTest() {
shenyuContext.setPath("/http/context/order/findById");
ContextMappingRuleHandle contextMappingRuleHandle = new ContextMappingRuleHandle();
contextMappingRuleHandle.setContextPath("/http/context");
when(ruleData.getId()).thenReturn("1");
CACHE... |
@Override
public List<MultipartUpload> find(final Path file) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Finding multipart uploads for %s", file));
}
final List<MultipartUpload> uploads = new ArrayList<>();
// This operation lists in-p... | @Test
public void testFind() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path directory = new S3DirectoryFeature(ses... |
@Override
public Optional<AuthProperty> inferAuth(String registry) throws InferredAuthException {
Server server = getServerFromMavenSettings(registry);
if (server == null) {
return Optional.empty();
}
SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
Setting... | @Test
public void testInferredAuth_successUnencrypted() throws InferredAuthException {
Optional<AuthProperty> auth = mavenSettingsServerCredentials.inferAuth("simpleServer");
Assert.assertTrue(auth.isPresent());
Assert.assertEquals("simpleUser", auth.get().getUsername());
Assert.assertEquals("password... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseStringAndJson() {
TypeInfo typeInfo = TypeInfoFactory.STRING;
Type result = EntityConvertUtils.convertType(typeInfo);
Type expectedType = ScalarType.createDefaultCatalogString();
assertEquals(expectedType, result);
} |
@Override
public String named() {
return PluginEnum.CACHE.getName();
} | @Test
public void namedTest() {
final CachePlugin cachePlugin = new CachePlugin();
Assertions.assertEquals(cachePlugin.named(), PluginEnum.CACHE.getName());
} |
public void setupScanRangeLocations() throws Exception {
List<RemoteFileDesc> files = fileTable.getFileDescs();
for (RemoteFileDesc file : files) {
addScanRangeLocations(file);
}
} | @Test
public void testSetupScanRangeLocations() throws Exception {
class ExtFileTable extends FileTable {
public ExtFileTable(Map<String, String> properties)
throws DdlException {
super(0, "XX", new ArrayList<>(), properties);
}
@Overr... |
public <T> CompletableFuture<PushNotificationExperimentSample<T>> recordFinalState(final UUID accountIdentifier,
final byte deviceId,
final String experimentName,
final T finalState) {
CompletableFuture<String> finalStateJsonFuture;
// Process the final state JSON on the calling thread, but ... | @Test
void recordFinalState() throws JsonProcessingException {
final String experimentName = "test-experiment";
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
final boolean inExperimentGroup = ThreadLocalRan... |
public ActorSystem getActorSystem() {
return actorSystem;
} | @Test
void testRpcServiceShutDownWithRpcEndpoints() throws Exception {
final PekkoRpcService pekkoRpcService = startRpcService();
try {
final int numberActors = 5;
final RpcServiceShutdownTestHelper rpcServiceShutdownTestHelper =
startStopNCountingAsynch... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() != 6) {
onInvalidDataReceived(device, data);
return;
}
final int featuresValue = data.getIntValue(Data.FORMAT_UINT24_LE, 0);
final int typeAndSam... | @Test
public void onInvalidDataReceived_wrongDefaultCrc() {
final DataReceivedCallback callback = new CGMFeatureDataCallback() {
@Override
public void onContinuousGlucoseMonitorFeaturesReceived(@NonNull final BluetoothDevice device, @NonNull final CGMFeatures features,
final int type, final ... |
@JsonCreator
public static WindowInfo of(
@JsonProperty(value = "type", required = true) final WindowType type,
@JsonProperty(value = "size") final Optional<Duration> size,
@JsonProperty(value = "emitStrategy") final Optional<OutputRefinement> emitStrategy) {
return new WindowInfo(type, size, em... | @Test(expected = IllegalArgumentException.class)
public void shouldThrowIfSizeZero() {
WindowInfo.of(TUMBLING, Optional.of(Duration.ZERO), Optional.empty());
} |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldFailDropStreamWhenAnInsertQueryIsReadingTheStream() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create stream bar as select * from test1;"
+ "create stream foo as select * from t... |
@Override
public void addPath(String word, int outputSymbol) {
MutableState state = getStartState();
if (state == null) {
throw new IllegalStateException("Start state cannot be null");
}
List<MutableArc> arcs = state.getArcs();
boolean isFound = false;
for (MutableArc arc : arcs) {
... | @Test
public void testRegexMatcherSuffix2() {
MutableFST fst = new MutableFSTImpl();
fst.addPath("hello-world", 12);
fst.addPath("hello-world123", 21);
fst.addPath("still", 123);
RoaringBitmapWriter<MutableRoaringBitmap> writer = RoaringBitmapWriter.bufferWriter().get();
RealTimeRegexpMatche... |
public boolean equals(byte[] that)
{
return Arrays.equals(data, that);
} | @Test
public void testEquals()
{
ZData data = new ZData("test".getBytes(ZMQ.CHARSET));
ZData other = new ZData("test".getBytes(ZMQ.CHARSET));
assertThat(data.equals(other), is(true));
} |
@Override
public Set<Path> getPaths(ElementId src, ElementId dst) {
checkPermission(TOPOLOGY_READ);
return getPaths(src, dst, (LinkWeigher) null);
} | @Test
public void infraToEdge() {
DeviceId src = did("src");
HostId dst = hid("12:34:56:78:90:ab/1");
fakeTopoMgr.paths.add(createPath("src", "middle", "edge"));
fakeHostMgr.hosts.put(dst, host("12:34:56:78:90:ab/1", "edge"));
Set<Path> paths = service.getPaths(src, dst);
... |
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
} | @Test
public void testIsEmpty() {
assertThat(StringUtils.isEmpty(null)).isTrue();
assertThat(StringUtils.isEmpty("abc")).isFalse();
assertThat(StringUtils.isEmpty("")).isTrue();
assertThat(StringUtils.isEmpty(" ")).isFalse();
} |
public synchronized void invalidateCachedControllerLeader() {
long now = getCurrentTimeMs();
long millisSinceLastInvalidate = now - _lastCacheInvalidationTimeMs;
if (millisSinceLastInvalidate < MIN_INVALIDATE_INTERVAL_MS) {
LOGGER.info("Millis since last controller cache value invalidate {} is less th... | @Test
public void testInvalidateCachedControllerLeader() {
HelixManager helixManager = mock(HelixManager.class);
HelixDataAccessor helixDataAccessor = mock(HelixDataAccessor.class);
final String leaderHost = "host";
final int leaderPort = 12345;
// Lead controller resource disabled.
ConfigAcc... |
public static <T> T convert(Class<T> type, Object value) throws ConvertException {
return convert((Type) type, value);
} | @Test
public void toStrTest2() {
final String result = Convert.convert(String.class, "aaaa");
assertEquals("aaaa", result);
} |
@Override
public void upgrade() {
boolean indexExists = false;
for (Document document : collection.listIndexes()) {
if (MongoDbGrokPatternService.INDEX_NAME.equals(document.getString("name")) && document.getBoolean("unique")) {
indexExists = true;
break;
... | @Test
public void insertingDuplicateGrokPatternsIsNotPossibleAfterUpgrade() {
collection.insertOne(grokPattern("FOO", "[a-z]+"));
migration.upgrade();
assertThatThrownBy(() -> collection.insertOne(grokPattern("FOO", "[a-z]+")))
.isInstanceOf(MongoWriteException.class)
... |
@Bean
public PluginDataHandler keyAuthPluginDataHandler() {
return new KeyAuthPluginDataHandler();
} | @Test
public void testKeyAuthPluginDataHandler() {
applicationContextRunner.run(context -> assertNotNull(context.getBean("keyAuthPluginDataHandler")));
} |
public PickTableLayoutWithoutPredicate pickTableLayoutWithoutPredicate()
{
return new PickTableLayoutWithoutPredicate(metadata);
} | @Test
public void ruleAddedTableLayoutToTableScan()
{
tester().assertThat(pickTableLayout.pickTableLayoutWithoutPredicate())
.on(p -> p.tableScan(
new TableHandle(
connectorId,
new TpchTableHandle("na... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine());
if (reportCoverage != null) {
processCoverage(lineBuilder, reportCoverage);
coverage = null;
}
return Optio... | @Test
public void nothing_to_do_when_no_coverage_info_for_current_line() {
CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(
ScannerReport.LineCoverage.newBuilder()
.setLine(1)
.setConditions(10)
.setHits(true)
.setCoveredConditions(2)
.bui... |
@Override
public final void run() {
long valueCount = collector.getMergingValueCount();
if (valueCount == 0) {
return;
}
runInternal();
assert operationCount > 0 : "No merge operations have been invoked in AbstractContainerMerger";
try {
lon... | @Test
@RequireAssertEnabled
public void testMergerRun() {
TestMergeOperation operation = new TestMergeOperation();
TestContainerMerger merger = new TestContainerMerger(collector, nodeEngine, operation);
merger.run();
assertTrue("Expected the merge operation to be invoked", oper... |
@Override
public PageResult<MemberTagDO> getTagPage(MemberTagPageReqVO pageReqVO) {
return memberTagMapper.selectPage(pageReqVO);
} | @Test
public void testGetTagPage() {
// mock 数据
MemberTagDO dbTag = randomPojo(MemberTagDO.class, o -> { // 等会查询到
o.setName("test");
o.setCreateTime(buildTime(2023, 2, 18));
});
tagMapper.insert(dbTag);
// 测试 name 不匹配
tagMapper.insert(cloneIgno... |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testDocumentNotDividedViaHorizontalRulesWhenIsDisabled() {
MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
.withHorizontalRuleCreateDocument(false)
.build();
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/horizontal-rules.md", config);
List<... |
@VisibleForTesting
String validateMail(String mail) {
if (StrUtil.isEmpty(mail)) {
throw exception(MAIL_SEND_MAIL_NOT_EXISTS);
}
return mail;
} | @Test
public void testValidateMail_notExists() {
// 准备参数
// mock 方法
// 调用,并断言异常
assertServiceException(() -> mailSendService.validateMail(null),
MAIL_SEND_MAIL_NOT_EXISTS);
} |
public List<String> getAllOn(String fieldName) {
List<String> list = get(fieldName);
return (list == null) ? new ArrayList<>() : list;
} | @Test
public void shouldReturnEmptyListWhenNoGetAllErrorsOnExists() {
assertThat(new ConfigErrors().getAllOn("field"), is(Collections.emptyList()));
} |
@Override
public DnsCacheEntry cache(String hostname, DnsRecord[] additionals,
InetAddress address, long originalTtl, EventLoop loop) {
checkNotNull(hostname, "hostname");
checkNotNull(address, "address");
checkNotNull(loop, "loop");
DefaultDnsCacheEntr... | @Test
public void testExpireWithToBigMinTTL() {
EventLoopGroup group = new NioEventLoopGroup(1);
try {
EventLoop loop = group.next();
final DefaultDnsCache cache = new DefaultDnsCache(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
assertNotNull(cache.c... |
@Override
public JmxTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName)
{
return getTableHandle(tableName);
} | @Test
public void testGetTableHandle()
{
JmxTableHandle handle = metadata.getTableHandle(SESSION, RUNTIME_TABLE);
assertEquals(handle.getObjectNames(), ImmutableList.of(RUNTIME_OBJECT));
List<JmxColumnHandle> columns = handle.getColumnHandles();
assertTrue(columns.contains(new J... |
private void executeOnKey(String[] args) {
// executeOnKey <echo-string> <key>
doExecute(true, false, args);
} | @Test
public void executeOnKey() {
for (int i = 0; i < 100; i++) {
consoleApp.handleCommand(String.format("executeOnKey message%d key%d", i, i));
assertTextInSystemOut("message" + i);
}
} |
public static boolean isDirectory(Path path, Configuration conf) {
try {
FileSystem fileSystem = FileSystem.get(path.toUri(), conf);
return fileSystem.getFileStatus(path).isDirectory();
} catch (IOException e) {
LOG.error("Failed checking path {}", path, e);
... | @Test
public void testIsDirectory() {
Path path = new Path("hdfs://127.0.0.1:9000/user/hive/warehouse/db");
ExceptionChecker.expectThrowsWithMsg(StarRocksConnectorException.class,
"Failed checking path",
() -> HiveWriteUtils.isDirectory(path, new Configuration()));
... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseResumeStatement() {
// When:
List<CommandParser.ParsedCommand> commands = parse("resume some_query_id;");
// Then:
assertThat(commands.size(), is(1));
assertThat(commands.get(0).getCommand(), is("resume some_query_id;"));
} |
@Override
public void apply(IntentOperationContext<FlowRuleIntent> context) {
Optional<IntentData> toUninstall = context.toUninstall();
Optional<IntentData> toInstall = context.toInstall();
if (toInstall.isPresent() && toUninstall.isPresent()) {
Intent intentToInstall = toInstal... | @Test
public void testUninstallOnly() {
List<Intent> intentsToInstall = Lists.newArrayList();
List<Intent> intentsToUninstall = createFlowRuleIntents();
IntentData toInstall = null;
IntentData toUninstall = new IntentData(createP2PIntent(),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.