focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@JsonCreator
public static TypeSignature parseTypeSignature(String signature)
{
return parseTypeSignature(signature, new HashSet<>());
} | @Test
public void parseRowSignature()
{
// row signature with named fields
assertRowSignature(
"row(a bigint,b varchar)",
rowSignature(namedParameter("a", false, signature("bigint")), namedParameter("b", false, varchar())));
assertRowSignature(
"row(__a__ bigint,_b@_: _varchar)",
rowSignature(namedParameter("__a__", false, signature("bigint")), namedParameter("_b@_:", false, signature("_varchar"))));
assertRowSignature(
"row(a bigint,b array(bigint),c row(a bigint))",
rowSignature(
namedParameter("a", false, signature("bigint")),
namedParameter("b", false, array(signature("bigint"))),
namedParameter("c", false, rowSignature(namedParameter("a", false, signature("bigint"))))));
assertRowSignature(
"row(a varchar(10),b row(a bigint))",
rowSignature(
namedParameter("a", false, varchar(10)),
namedParameter("b", false, rowSignature(namedParameter("a", false, signature("bigint"))))));
assertRowSignature(
"array(row(col0 bigint,col1 double))",
array(rowSignature(namedParameter("col0", false, signature("bigint")), namedParameter("col1", false, signature("double")))));
assertRowSignature(
"row(col0 array(row(col0 bigint,col1 double)))",
rowSignature(namedParameter("col0", false, array(
rowSignature(namedParameter("col0", false, signature("bigint")), namedParameter("col1", false, signature("double")))))));
assertRowSignature(
"row(a decimal(p1,s1),b decimal(p2,s2))",
ImmutableSet.of("p1", "s1", "p2", "s2"),
rowSignature(namedParameter("a", false, decimal("p1", "s1")), namedParameter("b", false, decimal("p2", "s2"))));
// row with mixed fields
assertRowSignature(
"row(bigint,varchar)",
rowSignature(unnamedParameter(signature("bigint")), unnamedParameter(varchar())));
assertRowSignature(
"row(bigint,array(bigint),row(a bigint))",
rowSignature(
unnamedParameter(signature("bigint")),
unnamedParameter(array(signature("bigint"))),
unnamedParameter(rowSignature(namedParameter("a", false, signature("bigint"))))));
assertRowSignature(
"row(varchar(10),b row(bigint))",
rowSignature(
unnamedParameter(varchar(10)),
namedParameter("b", false, rowSignature(unnamedParameter(signature("bigint"))))));
assertRowSignature(
"array(row(col0 bigint,double))",
array(rowSignature(namedParameter("col0", false, signature("bigint")), unnamedParameter(signature("double")))));
assertRowSignature(
"row(col0 array(row(bigint,double)))",
rowSignature(namedParameter("col0", false, array(
rowSignature(unnamedParameter(signature("bigint")), unnamedParameter(signature("double")))))));
assertRowSignature(
"row(a decimal(p1,s1),decimal(p2,s2))",
ImmutableSet.of("p1", "s1", "p2", "s2"),
rowSignature(namedParameter("a", false, decimal("p1", "s1")), unnamedParameter(decimal("p2", "s2"))));
// named fields of types with spaces
assertRowSignature(
"row(time time with time zone)",
rowSignature(namedParameter("time", false, signature("time with time zone"))));
assertRowSignature(
"row(time timestamp with time zone)",
rowSignature(namedParameter("time", false, signature("timestamp with time zone"))));
assertRowSignature(
"row(interval interval day to second)",
rowSignature(namedParameter("interval", false, signature("interval day to second"))));
assertRowSignature(
"row(interval interval year to month)",
rowSignature(namedParameter("interval", false, signature("interval year to month"))));
assertRowSignature(
"row(double double precision)",
rowSignature(namedParameter("double", false, signature("double precision"))));
// unnamed fields of types with spaces
assertRowSignature(
"row(time with time zone)",
rowSignature(unnamedParameter(signature("time with time zone"))));
assertRowSignature(
"row(timestamp with time zone)",
rowSignature(unnamedParameter(signature("timestamp with time zone"))));
assertRowSignature(
"row(interval day to second)",
rowSignature(unnamedParameter(signature("interval day to second"))));
assertRowSignature(
"row(interval year to month)",
rowSignature(unnamedParameter(signature("interval year to month"))));
assertRowSignature(
"row(double precision)",
rowSignature(unnamedParameter(signature("double precision"))));
assertRowSignature(
"row(array(time with time zone))",
rowSignature(unnamedParameter(array(signature("time with time zone")))));
assertRowSignature(
"row(map(timestamp with time zone,interval day to second))",
rowSignature(unnamedParameter(map(signature("timestamp with time zone"), signature("interval day to second")))));
// quoted field names
assertRowSignature(
"row(\"time with time zone\" time with time zone,\"double\" double)",
rowSignature(
namedParameter("time with time zone", true, signature("time with time zone")),
namedParameter("double", true, signature("double"))));
// allow spaces
assertSignature(
"row( time time with time zone, array( interval day to seconds ) )",
"row",
ImmutableList.of("time time with time zone", "array(interval day to seconds)"),
"row(time time with time zone,array(interval day to seconds))");
// preserve base name case
assertRowSignature(
"RoW(a bigint,b varchar)",
rowSignature(namedParameter("a", false, signature("bigint")), namedParameter("b", false, varchar())));
// field type canonicalization
assertEquals(parseTypeSignature("row(col iNt)"), parseTypeSignature("row(col integer)"));
assertEquals(parseTypeSignature("row(a Int(p1))"), parseTypeSignature("row(a integer(p1))"));
// signature with invalid type
assertRowSignature(
"row(\"time\" with time zone)",
rowSignature(namedParameter("time", true, signature("with time zone"))));
} |
public int format(String... args) throws UsageException {
CommandLineOptions parameters = processArgs(args);
if (parameters.version()) {
errWriter.println(versionString());
return 0;
}
if (parameters.help()) {
throw new UsageException();
}
JavaFormatterOptions options =
JavaFormatterOptions.builder()
.style(parameters.aosp() ? Style.AOSP : Style.GOOGLE)
.formatJavadoc(parameters.formatJavadoc())
.build();
if (parameters.stdin()) {
return formatStdin(parameters, options);
} else {
return formatFiles(parameters, options);
}
} | @Test
public void optimizeImportsDoesNotLeaveEmptyLines() throws Exception {
String[] input = {
"package abc;",
"",
"import java.util.LinkedList;",
"import java.util.List;",
"import java.util.ArrayList;",
"",
"import static java.nio.charset.StandardCharsets.UTF_8;",
"",
"import java.util.EnumSet;",
"",
"class Test ",
"extends ArrayList {",
"}"
};
String[] expected = {
"package abc;", //
"",
"import java.util.ArrayList;",
"",
"class Test extends ArrayList {}",
""
};
// pre-check expectation with local formatter instance
String optimized = new Formatter().formatSourceAndFixImports(joiner.join(input));
assertThat(optimized).isEqualTo(joiner.join(expected));
InputStream in = new ByteArrayInputStream(joiner.join(input).getBytes(UTF_8));
StringWriter out = new StringWriter();
Main main =
new Main(
new PrintWriter(out, true),
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true),
in);
assertThat(main.format("-")).isEqualTo(0);
assertThat(out.toString()).isEqualTo(joiner.join(expected));
} |
public String stringify(boolean value) {
throw new UnsupportedOperationException(
"stringify(boolean) was called on a non-boolean stringifier: " + toString());
} | @Test
public void testTimestampMicrosStringifier() {
for (PrimitiveStringifier stringifier :
asList(TIMESTAMP_MICROS_STRINGIFIER, TIMESTAMP_MICROS_UTC_STRINGIFIER)) {
String timezoneAmendment = (stringifier == TIMESTAMP_MICROS_STRINGIFIER ? "" : "+0000");
assertEquals(withZoneString("1970-01-01T00:00:00.000000", timezoneAmendment), stringifier.stringify(0l));
Calendar cal = Calendar.getInstance(UTC);
cal.clear();
cal.set(2053, Calendar.JULY, 10, 22, 13, 24);
cal.set(Calendar.MILLISECOND, 84);
long micros = cal.getTimeInMillis() * 1000 + 900;
assertEquals(
withZoneString("2053-07-10T22:13:24.084900", timezoneAmendment), stringifier.stringify(micros));
cal.clear();
cal.set(1848, Calendar.MARCH, 15, 9, 23, 59);
cal.set(Calendar.MILLISECOND, 765);
micros = cal.getTimeInMillis() * 1000 - 1;
assertEquals(
withZoneString("1848-03-15T09:23:59.764999", timezoneAmendment), stringifier.stringify(micros));
checkThrowingUnsupportedException(stringifier, Long.TYPE);
}
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void
testParseNewStyleResourceWithPercentagesVcoresNegativeWithMoreSpaces()
throws Exception {
expectNegativePercentageNewStyle();
parseResourceConfigValue("vcores = -75%, memory-mb = 40%");
} |
public static String parseToString(Map<String, String> attributes) {
if (attributes == null || attributes.size() == 0) {
return "";
}
List<String> kvs = new ArrayList<>();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
String value = entry.getValue();
if (Strings.isNullOrEmpty(value)) {
kvs.add(entry.getKey());
} else {
kvs.add(entry.getKey() + ATTR_KEY_VALUE_EQUAL_SIGN + entry.getValue());
}
}
return String.join(ATTR_ARRAY_SEPARATOR_COMMA, kvs);
} | @Test
public void parseToString_ValidAttributes_ReturnsExpectedString() {
Map<String, String> attributes = new HashMap<>();
attributes.put("key1", "value1");
attributes.put("key2", "value2");
attributes.put("key3", "");
String result = AttributeParser.parseToString(attributes);
String expectedString = "key1=value1,key2=value2,key3";
assertEquals(expectedString, result);
} |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDate(shardingValue.getValue())));
return ShardingAutoTableAlgorithmUtils.findMatchedTargetName(availableTargetNames, tableNameSuffix, shardingValue.getDataNodeInfo()).orElse(null);
} | @Test
void assertRangeDoShardingWithGreaterTenTables() {
Properties props = PropertiesBuilder.build(
new Property("datetime-lower", "2020-01-01 00:00:00"), new Property("datetime-upper", "2020-01-01 00:00:30"), new Property("sharding-seconds", "1"));
AutoIntervalShardingAlgorithm shardingAlgorithm = (AutoIntervalShardingAlgorithm) TypedSPILoader.getService(ShardingAlgorithm.class, "AUTO_INTERVAL", props);
List<String> availableTargetNames = new LinkedList<>();
for (int i = 0; i < 32; i++) {
availableTargetNames.add("t_order_" + i);
}
Collection<String> actual = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("2020-01-01 00:00:00", "2020-01-01 00:00:10")));
assertThat(actual.size(), is(11));
} |
public static List<Base64String> wrapList(final List<String> base64Strings) {
return base64Strings.stream().map(Base64String::wrap).collect(Collectors.toList());
} | @Test
public void testWrapList() {
assertEquals(BASE64_WRAPPED_LIST, Base64String.wrapList(BASE64_LIST));
assertEquals(BASE64_4_WRAPPED_LIST, Base64String.wrapList(BASE64_4_LIST));
assertEquals(BASE64_4_WRAPPED_LIST, Base64String.wrapList(BASE64_4, BASE64_4));
} |
protected List<String> filterPartitionPaths(List<String> partitionPaths) {
List<String> filteredPartitions = ClusteringPlanPartitionFilter.filter(partitionPaths, getWriteConfig());
LOG.debug("Filtered to the following partitions: " + filteredPartitions);
return filteredPartitions;
} | @Test
public void testFilterPartitionPaths() {
PartitionAwareClusteringPlanStrategy strategyTestRegexPattern = new DummyPartitionAwareClusteringPlanStrategy(table, context, hoodieWriteConfig);
ArrayList<String> fakeTimeBasedPartitionsPath = new ArrayList<>();
fakeTimeBasedPartitionsPath.add("20210718");
fakeTimeBasedPartitionsPath.add("20210715");
fakeTimeBasedPartitionsPath.add("20210723");
fakeTimeBasedPartitionsPath.add("20210716");
fakeTimeBasedPartitionsPath.add("20210719");
fakeTimeBasedPartitionsPath.add("20210721");
List list = strategyTestRegexPattern.getRegexPatternMatchedPartitions(hoodieWriteConfig, fakeTimeBasedPartitionsPath);
assertEquals(2, list.size());
assertTrue(list.contains("20210721"));
assertTrue(list.contains("20210723"));
} |
@Override
public Collection<Service> getAllSubscribeService() {
return subscribers.keySet();
} | @Test
void getAllSubscribeService() {
Collection<Service> allSubscribeService = abstractClient.getAllSubscribeService();
assertNotNull(allSubscribeService);
} |
@Override
public void commitJob(JobContext originalContext) throws IOException {
JobContext jobContext = TezUtil.enrichContextWithVertexId(originalContext);
JobConf jobConf = jobContext.getJobConf();
long startTime = System.currentTimeMillis();
LOG.info("Committing job {} has started", jobContext.getJobID());
Collection<String> outputs = HiveIcebergStorageHandler.outputTables(jobContext.getJobConf());
Collection<String> jobLocations = new ConcurrentLinkedQueue<>();
ExecutorService fileExecutor = fileExecutor(jobConf);
ExecutorService tableExecutor = tableExecutor(jobConf, outputs.size());
try {
// Commits the changes for the output tables in parallel
Tasks.foreach(outputs)
.throwFailureWhenFinished()
.stopOnFailure()
.executeWith(tableExecutor)
.run(
output -> {
Table table = HiveIcebergStorageHandler.table(jobConf, output);
if (table != null) {
String catalogName = HiveIcebergStorageHandler.catalogName(jobConf, output);
jobLocations.add(
generateJobLocation(table.location(), jobConf, jobContext.getJobID()));
commitTable(
table.io(), fileExecutor, jobContext, output, table.location(), catalogName);
} else {
LOG.info(
"CommitJob found no serialized table in config for table: {}. Skipping job commit.",
output);
}
});
} finally {
fileExecutor.shutdown();
if (tableExecutor != null) {
tableExecutor.shutdown();
}
}
LOG.info(
"Commit took {} ms for job {}",
System.currentTimeMillis() - startTime,
jobContext.getJobID());
cleanup(jobContext, jobLocations);
} | @Test
public void testSuccessfulUnpartitionedWrite() throws IOException {
HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter();
Table table = table(temp.toFile().getPath(), false);
JobConf conf = jobConf(table, 1);
List<Record> expected = writeRecords(table.name(), 1, 0, true, false, conf);
committer.commitJob(new JobContextImpl(conf, JOB_ID));
HiveIcebergTestUtils.validateFiles(table, conf, JOB_ID, 1);
HiveIcebergTestUtils.validateData(table, expected, 0);
} |
public static ContainerStatus createPreemptedContainerStatus(
ContainerId containerId, String diagnostics) {
return createAbnormalContainerStatus(containerId,
ContainerExitStatus.PREEMPTED, diagnostics);
} | @Test
public void testCreatePreemptedContainerStatus() {
ContainerStatus cd = SchedulerUtils.createPreemptedContainerStatus(
ContainerId.newContainerId(ApplicationAttemptId.newInstance(
ApplicationId.newInstance(System.currentTimeMillis(), 1), 1), 1), "x");
Assert.assertEquals(ContainerExitStatus.PREEMPTED, cd.getExitStatus());
} |
@Override
public boolean add(double score, V object) {
return get(addAsync(score, object));
} | @Test
public void testIteratorSequence() {
RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple");
for (int i = 0; i < 1000; i++) {
set.add(i, Integer.valueOf(i));
}
Set<Integer> setCopy = new HashSet<>();
for (int i = 0; i < 1000; i++) {
setCopy.add(Integer.valueOf(i));
}
checkIterator(set, setCopy);
} |
@Override
public DescribeUserScramCredentialsResult describeUserScramCredentials(List<String> users, DescribeUserScramCredentialsOptions options) {
final KafkaFutureImpl<DescribeUserScramCredentialsResponseData> dataFuture = new KafkaFutureImpl<>();
final long now = time.milliseconds();
Call call = new Call("describeUserScramCredentials", calcDeadlineMs(now, options.timeoutMs()),
new LeastLoadedNodeProvider()) {
@Override
public DescribeUserScramCredentialsRequest.Builder createRequest(final int timeoutMs) {
final DescribeUserScramCredentialsRequestData requestData = new DescribeUserScramCredentialsRequestData();
if (users != null && !users.isEmpty()) {
final List<UserName> userNames = new ArrayList<>(users.size());
for (final String user : users) {
if (user != null) {
userNames.add(new UserName().setName(user));
}
}
requestData.setUsers(userNames);
}
return new DescribeUserScramCredentialsRequest.Builder(requestData);
}
@Override
public void handleResponse(AbstractResponse abstractResponse) {
DescribeUserScramCredentialsResponse response = (DescribeUserScramCredentialsResponse) abstractResponse;
DescribeUserScramCredentialsResponseData data = response.data();
short messageLevelErrorCode = data.errorCode();
if (messageLevelErrorCode != Errors.NONE.code()) {
dataFuture.completeExceptionally(Errors.forCode(messageLevelErrorCode).exception(data.errorMessage()));
} else {
dataFuture.complete(data);
}
}
@Override
void handleFailure(Throwable throwable) {
dataFuture.completeExceptionally(throwable);
}
};
runnable.call(call, now);
return new DescribeUserScramCredentialsResult(dataFuture);
} | @Test
public void testDescribeUserScramCredentials() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
final String user0Name = "user0";
final ScramMechanism user0ScramMechanism0 = ScramMechanism.SCRAM_SHA_256;
final int user0Iterations0 = 4096;
final ScramMechanism user0ScramMechanism1 = ScramMechanism.SCRAM_SHA_512;
final int user0Iterations1 = 8192;
final CredentialInfo user0CredentialInfo0 = new CredentialInfo();
user0CredentialInfo0.setMechanism(user0ScramMechanism0.type());
user0CredentialInfo0.setIterations(user0Iterations0);
final CredentialInfo user0CredentialInfo1 = new CredentialInfo();
user0CredentialInfo1.setMechanism(user0ScramMechanism1.type());
user0CredentialInfo1.setIterations(user0Iterations1);
final String user1Name = "user1";
final ScramMechanism user1ScramMechanism = ScramMechanism.SCRAM_SHA_256;
final int user1Iterations = 4096;
final CredentialInfo user1CredentialInfo = new CredentialInfo();
user1CredentialInfo.setMechanism(user1ScramMechanism.type());
user1CredentialInfo.setIterations(user1Iterations);
final DescribeUserScramCredentialsResponseData responseData = new DescribeUserScramCredentialsResponseData();
responseData.setResults(asList(
new DescribeUserScramCredentialsResponseData.DescribeUserScramCredentialsResult()
.setUser(user0Name)
.setCredentialInfos(asList(user0CredentialInfo0, user0CredentialInfo1)),
new DescribeUserScramCredentialsResponseData.DescribeUserScramCredentialsResult()
.setUser(user1Name)
.setCredentialInfos(singletonList(user1CredentialInfo))));
final DescribeUserScramCredentialsResponse response = new DescribeUserScramCredentialsResponse(responseData);
final Set<String> usersRequestedSet = new HashSet<>();
usersRequestedSet.add(user0Name);
usersRequestedSet.add(user1Name);
for (final List<String> users : asList(null, new ArrayList<String>(), asList(user0Name, null, user1Name))) {
env.kafkaClient().prepareResponse(response);
final DescribeUserScramCredentialsResult result = env.adminClient().describeUserScramCredentials(users);
final Map<String, UserScramCredentialsDescription> descriptionResults = result.all().get();
final KafkaFuture<UserScramCredentialsDescription> user0DescriptionFuture = result.description(user0Name);
final KafkaFuture<UserScramCredentialsDescription> user1DescriptionFuture = result.description(user1Name);
final Set<String> usersDescribedFromUsersSet = new HashSet<>(result.users().get());
assertEquals(usersRequestedSet, usersDescribedFromUsersSet);
final Set<String> usersDescribedFromMapKeySet = descriptionResults.keySet();
assertEquals(usersRequestedSet, usersDescribedFromMapKeySet);
final UserScramCredentialsDescription userScramCredentialsDescription0 = descriptionResults.get(user0Name);
assertEquals(user0Name, userScramCredentialsDescription0.name());
assertEquals(2, userScramCredentialsDescription0.credentialInfos().size());
assertEquals(user0ScramMechanism0, userScramCredentialsDescription0.credentialInfos().get(0).mechanism());
assertEquals(user0Iterations0, userScramCredentialsDescription0.credentialInfos().get(0).iterations());
assertEquals(user0ScramMechanism1, userScramCredentialsDescription0.credentialInfos().get(1).mechanism());
assertEquals(user0Iterations1, userScramCredentialsDescription0.credentialInfos().get(1).iterations());
assertEquals(userScramCredentialsDescription0, user0DescriptionFuture.get());
final UserScramCredentialsDescription userScramCredentialsDescription1 = descriptionResults.get(user1Name);
assertEquals(user1Name, userScramCredentialsDescription1.name());
assertEquals(1, userScramCredentialsDescription1.credentialInfos().size());
assertEquals(user1ScramMechanism, userScramCredentialsDescription1.credentialInfos().get(0).mechanism());
assertEquals(user1Iterations, userScramCredentialsDescription1.credentialInfos().get(0).iterations());
assertEquals(userScramCredentialsDescription1, user1DescriptionFuture.get());
}
}
} |
@Override
public void putAll(Map<? extends K, ? extends V> m) {
checkNotNull(m, "The passed in map cannot be null.");
m.forEach((k, v) -> items.put(serializer.encode(k), serializer.encode(v)));
} | @Test
public void testPutAll() throws Exception {
//Tests adding of an outside map
Map<Integer, Integer> testMap = Maps.newHashMap();
fillMap(10);
map.putAll(testMap);
for (int i = 0; i < 10; i++) {
assertTrue("The map should contain the current 'i' value.", map.containsKey(i));
assertTrue("The map should contain the current 'i' value.", map.containsValue(i));
}
} |
@Override
public void onOpened() {
digestNotification();
} | @Test
public void onOpened_appVisible_dontSetInitialNotification() throws Exception {
setUpForegroundApp();
Activity currentActivity = mock(Activity.class);
when(mReactContext.getCurrentActivity()).thenReturn(currentActivity);
final PushNotification uut = createUUT();
uut.onOpened();
verify(InitialNotificationHolder.getInstance(), never()).set(any(PushNotificationProps.class));
} |
@Override
public void fire(final Connection connection, final Object[] oldRow, final Object[] newRow) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"INSERT IGNORE INTO PLUGIN_HANDLE (`ID`,`PLUGIN_ID`,`FIELD`,`LABEL`,`DATA_TYPE`,`TYPE`,`SORT`,`EXT_OBJ`)"
+ " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)")) {
BaseTrigger.sqlExecute(newRow, statement);
} catch (ShenyuException e) {
LOG.error("PluginHandleH2Trigger Error:", e);
}
} | @Test
public void testPluginHandleH2Trigger() throws SQLException {
final PluginHandleH2Trigger pluginHandleH2Trigger = new PluginHandleH2Trigger();
final Connection connection = mock(Connection.class);
when(connection.prepareStatement(anyString())).thenReturn(mock(PreparedStatement.class));
Assertions.assertDoesNotThrow(() -> pluginHandleH2Trigger.fire(connection, new Object[1], new Object[1]));
Assertions.assertDoesNotThrow(pluginHandleH2Trigger::close);
Assertions.assertDoesNotThrow(pluginHandleH2Trigger::remove);
} |
synchronized boolean processDeregister(FunctionMetaData deregisterRequestFs) throws IllegalArgumentException {
String functionName = deregisterRequestFs.getFunctionDetails().getName();
String tenant = deregisterRequestFs.getFunctionDetails().getTenant();
String namespace = deregisterRequestFs.getFunctionDetails().getNamespace();
return processDeregister(tenant, namespace, functionName, deregisterRequestFs.getVersion());
} | @Test
public void processDeregister() throws PulsarClientException {
SchedulerManager schedulerManager = mock(SchedulerManager.class);
WorkerConfig workerConfig = new WorkerConfig();
workerConfig.setWorkerId("worker-1");
FunctionMetaDataManager functionMetaDataManager = spy(
new FunctionMetaDataManager(workerConfig,
schedulerManager,
mockPulsarClient(), ErrorNotifier.getDefaultImpl()));
Function.FunctionMetaData m1 = Function.FunctionMetaData.newBuilder()
.setVersion(1)
.setFunctionDetails(Function.FunctionDetails.newBuilder().setName("func-1")
.setNamespace("namespace-1").setTenant("tenant-1")).build();
Assert.assertFalse(functionMetaDataManager.processDeregister(m1));
verify(functionMetaDataManager, times(0))
.setFunctionMetaData(any(Function.FunctionMetaData.class));
verify(schedulerManager, times(0)).schedule();
Assert.assertEquals(0, functionMetaDataManager.functionMetaDataMap.size());
// insert something
Assert.assertTrue(functionMetaDataManager.processUpdate(m1));
verify(functionMetaDataManager, times(1))
.setFunctionMetaData(any(Function.FunctionMetaData.class));
verify(schedulerManager, times(0)).schedule();
Assert.assertEquals(m1, functionMetaDataManager.functionMetaDataMap.get(
"tenant-1").get("namespace-1").get("func-1"));
Assert.assertEquals(1, functionMetaDataManager.functionMetaDataMap.get(
"tenant-1").get("namespace-1").size());
// outdated delete request
try {
functionMetaDataManager.processDeregister(m1);
Assert.assertTrue(false);
} catch (IllegalArgumentException e) {
Assert.assertEquals(e.getMessage(), "Delete request ignored because it is out of date. Please try again.");
}
verify(functionMetaDataManager, times(1))
.setFunctionMetaData(any(Function.FunctionMetaData.class));
verify(schedulerManager, times(0)).schedule();
Assert.assertEquals(m1, functionMetaDataManager.functionMetaDataMap.get(
"tenant-1").get("namespace-1").get("func-1"));
Assert.assertEquals(1, functionMetaDataManager.functionMetaDataMap.get(
"tenant-1").get("namespace-1").size());
// delete now
m1 = m1.toBuilder().setVersion(2).build();
Assert.assertTrue(functionMetaDataManager.processDeregister(m1));
verify(functionMetaDataManager, times(1))
.setFunctionMetaData(any(Function.FunctionMetaData.class));
verify(schedulerManager, times(0)).schedule();
Assert.assertEquals(0, functionMetaDataManager.functionMetaDataMap.get(
"tenant-1").get("namespace-1").size());
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));
return query;
} | @Test
public void fail_to_create_query_having_q_with_no_value() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(EQ).build()),
emptySet());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Query is invalid");
} |
@Udf
public <T extends Comparable<? super T>> T arrayMin(@UdfParameter(
description = "Array of values from which to find the minimum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candidate == null) {
candidate = thisVal;
} else if (thisVal.compareTo(candidate) < 0) {
candidate = thisVal;
}
}
}
return candidate;
} | @Test
public void shouldFindStringMin() {
final List<String> input = Arrays.asList("foo", "food", "bar");
assertThat(udf.arrayMin(input), is("bar"));
} |
@Override
// Exposes internal mutable reference by design - Spotbugs is right to warn that this is dangerous
public synchronized byte[] toByteArray() {
// Note: count == buf.length is not a correct criteria to "return buf;", because the internal
// buf may be reused after reset().
if (!isFallback && count > 0) {
return buf;
} else {
return super.toByteArray();
}
} | @Test
public void testWriteSingleArray() throws IOException {
writeToBoth(TEST_DATA);
assertStreamContentsEquals(stream, exposedStream);
assertNotSame(TEST_DATA, exposedStream.toByteArray());
} |
@SuppressWarnings("unchecked")
@Override
public boolean setFlushListener(final CacheFlushListener<K, V> listener,
final boolean sendOldValues) {
final KeyValueStore<Bytes, byte[]> wrapped = wrapped();
if (wrapped instanceof CachedStateStore) {
return ((CachedStateStore<byte[], byte[]>) wrapped).setFlushListener(
record -> listener.apply(
record.withKey(serdes.keyFrom(record.key()))
.withValue(new Change<>(
record.value().newValue != null ? serdes.valueFrom(record.value().newValue) : null,
record.value().oldValue != null ? serdes.valueFrom(record.value().oldValue) : null,
record.value().isLatest
))
),
sendOldValues);
}
return false;
} | @Test
public void shouldNotSetFlushListenerOnWrappedNoneCachingStore() {
setUpWithoutContext();
assertFalse(metered.setFlushListener(null, false));
} |
@Override
public Collection<SQLToken> generateSQLTokens(final InsertStatementContext insertStatementContext) {
InsertStatement insertStatement = insertStatementContext.getSqlStatement();
Preconditions.checkState(insertStatement.getOnDuplicateKeyColumns().isPresent());
Collection<ColumnAssignmentSegment> onDuplicateKeyColumnsSegments = insertStatement.getOnDuplicateKeyColumns().get().getColumns();
if (onDuplicateKeyColumnsSegments.isEmpty()) {
return Collections.emptyList();
}
String schemaName = insertStatementContext.getTablesContext().getSchemaName()
.orElseGet(() -> new DatabaseTypeRegistry(insertStatementContext.getDatabaseType()).getDefaultSchemaName(databaseName));
String tableName = insertStatement.getTable().getTableName().getIdentifier().getValue();
EncryptTable encryptTable = encryptRule.getEncryptTable(tableName);
Collection<SQLToken> result = new LinkedList<>();
for (ColumnAssignmentSegment each : onDuplicateKeyColumnsSegments) {
boolean leftColumnIsEncrypt = encryptTable.isEncryptColumn(each.getColumns().get(0).getIdentifier().getValue());
if (each.getValue() instanceof FunctionSegment && "VALUES".equalsIgnoreCase(((FunctionSegment) each.getValue()).getFunctionName())) {
Optional<ExpressionSegment> rightColumnSegment = ((FunctionSegment) each.getValue()).getParameters().stream().findFirst();
Preconditions.checkState(rightColumnSegment.isPresent());
boolean rightColumnIsEncrypt = encryptTable.isEncryptColumn(((ColumnSegment) rightColumnSegment.get()).getIdentifier().getValue());
if (!leftColumnIsEncrypt && !rightColumnIsEncrypt) {
continue;
}
}
if (!leftColumnIsEncrypt) {
continue;
}
EncryptColumn encryptColumn = encryptTable.getEncryptColumn(each.getColumns().get(0).getIdentifier().getValue());
generateSQLToken(schemaName, encryptTable, encryptColumn, each).ifPresent(result::add);
}
return result;
} | @Test
void assertGenerateSQLTokens() {
InsertStatementContext insertStatementContext = mock(InsertStatementContext.class, RETURNS_DEEP_STUBS);
when(insertStatementContext.getTablesContext().getSchemaName()).thenReturn(Optional.of("db_test"));
MySQLInsertStatement insertStatement = mock(MySQLInsertStatement.class, RETURNS_DEEP_STUBS);
when(insertStatement.getTable().getTableName().getIdentifier().getValue()).thenReturn("t_user");
OnDuplicateKeyColumnsSegment onDuplicateKeyColumnsSegment = mock(OnDuplicateKeyColumnsSegment.class);
when(onDuplicateKeyColumnsSegment.getColumns()).thenReturn(buildAssignmentSegment());
when(insertStatement.getOnDuplicateKeyColumns()).thenReturn(Optional.of(onDuplicateKeyColumnsSegment));
when(insertStatementContext.getSqlStatement()).thenReturn(insertStatement);
when(insertStatement.getOnDuplicateKeyColumns()).thenReturn(Optional.of(onDuplicateKeyColumnsSegment));
Iterator<SQLToken> actual = generator.generateSQLTokens(insertStatementContext).iterator();
assertEncryptAssignmentToken((EncryptAssignmentToken) actual.next(), "cipher_mobile = ?");
assertEncryptAssignmentToken((EncryptAssignmentToken) actual.next(), "cipher_mobile = VALUES(cipher_mobile)");
assertEncryptAssignmentToken((EncryptAssignmentToken) actual.next(), "cipher_mobile = 'encryptValue'");
assertFalse(actual.hasNext());
} |
@Nullable static String channelName(@Nullable Destination destination) {
if (destination == null) return null;
boolean isQueue = isQueue(destination);
try {
if (isQueue) {
return ((Queue) destination).getQueueName();
} else {
return ((Topic) destination).getTopicName();
}
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting destination name from {0}", destination, null);
}
return null;
} | @Test void channelName_queueAndTopic_topicOnNoQueueName() throws JMSException {
QueueAndTopic destination = mock(QueueAndTopic.class);
when(destination.getTopicName()).thenReturn("topic-foo");
assertThat(MessageParser.channelName(destination))
.isEqualTo("topic-foo");
} |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthenticationRequest((AuthenticationRequest) samlRequest, metadataFromDc, samlRequest.getServiceEntityId());
} else {
dcMetadataResponseMapper.dcMetadataToSamlRequest(samlRequest, metadataFromDc);
}
} | @Test
public void resolveDcMetadataNoLegacyWebserviceIdTest() throws DienstencatalogusException {
DcMetadataResponse dcMetadataResponse = dcClientStubGetMetadata(stubsCaMetadataFile, null);
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(dcMetadataResponse);
SamlRequest request = new AuthenticationRequest();
request.setConnectionEntityId(CONNECTION_ENTITY_ID);
request.setServiceEntityId(SERVICE_ENTITY_ID);
assertDoesNotThrow(() -> dcMetadataService.resolveDcMetadata(request));
} |
public void clearRange(Instant minTimestamp, Instant limitTimestamp) {
checkState(
!isClosed,
"OrderedList user state is no longer usable because it is closed for %s",
requestTemplate.getStateKey());
// Remove items (in a collection) in the specific range from pendingAdds.
// The old values of the removed sub map are kept, so that they will still be accessible in
// pre-existing iterables even after the sort key is cleared.
pendingAdds.subMap(minTimestamp, limitTimestamp).clear();
if (!isCleared) {
pendingRemoves.add(
Range.range(minTimestamp, BoundType.CLOSED, limitTimestamp, BoundType.OPEN));
}
} | @Test
public void testClearRange() throws Exception {
FakeBeamFnStateClient fakeClient =
new FakeBeamFnStateClient(
timestampedValueCoder,
ImmutableMap.of(
createOrderedListStateKey("A", 1),
asList(A1, B1),
createOrderedListStateKey("A", 4),
Collections.singletonList(A4),
createOrderedListStateKey("A", 2),
asList(A2, B2),
createOrderedListStateKey("A", 3),
Collections.singletonList(A3)));
OrderedListUserState<String> userState =
new OrderedListUserState<>(
Caches.noop(),
fakeClient,
"instructionId",
createOrderedListStateKey("A"),
StringUtf8Coder.of());
Iterable<TimestampedValue<String>> initStateFrom2To3 =
userState.readRange(Instant.ofEpochMilli(2), Instant.ofEpochMilli(4));
// clear range below the current timestamp range
userState.clearRange(Instant.ofEpochMilli(-1), Instant.ofEpochMilli(0));
assertArrayEquals(
asList(A2, B2, A3).toArray(), Iterables.toArray(initStateFrom2To3, TimestampedValue.class));
assertArrayEquals(
asList(A1, B1, A2, B2, A3, A4).toArray(),
Iterables.toArray(userState.read(), TimestampedValue.class));
// clear range above the current timestamp range
userState.clearRange(Instant.ofEpochMilli(5), Instant.ofEpochMilli(10));
assertArrayEquals(
asList(A2, B2, A3).toArray(), Iterables.toArray(initStateFrom2To3, TimestampedValue.class));
assertArrayEquals(
asList(A1, B1, A2, B2, A3, A4).toArray(),
Iterables.toArray(userState.read(), TimestampedValue.class));
// clear range that falls inside the current timestamp range
userState.clearRange(Instant.ofEpochMilli(2), Instant.ofEpochMilli(4));
assertArrayEquals(
asList(A2, B2, A3).toArray(), Iterables.toArray(initStateFrom2To3, TimestampedValue.class));
assertArrayEquals(
asList(A1, B1, A4).toArray(), Iterables.toArray(userState.read(), TimestampedValue.class));
// clear range that partially covers the current timestamp range
userState.clearRange(Instant.ofEpochMilli(3), Instant.ofEpochMilli(5));
assertArrayEquals(
asList(A2, B2, A3).toArray(), Iterables.toArray(initStateFrom2To3, TimestampedValue.class));
assertArrayEquals(
asList(A1, B1).toArray(), Iterables.toArray(userState.read(), TimestampedValue.class));
// clear range that fully covers the current timestamp range
userState.clearRange(Instant.ofEpochMilli(-1), Instant.ofEpochMilli(10));
assertArrayEquals(
asList(A2, B2, A3).toArray(), Iterables.toArray(initStateFrom2To3, TimestampedValue.class));
assertThat(userState.read(), is(emptyIterable()));
userState.asyncClose();
assertThrows(
IllegalStateException.class,
() -> userState.clearRange(Instant.ofEpochMilli(1), Instant.ofEpochMilli(2)));
} |
@Override
public boolean getBooleanValueOfVariable( String variableName, boolean defaultValue ) {
if ( !Utils.isEmpty( variableName ) ) {
String value = environmentSubstitute( variableName );
if ( !Utils.isEmpty( value ) ) {
return ValueMetaString.convertStringToBoolean( value );
}
}
return defaultValue;
} | @Test
public void testGetBooleanValueOfVariable() {
assertFalse( meta.getBooleanValueOfVariable( null, false ) );
assertTrue( meta.getBooleanValueOfVariable( "", true ) );
assertTrue( meta.getBooleanValueOfVariable( "true", true ) );
assertFalse( meta.getBooleanValueOfVariable( "${myVar}", false ) );
meta.setVariable( "myVar", "Y" );
assertTrue( meta.getBooleanValueOfVariable( "${myVar}", false ) );
} |
public static byte[] plus(byte[] in, int add) {
if (in.length == 0) return in;
final byte[] out = in.clone();
add(out, add);
return out;
} | @Test
public void plusShouldCarry() {
assertArrayEquals(new byte[] { 0, 0, 0}, ByteArrayUtils.plus(new byte[] { -1, -1, -1}, 1));
} |
@Override
public boolean databaseExists(String databaseName) throws CatalogException {
if (catalog instanceof SupportsNamespaces) {
boolean exists =
((SupportsNamespaces) catalog).namespaceExists(Namespace.of(databaseName));
log.info("Database {} existence status: {}", databaseName, exists);
return exists;
} else {
throw new UnsupportedOperationException(
"catalog not implements SupportsNamespaces so can't check database exists");
}
} | @Test
@Order(3)
void databaseExists() {
Assertions.assertTrue(icebergCatalog.databaseExists(databaseName));
Assertions.assertFalse(icebergCatalog.databaseExists("sssss"));
} |
@ScalarOperator(NOT_EQUAL)
@SqlType(StandardTypes.BOOLEAN)
public static boolean notEqual(@SqlType("unknown") boolean left, @SqlType("unknown") boolean right)
{
throw new AssertionError("value of unknown type should all be NULL");
} | @Test
public void testNotEqual()
{
assertFunction("NULL <> NULL", BOOLEAN, null);
} |
public double getRelevance() { return relevance; } | @Test
void testNaN2negativeInfinity() {
LeanHit nan = new LeanHit(gidA, 0, 0, Double.NaN);
assertFalse(Double.isNaN(nan.getRelevance()));
assertTrue(Double.isInfinite(nan.getRelevance()));
assertEquals(Double.NEGATIVE_INFINITY, nan.getRelevance(), DELTA);
} |
static void cleanStackTrace(Throwable throwable) {
new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet());
} | @Test
public void collapseStreaks() {
Throwable throwable =
createThrowableWithStackTrace(
"com.example.MyTest",
"junit.Foo",
"org.junit.Bar",
"com.google.testing.junit.Car",
"com.google.testing.testsize.Dar",
"com.google.testing.util.Far",
"com.example.Gar");
StackTraceCleaner.cleanStackTrace(throwable);
assertThat(throwable.getStackTrace())
.isEqualTo(
new StackTraceElement[] {
createStackTraceElement("com.example.MyTest"),
createCollapsedStackTraceElement("Testing framework", 5),
createStackTraceElement("com.example.Gar"),
});
} |
@Override
public int isNullable(final int column) {
Preconditions.checkArgument(1 == column);
return columnNoNulls;
} | @Test
void assertIsNullable() throws SQLException {
assertThat(actualMetaData.isNullable(1), is(ResultSetMetaData.columnNoNulls));
} |
@Override
public Integer getLocalValue() {
return this.min;
} | @Test
void testGet() {
IntMinimum min = new IntMinimum();
assertThat(min.getLocalValue().intValue()).isEqualTo(Integer.MAX_VALUE);
} |
public void writeTrailingBytes(byte[] value) {
if ((value == null) || (value.length == 0)) {
throw new IllegalArgumentException("Value cannot be null or have 0 elements");
}
encodedArrays.add(value);
} | @Test
public void testWriteTrailingBytes() {
byte[] escapeChars =
new byte[] {
OrderedCode.ESCAPE1,
OrderedCode.NULL_CHARACTER,
OrderedCode.SEPARATOR,
OrderedCode.ESCAPE2,
OrderedCode.INFINITY,
OrderedCode.FF_CHARACTER
};
byte[] anotherArray = new byte[] {'a', 'b', 'c', 'd', 'e'};
OrderedCode orderedCode = new OrderedCode();
orderedCode.writeTrailingBytes(escapeChars);
assertArrayEquals(orderedCode.getEncodedBytes(), escapeChars);
assertArrayEquals(orderedCode.readTrailingBytes(), escapeChars);
try {
orderedCode.readInfinity();
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException e) {
// expected
}
orderedCode = new OrderedCode();
orderedCode.writeTrailingBytes(anotherArray);
assertArrayEquals(orderedCode.getEncodedBytes(), anotherArray);
assertArrayEquals(orderedCode.readTrailingBytes(), anotherArray);
} |
public static List<ReporterSetup> fromConfiguration(
final Configuration configuration, @Nullable final PluginManager pluginManager) {
String includedReportersString = configuration.get(MetricOptions.REPORTERS_LIST, "");
Set<String> namedReporters =
findEnabledTraceReportersInConfiguration(
configuration,
includedReportersString,
metricReporterListPattern,
metricReporterClassPattern,
ConfigConstants.METRICS_REPORTER_PREFIX);
if (namedReporters.isEmpty()) {
return Collections.emptyList();
}
final List<Tuple2<String, Configuration>> reporterConfigurations =
loadReporterConfigurations(
configuration, namedReporters, ConfigConstants.METRICS_REPORTER_PREFIX);
final Map<String, MetricReporterFactory> reporterFactories =
loadAvailableReporterFactories(pluginManager);
return setupReporters(reporterFactories, reporterConfigurations);
} | @Test
void testReporterArgumentForwarding() {
final Configuration config = new Configuration();
configureReporter1(config);
final List<ReporterSetup> reporterSetups = ReporterSetup.fromConfiguration(config, null);
assertThat(reporterSetups).hasSize(1);
final ReporterSetup reporterSetup = reporterSetups.get(0);
assertReporter1Configured(reporterSetup);
} |
@Override
public void startInfrastructure(boolean shouldPoll) {
removeBundleDirectory();
goPluginOSGiFramework.start();
addPluginChangeListener(new PluginChangeListener() {
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
}
@Override
public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) {
synchronized (initializedPluginsWithTheirExtensionTypes) {
initializedPluginsWithTheirExtensionTypes.remove(pluginDescriptor);
}
}
});
monitor.addPluginJarChangeListener(defaultPluginJarChangeListener);
if (shouldPoll) {
monitor.start();
} else {
monitor.oneShot();
}
} | @Test
void shouldAddPluginChangeListener() {
DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, mock(GoPluginOSGiFramework.class), jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
pluginManager.startInfrastructure(true);
InOrder inOrder = inOrder(monitor);
inOrder.verify(monitor).addPluginJarChangeListener(jarChangeListener);
} |
public final boolean isRewardHalvingPoint(final int previousHeight) {
return ((previousHeight + 1) % REWARD_HALVING_INTERVAL) == 0;
} | @Test
public void isRewardHalvingPoint() {
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(209999));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(419999));
assertFalse(BITCOIN_PARAMS.isRewardHalvingPoint(629998));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(629999));
assertFalse(BITCOIN_PARAMS.isRewardHalvingPoint(630000));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(839999));
} |
@Override
public Ability processAbility(Ability ab) {
// Should never hit this
throw new RuntimeException("Should not process any ability in a vanilla toggle");
} | @Test
public void throwsOnProcessingAbility() {
Assertions.assertThrows(RuntimeException.class, () -> toggle.processAbility(defaultAbs.claimCreator()));
} |
public DnsName getHost() {
return host;
} | @Test
public void setFqdn() {
DummyConnectionConfiguration.Builder builder = newUnitTestBuilder();
final String fqdn = "foo.example.org";
builder.setHost(fqdn);
DummyConnectionConfiguration connectionConfiguration = builder.build();
assertEquals(fqdn, connectionConfiguration.getHost().toString());
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
if (readerWay.hasTag("hazmat", "no"))
hazEnc.setEnum(false, edgeId, edgeIntAccess, Hazmat.NO);
} | @Test
public void testNoNPE() {
ReaderWay readerWay = new ReaderWay(1);
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
assertEquals(Hazmat.YES, hazEnc.getEnum(false, edgeId, edgeIntAccess));
} |
@SuppressWarnings("rawtypes")
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingConditionValue> shardingConditionValues,
final DataNodeInfo dataNodeInfo, final ConfigurationProperties props) {
ShardingConditionValue shardingConditionValue = shardingConditionValues.iterator().next();
Collection<String> shardingResult = shardingConditionValue instanceof ListShardingConditionValue
? doSharding(availableTargetNames, (ListShardingConditionValue) shardingConditionValue, dataNodeInfo)
: doSharding(availableTargetNames, (RangeShardingConditionValue) shardingConditionValue, dataNodeInfo);
Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
result.addAll(shardingResult);
return result;
} | @Test
void assertDoShardingForListSharding() {
Collection<String> actualListSharding = standardShardingStrategy.doSharding(targets, Collections.singletonList(
new ListShardingConditionValue<>("column", "logicTable", Collections.singletonList(1))), dataNodeSegment, new ConfigurationProperties(new Properties()));
assertThat(actualListSharding.size(), is(1));
assertThat(actualListSharding.iterator().next(), is("1"));
} |
@GET
@Timed
@ApiOperation(value = "Get a list of all index sets")
@ApiResponses(value = {
@ApiResponse(code = 403, message = "Unauthorized"),
})
public IndexSetResponse list(@ApiParam(name = "skip", value = "The number of elements to skip (offset).", required = true)
@QueryParam("skip") @DefaultValue("0") int skip,
@ApiParam(name = "limit", value = "The maximum number of elements to return.", required = true)
@QueryParam("limit") @DefaultValue("0") int limit,
@ApiParam(name = "stats", value = "Include index set stats.")
@QueryParam("stats") @DefaultValue("false") boolean computeStats) {
final IndexSetConfig defaultIndexSet = indexSetService.getDefault();
List<IndexSetConfig> allowedConfigurations = indexSetService.findAll()
.stream()
.filter(indexSet -> isPermitted(RestPermissions.INDEXSETS_READ, indexSet.id()))
.toList();
return getPagedIndexSetResponse(skip, limit, computeStats, defaultIndexSet, allowedConfigurations);
} | @Test
public void list0() {
when(indexSetService.findAll()).thenReturn(Collections.emptyList());
final IndexSetResponse list = indexSetsResource.list(0, 0, false);
verify(indexSetService, times(1)).findAll();
verify(indexSetService, times(1)).getDefault();
verifyNoMoreInteractions(indexSetService);
assertThat(list.total()).isZero();
assertThat(list.indexSets()).isEmpty();
} |
@GET
@Path("stats")
@Timed
@ApiOperation(value = "Get stats of all index sets")
@ApiResponses(value = {
@ApiResponse(code = 403, message = "Unauthorized"),
})
public IndexSetStats globalStats() {
checkPermission(RestPermissions.INDEXSETS_READ);
return indices.getIndexSetStats();
} | @Test
public void globalStatsDenied() {
notPermitted();
expectedException.expect(ForbiddenException.class);
expectedException.expectMessage("Not authorized");
try {
indexSetsResource.globalStats();
} finally {
verifyNoMoreInteractions(indexSetService);
}
} |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.0");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();
// find out which member it is
if (name.equals(CLIENTS)) {
readClients(reader);
} else if (name.equals(GRANTS)) {
readGrants(reader);
} else if (name.equals(WHITELISTEDSITES)) {
readWhitelistedSites(reader);
} else if (name.equals(BLACKLISTEDSITES)) {
readBlacklistedSites(reader);
} else if (name.equals(AUTHENTICATIONHOLDERS)) {
readAuthenticationHolders(reader);
} else if (name.equals(ACCESSTOKENS)) {
readAccessTokens(reader);
} else if (name.equals(REFRESHTOKENS)) {
readRefreshTokens(reader);
} else if (name.equals(SYSTEMSCOPES)) {
readSystemScopes(reader);
} else {
for (MITREidDataServiceExtension extension : extensions) {
if (extension.supportsVersion(THIS_VERSION)) {
if (extension.supportsVersion(THIS_VERSION)) {
extension.importExtensionData(name, reader);
break;
}
}
}
// unknown token, skip it
reader.skipValue();
}
break;
case END_OBJECT:
// the object ended, we're done here
reader.endObject();
continue;
default:
logger.debug("Found unexpected entry");
reader.skipValue();
continue; }
}
fixObjectReferences();
for (MITREidDataServiceExtension extension : extensions) {
if (extension.supportsVersion(THIS_VERSION)) {
extension.fixExtensionObjectReferences(maps);
break;
}
}
maps.clearAll();
} | @Test
public void testImportGrants() throws IOException, ParseException {
Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+00:00", Locale.ENGLISH);
Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH);
OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class);
when(mockToken1.getId()).thenReturn(1L);
ApprovedSite site1 = new ApprovedSite();
site1.setId(1L);
site1.setClientId("foo");
site1.setCreationDate(creationDate1);
site1.setAccessDate(accessDate1);
site1.setUserId("user1");
site1.setAllowedScopes(ImmutableSet.of("openid", "phone"));
when(mockToken1.getApprovedSite()).thenReturn(site1);
Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH);
Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH);
Date timeoutDate2 = formatter.parse("2014-10-01T20:49:44.090+00:00", Locale.ENGLISH);
ApprovedSite site2 = new ApprovedSite();
site2.setId(2L);
site2.setClientId("bar");
site2.setCreationDate(creationDate2);
site2.setAccessDate(accessDate2);
site2.setUserId("user2");
site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile"));
site2.setTimeoutDate(timeoutDate2);
String configJson = "{" +
"\"" + MITREidDataService.CLIENTS + "\": [], " +
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
"\"" + MITREidDataService.GRANTS + "\": [" +
"{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+00:00\",\"accessDate\":\"2014-09-10T23:49:44.090+00:00\","
+ "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1,"
+ "\"approvedAccessTokens\":[1]}," +
"{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+00:00\",\"accessDate\":\"2014-09-11T20:49:44.090+00:00\","
+ "\"timeoutDate\":\"2014-10-01T20:49:44.090+00:00\",\"userId\":\"user2\","
+ "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" +
" ]" +
"}";
System.err.println(configJson);
JsonReader reader = new JsonReader(new StringReader(configJson));
final Map<Long, ApprovedSite> fakeDb = new HashMap<>();
when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer<ApprovedSite>() {
Long id = 343L;
@Override
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0];
if(_site.getId() == null) {
_site.setId(id++);
}
fakeDb.put(_site.getId(), _site);
return _site;
}
});
when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer<ApprovedSite>() {
@Override
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
Long _id = (Long) invocation.getArguments()[0];
return fakeDb.get(_id);
}
});
when(wlSiteRepository.getById(isNull(Long.class))).thenAnswer(new Answer<WhitelistedSite>() {
Long id = 244L;
@Override
public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable {
WhitelistedSite _site = mock(WhitelistedSite.class);
when(_site.getId()).thenReturn(id++);
return _site;
}
});
when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
Long id = 221L;
@Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class);
when(_token.getId()).thenReturn(id++);
return _token;
}
});
when(tokenRepository.getAccessTokensForApprovedSite(site1)).thenReturn(Lists.newArrayList(mockToken1));
dataService.importData(reader);
//2 for sites, 1 for updating access token ref on #1
verify(approvedSiteRepository, times(3)).save(capturedApprovedSites.capture());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
assertThat(savedSites.size(), is(2));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
} |
@Override
public String toString() {
return columns.isEmpty() ? "" : "(" + String.join(", ", columns) + ")";
} | @Test
void assertToStringWithEmptyColumn() {
assertThat(new UseDefaultInsertColumnsToken(0, Collections.emptyList()).toString(), is(""));
} |
public static Expression resolve(final Expression expression, final SqlType sqlType) {
if (sqlType instanceof SqlDecimal) {
return resolveToDecimal(expression, (SqlDecimal)sqlType);
}
return expression;
} | @Test
public void shouldNotResolveNonDecimalTarget() {
// When
final Expression expression =
ImplicitlyCastResolver.resolve(new IntegerLiteral(5), SqlTypes.STRING);
// Then
assertThat(expression, instanceOf(IntegerLiteral.class));
assertThat(((IntegerLiteral)expression).getValue(), is(5));
} |
@Override
public Statistics getTableStatistics(OptimizerContext session,
Table table,
Map<ColumnRefOperator, Column> columns,
List<PartitionKey> partitionKeys,
ScalarOperator predicate,
long limit,
TableVersionRange version) {
IcebergTable icebergTable = (IcebergTable) table;
long snapshotId;
if (version.end().isPresent()) {
snapshotId = version.end().get();
} else {
Statistics.Builder statisticsBuilder = Statistics.builder();
statisticsBuilder.setOutputRowCount(1);
statisticsBuilder.addColumnStatistics(statisticProvider.buildUnknownColumnStatistics(columns.keySet()));
return statisticsBuilder.build();
}
PredicateSearchKey key = PredicateSearchKey.of(
icebergTable.getRemoteDbName(), icebergTable.getRemoteTableName(), snapshotId, predicate);
triggerIcebergPlanFilesIfNeeded(key, icebergTable, predicate, limit);
if (!session.getSessionVariable().enableIcebergColumnStatistics()) {
List<FileScanTask> icebergScanTasks = splitTasks.get(key);
if (icebergScanTasks == null) {
throw new StarRocksConnectorException("Missing iceberg split task for table:[{}.{}]. predicate:[{}]",
icebergTable.getRemoteDbName(), icebergTable.getRemoteTableName(), predicate);
}
try (Timer ignored = Tracers.watchScope(EXTERNAL, "ICEBERG.calculateCardinality" + key)) {
return statisticProvider.getCardinalityStats(columns, icebergScanTasks);
}
} else {
return statisticProvider.getTableStatistics(icebergTable, columns, session, predicate, version);
}
} | @Test
public void testGetTableStatistics() {
IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG);
IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_ENVIRONMENT, icebergHiveCatalog,
Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), null);
mockedNativeTableA.newFastAppend().appendFile(FILE_A).appendFile(FILE_A_1).commit();
IcebergTable icebergTable = new IcebergTable(1, "srTableName", CATALOG_NAME, "resource_name", "db_name",
"table_name", "", Lists.newArrayList(), mockedNativeTableA, Maps.newHashMap());
Map<ColumnRefOperator, Column> colRefToColumnMetaMap = new HashMap<ColumnRefOperator, Column>();
ColumnRefOperator columnRefOperator1 = new ColumnRefOperator(3, Type.INT, "id", true);
ColumnRefOperator columnRefOperator2 = new ColumnRefOperator(4, Type.STRING, "data", true);
colRefToColumnMetaMap.put(columnRefOperator1, new Column("id", Type.INT));
colRefToColumnMetaMap.put(columnRefOperator2, new Column("data", Type.STRING));
OptimizerContext context = new OptimizerContext(new Memo(), new ColumnRefFactory());
Assert.assertFalse(context.getSessionVariable().enableIcebergColumnStatistics());
Assert.assertTrue(context.getSessionVariable().enableReadIcebergPuffinNdv());
TableVersionRange versionRange = TableVersionRange.withEnd(Optional.of(
mockedNativeTableA.currentSnapshot().snapshotId()));
Statistics statistics = metadata.getTableStatistics(
context, icebergTable, colRefToColumnMetaMap, null, null, -1, versionRange);
Assert.assertEquals(4.0, statistics.getOutputRowCount(), 0.001);
Assert.assertEquals(2, statistics.getColumnStatistics().size());
Assert.assertTrue(statistics.getColumnStatistic(columnRefOperator1).isUnknown());
Assert.assertTrue(statistics.getColumnStatistic(columnRefOperator2).isUnknown());
} |
public Optional<UfsStatus[]> listFromUfs(String path, boolean isRecursive)
throws IOException {
ListOptions ufsListOptions = ListOptions.defaults().setRecursive(isRecursive);
UnderFileSystem ufs = getUfsInstance(path);
try {
UfsStatus[] listResults = ufs.listStatus(path, ufsListOptions);
if (listResults != null) {
return Optional.of(listResults);
}
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
throw e;
}
}
// TODO(yimin) put the ufs status into the metastore
// If list does not give a result,
// the request path might either be a regular file/object or not exist.
// Try getStatus() instead.
try {
UfsStatus status = ufs.getStatus(path);
if (status == null) {
return Optional.empty();
}
// Success. Create an array with only one element.
status.setName(""); // listStatus() expects relative name to the @path.
return Optional.of(new UfsStatus[] {status});
} catch (FileNotFoundException e) {
return Optional.empty();
}
} | @Test
public void listFromUfsGetWhenGetSuccess() throws IOException {
UnderFileSystem system = mock(UnderFileSystem.class);
UfsStatus fakeStatus = mock(UfsStatus.class);
when(system.listStatus(anyString())).thenReturn(null);
when(system.getStatus(anyString())).thenReturn(fakeStatus);
doReturn(system).when(mDoraUfsManager).getOrAdd(any(), any());
Optional<UfsStatus[]> status = mManager.listFromUfs("/test", false);
assertEquals(status.get()[0], fakeStatus);
} |
@Override
public String convertToDatabaseColumn(MonetaryAmount amount) {
return amount == null ? null
: String.format("%s %s", amount.getCurrency().toString(), amount.getNumber().toString());
} | @Test
void doesNotRoundValues() {
assertThat(converter.convertToDatabaseColumn(Money.of(1.23456, "EUR"))).isEqualTo("EUR 1.23456");
} |
public static void checkArgument(boolean isValid, String message) throws IllegalArgumentException {
if (!isValid) {
throw new IllegalArgumentException(message);
}
} | @Test
public void testCheckArgumentWithThreeParams() {
try {
Preconditions.checkArgument(true, "Test message %s %s %s", 12, null, "column");
} catch (IllegalArgumentException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkArgument(false, "Test message %s %s %s", 12, null, "column");
Assert.fail("Should throw exception when isValid is false");
} catch (IllegalArgumentException e) {
Assert.assertEquals("Should format message", "Test message 12 null column", e.getMessage());
}
} |
protected final void setAccessExpireTime(K key, Expirable<?> expirable, long currentTimeMS) {
try {
Duration duration = expiry.getExpiryForAccess();
if (duration == null) {
return;
} else if (duration.isZero()) {
expirable.setExpireTimeMS(0L);
} else if (duration.isEternal()) {
expirable.setExpireTimeMS(Long.MAX_VALUE);
} else {
if (currentTimeMS == 0L) {
currentTimeMS = currentTimeMillis();
}
long expireTimeMS = duration.getAdjustedTime(currentTimeMS);
expirable.setExpireTimeMS(expireTimeMS);
}
cache.policy().expireVariably().ifPresent(policy -> {
policy.setExpiresAfter(key, duration.getDurationAmount(), duration.getTimeUnit());
});
} catch (RuntimeException e) {
logger.log(Level.WARNING, "Failed to set the entry's expiration time", e);
}
} | @Test
public void setAccessExpireTime_exception() {
when(expiry.getExpiryForAccess()).thenThrow(IllegalStateException.class);
var expirable = new Expirable<Integer>(KEY_1, 0);
jcache.setAccessExpireTime(KEY_1, expirable, 0);
assertThat(expirable.getExpireTimeMS()).isEqualTo(0);
} |
DescriptorDigest getDigestFromFilename(Path layerFile) throws CacheCorruptedException {
try {
String hash = layerFile.getFileName().toString();
return DescriptorDigest.fromHash(hash);
} catch (DigestException | IndexOutOfBoundsException ex) {
throw new CacheCorruptedException(
cacheDirectory, "Layer file did not include valid hash: " + layerFile, ex);
}
} | @Test
public void testGetDiffId() throws DigestException, CacheCorruptedException {
Assert.assertEquals(
DescriptorDigest.fromHash(
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),
TEST_CACHE_STORAGE_FILES.getDigestFromFilename(
Paths.get(
"layer",
"file",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")));
Assert.assertEquals(
DescriptorDigest.fromHash(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
TEST_CACHE_STORAGE_FILES.getDigestFromFilename(
Paths.get("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")));
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently available in the standard converters
final JsonNode value = isJsonSchema
? JsonSerdeUtils.readJsonSR(bytes, MAPPER, JsonNode.class)
: MAPPER.readTree(bytes);
final Object coerced = enforceFieldType(
"$",
new JsonValueContext(value, schema)
);
if (LOG.isTraceEnabled()) {
LOG.trace("Deserialized {}. topic:{}, row:{}", target, topic, coerced);
}
return SerdeUtils.castToTargetType(coerced, targetType);
} catch (final Exception e) {
// Clear location in order to avoid logging data, for security reasons
if (e instanceof JsonParseException) {
((JsonParseException) e).clearLocation();
}
throw new SerializationException(
"Failed to deserialize " + target + " from topic: " + topic + ". " + e.getMessage(), e);
}
} | @Test
public void shouldNotIncludeBadValueInExceptionAsThatWouldBeASecurityIssue() {
// Given:
final KsqlJsonDeserializer<Long> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_INT64_SCHEMA, Long.class);
final byte[] bytes = "\"personal info: do not log me\"".getBytes(StandardCharsets.UTF_8);
try {
// When:
deserializer.deserialize(SOME_TOPIC, bytes);
fail("Invalid test: should throw");
} catch (final Exception e) {
assertThat(ExceptionUtils.getStackTrace(e), not(containsString("personal info")));
}
} |
public static <T> PCollections<T> pCollections() {
return new PCollections<>();
} | @Test
@Category(ValidatesRunner.class)
public void testFlattenPCollectionsSingletonList() {
PCollection<String> input = p.apply(Create.of(LINES));
PCollection<String> output = PCollectionList.of(input).apply(Flatten.pCollections());
assertThat(output, not(equalTo(input)));
PAssert.that(output).containsInAnyOrder(LINES);
p.run();
} |
public static Class<?> getGenericClass(Class<?> cls) {
return getGenericClass(cls, 0);
} | @Test
void testGetGenericClassWithIndex() {
assertThat(ReflectUtils.getGenericClass(Foo1.class, 0), sameInstance(String.class));
assertThat(ReflectUtils.getGenericClass(Foo1.class, 1), sameInstance(Integer.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 0), sameInstance(List.class));
assertThat(ReflectUtils.getGenericClass(Foo2.class, 1), sameInstance(int.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 0), sameInstance(Foo1.class));
assertThat(ReflectUtils.getGenericClass(Foo3.class, 1), sameInstance(Foo2.class));
} |
public WriteResult<T, K> save(T object) {
return save(object, null);
} | @Test
void save() {
final var collection = jacksonCollection("simple", Simple.class);
final var foo = new Simple("000000000000000000000001", "foo");
final var saveFooResult = collection.save(foo);
assertThat(saveFooResult.getSavedObject()).isEqualTo(foo);
assertThat(collection.findOneById(saveFooResult.getSavedId())).isEqualTo(foo);
final Simple updated = new Simple(foo.id(), "baz");
final var saveUpdatedResult = collection.save(updated);
assertThat(saveUpdatedResult.getSavedObject()).isEqualTo(updated);
assertThat(collection.findOneById(foo.id())).isEqualTo(updated);
final var saveBarResult = collection.save(new Simple(null, "bar"));
assertThat(collection.findOneById(saveBarResult.getSavedId()).name()).isEqualTo("bar");
assertThatThrownBy(() -> collection.save(foo, WriteConcern.W2))
.isInstanceOf(MongoCommandException.class)
.hasMessageContaining("cannot use 'w' > 1 when a host is not replicated");
} |
int decreaseAndGet(final WorkerResourceSpec workerResourceSpec) {
final Integer newValue =
workerNums.compute(
Preconditions.checkNotNull(workerResourceSpec),
(ignored, num) -> {
Preconditions.checkState(
num != null && num > 0,
"Cannot decrease, no worker of spec %s.",
workerResourceSpec);
return num == 1 ? null : num - 1;
});
return newValue != null ? newValue : 0;
} | @Test
void testWorkerCounterDecreaseOnZero() {
final WorkerResourceSpec spec = new WorkerResourceSpec.Builder().build();
final WorkerCounter counter = new WorkerCounter();
assertThatThrownBy(() -> counter.decreaseAndGet(spec))
.isInstanceOf(IllegalStateException.class);
} |
@Override
protected void validateDataImpl(TenantId tenantId, DeviceProfile deviceProfile) {
validateString("Device profile name", deviceProfile.getName());
if (deviceProfile.getType() == null) {
throw new DataValidationException("Device profile type should be specified!");
}
if (deviceProfile.getTransportType() == null) {
throw new DataValidationException("Device profile transport type should be specified!");
}
if (deviceProfile.getTenantId() == null) {
throw new DataValidationException("Device profile should be assigned to tenant!");
} else {
if (!tenantService.tenantExists(deviceProfile.getTenantId())) {
throw new DataValidationException("Device profile is referencing to non-existent tenant!");
}
}
if (deviceProfile.isDefault()) {
DeviceProfile defaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(tenantId);
if (defaultDeviceProfile != null && !defaultDeviceProfile.getId().equals(deviceProfile.getId())) {
throw new DataValidationException("Another default device profile is present in scope of current tenant!");
}
}
if (StringUtils.isNotEmpty(deviceProfile.getDefaultQueueName())) {
Queue queue = queueService.findQueueByTenantIdAndName(tenantId, deviceProfile.getDefaultQueueName());
if (queue == null) {
throw new DataValidationException("Device profile is referencing to non-existent queue!");
}
}
if (deviceProfile.getProvisionType() == null) {
deviceProfile.setProvisionType(DeviceProfileProvisionType.DISABLED);
}
if (deviceProfile.getProvisionDeviceKey() != null && DeviceProfileProvisionType.X509_CERTIFICATE_CHAIN.equals(deviceProfile.getProvisionType())) {
if (isDeviceProfileCertificateInJavaCacerts(deviceProfile.getProfileData().getProvisionConfiguration().getProvisionDeviceSecret())) {
throw new DataValidationException("Device profile certificate cannot be well known root CA!");
}
}
DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration();
transportConfiguration.validate();
if (transportConfiguration instanceof MqttDeviceProfileTransportConfiguration) {
MqttDeviceProfileTransportConfiguration mqttTransportConfiguration = (MqttDeviceProfileTransportConfiguration) transportConfiguration;
if (mqttTransportConfiguration.getTransportPayloadTypeConfiguration() instanceof ProtoTransportPayloadConfiguration) {
ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration =
(ProtoTransportPayloadConfiguration) mqttTransportConfiguration.getTransportPayloadTypeConfiguration();
validateProtoSchemas(protoTransportPayloadConfiguration);
validateTelemetryDynamicMessageFields(protoTransportPayloadConfiguration);
validateRpcRequestDynamicMessageFields(protoTransportPayloadConfiguration);
}
} else if (transportConfiguration instanceof CoapDeviceProfileTransportConfiguration) {
CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration;
CoapDeviceTypeConfiguration coapDeviceTypeConfiguration = coapDeviceProfileTransportConfiguration.getCoapDeviceTypeConfiguration();
if (coapDeviceTypeConfiguration instanceof DefaultCoapDeviceTypeConfiguration) {
DefaultCoapDeviceTypeConfiguration defaultCoapDeviceTypeConfiguration = (DefaultCoapDeviceTypeConfiguration) coapDeviceTypeConfiguration;
TransportPayloadTypeConfiguration transportPayloadTypeConfiguration = defaultCoapDeviceTypeConfiguration.getTransportPayloadTypeConfiguration();
if (transportPayloadTypeConfiguration instanceof ProtoTransportPayloadConfiguration) {
ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = (ProtoTransportPayloadConfiguration) transportPayloadTypeConfiguration;
validateProtoSchemas(protoTransportPayloadConfiguration);
validateTelemetryDynamicMessageFields(protoTransportPayloadConfiguration);
validateRpcRequestDynamicMessageFields(protoTransportPayloadConfiguration);
}
}
} else if (transportConfiguration instanceof Lwm2mDeviceProfileTransportConfiguration) {
List<LwM2MBootstrapServerCredential> lwM2MBootstrapServersConfigurations = ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).getBootstrap();
if (lwM2MBootstrapServersConfigurations != null) {
validateLwm2mServersConfigOfBootstrapForClient(lwM2MBootstrapServersConfigurations,
((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable());
for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) {
validateLwm2mServersCredentialOfBootstrapForClient(bootstrapServerCredential);
}
}
}
List<DeviceProfileAlarm> profileAlarms = deviceProfile.getProfileData().getAlarms();
if (!CollectionUtils.isEmpty(profileAlarms)) {
Set<String> alarmTypes = new HashSet<>();
for (DeviceProfileAlarm alarm : profileAlarms) {
String alarmType = alarm.getAlarmType();
if (StringUtils.isEmpty(alarmType)) {
throw new DataValidationException("Alarm rule type should be specified!");
}
if (!alarmTypes.add(alarmType)) {
throw new DataValidationException(String.format("Can't create device profile with the same alarm rule types: \"%s\"!", alarmType));
}
}
}
if (deviceProfile.getDefaultRuleChainId() != null) {
RuleChain ruleChain = ruleChainService.findRuleChainById(tenantId, deviceProfile.getDefaultRuleChainId());
if (ruleChain == null) {
throw new DataValidationException("Can't assign non-existent rule chain!");
}
if (!ruleChain.getTenantId().equals(deviceProfile.getTenantId())) {
throw new DataValidationException("Can't assign rule chain from different tenant!");
}
}
if (deviceProfile.getDefaultDashboardId() != null) {
DashboardInfo dashboard = dashboardService.findDashboardInfoById(tenantId, deviceProfile.getDefaultDashboardId());
if (dashboard == null) {
throw new DataValidationException("Can't assign non-existent dashboard!");
}
if (!dashboard.getTenantId().equals(deviceProfile.getTenantId())) {
throw new DataValidationException("Can't assign dashboard from different tenant!");
}
}
validateOtaPackage(tenantId, deviceProfile, deviceProfile.getId());
} | @Test
void testValidateNameInvocation() {
DeviceProfile deviceProfile = new DeviceProfile();
deviceProfile.setName("default");
deviceProfile.setType(DeviceProfileType.DEFAULT);
deviceProfile.setTransportType(DeviceTransportType.DEFAULT);
DeviceProfileData data = new DeviceProfileData();
data.setTransportConfiguration(new DefaultDeviceProfileTransportConfiguration());
deviceProfile.setProfileData(data);
deviceProfile.setTenantId(tenantId);
validator.validateDataImpl(tenantId, deviceProfile);
verify(validator).validateString("Device profile name", deviceProfile.getName());
} |
@Override
public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) {
return uploadSegment(segmentFile, segmentName, _timeoutInMs);
} | @Test
public void testNoSegmentStoreConfigured() {
SegmentUploader segmentUploader = new PinotFSSegmentUploader("", TIMEOUT_IN_MS, _serverMetrics);
URI segmentURI = segmentUploader.uploadSegment(_file, _llcSegmentName);
Assert.assertNull(segmentURI);
} |
@Override
public void deleteConfig(Long id) {
// 校验配置存在
ConfigDO config = validateConfigExists(id);
// 内置配置,不允许删除
if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) {
throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE);
}
// 删除
configMapper.deleteById(id);
} | @Test
public void testDeleteConfig_canNotDeleteSystemType() {
// mock 数据
ConfigDO dbConfig = randomConfigDO(o -> {
o.setType(ConfigTypeEnum.SYSTEM.getType()); // SYSTEM 不允许删除
});
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbConfig.getId();
// 调用, 并断言异常
assertServiceException(() -> configService.deleteConfig(id), CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE);
} |
public static void start(IDetachedRunnable runnable, Object... args)
{
// Prepare child thread
Thread shim = new ShimThread(runnable, args);
shim.setDaemon(true);
shim.start();
} | @Test
public void testDetached()
{
final CountDownLatch stopped = new CountDownLatch(1);
ZThread.start((args) -> {
try (ZContext ctx = new ZContext()) {
Socket push = ctx.createSocket(SocketType.PUSH);
assertThat(push, notNullValue());
}
stopped.countDown();
});
try {
stopped.await();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
} |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithMultipleLineFeedCharacter() {
CharSequence value = "\n\n";
CharSequence expected = "\"\n\n\"";
escapeCsv(value, expected);
} |
public String defaultRemoteUrl() {
final String sanitizedUrl = sanitizeUrl();
try {
URI uri = new URI(sanitizedUrl);
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
return uri.toString();
}
} catch (URISyntaxException e) {
return sanitizedUrl;
}
return sanitizedUrl;
} | @Test
void shouldReturnAURLWhenPasswordIsNotSpecified() {
assertThat(new HgUrlArgument("http://user@url##branch").defaultRemoteUrl(), is("http://user@url#branch"));
} |
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders,
FullHttpMessage destinationMessage, boolean addToTrailer) throws Http2Exception {
addHttp2ToHttpHeaders(streamId, inputHeaders,
addToTrailer ? destinationMessage.trailingHeaders() : destinationMessage.headers(),
destinationMessage.protocolVersion(), addToTrailer, destinationMessage instanceof HttpRequest);
} | @Test
public void http2ToHttpHeaderTest() throws Exception {
Http2Headers http2Headers = new DefaultHttp2Headers();
http2Headers.status("200");
http2Headers.path("/meow"); // HTTP/2 Header response should not contain 'path' in response.
http2Headers.set("cat", "meow");
HttpHeaders httpHeaders = new DefaultHttpHeaders();
HttpConversionUtil.addHttp2ToHttpHeaders(3, http2Headers, httpHeaders, HttpVersion.HTTP_1_1, false, true);
assertFalse(httpHeaders.contains(HttpConversionUtil.ExtensionHeaderNames.PATH.text()));
assertEquals("meow", httpHeaders.get("cat"));
httpHeaders.clear();
HttpConversionUtil.addHttp2ToHttpHeaders(3, http2Headers, httpHeaders, HttpVersion.HTTP_1_1, false, false);
assertTrue(httpHeaders.contains(HttpConversionUtil.ExtensionHeaderNames.PATH.text()));
assertEquals("meow", httpHeaders.get("cat"));
} |
@Override
public ExecutionResult toExecutionResult(String responseBody) {
ExecutionResult executionResult = new ExecutionResult();
ArrayList<String> exceptions = new ArrayList<>();
try {
Map result = (Map) GSON.fromJson(responseBody, Object.class);
if (!(result.containsKey("success") && result.get("success") instanceof Boolean)) {
exceptions.add("The Json for Execution Result must contain a not-null 'success' field of type Boolean");
}
if (result.containsKey("message") && (!(result.get("message") instanceof String))) {
exceptions.add("If the 'message' key is present in the Json for Execution Result, it must contain a not-null message of type String");
}
if (!exceptions.isEmpty()) {
throw new RuntimeException(StringUtils.join(exceptions, ", "));
}
if ((Boolean) result.get("success")) {
executionResult.withSuccessMessages((String) result.get("message"));
} else {
executionResult.withErrorMessages((String) result.get("message"));
}
return executionResult;
} catch (Exception e) {
LOGGER.error("Error occurred while converting the Json to Execution Result. Error: {}. The Json received was '{}'.", e.getMessage(), responseBody);
throw new RuntimeException(String.format("Error occurred while converting the Json to Execution Result. Error: %s.", e.getMessage()));
}
} | @Test
public void shouldConstructExecutionResultFromFailureExecutionResponse() {
GoPluginApiResponse response = mock(GoPluginApiResponse.class);
when(response.responseBody()).thenReturn("{\"success\":false,\"message\":\"error1\"}");
ExecutionResult result = new JsonBasedTaskExtensionHandler_V1().toExecutionResult(response.responseBody());
assertThat(result.isSuccessful(), is(false));
assertThat(result.getMessagesForDisplay(), is("error1"));
} |
@Override
public Executor getExecutor(URL url) {
String name =
url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));
int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS);
int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);
BlockingQueue<Runnable> blockingQueue;
if (queues == 0) {
blockingQueue = new SynchronousQueue<>();
} else if (queues < 0) {
blockingQueue = new MemorySafeLinkedBlockingQueue<>();
} else {
blockingQueue = new LinkedBlockingQueue<>(queues);
}
return new ThreadPoolExecutor(
threads,
threads,
0,
TimeUnit.MILLISECONDS,
blockingQueue,
new NamedInternalThreadFactory(name, true),
new AbortPolicyWithReport(name, url));
} | @Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new FixedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(2));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(0L));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
}
});
latch.await();
assertThat(latch.getCount(), is(0L));
} |
public static Map<TopicPartition, ListOffsetsResultInfo> fetchEndOffsets(final Collection<TopicPartition> partitions,
final Admin adminClient) {
if (partitions.isEmpty()) {
return Collections.emptyMap();
}
return getEndOffsets(fetchEndOffsetsFuture(partitions, adminClient));
} | @Test
public void fetchEndOffsetsShouldRethrowRuntimeExceptionAsStreamsException() throws Exception {
final Admin adminClient = mock(AdminClient.class);
final ListOffsetsResult result = mock(ListOffsetsResult.class);
@SuppressWarnings("unchecked")
final KafkaFuture<Map<TopicPartition, ListOffsetsResultInfo>> allFuture = mock(KafkaFuture.class);
when(adminClient.listOffsets(any())).thenReturn(result);
when(result.all()).thenReturn(allFuture);
when(allFuture.get()).thenThrow(new RuntimeException());
assertThrows(StreamsException.class, () -> fetchEndOffsets(PARTITIONS, adminClient));
} |
public static Event createProfile(String name, @Nullable String data, @Nullable String description) {
return new Event(name, Category.PROFILE, data, description);
} | @Test
public void createProfile_fail_fast_null_check_on_null_name() {
assertThatThrownBy(() -> Event.createProfile(null, SOME_DATA, SOME_DESCRIPTION))
.isInstanceOf(NullPointerException.class);
} |
@Override
protected String getObjectDescription() {
return "Artifact store";
} | @Test
public void shouldReturnObjectDescription() {
assertThat(new ArtifactStore().getObjectDescription(), is("Artifact store"));
} |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldFailForCheckingComplexTypeEquality() {
// Given:
final Expression expression = new ComparisonExpression(Type.EQUAL, MAPCOL, ADDRESS);
// When:
final KsqlStatementException e = assertThrows(
KsqlStatementException.class,
() -> expressionTypeManager.getExpressionSqlType(expression)
);
// Then:
assertThat(e.getMessage(), containsString(
"Cannot compare MAP<BIGINT, DOUBLE> "
+ "to STRUCT<`NUMBER` BIGINT, `STREET` STRING, `CITY` STRING,"
+ " `STATE` STRING, `ZIPCODE` BIGINT> with EQUAL."
));
assertThat(e.getUnloggedMessage(), containsString(
"Cannot compare COL5 (MAP<BIGINT, DOUBLE>) to COL6 "
+ "(STRUCT<`NUMBER` BIGINT, `STREET` STRING, `CITY` STRING, `STATE` STRING, "
+ "`ZIPCODE` BIGINT>) with EQUAL"
));
} |
public List<ServiceInstance> findAllInstancesInNotRunningState() {
return jdbcRepository.getDslContextWrapper().transactionResult(
configuration -> findAllInstancesInNotRunningState(configuration, false)
);
} | @Test
protected void shouldFindAllInstancesInNotRunningState() {
// Given
AbstractJdbcServiceInstanceRepositoryTest.Fixtures.all().forEach(repository::save);
// When
List<ServiceInstance> results = repository.findAllInstancesInNotRunningState();
// Then
assertEquals(AbstractJdbcServiceInstanceRepositoryTest.Fixtures.allInNotRunningState().size(), results.size());
assertThat(results, Matchers.containsInAnyOrder(AbstractJdbcServiceInstanceRepositoryTest.Fixtures.allInNotRunningState().toArray()));
} |
@Override
public Address getThisNodesAddress() {
// no need to implement this for client part
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetThisNodesAddress() {
context.getThisNodesAddress();
} |
@Override
public CompressionOutputStream createOutputStream( OutputStream out ) throws IOException {
return new NoneCompressionOutputStream( out, this );
} | @Test
public void testCreateOutputStream() throws IOException {
NoneCompressionProvider provider = (NoneCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME );
ByteArrayOutputStream out = new ByteArrayOutputStream();
NoneCompressionOutputStream outStream = new NoneCompressionOutputStream( out, provider );
assertNotNull( outStream );
NoneCompressionOutputStream ncis = (NoneCompressionOutputStream) provider.createOutputStream( out );
assertNotNull( ncis );
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently available in the standard converters
final JsonNode value = isJsonSchema
? JsonSerdeUtils.readJsonSR(bytes, MAPPER, JsonNode.class)
: MAPPER.readTree(bytes);
final Object coerced = enforceFieldType(
"$",
new JsonValueContext(value, schema)
);
if (LOG.isTraceEnabled()) {
LOG.trace("Deserialized {}. topic:{}, row:{}", target, topic, coerced);
}
return SerdeUtils.castToTargetType(coerced, targetType);
} catch (final Exception e) {
// Clear location in order to avoid logging data, for security reasons
if (e instanceof JsonParseException) {
((JsonParseException) e).clearLocation();
}
throw new SerializationException(
"Failed to deserialize " + target + " from topic: " + topic + ". " + e.getMessage(), e);
}
} | @Test
public void shouldThrowIfCanNotCoerceToBigInt() {
// Given:
final KsqlJsonDeserializer<Long> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_INT64_SCHEMA, Long.class);
final byte[] bytes = serializeJson(BooleanNode.valueOf(true));
// When:
final Exception e = assertThrows(
SerializationException.class,
() -> deserializer.deserialize(SOME_TOPIC, bytes)
);
// Then:
assertThat(e.getCause(), (hasMessage(startsWith(
"Can't convert type. sourceType: BooleanNode, requiredType: BIGINT"))));
} |
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException {
if (response.length == 1 && response[0] == OAuthBearerSaslClient.BYTE_CONTROL_A && errorMessage != null) {
log.debug("Received %x01 response from client after it received our error");
throw new SaslAuthenticationException(errorMessage);
}
errorMessage = null;
OAuthBearerClientInitialResponse clientResponse;
try {
clientResponse = new OAuthBearerClientInitialResponse(response);
} catch (SaslException e) {
log.debug(e.getMessage());
throw e;
}
return process(clientResponse.tokenValue(), clientResponse.authorizationId(), clientResponse.extensions());
} | @Test
public void authorizationIdEqualsAuthenticationId() throws Exception {
byte[] nextChallenge = saslServer
.evaluateResponse(clientInitialResponse(USER));
assertEquals(0, nextChallenge.length, "Next challenge is not empty");
} |
public ConsumerGroup consumerGroup(
String groupId,
long committedOffset
) throws GroupIdNotFoundException {
Group group = group(groupId, committedOffset);
if (group.type() == CONSUMER) {
return (ConsumerGroup) group;
} else {
// We don't support upgrading/downgrading between protocols at the moment so
// we throw an exception if a group exists with the wrong type.
throw new GroupIdNotFoundException(String.format("Group %s is not a consumer group.",
groupId));
}
} | @Test
public void testJoiningConsumerGroupWithExistingStaticMemberAndNewSubscription() throws Exception {
String groupId = "group-id";
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
Uuid barTopicId = Uuid.randomUuid();
String barTopicName = "bar";
Uuid zarTopicId = Uuid.randomUuid();
String zarTopicName = "zar";
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
String instanceId = "instance-id";
MockPartitionAssignor assignor = new MockPartitionAssignor("range");
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.withConsumerGroupAssignors(Collections.singletonList(assignor))
.withMetadataImage(new MetadataImageBuilder()
.addTopic(fooTopicId, fooTopicName, 2)
.addTopic(barTopicId, barTopicName, 1)
.addTopic(zarTopicId, zarTopicName, 1)
.addRacks()
.build())
.withConsumerGroup(new ConsumerGroupBuilder(groupId, 10)
.withSubscriptionMetadata(new HashMap<String, TopicMetadata>() {
{
put(fooTopicName, new TopicMetadata(fooTopicId, fooTopicName, 2, mkMapOfPartitionRacks(2)));
put(barTopicName, new TopicMetadata(barTopicId, barTopicName, 1, mkMapOfPartitionRacks(1)));
put(zarTopicName, new TopicMetadata(zarTopicId, zarTopicName, 1, mkMapOfPartitionRacks(1)));
}
})
.withMember(new ConsumerGroupMember.Builder(memberId1)
.setInstanceId(instanceId)
.setState(MemberState.STABLE)
.setMemberEpoch(10)
.setPreviousMemberEpoch(10)
.setRebalanceTimeoutMs(500)
.setClientId(DEFAULT_CLIENT_ID)
.setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
.setSubscribedTopicNames(Arrays.asList(fooTopicName, barTopicName))
.setAssignedPartitions(mkAssignment(
mkTopicAssignment(fooTopicId, 0),
mkTopicAssignment(barTopicId, 0)))
.setClassicMemberMetadata(
new ConsumerGroupMemberMetadataValue.ClassicMemberMetadata()
.setSessionTimeoutMs(5000)
.setSupportedProtocols(ConsumerGroupMember.classicProtocolListFromJoinRequestProtocolCollection(
GroupMetadataManagerTestContext.toConsumerProtocol(
Arrays.asList(fooTopicName, barTopicName),
Arrays.asList(new TopicPartition(fooTopicName, 0), new TopicPartition(fooTopicName, 1))
)
))
)
.build())
.withMember(new ConsumerGroupMember.Builder(memberId2)
.setState(MemberState.STABLE)
.setMemberEpoch(10)
.setPreviousMemberEpoch(10)
.setRebalanceTimeoutMs(500)
.setClientId(DEFAULT_CLIENT_ID)
.setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
.setSubscribedTopicNames(Arrays.asList(fooTopicName, barTopicName))
.setAssignedPartitions(mkAssignment(
mkTopicAssignment(fooTopicId, 1)))
.build())
.withAssignment(memberId1, mkAssignment(
mkTopicAssignment(fooTopicId, 0),
mkTopicAssignment(barTopicId, 0)))
.withAssignment(memberId2, mkAssignment(
mkTopicAssignment(fooTopicId, 1)))
.withAssignmentEpoch(10))
.build();
ConsumerGroup group = context.groupMetadataManager.consumerGroup(groupId);
group.setMetadataRefreshDeadline(Long.MAX_VALUE, 11);
assignor.prepareGroupAssignment(new GroupAssignment(
new HashMap<String, MemberAssignment>() {
{
put(memberId1, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 0),
mkTopicAssignment(zarTopicId, 0)
)));
put(memberId2, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(barTopicId, 0),
mkTopicAssignment(fooTopicId, 1)
)));
}
}
));
// Member 1 rejoins with a new subscription list.
JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
.withGroupId(groupId)
.withMemberId(memberId1)
.withProtocols(GroupMetadataManagerTestContext.toConsumerProtocol(
Arrays.asList(fooTopicName, barTopicName, zarTopicName),
Collections.emptyList()))
.build();
GroupMetadataManagerTestContext.JoinResult joinResult = context.sendClassicGroupJoin(request);
ConsumerGroupMember expectedMember = new ConsumerGroupMember.Builder(memberId1)
.setInstanceId(instanceId)
.setMemberEpoch(11)
.setPreviousMemberEpoch(10)
.setRebalanceTimeoutMs(500)
.setClientId(DEFAULT_CLIENT_ID)
.setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
.setState(MemberState.STABLE)
.setSubscribedTopicNames(Arrays.asList(fooTopicName, barTopicName, zarTopicName))
.setAssignedPartitions(mkAssignment(
mkTopicAssignment(fooTopicId, 0),
mkTopicAssignment(zarTopicId, 0)))
.setClassicMemberMetadata(
new ConsumerGroupMemberMetadataValue.ClassicMemberMetadata()
.setSessionTimeoutMs(request.sessionTimeoutMs())
.setSupportedProtocols(ConsumerGroupMember.classicProtocolListFromJoinRequestProtocolCollection(
GroupMetadataManagerTestContext.toConsumerProtocol(
Arrays.asList(fooTopicName, barTopicName, zarTopicName),
Collections.emptyList()
)
))
)
.build();
List<CoordinatorRecord> expectedRecords = Arrays.asList(
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId, expectedMember),
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 11),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId, memberId1, mkAssignment(
mkTopicAssignment(fooTopicId, 0),
mkTopicAssignment(zarTopicId, 0))),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId, memberId2, mkAssignment(
mkTopicAssignment(barTopicId, 0),
mkTopicAssignment(fooTopicId, 1))),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentEpochRecord(groupId, 11),
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId, expectedMember)
);
assertRecordsEquals(expectedRecords.subList(0, 2), joinResult.records.subList(0, 2));
assertUnorderedListEquals(expectedRecords.subList(2, 4), joinResult.records.subList(2, 4));
assertRecordsEquals(expectedRecords.subList(4, 6), joinResult.records.subList(4, 6));
joinResult.appendFuture.complete(null);
assertEquals(
new JoinGroupResponseData()
.setMemberId(memberId1)
.setGenerationId(11)
.setProtocolType(ConsumerProtocol.PROTOCOL_TYPE)
.setProtocolName("range"),
joinResult.joinFuture.get()
);
context.assertSessionTimeout(groupId, memberId1, request.sessionTimeoutMs());
context.assertSyncTimeout(groupId, memberId1, request.rebalanceTimeoutMs());
} |
public static String getSimpleClassName(String qualifiedName) {
if (null == qualifiedName) {
return null;
}
int i = qualifiedName.lastIndexOf('.');
return i < 0 ? qualifiedName : qualifiedName.substring(i + 1);
} | @Test
void testGetSimpleClassName() {
Assertions.assertNull(ClassUtils.getSimpleClassName(null));
Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getName()));
Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName()));
} |
public long getLong(String key, long _default) {
Object object = map.get(key);
return object instanceof Number ? ((Number) object).longValue() : _default;
} | @Test
public void numericPropertyCanBeRetrievedAsLong() {
PMap subject = new PMap("foo=1234|bar=5678");
assertEquals(1234L, subject.getLong("foo", 0));
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
@SuppressWarnings("unchecked")
public void testDecodeStaticArrayValue() {
List<TypeReference<Type>> outputParameters = new ArrayList<>(1);
outputParameters.add(
(TypeReference)
new TypeReference.StaticArrayTypeReference<StaticArray<Uint256>>(2) {});
outputParameters.add((TypeReference) new TypeReference<Uint256>() {});
List<Type> decoded =
FunctionReturnDecoder.decode(
"0x0000000000000000000000000000000000000000000000000000000000000037"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "000000000000000000000000000000000000000000000000000000000000000a",
outputParameters);
StaticArray2<Uint256> uint256StaticArray2 =
new StaticArray2<>(
new Uint256(BigInteger.valueOf(55)), new Uint256(BigInteger.ONE));
List<Type> expected = Arrays.asList(uint256StaticArray2, new Uint256(BigInteger.TEN));
assertEquals(decoded, (expected));
} |
public int mul(int... nums) {
LOGGER.info("Arithmetic mul {}", VERSION);
return source.accumulateMul(nums);
} | @Test
void testMul() {
assertEquals(0, arithmetic.mul(-1, 0, 1));
} |
public static void load(Configuration conf, InputStream is) throws IOException {
conf.addResource(is);
} | @Test
public void constructors() throws Exception {
Configuration conf = new Configuration(false);
assertEquals(conf.size(), 0);
byte[] bytes = "<configuration><property><name>a</name><value>A</value></property></configuration>".getBytes();
InputStream is = new ByteArrayInputStream(bytes);
conf = new Configuration(false);
ConfigurationUtils.load(conf, is);
assertEquals(conf.size(), 1);
assertEquals(conf.get("a"), "A");
} |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
List<FlowObjectiveIntent> uninstallIntents = intentOperationContext.intentsToUninstall();
List<FlowObjectiveIntent> installIntents = intentOperationContext.intentsToInstall();
if (!toInstall.isPresent() && !toUninstall.isPresent()) {
intentInstallCoordinator.intentInstallSuccess(intentOperationContext);
return;
}
if (toUninstall.isPresent()) {
IntentData intentData = toUninstall.get();
trackerService.removeTrackedResources(intentData.key(), intentData.intent().resources());
uninstallIntents.forEach(installable ->
trackerService.removeTrackedResources(intentData.intent().key(),
installable.resources()));
}
if (toInstall.isPresent()) {
IntentData intentData = toInstall.get();
trackerService.addTrackedResources(intentData.key(), intentData.intent().resources());
installIntents.forEach(installable ->
trackerService.addTrackedResources(intentData.key(),
installable.resources()));
}
FlowObjectiveIntentInstallationContext intentInstallationContext =
new FlowObjectiveIntentInstallationContext(intentOperationContext);
uninstallIntents.stream()
.map(intent -> buildObjectiveContexts(intent, REMOVE))
.flatMap(Collection::stream)
.forEach(context -> {
context.intentInstallationContext(intentInstallationContext);
intentInstallationContext.addContext(context);
intentInstallationContext.addPendingContext(context);
});
installIntents.stream()
.map(intent -> buildObjectiveContexts(intent, ADD))
.flatMap(Collection::stream)
.forEach(context -> {
context.intentInstallationContext(intentInstallationContext);
intentInstallationContext.addContext(context);
intentInstallationContext.addNextPendingContext(context);
});
intentInstallationContext.apply();
} | @Test
public void testGroupAlreadyRemoved() {
// group already removed
intentInstallCoordinator = new TestIntentInstallCoordinator();
installer.intentInstallCoordinator = intentInstallCoordinator;
errors = ImmutableList.of(GROUPMISSING);
installer.flowObjectiveService = new TestFailedFlowObjectiveService(errors);
context = createUninstallContext();
installer.apply(context);
successContext = intentInstallCoordinator.successContext;
assertEquals(successContext, context);
} |
public static String extractAccountNameFromHostName(final String hostName) {
if (hostName == null || hostName.isEmpty()) {
return null;
}
if (!containsAbfsUrl(hostName)) {
return null;
}
String[] splitByDot = hostName.split("\\.");
if (splitByDot.length == 0) {
return null;
}
return splitByDot[0];
} | @Test
public void testExtractRawAccountName() throws Exception {
Assert.assertEquals("abfs", UriUtils.extractAccountNameFromHostName("abfs.dfs.core.windows.net"));
Assert.assertEquals("abfs", UriUtils.extractAccountNameFromHostName("abfs.dfs.preprod.core.windows.net"));
Assert.assertEquals(null, UriUtils.extractAccountNameFromHostName("abfs.dfs.cores.windows.net"));
Assert.assertEquals(null, UriUtils.extractAccountNameFromHostName(""));
Assert.assertEquals(null, UriUtils.extractAccountNameFromHostName(null));
Assert.assertEquals(null, UriUtils.extractAccountNameFromHostName("abfs.dfs.cores.windows.net"));
} |
@Override
public <V1, R> KTable<K, R> leftJoin(final KTable<K, V1> other,
final ValueJoiner<? super V, ? super V1, ? extends R> joiner) {
return leftJoin(other, joiner, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullOtherTableOnLeftJoin() {
assertThrows(NullPointerException.class, () -> table.leftJoin(null, MockValueJoiner.TOSTRING_JOINER));
} |
public static ContainerPort createContainerPort(String name, int port) {
return new ContainerPortBuilder()
.withName(name)
.withProtocol("TCP")
.withContainerPort(port)
.build();
} | @Test
public void testCreateContainerPort() {
ContainerPort port = ContainerUtils.createContainerPort("my-port", 1874);
assertThat(port.getName(), is("my-port"));
assertThat(port.getContainerPort(), is(1874));
assertThat(port.getProtocol(), is("TCP"));
} |
@Subscribe
public void inputUpdated(InputUpdated inputUpdatedEvent) {
final String inputId = inputUpdatedEvent.id();
LOG.debug("Input updated: {}", inputId);
final Input input;
try {
input = inputService.find(inputId);
} catch (NotFoundException e) {
LOG.warn("Received InputUpdated event but could not find input {}", inputId, e);
return;
}
final boolean startInput;
final IOState<MessageInput> inputState = inputRegistry.getInputState(inputId);
if (inputState != null) {
startInput = inputState.getState() == IOState.Type.RUNNING;
inputRegistry.remove(inputState);
} else {
startInput = false;
}
if (startInput && (input.isGlobal() || this.nodeId.getNodeId().equals(input.getNodeId()))) {
startInput(input);
}
} | @Test
public void inputUpdatedDoesNotStartLocalInputOnOtherNode() throws Exception {
final String inputId = "input-id";
final Input input = mock(Input.class);
@SuppressWarnings("unchecked")
final IOState<MessageInput> inputState = mock(IOState.class);
when(inputState.getState()).thenReturn(IOState.Type.RUNNING);
when(inputService.find(inputId)).thenReturn(input);
when(input.getNodeId()).thenReturn(OTHER_NODE_ID);
when(input.isGlobal()).thenReturn(false);
final MessageInput messageInput = mock(MessageInput.class);
when(inputService.getMessageInput(input)).thenReturn(messageInput);
listener.inputUpdated(InputUpdated.create(inputId));
verify(inputLauncher, never()).launch(messageInput);
} |
@Override
public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) {
refreshClassLoader(classLoader);
} | @Test
void testSerializable2() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.isCheckSerializable());
frameworkModel.destroy();
} |
@Override
public void initialize(ServerAbilities abilities) {
abilities.getRemoteAbility().setSupportRemoteConnection(true);
} | @Test
void testInitialize() {
RemoteAbilityInitializer initializer = new RemoteAbilityInitializer();
ServerAbilities serverAbilities = new ServerAbilities();
assertFalse(serverAbilities.getRemoteAbility().isSupportRemoteConnection());
initializer.initialize(serverAbilities);
assertTrue(serverAbilities.getRemoteAbility().isSupportRemoteConnection());
} |
public Matrix aat() {
Matrix C = new Matrix(m, m);
C.mm(NO_TRANSPOSE, this, TRANSPOSE, this);
C.uplo(LOWER);
return C;
} | @Test
public void testAAT() {
System.out.println("AAT");
Matrix c = matrix.aat();
assertEquals(c.nrow(), 3);
assertEquals(c.ncol(), 3);
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < C[i].length; j++) {
assertEquals(C[i][j], c.get(i, j), 1E-7);
}
}
} |
@SuppressWarnings("unchecked")
@Override
public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request)
throws YarnException, IOException {
NodeStatus remoteNodeStatus = request.getNodeStatus();
/**
* Here is the node heartbeat sequence...
* 1. Check if it's a valid (i.e. not excluded) node
* 2. Check if it's a registered node
* 3. Check if it's a 'fresh' heartbeat i.e. not duplicate heartbeat
* 4. Send healthStatus to RMNode
* 5. Update node's labels if distributed Node Labels configuration is enabled
*/
NodeId nodeId = remoteNodeStatus.getNodeId();
// 1. Check if it's a valid (i.e. not excluded) node, if not, see if it is
// in decommissioning.
if (!this.nodesListManager.isValidNode(nodeId.getHost())
&& !isNodeInDecommissioning(nodeId)) {
String message =
"Disallowed NodeManager nodeId: " + nodeId + " hostname: "
+ nodeId.getHost();
LOG.info(message);
return YarnServerBuilderUtils.newNodeHeartbeatResponse(
NodeAction.SHUTDOWN, message);
}
// 2. Check if it's a registered node
RMNode rmNode = this.rmContext.getRMNodes().get(nodeId);
if (rmNode == null) {
/* node does not exist */
String message = "Node not found resyncing " + remoteNodeStatus.getNodeId();
LOG.info(message);
return YarnServerBuilderUtils.newNodeHeartbeatResponse(NodeAction.RESYNC,
message);
}
// Send ping
this.nmLivelinessMonitor.receivedPing(nodeId);
this.decommissioningWatcher.update(rmNode, remoteNodeStatus);
// 3. Check if it's a 'fresh' heartbeat i.e. not duplicate heartbeat
NodeHeartbeatResponse lastNodeHeartbeatResponse = rmNode.getLastNodeHeartBeatResponse();
if (getNextResponseId(
remoteNodeStatus.getResponseId()) == lastNodeHeartbeatResponse
.getResponseId()) {
LOG.info("Received duplicate heartbeat from node "
+ rmNode.getNodeAddress()+ " responseId=" + remoteNodeStatus.getResponseId());
return lastNodeHeartbeatResponse;
} else if (remoteNodeStatus.getResponseId() != lastNodeHeartbeatResponse
.getResponseId()) {
String message =
"Too far behind rm response id:"
+ lastNodeHeartbeatResponse.getResponseId() + " nm response id:"
+ remoteNodeStatus.getResponseId();
LOG.info(message);
// TODO: Just sending reboot is not enough. Think more.
this.rmContext.getDispatcher().getEventHandler().handle(
new RMNodeEvent(nodeId, RMNodeEventType.REBOOTING));
return YarnServerBuilderUtils.newNodeHeartbeatResponse(NodeAction.RESYNC,
message);
}
// Evaluate whether a DECOMMISSIONING node is ready to be DECOMMISSIONED.
if (rmNode.getState() == NodeState.DECOMMISSIONING &&
decommissioningWatcher.checkReadyToBeDecommissioned(
rmNode.getNodeID())) {
String message = "DECOMMISSIONING " + nodeId +
" is ready to be decommissioned";
LOG.info(message);
this.rmContext.getDispatcher().getEventHandler().handle(
new RMNodeEvent(nodeId, RMNodeEventType.DECOMMISSION));
this.nmLivelinessMonitor.unregister(nodeId);
return YarnServerBuilderUtils.newNodeHeartbeatResponse(
NodeAction.SHUTDOWN, message);
}
if (timelineServiceV2Enabled) {
// Check & update collectors info from request.
updateAppCollectorsMap(request);
}
// Heartbeat response
long newInterval = nextHeartBeatInterval;
if (heartBeatIntervalScalingEnable) {
newInterval = rmNode.calculateHeartBeatInterval(
nextHeartBeatInterval, heartBeatIntervalMin,
heartBeatIntervalMax, heartBeatIntervalSpeedupFactor,
heartBeatIntervalSlowdownFactor);
}
NodeHeartbeatResponse nodeHeartBeatResponse =
YarnServerBuilderUtils.newNodeHeartbeatResponse(
getNextResponseId(lastNodeHeartbeatResponse.getResponseId()),
NodeAction.NORMAL, null, null, null, null, newInterval);
rmNode.setAndUpdateNodeHeartbeatResponse(nodeHeartBeatResponse);
populateKeys(request, nodeHeartBeatResponse);
populateTokenSequenceNo(request, nodeHeartBeatResponse);
if (timelineServiceV2Enabled) {
// Return collectors' map that NM needs to know
setAppCollectorsMapToResponse(rmNode.getRunningApps(),
nodeHeartBeatResponse);
}
// 4. Send status to RMNode, saving the latest response.
RMNodeStatusEvent nodeStatusEvent =
new RMNodeStatusEvent(nodeId, remoteNodeStatus);
if (request.getLogAggregationReportsForApps() != null
&& !request.getLogAggregationReportsForApps().isEmpty()) {
nodeStatusEvent.setLogAggregationReportsForApps(request
.getLogAggregationReportsForApps());
}
this.rmContext.getDispatcher().getEventHandler().handle(nodeStatusEvent);
// 5. Update node's labels to RM's NodeLabelManager.
if (isDistributedNodeLabelsConf && request.getNodeLabels() != null) {
try {
updateNodeLabelsFromNMReport(
NodeLabelsUtils.convertToStringSet(request.getNodeLabels()),
nodeId);
nodeHeartBeatResponse.setAreNodeLabelsAcceptedByRM(true);
} catch (IOException ex) {
//ensure the error message is captured and sent across in response
nodeHeartBeatResponse.setDiagnosticsMessage(ex.getMessage());
nodeHeartBeatResponse.setAreNodeLabelsAcceptedByRM(false);
}
}
// 6. check if node's capacity is load from dynamic-resources.xml
// if so, send updated resource back to NM.
String nid = nodeId.toString();
Resource capability = loadNodeResourceFromDRConfiguration(nid);
// sync back with new resource if not null.
if (capability != null) {
nodeHeartBeatResponse.setResource(capability);
}
// Check if we got an event (AdminService) that updated the resources
if (rmNode.isUpdatedCapability()) {
nodeHeartBeatResponse.setResource(rmNode.getTotalCapability());
rmNode.resetUpdatedCapability();
}
// 7. Send Container Queuing Limits back to the Node. This will be used by
// the node to truncate the number of Containers queued for execution.
if (this.rmContext.getNodeManagerQueueLimitCalculator() != null) {
nodeHeartBeatResponse.setContainerQueuingLimit(
this.rmContext.getNodeManagerQueueLimitCalculator()
.createContainerQueuingLimit());
}
// 8. Get node's attributes and update node-to-attributes mapping
// in RMNodeAttributeManager.
if (request.getNodeAttributes() != null) {
try {
// update node attributes if necessary then update heartbeat response
updateNodeAttributesIfNecessary(nodeId, request.getNodeAttributes());
nodeHeartBeatResponse.setAreNodeAttributesAcceptedByRM(true);
} catch (IOException ex) {
//ensure the error message is captured and sent across in response
String errorMsg =
nodeHeartBeatResponse.getDiagnosticsMessage() == null ?
ex.getMessage() :
nodeHeartBeatResponse.getDiagnosticsMessage() + "\n" + ex
.getMessage();
nodeHeartBeatResponse.setDiagnosticsMessage(errorMsg);
nodeHeartBeatResponse.setAreNodeAttributesAcceptedByRM(false);
}
}
return nodeHeartBeatResponse;
} | @Test
public void testGracefulDecommissionNoApp() throws Exception {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile
.getAbsolutePath());
writeToHostsFile("");
rm = new MockRM(conf);
rm.start();
MockNM nm1 = rm.registerNode("host1:1234", 5120);
MockNM nm2 = rm.registerNode("host2:5678", 10240);
MockNM nm3 = rm.registerNode("host3:4433", 5120);
int metricCount = ClusterMetrics.getMetrics().getNumDecommisionedNMs();
NodeHeartbeatResponse nodeHeartbeat1 = nm1.nodeHeartbeat(true);
NodeHeartbeatResponse nodeHeartbeat2 = nm2.nodeHeartbeat(true);
NodeHeartbeatResponse nodeHeartbeat3 = nm3.nodeHeartbeat(true);
Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat1.getNodeAction()));
Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat2.getNodeAction()));
Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat3.getNodeAction()));
rm.waitForState(nm2.getNodeId(), NodeState.RUNNING);
rm.waitForState(nm3.getNodeId(), NodeState.RUNNING);
// Graceful decommission both host2 and host3.
writeToHostsFile("host2", "host3");
rm.getNodesListManager().refreshNodes(conf, true);
rm.waitForState(nm2.getNodeId(), NodeState.DECOMMISSIONING);
rm.waitForState(nm3.getNodeId(), NodeState.DECOMMISSIONING);
nodeHeartbeat1 = nm1.nodeHeartbeat(true);
nodeHeartbeat2 = nm2.nodeHeartbeat(true);
nodeHeartbeat3 = nm3.nodeHeartbeat(true);
checkDecommissionedNMCount(rm, metricCount + 2);
rm.waitForState(nm2.getNodeId(), NodeState.DECOMMISSIONED);
rm.waitForState(nm3.getNodeId(), NodeState.DECOMMISSIONED);
Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat1.getNodeAction()));
Assert.assertEquals(NodeAction.SHUTDOWN, nodeHeartbeat2.getNodeAction());
Assert.assertEquals(NodeAction.SHUTDOWN, nodeHeartbeat3.getNodeAction());
} |
public static <T> Supplier<T> recover(Supplier<T> supplier,
Predicate<T> resultPredicate, UnaryOperator<T> resultHandler) {
return () -> {
T result = supplier.get();
if(resultPredicate.test(result)){
return resultHandler.apply(result);
}
return result;
};
} | @Test(expected = RuntimeException.class)
public void shouldRethrowException() {
Supplier<String> supplier = () -> {
throw new RuntimeException("BAM!");
};
Supplier<String> supplierWithRecovery = SupplierUtils.recover(supplier, (ex) -> {
throw new RuntimeException();
});
supplierWithRecovery.get();
} |
public static String getHostAddress()
throws SocketException, UnknownHostException {
boolean isIPv6Preferred = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses"));
DatagramSocket ds = new DatagramSocket();
try {
ds.connect(isIPv6Preferred ? Inet6Address.getByName(DUMMY_OUT_IPV6) : Inet4Address.getByName(DUMMY_OUT_IPV4),
HTTP_PORT);
} catch (java.io.UncheckedIOException e) {
LOGGER.warn(e.getMessage());
if (isIPv6Preferred) {
LOGGER.warn("No IPv6 route available on host, falling back to IPv4");
ds.connect(Inet4Address.getByName(DUMMY_OUT_IPV4), HTTP_PORT);
} else {
LOGGER.warn("No IPv4 route available on host, falling back to IPv6");
ds.connect(Inet6Address.getByName(DUMMY_OUT_IPV6), HTTP_PORT);
}
}
InetAddress localAddress = ds.getLocalAddress();
if (localAddress.isAnyLocalAddress()) {
localAddress = isIPv6Preferred ? getLocalIPv6Address() : InetAddress.getLocalHost();
}
return localAddress.getHostAddress();
} | @Test(description = "Test getHostAddress with no preferIPv6Addresses in IPv4 only environment")
public void testGetHostAddressIPv4Env() {
InetAddress mockInetAddress = mock(InetAddress.class);
when(mockInetAddress.isAnyLocalAddress()).thenReturn(false);
when(mockInetAddress.getHostAddress()).thenReturn(LOCAL_ADDRESS_IPV4);
try (MockedConstruction<DatagramSocket> mockedConstructionDatagramSocket = mockConstruction(DatagramSocket.class,
initDatagramSocket(mockInetAddress, NetworkEnv.IPV4))) {
String hostAddress = NetUtils.getHostAddress();
DatagramSocket mockDatagramSocket = mockedConstructionDatagramSocket.constructed().get(0);
assertEquals(LOCAL_ADDRESS_IPV4, hostAddress);
assertEquals(1, mockedConstructionDatagramSocket.constructed().size());
verify(mockDatagramSocket, times(1)).connect(any(), anyInt());
} catch (SocketException | UnknownHostException e) {
Assert.fail("Should not throw: " + e.getMessage());
}
} |
public static String md5(String data) {
return md5(data.getBytes());
} | @Test
public void testMd5() throws Exception {
String biezhiMD5 = "b3b71cd2fbee70ae501d024fe12a8fba";
Assert.assertEquals(
biezhiMD5,
EncryptKit.md5("biezhi")
);
Assert.assertEquals(
biezhiMD5,
EncryptKit.md5("biezhi".getBytes())
);
TestCase.assertTrue(
Arrays.equals(
ConvertKit.hexString2Bytes(biezhiMD5),
EncryptKit.md5ToByte("biezhi".getBytes())
)
);
} |
public T findAndRemove(Bson filter) {
return delegate.findOneAndDelete(filter);
} | @Test
void findAndRemove() {
final var collection = jacksonCollection("simple", Simple.class);
final var foo = new Simple("000000000000000000000001", "foo");
final var bar = new Simple("000000000000000000000002", "bar");
collection.insert(List.of(foo, bar));
assertThat(collection.findAndRemove(DBQuery.is("_id", objectId(foo.id())))).isEqualTo(foo);
assertThat(collection.findAndRemove(DBQuery.is("_id", objectId(bar.id())))).isEqualTo(bar);
assertThat(collection.count()).isZero();
} |
public int charAt(int position) {
if (position > this.length) return -1; // too long
if (position < 0) return -1; // duh.
ByteBuffer bb = (ByteBuffer)ByteBuffer.wrap(bytes).position(position);
return bytesToCodePoint(bb.slice());
} | @Test
public void testCharAt() {
String line = "adsawseeeeegqewgasddga";
Text text = new Text(line);
for (int i = 0; i < line.length(); i++) {
assertTrue("testCharAt error1 !!!", text.charAt(i) == line.charAt(i));
}
assertEquals("testCharAt error2 !!!", -1, text.charAt(-1));
assertEquals("testCharAt error3 !!!", -1, text.charAt(100));
} |
public static String removeLeadingSlashes(String path) {
return SLASH_PREFIX_PATTERN.matcher(path).replaceFirst("");
} | @Test
public void removeLeadingSlashes_whenMultipleLeadingSlashes_removesLeadingSlashes() {
assertThat(removeLeadingSlashes("/////a/b/c/")).isEqualTo("a/b/c/");
} |
public boolean enabled() {
return get(ENABLED, defaultValue);
} | @Test
public void basicTest() {
ConfigApplyDelegate delegate = configApply -> { };
ObjectMapper mapper = new ObjectMapper();
TestConfig enabled = new TestConfig(true);
TestConfig disabled = new TestConfig(false);
enabled.init("enabled", "KEY", JsonNodeFactory.instance.objectNode(), mapper, delegate);
disabled.init("disabled", "KEY", JsonNodeFactory.instance.objectNode(), mapper, delegate);
assertThat(enabled.enabled(), is(true));
assertThat(disabled.enabled(), is(false));
disabled.enabled(true);
enabled.enabled(false);
assertThat(enabled.enabled(), is(false));
assertThat(disabled.enabled(), is(true));
} |
@Override
@TpsControl(pointName = "ConfigRemove")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigRemoveResponse handle(ConfigRemoveRequest configRemoveRequest, RequestMeta meta)
throws NacosException {
// check tenant
String tenant = configRemoveRequest.getTenant();
String dataId = configRemoveRequest.getDataId();
String group = configRemoveRequest.getGroup();
String tag = configRemoveRequest.getTag();
try {
ParamUtils.checkTenant(tenant);
ParamUtils.checkParam(dataId, group, "datumId", "rm");
ParamUtils.checkParam(tag);
String persistEvent = ConfigTraceService.PERSISTENCE_EVENT;
String clientIp = meta.getClientIp();
if (StringUtils.isBlank(tag)) {
configInfoPersistService.removeConfigInfo(dataId, group, tenant, clientIp, null);
} else {
persistEvent = ConfigTraceService.PERSISTENCE_EVENT_TAG + "-" + tag;
configInfoTagPersistService.removeConfigInfoTag(dataId, group, tenant, tag, clientIp, null);
}
final Timestamp time = TimeUtils.getCurrentTime();
ConfigTraceService.logPersistenceEvent(dataId, group, tenant, null, time.getTime(), clientIp, persistEvent,
ConfigTraceService.PERSISTENCE_TYPE_REMOVE, null);
ConfigChangePublisher.notifyConfigChange(
new ConfigDataChangeEvent(false, dataId, group, tenant, tag, time.getTime()));
return ConfigRemoveResponse.buildSuccessResponse();
} catch (Exception e) {
Loggers.REMOTE_DIGEST.error("remove config error,error msg is {}", e.getMessage(), e);
return ConfigRemoveResponse.buildFailResponse(e.getMessage());
}
} | @Test
void testHandle() {
ConfigRemoveRequest configRemoveRequest = new ConfigRemoveRequest();
configRemoveRequest.setRequestId("requestId");
configRemoveRequest.setGroup("group");
configRemoveRequest.setDataId("dataId");
configRemoveRequest.setTenant("tenant");
RequestMeta meta = new RequestMeta();
meta.setClientIp("1.1.1.1");
try {
ConfigRemoveResponse configRemoveResponse = configRemoveRequestHandler.handle(configRemoveRequest, meta);
assertEquals(ResponseCode.SUCCESS.getCode(), configRemoveResponse.getResultCode());
} catch (NacosException e) {
e.printStackTrace();
assertTrue(false);
}
} |
public static String buildAppAuthPath(final String appKey) {
return String.join(PATH_SEPARATOR, APP_AUTH_PARENT, appKey);
} | @Test
public void testBuildAppAuthPath() {
String appKey = RandomStringUtils.randomAlphanumeric(10);
String appAuthPath = DefaultPathConstants.buildAppAuthPath(appKey);
assertThat(appAuthPath, notNullValue());
assertThat(String.join(SEPARATOR, APP_AUTH_PARENT, appKey), equalTo(appAuthPath));
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateComparisons_decimal() {
// Given:
final Expression expression1 = new ComparisonExpression(
ComparisonExpression.Type.GREATER_THAN,
COL8,
new DecimalLiteral(new BigDecimal("1.2"))
);
final Expression expression2 = new ComparisonExpression(
ComparisonExpression.Type.LESS_THAN,
COL8,
new DecimalLiteral(new BigDecimal("5.1"))
);
final Expression expression3 = new ComparisonExpression(
ComparisonExpression.Type.EQUAL,
COL8,
new DecimalLiteral(new BigDecimal("10.4"))
);
final Expression expression4 = new ComparisonExpression(
ComparisonExpression.Type.GREATER_THAN,
COL8,
new IntegerLiteral(5)
);
final Expression expression5 = new ComparisonExpression(
ComparisonExpression.Type.LESS_THAN,
COL8,
new DoubleLiteral(6.5)
);
final Expression expression6 = new ComparisonExpression(
ComparisonExpression.Type.LESS_THAN,
COL8,
new LongLiteral(10L)
);
// When:
InterpretedExpression interpreter1 = interpreter(expression1);
InterpretedExpression interpreter2 = interpreter(expression2);
InterpretedExpression interpreter3 = interpreter(expression3);
InterpretedExpression interpreter4 = interpreter(expression4);
InterpretedExpression interpreter5 = interpreter(expression5);
InterpretedExpression interpreter6 = interpreter(expression6);
// Then:
assertThat(interpreter1.evaluate(make(8, new BigDecimal("3.4"))), is(true));
assertThat(interpreter1.evaluate(make(8, new BigDecimal("1.1"))), is(false));
assertThat(interpreter2.evaluate(make(8, new BigDecimal("4.9"))), is(true));
assertThat(interpreter2.evaluate(make(8, new BigDecimal("5.2"))), is(false));
assertThat(interpreter3.evaluate(make(8, new BigDecimal("10.4"))), is(true));
assertThat(interpreter3.evaluate(make(8, new BigDecimal("10.5"))), is(false));
assertThat(interpreter4.evaluate(make(8, new BigDecimal("6.5"))), is(true));
assertThat(interpreter4.evaluate(make(8, new BigDecimal("4.5"))), is(false));
assertThat(interpreter5.evaluate(make(8, new BigDecimal("5.5"))), is(true));
assertThat(interpreter5.evaluate(make(8, new BigDecimal("7.5"))), is(false));
assertThat(interpreter6.evaluate(make(8, new BigDecimal("7"))), is(true));
assertThat(interpreter6.evaluate(make(8, new BigDecimal("19.567"))), is(false));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.