focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public TokenResponse exchangePkceCode(
URI tokenEndpoint, String code, String redirectUri, String clientId, String codeVerifier) {
var body =
UrlFormBodyBuilder.create()
.param("grant_type", "authorization_code")
.param("redirect_uri", redirectUri)
.param("client_i... | @Test
void exchangePkceCode_badStatus(WireMockRuntimeInfo wm) {
var path = "/auth/token";
stubFor(post(path).willReturn(badRequest()));
var base = URI.create(wm.getHttpBaseUrl());
var tokenEndpoint = base.resolve(path);
var e =
assertThrows(
HttpException.class,
... |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis... | @Test
public void shouldThrowOnPullQueryThatHasRefinement() {
// Given:
when(analysis.getRefinementInfo()).thenReturn(Optional.of(refinementInfo));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> validator.validate(analysis)
);
// Then:
assertThat(e.... |
@Override
public void createOrUpdate(final String path, final Object data) {
zkClient.createOrUpdate(path, data, CreateMode.PERSISTENT);
} | @Test
public void testOnRuleChangedUpdate() {
RuleData ruleData = RuleData.builder()
.id(MOCK_ID)
.name(MOCK_NAME)
.pluginName(MOCK_PLUGIN_NAME)
.selectorId(MOCK_SELECTOR_ID)
.build();
String ruleRealPath = DefaultPathCo... |
@Override
public String toString() {
return "SymmetricEncryptionConfig{"
+ "enabled=" + enabled
+ ", algorithm='" + algorithm + '\''
+ ", password='***'"
+ ", salt='***'"
+ ", iterationCount=***"
+ ", key=***"
... | @Test
public void testToString() {
assertContains(config.toString(), "SymmetricEncryptionConfig");
} |
public Future<Void> deletePersistentClaims(List<String> maybeDeletePvcs, List<String> desiredPvcs) {
List<Future<Void>> futures = new ArrayList<>();
maybeDeletePvcs.removeAll(desiredPvcs);
for (String pvcName : maybeDeletePvcs) {
LOGGER.debugCr(reconciliation, "Considering PVC {} ... | @Test
public void testVolumesDeletion(VertxTestContext context) {
PersistentVolumeClaim pvcWithDeleteClaim = new PersistentVolumeClaimBuilder(createPvc("data-pod-3"))
.editMetadata()
.withAnnotations(Map.of(Annotations.ANNO_STRIMZI_IO_DELETE_CLAIM, "true"))
... |
public RestLiAttachmentReader(final MultiPartMIMEReader multiPartMIMEReader)
{
_multiPartMIMEReader = multiPartMIMEReader;
} | @Test
public void testRestLiAttachmentReader()
{
//Create a mock MultiPartMIMEReader and pass to the RestLiAttachmentReader. Verify that API calls are propagated accordingly.
final MultiPartMIMEReader multiPartMIMEReader = mock(MultiPartMIMEReader.class);
final RestLiAttachmentReader attachmentReader = ... |
@Override
public EpoxyModel<?> set(int index, EpoxyModel<?> element) {
EpoxyModel<?> previousModel = super.set(index, element);
if (previousModel.id() != element.id()) {
notifyRemoval(index, 1);
notifyInsertion(index, 1);
}
return previousModel;
} | @Test
public void testSetSameIdDoesntNotify() {
EpoxyModel<?> newModelWithSameId = new TestModel();
newModelWithSameId.id(modelList.get(0).id());
modelList.set(0, newModelWithSameId);
verifyNoMoreInteractions(observer);
assertEquals(newModelWithSameId, modelList.get(0));
} |
@Override
public void filter(final ContainerRequestContext requestContext,
ContainerResponseContext response) {
final Object entity = response.getEntity();
if (isEmptyOptional(entity)) {
response.setStatus(Response.Status.NO_CONTENT.getStatusCode());
re... | @Test
void changesStatusToNoContentForEmptyOptional() {
doReturn(Optional.empty()).when(response).getEntity();
toTest.filter(requestContext, response);
verify(response).setStatus(204);
verify(response).setEntity(null);
} |
@Override
public void subscribe(Collection<String> topics) {
subscribeInternal(topics, Optional.empty());
} | @Test
public void testSubscriptionOnNullTopic() {
consumer = newConsumer();
assertThrows(IllegalArgumentException.class, () -> consumer.subscribe(singletonList(null)));
} |
@Override
public Status check() {
if (applicationContext == null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
... | @Test
void testWithDatasourceNotHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConne... |
public LogicalSlot allocateLogicalSlot() {
LOG.debug("Allocating logical slot from shared slot ({})", physicalSlotRequestId);
Preconditions.checkState(
state == State.ALLOCATED, "The shared slot has already been released.");
final LogicalSlot slot =
new SingleLog... | @Test
void testReturnLogicalSlotTriggersExternalReleaseOnLastSlot() {
final TestingPhysicalSlot physicalSlot = TestingPhysicalSlot.builder().build();
final AtomicBoolean externalReleaseInitiated = new AtomicBoolean(false);
final SharedSlot sharedSlot =
new SharedSlot(
... |
@Override
boolean putIfAbsent(String name, Mapping mapping) {
return storage().putIfAbsent(name, mapping) == null;
} | @Test
public void when_putIfAbsent_then_doesNotOverwrite() {
String name = randomName();
assertThat(storage.putIfAbsent(name, mapping(name, "type-1"))).isTrue();
assertThat(storage.putIfAbsent(name, mapping(name, "type-2"))).isFalse();
assertTrue(storage.allObjects().stream().anyMat... |
@Override
public List<SelectorData> convert(final String json) {
return GsonUtils.getInstance().fromList(json, SelectorData.class);
} | @Test
public void testConvert() {
List<SelectorData> selectorDataList = new LinkedList<>();
ConditionData conditionData = new ConditionData();
conditionData.setParamName("conditionName-" + 0);
List<ConditionData> conditionDataList = Collections.singletonList(conditionData);
s... |
@Override
public int write(ByteBuffer src) throws IOException {
checkNotNull(src);
checkOpen();
checkWritable();
int written = 0; // will definitely either be assigned or an exception will be thrown
synchronized (this) {
boolean completed = false;
try {
if (!beginBlocking()) ... | @Test
public void testWrite() throws IOException {
RegularFile file = regularFile(0);
FileChannel channel = channel(file, WRITE);
assertEquals(0, channel.position());
ByteBuffer buf = buffer("1234567890");
ByteBuffer buf2 = buffer("1234567890");
assertEquals(10, channel.write(buf));
asser... |
@Override
public URL use(ApplicationId applicationId, String resourceKey)
throws YarnException {
Path resourcePath = null;
UseSharedCacheResourceRequest request = Records.newRecord(
UseSharedCacheResourceRequest.class);
request.setAppId(applicationId);
request.setResourceKey(resourceKey)... | @Test(expected = YarnException.class)
public void testUseError() throws Exception {
String message = "Mock IOExcepiton!";
when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenThrow(
new IOException(message));
client.use(mock(ApplicationId.class), "key");
} |
@SuppressWarnings("unchecked")
static SelMap of(Map<String, Object> input) {
if (input == null) {
return new SelMap(null);
}
SelMap map = new SelMap(new HashMap<>());
for (Map.Entry<String, Object> entry : input.entrySet()) {
if (entry.getValue() instanceof String) {
map.val.put(Se... | @Test(expected = IllegalArgumentException.class)
public void testInvalidTypeNullValue() {
SelMap.of(Collections.singletonMap("bar", null));
} |
public static boolean isAssignableFrom(Class clazz, Class cls) {
Objects.requireNonNull(cls, "cls");
return clazz.isAssignableFrom(cls);
} | @Test
public void isAssignableFromTest() {
final boolean assignableFrom = ClassUtil.isAssignableFrom(TestClass.class, TestSubClass.class);
Assert.isTrue(assignableFrom);
} |
public void setReactorNameSupplier(Supplier<String> reactorNameSupplier) {
this.reactorNameSupplier = checkNotNull(reactorNameSupplier, "reactorNameSupplier");
} | @Test
public void test_setReactorNameSupplier_whenNull() {
ReactorBuilder builder = newBuilder();
assertThrows(NullPointerException.class, () -> builder.setReactorNameSupplier(null));
} |
public static Class getJavaType(int sqlType) {
switch (sqlType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
... | @Test
public void testError() {
Exception e = assertThrows(Exception.class, () -> Util.getJavaType(Types.REF));
assertEquals("We do not support tables with SqlType: REF", e.getMessage());
e = assertThrows(Exception.class, () -> Util.getJavaType(-1000));
assertEquals("Unknown sqlType ... |
public static String getStackTrace(final Throwable t) {
if (t == null) {
return "";
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(out);
t.printStackTrace(ps);
ps.flush();
return out.toS... | @Test
void testGetStackTrace() {
assertEquals("", ExceptionUtil.getStackTrace(null));
String stackTrace = ExceptionUtil.getStackTrace(nacosRuntimeException);
assertTrue(
stackTrace.contains("com.alibaba.nacos.api.exception.runtime.NacosRuntimeException: errCode: 500, errMsg: ... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNull_Collection_AndReducerSuffixInNotEmpty_thenReturnNullGetter()
throws Exception {
OuterObject object = OuterObject.nullInner("name");
Getter getter = GetterFactory.newFieldGetter(object, null, innersCollectionField, "[any]");
... |
@Override
public SnowflakeTableMetadata loadTableMetadata(SnowflakeIdentifier tableIdentifier) {
Preconditions.checkArgument(
tableIdentifier.type() == SnowflakeIdentifier.Type.TABLE,
"loadTableMetadata requires a TABLE identifier, got '%s'",
tableIdentifier);
SnowflakeTableMetadata ta... | @SuppressWarnings("unchecked")
@Test
public void testGetTableMetadataInterruptedException() throws SQLException, InterruptedException {
Exception injectedException = new InterruptedException("Fake interrupted exception");
when(mockClientPool.run(any(ClientPool.Action.class))).thenThrow(injectedException);
... |
public static <T> String render(ClassPluginDocumentation<T> classPluginDocumentation) throws IOException {
return render("task", JacksonMapper.toMap(classPluginDocumentation));
} | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void dag() throws IOException {
PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader());
RegisteredPlugin scan = pluginScanner.scan();
Class dag = scan.findClass(Dag.class.getName()).orElseThr... |
public static MetricsReporter loadMetricsReporter(Map<String, String> properties) {
String impl = properties.get(CatalogProperties.METRICS_REPORTER_IMPL);
if (impl == null) {
return LoggingMetricsReporter.instance();
}
LOG.info("Loading custom MetricsReporter implementation: {}", impl);
DynCo... | @Test
public void loadCustomMetricsReporter_badClass() {
assertThatThrownBy(
() ->
CatalogUtil.loadMetricsReporter(
ImmutableMap.of(
CatalogProperties.METRICS_REPORTER_IMPL,
TestFileIONotImpl.class.getName())))
... |
@Override
public ReadwriteSplittingRuleConfiguration swapToObject(final YamlReadwriteSplittingRuleConfiguration yamlConfig) {
Collection<ReadwriteSplittingDataSourceGroupRuleConfiguration> dataSources = yamlConfig.getDataSourceGroups().entrySet().stream()
.map(entry -> swapToObject(entry.get... | @Test
void assertSwapToObject() {
ReadwriteSplittingRuleConfiguration actual = getSwapper().swapToObject(createYamlReadwriteSplittingRuleConfiguration());
assertThat(actual.getDataSourceGroups().size(), is(1));
assertThat(actual.getLoadBalancers().size(), is(1));
assertReadwriteSplit... |
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI.
public long parse(final String text) {
final String date;
final String time;
final String timezone;
if (text.contains("T")) {
date = text.substring(0, text.indexOf('T'));
final String withTimezone = text.substring(text.i... | @Test
public void shouldParseYear() {
// When:
assertThat(parser.parse("2017"), is(fullParse("2017-01-01T00:00:00.000+0000")));
} |
@DoNotSub public int size()
{
return size;
} | @Test
void shouldReportEmpty()
{
assertThat(list.size(), is(0));
assertThat(list.isEmpty(), is(true));
} |
@Override
public boolean isEmpty() {
checkState(!destroyed, destroyedMessage);
return size() == 0;
} | @Test
public void testIsEmpty() throws Exception {
expectPeerMessage(clusterCommunicator);
assertTrue(ecMap.isEmpty());
ecMap.put(KEY1, VALUE1);
assertFalse(ecMap.isEmpty());
ecMap.remove(KEY1);
assertTrue(ecMap.isEmpty());
} |
@SneakyThrows(SQLException.class)
public static boolean isMatched(final EqualsBuilder equalsBuilder, final Object thisColumnValue, final Object thatColumnValue) {
equalsBuilder.reset();
if (thisColumnValue instanceof Number && thatColumnValue instanceof Number) {
return isNumberEquals((N... | @Test
void assertIsIntegerEquals() {
EqualsBuilder equalsBuilder = new EqualsBuilder();
String value = "123";
Long longValue = Long.parseLong(value);
assertTrue(DataConsistencyCheckUtils.isMatched(equalsBuilder, longValue, Integer.parseInt(value)));
assertTrue(DataConsistency... |
@Override
public void execute(Exchange exchange) throws SmppException {
byte[] message = getShortMessage(exchange.getIn());
ReplaceSm replaceSm = createReplaceSmTempate(exchange);
replaceSm.setShortMessage(message);
if (log.isDebugEnabled()) {
log.debug("Sending replace... | @Test
public void bodyWithLatin1DataCodingNarrowedToCharset() throws Exception {
final int dataCoding = 0x03; /* ISO-8859-1 (Latin1) */
byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };
byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (byte) 0... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testDowngradeWithOlderSubversions(VertxTestContext context) {
String oldKafkaVersion = KafkaVersionTestUtils.LATEST_KAFKA_VERSION;
String oldInterBrokerProtocolVersion = "2.8";
String oldLogMessageFormatVersion = "2.8";
String kafkaVersion = KafkaVersionTestUtils.P... |
@Override
public RestResponse<KsqlEntityList> makeKsqlRequest(
final URI serverEndPoint,
final String sql,
final Map<String, ?> requestProperties) {
final KsqlTarget target = sharedClient
.target(serverEndPoint);
return getTarget(target)
.postKsqlRequest(sql, requestProperti... | @Test
public void shouldHandleNoAuthHeader() {
// Given:
client = new DefaultKsqlClient(Optional.empty(), sharedClient, ksqlConfig);
// When:
final RestResponse<KsqlEntityList> result = client.makeKsqlRequest(SERVER_ENDPOINT, "Sql", ImmutableMap.of());
// Then:
verify(target, never()).author... |
@Override
public String toString() {
final String nInfo = n == 1 ? "" : "(" + n + ")";
return getClass().getSimpleName() + nInfo + "[" + this.indicator + "]";
} | @Test
public void testToStringMethodWithN1() {
prevValueIndicator = new PreviousValueIndicator(openPriceIndicator);
final String prevValueIndicatorAsString = prevValueIndicator.toString();
assertTrue(prevValueIndicatorAsString.startsWith("PreviousValueIndicator["));
assertTrue(prev... |
@Override
public List<Input<int[][]>> divideData(int num) {
if (this.data == null) {
return null;
} else {
var divisions = makeDivisions(this.data, num);
var result = new ArrayList<Input<int[][]>>(num);
var rowsDone = 0; //number of rows divided so far
for (var i = 0; i < num; i+... | @Test
void divideDataTest() {
var rows = 10;
var columns = 10;
var inputMatrix = new int[rows][columns];
var rand = new Random();
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
inputMatrix[i][j] = rand.nextInt(10);
}
}
var i = new ArrayInput(inputM... |
public static boolean checkOK(String checkIPsResult) {
return CHECK_OK.equals(checkIPsResult);
} | @Test
void testCheckOk() {
assertTrue(InternetAddressUtil.checkOK("ok"));
assertFalse(InternetAddressUtil.checkOK("ojbk"));
} |
protected static int parseUpdate(String runtimeVersion) {
LOGGER.debug(runtimeVersion);
try {
String[] parts = runtimeVersion.split("\\.");
if (parts.length == 4 && isNumeric(parts)) {
return Integer.parseInt(parts[2]);
}
int pos = runtimeV... | @Test
public void testParseUpdate() {
String runtimeVersion = "1.8.0_252-8u252-b09-1~deb9u1-b09";
int expResult = 252;
int result = Utils.parseUpdate(runtimeVersion);
assertEquals(expResult, result);
runtimeVersion = "1.8.0_144";
expResult = 144;
result = Ut... |
@VisibleForTesting
public String validateMobile(String mobile) {
if (StrUtil.isEmpty(mobile)) {
throw exception(SMS_SEND_MOBILE_NOT_EXISTS);
}
return mobile;
} | @Test
public void testCheckMobile_notExists() {
// 准备参数
// mock 方法
// 调用,并断言异常
assertServiceException(() -> smsSendService.validateMobile(null),
SMS_SEND_MOBILE_NOT_EXISTS);
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
JsonObject json = JsonParser.parseString(msg.getData()).getAsJsonObject();
String tmp;
if (msg.getOriginator().getEntityType() != EntityType.DEVICE) {
ctx.tellFailure(msg, new RuntimeException("Message originator is not a de... | @Test
public void givenRequestId_whenOnMsg_thenVerifyRequest() {
given(ctxMock.getRpcService()).willReturn(rpcServiceMock);
given(ctxMock.getTenantId()).willReturn(TENANT_ID);
String data = """
{
"method": "setGpio",
"params": {
... |
@Override
public Ring<T> createRing(Map<T, Integer> pointsMap) {
return _ringFactory.createRing(pointsMap);
} | @Test(groups = { "small", "back-end" })
public void testFactoryWithHashMethod() {
RingFactory<String> factory = new DelegatingRingFactory<>(configBuilder(null, "uriRegex"));
Ring<String> ring = factory.createRing(buildPointsMap(10));
assertTrue(ring instanceof MPConsistentHashRing);
} |
public ClusterInfo getBrokerClusterInfo(
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CLUSTER_INFO... | @Test
public void assertGetBrokerClusterInfo() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
ClusterInfo responseBody = new ClusterInfo();
Map<String, Set<String>> clusterAddrTable = new HashMap<>();
clusterAddrTable.put(clusterName, new HashSe... |
public static byte[] longToByteArray(long longValue, int length) {
return longToByteArray(longValue, length, true);
} | @Test
public void testLongToByteArray() {
BeaconParser parser = new BeaconParser();
byte[] bytes = parser.longToByteArray(10, 1);
assertEquals("first byte should be 10", 10, bytes[0]);
} |
public void defineDataTableType(DataTableType dataTableType) {
DataTableType existing = tableTypeByType.get(dataTableType.getTargetType());
if (existing != null && !existing.isReplaceable()) {
throw new DuplicateTypeException(format("" +
"There already is a data table typ... | @Test
void throws_duplicate_type_exception() {
registry.defineDataTableType(new DataTableType(
Place.class,
(TableTransformer<Place>) table -> new Place(table.cell(0, 0))));
DuplicateTypeException exception = assertThrows(DuplicateTypeException.class,
() -> regi... |
public final void containsKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).contains(key);
} | @Test
public void failMapContainsKeyWithNull() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsKey(null);
assertFailureKeys("value of", "expected to contain", "but was", "map was");
assertFailureValue("value of", "map.keySet()");
asse... |
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) {
List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext()
? createShardingConditionsWithInsertValues(sqlStatementContext, params)
... | @Test
void assertCreateShardingConditionsWithParameterMarkers() {
InsertValueContext insertValueContext = new InsertValueContext(Collections.singleton(new ParameterMarkerExpressionSegment(0, 0, 0)), Collections.singletonList(1), 0);
when(insertStatementContext.getInsertValueContexts()).thenReturn(Co... |
@Override
public Cancellable schedule(final long delay, final TimeUnit unit, final Runnable command) {
final IndirectRunnable indirectRunnable = new IndirectRunnable(command);
final Cancellable cancellable = _executor.schedule(delay, unit, indirectRunnable);
return new IndirectCancellable(cancellable, ind... | @Test
public void testSchedule() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Cancellable cancellable = _executor.schedule(50, TimeUnit.MILLISECONDS, new Runnable() {
@Override
public void run() {
latch.countDown();
}
});
assertTrue... |
public boolean isLast() {
return this.page >= (this.totalPage - 1);
} | @Test
public void isLastTest(){
// 每页2条,共10条,总共5页,第一页是0,最后一页应该是4
final PageResult<String> result = new PageResult<>(4, 2, 10);
assertTrue(result.isLast());
} |
public static int getPidFromID(String msgID) {
byte[] bytes = UtilAll.string2bytes(msgID);
ByteBuffer wrap = ByteBuffer.wrap(bytes);
int value = wrap.getShort(bytes.length - 2 - 4 - 4 - 2);
return value & 0x0000FFFF;
} | @Test
public void testGetPidFromID() {
// Temporary fix on MacOS
short pid = (short) UtilAll.getPid();
String uniqID = MessageClientIDSetter.createUniqID();
short pidFromID = (short) MessageClientIDSetter.getPidFromID(uniqID);
assertThat(pid).isEqualTo(pidFromID);
} |
public EmbeddedMetaStore getEmbeddedMetaStore() {
return embeddedMetaStore;
} | @Test
public void testGetEmbeddedMetaStore() {
assertNotNull( meta.getEmbeddedMetaStore() );
} |
@HighFrequencyInvocation
public Optional<ShardingSphereUser> findUser(final Grantee grantee) {
return configuration.getUsers().stream().filter(each -> each.getGrantee().accept(grantee)).findFirst();
} | @Test
void assertNotFindUser() {
assertFalse(createAuthorityRule().findUser(new Grantee("admin", "127.0.0.1")).isPresent());
} |
public abstract void prepareSnapshotPreBarrier(long checkpointId) throws Exception; | @Test
void testPrepareCheckpointPreBarrier() throws Exception {
final AtomicInteger intRef = new AtomicInteger();
final OneInputStreamOperator<String, String> one = new ValidatingOperator(intRef, 0);
final OneInputStreamOperator<String, String> two = new ValidatingOperator(intRef, 1);
... |
public void renewPresence(final UUID accountUuid, final byte deviceId) {
renewPresenceScript.execute(List.of(getPresenceKey(accountUuid, deviceId)),
List.of(managerId, String.valueOf(PRESENCE_EXPIRATION_SECONDS)));
} | @Test
void testRenewPresence() {
final UUID accountUuid = UUID.randomUUID();
final byte deviceId = 1;
final String presenceKey = ClientPresenceManager.getPresenceKey(accountUuid, deviceId);
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
connection.sync().set(presenceKey, ... |
public JMXUriBuilder withServerName(String aServerName) {
setServerName(aServerName);
return this;
} | @Test
public void withServerName() {
assertEquals("jmx:service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi",
new JMXUriBuilder().withServerName("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi").toString());
} |
@Override
public void put(final K key,
final V value) {
Objects.requireNonNull(key, "key cannot be null");
try {
maybeMeasureLatency(() -> wrapped().put(keyBytes(key), serdes.rawValue(value)), time, putSensor);
maybeRecordE2ELatency();
} catch (fin... | @Test
public void shouldThrowNullPointerOnPutIfKeyIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> metered.put(null, VALUE));
} |
@Override
public PortDescription combine(ConnectPoint cp, PortDescription descr) {
checkNotNull(cp);
// short-circuit for non-optical ports
// must be removed if we need type override
if (descr != null && !optical.contains(descr.type())) {
return descr;
}
... | @Test
public void testConfigAddStaticLambda() {
opc.portType(Port.Type.ODUCLT)
.portNumberName(PORT_NUMBER)
.staticLambda(CFG_STATIC_LAMBDA);
PortDescription res;
res = oper.combine(CP, N_DESC);
assertEquals("Original port name expected",
... |
public JobStatus getJobStatus(JobID oldJobID) throws IOException {
org.apache.hadoop.mapreduce.v2.api.records.JobId jobId =
TypeConverter.toYarn(oldJobID);
GetJobReportRequest request =
recordFactory.newRecordInstance(GetJobReportRequest.class);
request.setJobId(jobId);
JobReport report = ... | @Test
public void testUnknownAppInRM() throws Exception {
MRClientProtocol historyServerProxy = mock(MRClientProtocol.class);
when(historyServerProxy.getJobReport(getJobReportRequest())).thenReturn(
getJobReportResponse());
ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate(
... |
public BigDecimal calculateTDEE(ActiveLevel activeLevel) {
if(activeLevel == null) return BigDecimal.valueOf(0);
BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer());
return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN);
} | @Test
void calculateTDEE_VERY_ACTIVE() {
BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(ActiveLevel.VERY);
assertEquals(new BigDecimal("3523.31"), TDEE);
} |
public static ThreadPoolExecutor newExecutor(int corePoolSize) {
ExecutorBuilder builder = ExecutorBuilder.create();
if (corePoolSize > 0) {
builder.setCorePoolSize(corePoolSize);
}
return builder.build();
} | @Test
public void newExecutorTest(){
ThreadPoolExecutor executor = ThreadUtil.newExecutor(5);
// 查询线程池 线程数
assertEquals(5, executor.getCorePoolSize());
} |
public Map<String, String> penRequestAllowed(PenRequest request) throws PenRequestException, SharedServiceClientException {
final List<PenRequestStatus> result = repository.findByBsnAndDocTypeAndSequenceNo(request.getBsn(), request.getDocType(), request.getSequenceNo());
checkIfTooSoonOrTooOften(result)... | @Test
public void pinRequestTooSoonThrowsDWS1Exception() throws PenRequestException, SharedServiceClientException {
// create a pinRequestStatus with a RequestDateTime in the repo
status.setRequestDatetime(LocalDateTime.now(clock));
mockStatusList.add(status);
// return arraylist wi... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test
public void testMlsd() throws Exception {
Path path = new Path(
"/www", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{
"Type=file;Perm=awr;Unique=keVO1+8G4; writable",
"Type=file;Perm=r;Unique=keVO1+IH4; leading space",
... |
@Injection( name = "IGNORE_INSERT_ERRORS" )
public void metaSetIgnoreInsertErrors( String value ) {
setIgnoreErrors( "Y".equalsIgnoreCase( value ) );
} | @Test
public void metaSetIgnoreInsertErrors() {
TableOutputMeta tableOutputMeta = new TableOutputMeta();
tableOutputMeta.metaSetIgnoreInsertErrors( "Y" );
assertTrue( tableOutputMeta.ignoreErrors() );
tableOutputMeta.metaSetIgnoreInsertErrors( "N" );
assertFalse( tableOutputMeta.ignoreErrors() );
... |
public URLNormalizer sortQueryParameters() {
// Does it have query parameters?
if (!url.contains("?")) {
return this;
}
// It does, so proceed
List<String> keyValues = new ArrayList<>();
String queryString = StringUtils.substringAfter(url, "?");
// ex... | @Test
public void testSortQueryParameters() {
// test with fragment
s = "http://example.com?z=1&a=1#frag";
t = "http://example.com?a=1&z=1#frag";
assertEquals(t, n(s).sortQueryParameters().toString());
// test duplicate params
s = "http://example.com?z=1&a=1&a=1";
... |
@GetMapping("/api/v1/meetings/{uuid}/confirm")
public MomoApiResponse<ConfirmedMeetingResponse> findConfirmedMeeting(@PathVariable String uuid) {
ConfirmedMeetingResponse response = meetingConfirmService.findByUuid(uuid);
return new MomoApiResponse<>(response);
} | @DisplayName("확정된 약속을 조회하면 200 상태 코드를 응답한다.")
@Test
void findConfirmedMeeting() {
Meeting meeting = MeetingFixture.MOVIE.create();
meeting.lock();
meeting = meetingRepository.save(meeting);
confirmedMeetingRepository.save(ConfirmedMeetingFixture.MOVIE.create(meeting));
R... |
@Override
public boolean isSupported(final Path file, final Type type) {
if(StringUtils.equals(EueResourceIdProvider.TRASH, file.attributes().getFileId())) {
return false;
}
if(type == Type.upload) {
return file.isDirectory();
}
return DescriptiveUrl.E... | @Test
public void testUploadUrlForFile() {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path file = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final EueShareFeature f = new EueShareFeature(session, fileid);
... |
@Override
public Sensor addRateTotalSensor(final String scopeName,
final String entityName,
final String operationName,
final Sensor.RecordingLevel recordingLevel,
fina... | @Test
public void shouldThrowIfRateTotalSensorIsAddedWithOddTags() {
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> streamsMetrics.addRateTotalSensor(
SCOPE_NAME,
ENTITY_NAME,
OPERATION_NA... |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingStructRowWithUnknownModTypeAndValueCaptureTypeToDataChangeRecord() {
final DataChangeRecord dataChangeRecord =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"transactionId",
false,
... |
@Override
public ReadwriteSplittingRuleConfiguration buildToBeDroppedRuleConfiguration(final DropReadwriteSplittingRuleStatement sqlStatement) {
Collection<ReadwriteSplittingDataSourceGroupRuleConfiguration> toBeDroppedDataSourceGroups = new LinkedList<>();
Map<String, AlgorithmConfiguration> toBeDr... | @Test
void assertBuildToBeDroppedRuleConfigurationWithInUsedLoadBalancer() {
ReadwriteSplittingRuleConfiguration ruleConfig = createMultipleCurrentRuleConfigurations();
ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class);
when(rule.getConfiguration()).thenReturn(ruleConfig);
... |
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
if (registryAttr inst... | @Test(expected = ServletException.class)
public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception {
final ServletContext servletContext = mock(ServletContext.class);
final ServletConfig servletConfig = mock(ServletConfig.class);
when(serv... |
public FactMapping addFactMapping(int index, FactMapping toClone) {
FactMapping toReturn = toClone.cloneFactMapping();
factMappings.add(index, toReturn);
return toReturn;
} | @Test
public void addFactMappingByIndexAndFactIdentifierAndExpressionIdentifierFail() {
assertThatIllegalArgumentException().isThrownBy(() -> modelDescriptor.addFactMapping(1, factIdentifier, expressionIdentifier));
} |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
try {
final IRODSAccount account = client.getIRODSAccount();
final Credentials credentials = host.getCredentials();
account.setUserName(credentials.getUsernam... | @Test
public void testLoginWhitespaceHomeDirectory() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/... |
@Override
public synchronized Optional<ListenableFuture<V>> schedule(
Checkable<K, V> target, K context) {
if (checksInProgress.containsKey(target)) {
return Optional.empty();
}
final LastCheckResult<V> result = completedChecks.get(target);
if (result != null) {
final long msSinceLa... | @Test (timeout=60000)
public void testConcurrentChecks() throws Exception {
final StalledCheckable target = new StalledCheckable();
final FakeTimer timer = new FakeTimer();
ThrottledAsyncChecker<Boolean, Boolean> checker =
new ThrottledAsyncChecker<>(timer, MIN_ERROR_CHECK_GAP, 0,
getE... |
@Override public long remove(long key) {
final long valueAddr = hsa.get(key);
if (valueAddr == NULL_ADDRESS) {
return nullValue;
}
final long oldValue = mem.getLong(valueAddr);
hsa.remove(key);
return oldValue;
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void test_removeIfEquals_Value() {
map.remove(newKey(), MISSING_VALUE);
} |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test
public void require_that_container_endpoints_are_written_and_used() throws Exception {
var modelFactory = new TestModelFactory(version123);
preparer = createPreparer(new ModelFactoryRegistry(List.of(modelFactory)), HostProvisionerProvider.empty());
var endpoints = "[\n" +
... |
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
advance(length);
super.characters(ch, start, length);
} | @Test
public void testSomeCharactersWithoutInput() throws IOException {
try {
char[] ch = new char[100];
for (int i = 0; i < 100; i++) {
handler.characters(ch, 0, ch.length);
}
} catch (SAXException e) {
fail("Unexpected SAXException");... |
public static String urlSanitize(String string) {
StringBuilder sanitized = new StringBuilder();
for (char c : string.toCharArray()) {
sanitized.append(ALLOWED_CHARS_SET.contains(c) ? c : REPLACE_CHAR);
}
return sanitized.toString();
} | @Test
void testUrlSanitize() {
String url = Sanitizer.urlSanitize("weird|~url.json");
assertEquals("weird--url.json", url);
} |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test
public void testMergeEqual() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createSinkConfig();
SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig);
assertEquals(
new Gson().toJson(sinkConfig),
... |
public static UnixMountInfo parseMountInfo(String line) {
// Example mount lines:
// ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb)
// map -hosts on /net (autofs, nosuid, automounted, nobrowse)
UnixMountInfo.Builder builder = new UnixMountInfo.Builder();
// First get and remove the mount t... | @Test
public void parseMountInfoInvalidOutput() throws Exception {
UnixMountInfo info = ShellUtils.parseMountInfo("invalid output");
assertFalse(info.getDeviceSpec().isPresent());
assertFalse(info.getMountPoint().isPresent());
assertFalse(info.getFsType().isPresent());
assertFalse(info.getOptions(... |
@Override
public boolean containsAll(Collection<?> c) {
if (c instanceof IntSet) {
return containsAll((IntSet) c);
}
for (Object o : c) {
if (!contains(o))
return false;
}
return true;
} | @Test
public void containsAll() throws Exception {
RangeSet rs = new RangeSet(4);
RangeSet rs2 = new RangeSet(4);
assertTrue(rs.containsAll(rs2));
RangeSet rs3 = new RangeSet(3);
assertTrue(rs.containsAll(rs3));
assertFalse(rs3.containsAll(rs));
} |
@ExecuteOn(TaskExecutors.IO)
@Post(consumes = MediaType.APPLICATION_YAML)
@Operation(tags = {"Flows"}, summary = "Create a flow from yaml source")
public HttpResponse<FlowWithSource> create(
@Parameter(description = "The flow") @Body String flow
) throws ConstraintViolationException {
Fl... | @SuppressWarnings("OptionalGetWithoutIsPresent")
@Test
void invalidUpdateFlow() {
String flowId = IdUtils.create();
Flow flow = generateFlow(flowId, "io.kestra.unittest", "a");
Flow result = client.toBlocking().retrieve(POST("/api/v1/flows", flow), Flow.class);
assertThat(resul... |
public ClusterSerdes init(Environment env,
ClustersProperties clustersProperties,
int clusterIndex) {
ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex);
log.debug("Configuring serdes for cluster {}", clusterP... | @Test
void serdeWithBuiltInNameAndNoPropertiesCantBeInitializedIfSerdeNotSupportAutoConfigure() {
ClustersProperties.SerdeConfig serdeConfig = new ClustersProperties.SerdeConfig();
serdeConfig.setName("BuiltIn2"); //auto-configuration not supported
serdeConfig.setTopicKeysPattern("keys");
serdeConfig.... |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testLists() {
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/lists.md");
List<Document> documents = reader.get();
assertThat(documents).hasSize(2)
.extracting(Document::getMetadata, Document::getContent)
.containsOnly(tuple(Map.of("category", "header_2", "title", "Order... |
@Bean
public MetaDataHandler tarsMetaDataHandler() {
return new TarsMetaDataHandler();
} | @Test
public void testTarsMetaDataHandler() {
applicationContextRunner.run(context -> {
MetaDataHandler handler = context.getBean("tarsMetaDataHandler", MetaDataHandler.class);
assertNotNull(handler);
}
);
} |
@Override
public DefaultResultPartition getResultPartition(
final IntermediateResultPartitionID intermediateResultPartitionId) {
final DefaultResultPartition resultPartition =
resultPartitionsById.get(intermediateResultPartitionId);
if (resultPartition == null) {
... | @Test
void testGetResultPartition() {
for (ExecutionVertex vertex : executionGraph.getAllExecutionVertices()) {
for (Map.Entry<IntermediateResultPartitionID, IntermediateResultPartition> entry :
vertex.getProducedPartitions().entrySet()) {
IntermediateResultPa... |
@Override
public int read() throws IOException {
Preconditions.checkState(!closed, "Cannot read: already closed");
positionStream();
pos += 1;
next += 1;
readBytes.increment();
readOperations.increment();
return stream.read();
} | @Test
public void testReadSingle() throws Exception {
int i0 = 1;
int i1 = 255;
byte[] data = {(byte) i0, (byte) i1};
setupData(data);
try (SeekableInputStream in =
new ADLSInputStream(fileClient(), null, azureProperties, MetricsContext.nullMetrics())) {
assertThat(in.read()).isEqu... |
@Override
public void write(final MySQLPacketPayload payload, final Object value) {
if (value instanceof byte[]) {
payload.writeBytesLenenc((byte[]) value);
} else {
payload.writeStringLenenc(value.toString());
}
} | @Test
void assertWriteString() {
new MySQLStringLenencBinaryProtocolValue().write(payload, "value");
verify(payload).writeStringLenenc("value");
} |
@Override
public String pluginNamed() {
return PluginEnum.LOGGING_ELASTIC_SEARCH.getName();
} | @Test
public void testPluginNamed() {
Assertions.assertEquals(loggingElasticSearchPluginDataHandler.pluginNamed(), "loggingElasticSearch");
} |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseToDateTimeTest3() {
final String dateStr1 = "2017-02-01 12:23:45";
final String dateStr2 = "2017/02/01 12:23:45";
final String dateStr3 = "2017.02.01 12:23:45";
final String dateStr4 = "2017年02月01日 12时23分45秒";
final DateTime dt1 = DateUtil.parse(dateStr1);
final DateTime dt2 = DateU... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testMessageFormatDownConversion() throws Exception {
// this test case verifies the behavior when the version of the produce request supported by the
// broker changes after the record set is created
long offset = 0;
// start off support produce request v3
... |
@Override
public void collect(long elapsedTime, StatementContext ctx) {
final Timer timer = getTimer(ctx);
timer.update(elapsedTime, TimeUnit.NANOSECONDS);
} | @Test
public void updatesTimerForNonSqlishRawSql() throws Exception {
final StatementNameStrategy strategy = new SmartNameStrategy();
final InstrumentedTimingCollector collector = new InstrumentedTimingCollector(registry,
... |
@Override
public String toString() {
return buildStringRepresentation();
} | @Test
void shouldIncludePropsInToString() {
var props = Map.of(KEY, (Object) VALUE);
var document = new DocumentImplementation(props);
assertTrue(document.toString().contains(KEY));
assertTrue(document.toString().contains(VALUE));
} |
public static String basicEscape(String s) {
char c;
int len = s.length();
StringBuilder sbuf = new StringBuilder(len);
int i = 0;
while (i < len) {
c = s.charAt(i++);
if (c == '\\' && i < len ) {
c = s.charAt(i++);
if (c ... | @Test
public void basicEscape() {
assertEquals("a", RegularEscapeUtil.basicEscape("a"));
assertEquals("a\t", RegularEscapeUtil.basicEscape("a\t"));
assertEquals("a\\", RegularEscapeUtil.basicEscape("a\\"));
assertEquals("a\\", RegularEscapeUtil.basicEscape("a\\\\"));
} |
public SlidingTimeWindowMetrics(int timeWindowSizeInSeconds, Clock clock) {
this.clock = clock;
this.timeWindowSizeInSeconds = timeWindowSizeInSeconds;
this.partialAggregations = new PartialAggregation[timeWindowSizeInSeconds];
this.headIndex = 0;
long epochSecond = clock.instant... | @Test
public void testSlidingTimeWindowMetrics() {
MockClock clock = MockClock.at(2019, 8, 4, 12, 0, 0, ZoneId.of("UTC"));
Metrics metrics = new SlidingTimeWindowMetrics(5, clock);
Snapshot result = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.ERROR);
assertThat(resul... |
public static IntIndexedContainer withoutConsecutiveDuplicates(IntIndexedContainer arr) {
IntArrayList result = new IntArrayList();
if (arr.isEmpty())
return result;
int prev = arr.get(0);
result.add(prev);
for (int i = 1; i < arr.size(); i++) {
int val = ... | @Test
public void testWithoutConsecutiveDuplicates() {
assertEquals(from(), ArrayUtil.withoutConsecutiveDuplicates(from()));
assertEquals(from(1), ArrayUtil.withoutConsecutiveDuplicates(from(1)));
assertEquals(from(1), ArrayUtil.withoutConsecutiveDuplicates(from(1, 1)));
assertEquals... |
public static String getActivityTitle(Activity activity) {
try {
if (activity != null) {
try {
String activityTitle = null;
if (Build.VERSION.SDK_INT >= 11) {
String toolbarTitle = SensorsDataUtils.getToolbarTitle(activ... | @Test
public void getActivityTitle() {
TestActivity activity = Robolectric.setupActivity(TestActivity.class);
String title = SensorsDataUtils.getActivityTitle(activity);
System.out.println("ActivityTitle = " + title);
Assert.assertEquals("com.sensorsdata.analytics.android.sdk.util.Se... |
public static boolean equal(Number lhs, Number rhs) {
Class lhsClass = lhs.getClass();
Class rhsClass = rhs.getClass();
assert lhsClass != rhsClass;
if (isDoubleRepresentable(lhsClass)) {
if (isDoubleRepresentable(rhsClass)) {
return equalDoubles(lhs.doubleVa... | @SuppressWarnings("ConstantConditions")
@Test(expected = Throwable.class)
public void testNullRhsInEqualThrows() {
equal(1, null);
} |
@Override
public UnboundedReader<KV<byte[], byte[]>> createReader(
PipelineOptions options, @Nullable SyntheticRecordsCheckpoint checkpoint) {
if (checkpoint == null) {
return new SyntheticUnboundedReader(this, this.startOffset);
} else {
return new SyntheticUnboundedReader(this, checkpoint... | @Test
public void startPositionShouldBeExclusive() throws IOException {
int startPosition = 0;
checkpoint = new SyntheticRecordsCheckpoint(startPosition);
UnboundedSource.UnboundedReader<KV<byte[], byte[]>> reader =
source.createReader(pipeline.getOptions(), checkpoint);
reader.start();
... |
public static TableSchema toSchema(RowType rowType) {
TableSchema.Builder builder = TableSchema.builder();
for (RowType.RowField field : rowType.getFields()) {
builder.field(field.getName(), TypeConversions.fromLogicalToDataType(field.getType()));
}
return builder.build();
} | @Test
public void testConvertFlinkSchemaWithNestedColumnInPrimaryKeys() {
Schema icebergSchema =
new Schema(
Lists.newArrayList(
Types.NestedField.required(
1,
"struct",
Types.StructType.of(
Typ... |
public CruiseConfig deserializeConfig(String content) throws Exception {
String md5 = md5Hex(content);
Element element = parseInputStream(new ByteArrayInputStream(content.getBytes()));
LOGGER.debug("[Config Save] Updating config cache with new XML");
CruiseConfig configForEdit = classPa... | @Test
void shouldThrowExceptionWhenCommandsContainTrailingSpaces() {
String configXml =
("""
<cruise schemaVersion='%d'>
<pipelines group='first'>
<pipeline name='Test'>
<materials>
... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.GAMEMESSAGE && event.getType() != ChatMessageType.SPAM)
{
return;
}
String message = event.getMessage();
if (message.equals("Your Ring of endurance doubles the duration of your stamina potion's effect."))
... | @Test
public void testPotionMessage()
{
String potionMessage = "Your Ring of endurance doubles the duration of your stamina potion's effect.";
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", potionMessage, "", 0);
runEnergyPlugin.onChatMessage(chatMessage);
verify(configManager).set... |
@Override
public void shutdown() {
dLedgerServer.shutdown();
} | @Test
public void testDLedgerAbnormallyRecover() throws Exception {
String base = createBaseDir();
String peers = String.format("n0-localhost:%d", nextPort());
String group = UUID.randomUUID().toString();
String topic = UUID.randomUUID().toString();
int messageNumPerQueue = ... |
@Override
public ColumnStatistics buildColumnStatistics()
{
Optional<IntegerStatistics> integerStatistics = buildIntegerStatistics();
if (integerStatistics.isPresent()) {
return new IntegerColumnStatistics(nonNullValueCount, null, rawSize, storageSize, integerStatistics.get());
... | @Test
public void testMergeOverflow()
{
List<ColumnStatistics> statisticsList = new ArrayList<>();
statisticsList.add(new IntegerStatisticsBuilder().buildColumnStatistics());
assertMergedIntegerStatistics(statisticsList, 0, 0L);
statisticsList.add(singleValueIntegerStatistics(M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.