focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public double calculateDensity(Graph graph, boolean isGraphDirected) {
double result;
double edgesCount = graph.getEdgeCount();
double nodesCount = graph.getNodeCount();
double multiplier = 1;
if (!isGraphDirected) {
multiplier = 2;
}
result = (multi... | @Test
public void testSelfLoopNodeDensity() {
GraphModel graphModel = GraphModel.Factory.newInstance();
UndirectedGraph undirectedGraph = graphModel.getUndirectedGraph();
Node currentNode = graphModel.factory().newNode("0");
undirectedGraph.addNode(currentNode);
Edge currentE... |
public CsvRow nextRow() throws IORuntimeException {
List<String> currentFields;
int fieldCount;
while (false == finished) {
currentFields = readLine();
fieldCount = currentFields.size();
if (fieldCount < 1) {
// 空List表示读取结束
break;
}
// 读取范围校验
if(lineNo < config.beginLineNo){
// 未达到读... | @Test
public void parseEscapeTest(){
// https://datatracker.ietf.org/doc/html/rfc4180#section-2
// 第七条规则
StringReader reader = StrUtil.getReader("\"b\"\"bb\"");
CsvParser parser = new CsvParser(reader, null);
CsvRow row = parser.nextRow();
assertNotNull(row);
assertEquals(1, row.size());
assertEquals("... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReturnNotAvailableWhenInputDateIsNull() throws Exception {
assertEquals(TimeConverter.ConvertedTime.NOT_AVAILABLE, timeConverter.getConvertedTime((Date) null));
} |
@Override
public void filterConsumer(Exchange exchange, WebServiceMessage response) {
if (exchange != null) {
AttachmentMessage responseMessage = exchange.getMessage(AttachmentMessage.class);
processHeaderAndAttachments(responseMessage, response);
}
} | @Test
public void removeCamelInternalHeaderAttributes() throws Exception {
exchange.getOut().getHeaders().put(SpringWebserviceConstants.SPRING_WS_SOAP_ACTION, "mustBeRemoved");
exchange.getOut().getHeaders().put(SpringWebserviceConstants.SPRING_WS_ADDRESSING_ACTION, "mustBeRemoved");
exchang... |
void activate(long newNextWriteOffset) {
if (active()) {
throw new RuntimeException("Can't activate already active OffsetControlManager.");
}
if (newNextWriteOffset < 0) {
throw new RuntimeException("Invalid negative newNextWriteOffset " +
newNextWrite... | @Test
public void testActivate() {
OffsetControlManager offsetControl = new OffsetControlManager.Builder().build();
offsetControl.activate(1000L);
assertEquals(1000L, offsetControl.nextWriteOffset());
assertTrue(offsetControl.active());
assertTrue(offsetControl.metrics().acti... |
@Override
int numBuffered(final TopicPartition partition) {
final RecordQueue recordQueue = partitionQueues.get(partition);
if (recordQueue == null) {
throw new IllegalStateException("Partition " + partition + " not found.");
}
return recordQueue.size();
} | @Test
public void shouldThrowIllegalStateExceptionUponNumBufferedIfPartitionUnknown() {
final PartitionGroup group = getBasicGroup();
final IllegalStateException exception = assertThrows(
IllegalStateException.class,
() -> group.numBuffered(unknownPartition));
assert... |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldReturnKVStoreWhenItExists() {
assertNotNull(storeProvider.getStore(StoreQueryParameters.fromNameAndType(keyValueStore, QueryableStoreTypes.keyValueStore())));
} |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testNestedSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(Nested.class));
assertEquals(NESTED_SCHEMA, schema);
} |
public List<Tuple2<JobID, BlobKey>> checkLimit(long size) {
checkArgument(size >= 0);
synchronized (lock) {
List<Tuple2<JobID, BlobKey>> blobsToDelete = new ArrayList<>();
long current = total;
for (Map.Entry<Tuple2<JobID, BlobKey>, Long> entry : caches.entrySet())... | @Test
void testCheckLimitForEmptyBlob() {
List<Tuple2<JobID, BlobKey>> keys = tracker.checkLimit(0L);
assertThat(keys).isEmpty();
} |
public static Sensor getInvocationSensor(
final Metrics metrics,
final String sensorName,
final String groupName,
final String functionDescription
) {
final Sensor sensor = metrics.sensor(sensorName);
if (sensor.hasMetrics()) {
return sensor;
}
final BiFunction<String, S... | @Test
public void shouldRegisterRateMetric() {
// Given:
when(metrics.metricName(SENSOR_NAME + "-rate", GROUP_NAME, description(RATE_DESC)))
.thenReturn(specificMetricName);
// When:
FunctionMetrics
.getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME);
// Then:
v... |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testValidationOnOverriddenMethods() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"Missing required value for "
+ "[public abstract java.lang.String org.apache.beam."
+ "sdk.options.PipelineOption... |
@Override
public void subscribe(String serviceName, EventListener listener) throws NacosException {
subscribe(serviceName, new ArrayList<>(), listener);
} | @Test
public void testSubscribe5() throws NacosException {
String serviceName = "service1";
String groupName = "group1";
EventListener listener = event -> {
};
//when
client.subscribe(serviceName, groupName, NamingSelectorFactory.HEALTHY_SELECTOR, listener);
... |
@Override
public String parseProperty(String key, String value, PropertiesLookup properties) {
log.trace("Parsing property '{}={}'", key, value);
if (value != null) {
initEncryptor();
Matcher matcher = PATTERN.matcher(value);
while (matcher.find()) {
... | @Test
public void testDecryptsMultitplePartsOfPartiallyEncryptedProperty() {
StringBuilder propertyValue = new StringBuilder();
StringBuilder expected = new StringBuilder();
for (int i = 0; i < 100; i++) {
propertyValue.append(format("param%s=%s%s%s()&", i,
J... |
public void initializeResources(Herder herder) {
this.herder = herder;
super.initializeResources();
} | @Test
public void testLoggerEndpointWithDefaults() throws IOException {
Map<String, String> configMap = new HashMap<>(baseServerProps());
final String logger = "a.b.c.s.W";
final String loggingLevel = "INFO";
final long lastModified = 789052637671L;
doReturn(KAFKA_CLUSTER_I... |
public static BsonTimestamp decodeTimestamp(BsonDocument resumeToken) {
BsonValue bsonValue =
Objects.requireNonNull(resumeToken, "Missing ResumeToken.").get(DATA_FIELD);
final byte[] keyStringBytes;
// Resume Tokens format: https://www.mongodb.com/docs/manual/changeStreams/#resu... | @Test
public void testDecodeHexFormatV1() {
BsonDocument resumeToken =
BsonDocument.parse(
"{\"_data\": \"82612E8513000000012B022C0100296E5A1004A5093ABB38FE4B9EA67F01BB1A96D812463C5F6964003C5F5F5F78000004\"}");
BsonTimestamp expected = new BsonTimestamp(163043... |
@Override
public List<Integer> embed(String text, Context context) {
throw new UnsupportedOperationException("This embedder only supports embed with tensor type");
} | @Test
public void testCachingInt() {
int initialEmbeddingsDone = runtime.embeddingsDone;
var context = new Embedder.Context("schema.indexing");
var input = "This is a test string to embed";
var t1 = (MixedTensor) embedder.embed(input, context, TensorType.fromSpec("tensor<int8>(dt{},... |
public Map<String, Object> getContext(Map<String, Object> modelMap, Class<? extends SparkController> controller, String viewName) {
Map<String, Object> context = new HashMap<>(modelMap);
context.put("currentGoCDVersion", CurrentGoCDVersion.getInstance().getGocdDistVersion());
context.put("railsA... | @Test
void shouldNotShowAnalyticsDashboardWhenUserIsNotAdmin() {
Map<String, Object> modelMap = new HashMap<>();
when(securityService.isUserAdmin(any(Username.class))).thenReturn(false);
CombinedPluginInfo combinedPluginInfo = new CombinedPluginInfo(analyticsPluginInfo());
when(plugi... |
@Override
public int removeAllCounted(Collection<? extends V> c) {
return get(removeAllCountedAsync(c));
} | @Test
public void testRemoveAllCounted() {
RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE);
set.add(0);
set.add(1);
set.add(2);
set.add(3);
assertThat(set.removeAllCounted(Arrays.asList(1, 2, 3, 4, 5))).isEqualTo(3);
} |
private void announceBacklog(NetworkSequenceViewReader reader, int backlog) {
checkArgument(backlog > 0, "Backlog must be positive.");
NettyMessage.BacklogAnnouncement announcement =
new NettyMessage.BacklogAnnouncement(backlog, reader.getReceiverId());
ctx.channel()
... | @Test
void testAnnounceBacklog() throws Exception {
PipelinedSubpartition subpartition =
PipelinedSubpartitionTest.createPipelinedSubpartition();
subpartition.add(createEventBufferConsumer(4096, Buffer.DataType.DATA_BUFFER));
subpartition.add(createEventBufferConsumer(4096, B... |
public static String getNativeDataTypeSimpleName( ValueMetaInterface v ) {
try {
return v.getType() != ValueMetaInterface.TYPE_BINARY ? v.getNativeDataTypeClass().getSimpleName() : "Binary";
} catch ( KettleValueException e ) {
LogChannelInterface log = new LogChannel( v );
log.logDebug( BaseM... | @Test
public void getNativeDataTypeSimpleName_Unknown() throws Exception {
KettleValueException e = new KettleValueException();
ValueMetaInterface v = mock( ValueMetaInterface.class );
doThrow( e ).when( v ).getNativeDataTypeClass();
assertEquals( "Object", FieldHelper.getNativeDataTypeSimpleName( v... |
public Node parse() throws ScanException {
return E();
} | @Test
public void testCompositeFormatting() throws Exception {
Parser<Object> p = new Parser<>("hello%5(XYZ)");
Node t = p.parse();
Node witness = new Node(Node.LITERAL, "hello");
CompositeNode composite = new CompositeNode(BARE);
composite.setFormatInfo(new FormatInfo(5, In... |
public static StringBuilder print_json_diff(LogBuffer buffer, long len, String columnName, int columnIndex,
String charsetName) {
return print_json_diff(buffer, len, columnName, columnIndex, Charset.forName(charsetName));
} | @Test
public void print_json_diffInputNotNullZeroNotNullZeroNotNullOutputIllegalArgumentException2()
throws InvocationTargetException {
// Arrange
final LogBuffer buffer = new LogBuffer();
buff... |
IpcPublication getSharedIpcPublication(final long streamId)
{
return findSharedIpcPublication(ipcPublications, streamId);
} | @Test
void shouldBeAbleToAddAndRemoveIpcPublication()
{
final long idAdd = driverProxy.addPublication(CHANNEL_IPC, STREAM_ID_1);
driverProxy.removePublication(idAdd);
doWorkUntil(() -> nanoClock.nanoTime() >= CLIENT_LIVENESS_TIMEOUT_NS);
final IpcPublication ipcPublication = dr... |
public boolean isEmptyConfig() {
return !isNotEmptyConfig();
} | @Test
public void testIsEmptyConfig() {
RequestHandle handle = new RequestHandle();
handle.setHeader(handle.new ShenyuRequestHeader());
handle.setParameter(handle.new ShenyuRequestParameter());
handle.setCookie(handle.new ShenyuCookie());
assertThat(handle.isEmptyCon... |
public static boolean isApprovedCommentCounter(Counter counter) {
String sceneValue = counter.getId().getTag(SCENE);
if (StringUtils.isBlank(sceneValue)) {
return false;
}
return APPROVED_COMMENT_SCENE.equals(sceneValue);
} | @Test
void isApprovedCommentCounter() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
Counter approvedCommentCounter =
MeterUtils.approvedCommentCounter(meterRegistry, "posts.content.halo.run/fake-post");
assertThat(MeterUtils.isApprovedCommentCounter(approvedCommentCo... |
@Override
public void deleteSocialClient(Long id) {
// 校验存在
validateSocialClientExists(id);
// 删除
socialClientMapper.deleteById(id);
} | @Test
public void testDeleteSocialClient_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> socialClientService.deleteSocialClient(id), SOCIAL_CLIENT_NOT_EXISTS);
} |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenStatsEnabled_whenForwardingActivityMsgToStateService_thenStatsAreRecorded() {
// GIVEN
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock);
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", true);
var... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseSpecificOverVarArgsAtBeginning() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING, STRING, STRING, STRING, INT),
function(OTHER, 0, STRING_VARARGS, STRING, STRING, STRING, INT)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFu... |
@Udf(schema = "ARRAY<STRUCT<K STRING, V BOOLEAN>>")
public List<Struct> entriesBoolean(
@UdfParameter(description = "The map to create entries from") final Map<String, Boolean> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
ret... | @Test
public void shouldReturnNullListForNullMapBoolean() {
assertNull(entriesUdf.entriesBoolean(null, false));
} |
public void checkForUpgradeAndExtraProperties() throws IOException {
if (upgradesEnabled()) {
checkForUpgradeAndExtraProperties(systemEnvironment.getAgentMd5(), systemEnvironment.getGivenAgentLauncherMd5(),
systemEnvironment.getAgentPluginsMd5(), systemEnvironment.getTfsImplMd5()... | @Test
void checkForUpgradeShouldKillAgentIfLauncherMD5doesNotMatch() {
when(systemEnvironment.getAgentMd5()).thenReturn("not-changing");
expectHeaderValue(SystemEnvironment.AGENT_CONTENT_MD5_HEADER, "not-changing");
when(systemEnvironment.getGivenAgentLauncherMd5()).thenReturn("old-launcher... |
public void alterResource(AlterResourceStmt stmt) throws DdlException {
this.writeLock();
try {
// check if the target resource exists .
String name = stmt.getResourceName();
Resource resource = this.getResource(name);
if (resource == null) {
... | @Test(expected = DdlException.class)
public void testAllowAlterHiveResourceOnly(@Injectable BrokerMgr brokerMgr, @Injectable EditLog editLog,
@Mocked GlobalStateMgr globalStateMgr)
throws UserException {
ResourceMgr mgr = new ResourceMgr();
... |
public static boolean equalIncreasingByteArray(int len, byte[] arr) {
return equalIncreasingByteArray(0, len, arr);
} | @Test
public void equalIncreasingByteArray() {
class TestCase {
boolean mExpected;
byte[] mArray;
int mLength;
int mStart;
public TestCase(boolean expected, byte[] array, int length, int start) {
mExpected = expected;
mArray = array;
mLength = length;
... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testAbaloneQuantile() {
test(Loss.quantile(0.5), "abalone", Abalone.formula, Abalone.train, 2.2958);
} |
public static RedissonClient create() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return create(config);
} | @Test
public void testMasterSlaveConnectionFail2() {
Assertions.assertThrows(RedisConnectionException.class, () -> {
Config config = new Config();
config.useMasterSlaveServers()
.setMasterAddress("redis://gadfgdfgdsfg:1111")
.addSlaveAddress("r... |
@JsonCreator
public static DataSize parse(CharSequence size) {
return parse(size, DataSizeUnit.BYTES);
} | @Test
void parseCaseInsensitive() {
assertThat(DataSize.parse("1b")).isEqualTo(DataSize.parse("1B"));
} |
public static String getDomain(String url) {
ProviderInfo providerInfo = ProviderHelper.toProviderInfo(url);
return providerInfo.getHost();
} | @Test
public void testGetDomain() {
assertEquals("alipay.com", getDomain("bolt://alipay.com:80?a=b"));
assertEquals("alipay.com", getDomain("alipay.com:80?a=b"));
assertEquals("alipay.com", getDomain("bolt://alipay.com:80"));
assertEquals("alipay.com", getDomain("alipay.com:80"));
... |
protected final void ensureCapacity(final int index, final int length)
{
if (index < 0 || length < 0)
{
throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length);
}
final long resultingPosition = index + (long)length;
if (resulti... | @Test
void ensureCapacityIsANoOpIfExistingCapacityIsEnough()
{
final int index = 1;
final int capacity = 5;
final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(capacity);
buffer.ensureCapacity(index, capacity - index);
assertEquals(capacity, buffer.capacity()... |
public void resizeRecordsMap(Map<Key, Record> recordsMap, int size) {
int numRecordsToEvict = recordsMap.size() - size;
if (numRecordsToEvict <= 0) {
return;
}
if (numRecordsToEvict <= size) {
// Fewer records to evict than retain, make a heap of records to evict
IntermediateRecord[] r... | @Test
public void testResizeRecordsMap() {
// Test resize algorithm with numRecordsToEvict < trimToSize.
// TotalRecords=5; trimToSize=3; numRecordsToEvict=2
// d1 asc
TableResizer tableResizer =
new TableResizer(DATA_SCHEMA, QueryContextConverterUtils.getQueryContext(QUERY_PREFIX + "d1"));
... |
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf = getConf() == null ?
new YarnConfiguration() : new YarnConfiguration(getConf());
boolean isFederationEnabled = yarnConf.getBoolean(YarnConfiguration.FEDERATION_ENABLED,
YarnConfiguration.DEFAULT_FEDERATION_E... | @Test
public void testSavePolicy() throws Exception {
PrintStream oldOutPrintStream = System.out;
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(dataOut));
oldOutPrintStream.println(dataOut);
String[] args = {"-policy", "-s", "root.a;SC-1:0.1,SC-2:0.9;S... |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testUnknownMemberIdJoinsConsumerGroup() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId = Uuid.randomUuid().toString();
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
... |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testOrQuery() throws ParseException {
final ParsedQuery query = parser.parse("unknown_field:(x OR y)");
assertThat(query.terms().size()).isEqualTo(2);
assertThat(query.terms())
.extracting(ParsedTerm::field)
.containsOnly("unknown_field");
} |
@Override
public Rule getByUuid(String uuid) {
ensureInitialized();
Rule rule = rulesByUuid.get(uuid);
checkArgument(rule != null, "Can not find rule for uuid %s. This rule does not exist in DB", uuid);
return rule;
} | @Test
public void first_call_to_getById_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() {
underTest.getByUuid(AB_RULE.getUuid());
verify(ruleDao, times(1)).selectAll(any(DbSession.class));
verifyNoMethodCallTriggersCallToDB();
} |
@Override
public void validatePostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得岗位信息
List<PostDO> posts = postMapper.selectBatchIds(ids);
Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId);
// 校验
ids.forEach(id ... | @Test
public void testValidatePostList_notEnable() {
// mock 数据
PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.DISABLE.getStatus());
postMapper.insert(postDO);
// 准备参数
List<Long> ids = singletonList(postDO.getId());
// 调用, 并断言异常
assertServiceExcept... |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldNotAllowEmptyViewForPerforce() {
String p4XML = Objects.requireNonNull(this.getClass().getResource("/data/p4-cruise-config-empty-view.xml")).getFile();
assertThatThrownBy(() -> xmlLoader.loadConfigHolder(loadWithMigration(p4XML)))
.as("Should not accept p4 section with e... |
protected void mergeAndRevive(ConsumeReviveObj consumeReviveObj) throws Throwable {
ArrayList<PopCheckPoint> sortList = consumeReviveObj.genSortList();
POP_LOGGER.info("reviveQueueId={}, ck listSize={}", queueId, sortList.size());
if (sortList.size() != 0) {
POP_LOGGER.info("reviveQu... | @Test
public void testReviveMsgFromCk_messageNotFound_noRetry() throws Throwable {
PopCheckPoint ck = buildPopCheckPoint(0, 0, 0);
PopReviveService.ConsumeReviveObj reviveObj = new PopReviveService.ConsumeReviveObj();
reviveObj.map.put("", ck);
reviveObj.endTime = System.currentTimeM... |
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) {
if (messageListener instanceof TracingMessageListener) return messageListener;
return new TracingMessageListener(messageListener, this, addConsumerSpan);
} | @Test void messageListener_doesntDoubleWrap() {
MessageListener wrapped = jmsTracing.messageListener(mock(MessageListener.class), false);
assertThat(jmsTracing.messageListener(wrapped, false))
.isSameAs(wrapped);
} |
public static URepeated create(CharSequence identifier, UExpression expression) {
return new AutoValue_URepeated(identifier.toString(), expression);
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(URepeated.create("foo", UFreeIdent.create("foo")));
} |
public Publisher<K> keyIterator() {
return keyIterator(null);
} | @Test
public void testKeyIterator() {
RMapRx<Integer, Integer> map = redisson.getMap("simple");
sync(map.put(1, 0));
sync(map.put(3, 5));
sync(map.put(4, 6));
sync(map.put(7, 8));
List<Integer> keys = new ArrayList<Integer>(Arrays.asList(1, 3, 4, 7));
for (It... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithElementsThatThrowWhenYouCallHashCodeFailureTooMany() {
HashCodeThrower one = new HashCodeThrower();
HashCodeThrower two = new HashCodeThrower();
expectFailureWhenTestingThat(asList(one, two)).containsExactly(one);
} |
boolean sendRecords() {
int processed = 0;
recordBatch(toSend.size());
final SourceRecordWriteCounter counter =
toSend.isEmpty() ? null : new SourceRecordWriteCounter(toSend.size(), sourceTaskMetricsGroup);
for (final SourceRecord preTransformRecord : toSend) {
... | @Test
public void testSendRecordsConvertsData() {
createWorkerTask();
// Can just use the same record for key and value
List<SourceRecord> records = Collections.singletonList(
new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD)
);
... |
@Override
public void write(int b) throws IOException
{
checkClosed();
if (chunkSize - currentBufferPointer <= 0)
{
expandBuffer();
}
currentBuffer.put((byte) b);
currentBufferPointer++;
pointer++;
if (pointer > size)
{
... | @Test
void testAlreadyClose() throws IOException
{
try (RandomAccess randomAccessReadWrite = new RandomAccessReadWriteBuffer())
{
byte[] bytes = new byte[RandomAccessReadBuffer.DEFAULT_CHUNK_SIZE_4KB];
randomAccessReadWrite.write(bytes);
randomAccessReadWrite.... |
@Override
public <VOut> KStream<K, VOut> processValues(
final FixedKeyProcessorSupplier<? super K, ? super V, VOut> processorSupplier,
final String... stateStoreNames
) {
return processValues(
processorSupplier,
Named.as(builder.newProcessorName(PROCESSVALUES_NAME... | @Test
public void shouldNotAllowNullStoreNameOnProcessValues() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.processValues(fixedKeyProcessorSupplier, (String) null));
assertThat(exception.getMessage(), equalTo("stateStoreN... |
@Override
public Properties processor(String config) throws IOException {
Properties properties = new Properties();
try (Reader reader = new InputStreamReader(new ByteArrayInputStream(config.getBytes()), StandardCharsets.UTF_8)) {
properties.load(reader);
}
return proper... | @Test
void processor() throws IOException {
String properties = "registry.type=file\n" +
"registry.file.name=file-test-pro.conf";
Properties processor = new ProcessorProperties().processor(properties);
Assertions.assertEquals("file", processor.get("registry.type"));
... |
public Optional<AlluxioURI> getRootUfsUri() {
return Optional.ofNullable(mRootUfsUri);
} | @Test
public void testGetRootUfsUri() {
mJCommander.parse("-m", "/tmp/fuse-mp", "-u", "scheme://host/path");
assertEquals(Optional.of(new AlluxioURI("scheme://host/path")), mOptions.getRootUfsUri());
} |
@Override
public void process(Exchange exchange) throws Exception {
final SchematronProcessor schematronProcessor = SchematronProcessorFactory.newSchematronEngine(endpoint.getRules());
final Object payload = exchange.getIn().getBody();
final String report;
if (payload instanceof Sou... | @Test
public void testProcessValidXML() throws Exception {
Exchange exc = new DefaultExchange(context, ExchangePattern.InOut);
exc.getIn().setBody(ClassLoader.getSystemResourceAsStream("xml/article-1.xml"));
// process xml payload
producer.process(exc);
// assert
as... |
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
// consumer side, if in provider side,loadTest always false
SofaTracerSpan currentSpan = SofaTraceContextHolder.getSofaTraceContext().getCurrentSpan();
boolean loadTest = TracerUtils.is... | @Test
public void testConsumerPressure() {
//consumer side
SofaTracerSpan currentSpan = SofaTraceContextHolder.getSofaTraceContext().getCurrentSpan();
Map<String, String> bizBaggage = currentSpan.getSofaTracerSpanContext().getBizBaggage();
bizBaggage.put("mark", "T");
Assert.... |
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) {
Future<Integer> tlsFuture;
if (certSecretSources == null || certSecretSources.isEmpty()) {
tlsFuture = Future.succeededFutu... | @Test
void getHashPatternNotMatching(VertxTestContext context) {
String namespace = "ns";
CertSecretSource cert1 = new CertSecretSourceBuilder()
.withSecretName("cert-secret")
.withPattern("*.pem")
.build();
Secret secret = new SecretBuilder(... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void negativeFloatLiteral() {
String inputExpression = "-10.5";
BaseNode number = parse( inputExpression );
assertThat( number).isInstanceOf(SignedUnaryNode.class);
assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertLocation( inputExpression, numb... |
@Udf
public <T extends Comparable<? super T>> List<T> arraySortWithDirection(@UdfParameter(
description = "The array to sort") final List<T> input,
@UdfParameter(
description = "Marks the end of the series (inclusive)") final String direction) {
if (input == null || direction == null) {
... | @Test
public void shouldSortIntsAscending() {
final List<Integer> input = Arrays.asList(1, 3, -2);
final List<Integer> output = udf.arraySortWithDirection(input, "ascEnDing");
assertThat(output, contains(-2, 1, 3));
} |
public static void saveInstanceInfo(RequestInfo requestInfo) {
String key = requestInfo.getHost() + RemovalConstants.CONNECTOR + requestInfo.getPort();
InstanceInfo info = INSTANCE_MAP.computeIfAbsent(key, value -> {
InstanceInfo instanceInfo = new InstanceInfo();
instanceInfo.se... | @Test
public void saveInstanceInfo() {
long time = System.currentTimeMillis();
for (int i = 0; i < NUM; i++) {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHost(HOST);
requestInfo.setPort(PORT);
requestInfo.setSuccess(true);
... |
@VisibleForTesting
public void validateConfigKeyUnique(Long id, String key) {
ConfigDO config = configMapper.selectByKey(key);
if (config == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的参数配置
if (id == null) {
throw exception(CONFIG_KEY_DUPLICATE);
... | @Test
public void testValidateConfigKeyUnique_success() {
// 调用,成功
configService.validateConfigKeyUnique(randomLongId(), randomString());
} |
protected synchronized void doRestartConnectorAndTasks(RestartRequest request) {
String connectorName = request.connectorName();
Optional<RestartPlan> maybePlan = buildRestartPlan(request);
if (!maybePlan.isPresent()) {
log.debug("Skipping restart of connector '{}' since no status is... | @Test
public void testDoRestartConnectorAndTasksEmptyPlan() {
RestartRequest restartRequest = new RestartRequest(CONN1, false, true);
doReturn(Optional.empty()).when(herder).buildRestartPlan(restartRequest);
herder.doRestartConnectorAndTasks(restartRequest);
verifyNoMoreInteractions... |
public static String stripTrailingSlash(String path) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "path must not be null or empty");
String result = path;
while (!result.endsWith("://") && result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return resul... | @Test
void testDoNotStripTrailingSlashForRootPath() {
String rootPath = "blobstore://";
assertThat(LocationUtil.stripTrailingSlash(rootPath))
.as("Should be root path")
.isEqualTo(rootPath);
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
FEELFnResult<BigDecimal> s = sum.invoke( list );
Function<FEELEven... | @Test
void invokeArrayEmpty() {
FunctionTestUtil.assertResultError(meanFunction.invoke(new Object[]{}), InvalidParametersEvent.class);
} |
public static Combine.CombineFn<Boolean, ?, Long> combineFn() {
return new CountIfFn();
} | @Test
public void testReturnsAccumulatorUnchangedForNullInput() {
Combine.CombineFn countIfFn = CountIf.combineFn();
long[] accumulator = (long[]) countIfFn.addInput(countIfFn.createAccumulator(), null);
assertEquals(0L, accumulator[0]);
} |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitStringStringTrueDoubledSplitChar() throws Exception {
assertThat(JOrphanUtils.split("a;;b;;;;;;d;;e;;;;f", ";;", true),
CoreMatchers.equalTo(new String[]{"a", "b", "d", "e", "f"}));
} |
public boolean containsShardingTable(final Collection<String> logicTableNames) {
for (String each : logicTableNames) {
if (isShardingTable(each)) {
return true;
}
}
return false;
} | @Test
void assertContainsShardingTable() {
assertTrue(createMaximumShardingRule().containsShardingTable(Collections.singleton("logic_table")));
} |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitSSSSingleDelimiterWithDefaultValue() {
// Test non-empty parameters
assertThat(JOrphanUtils.split("a,bc,,", ",", "?"), CoreMatchers.equalTo(new String[]{"a", "bc", "?", "?"}));
} |
@Nonnull
public BatchSource<T> build() {
requireNonNull(clientFn, "clientFn must be set");
requireNonNull(searchRequestFn, "searchRequestFn must be set");
requireNonNull(mapToItemFn, "mapToItemFn must be set");
ElasticSourceConfiguration<T> configuration = new ElasticSourceConfigura... | @Test
public void when_createElasticSourceUsingBuilder_then_sourceHasCorrectName() {
BatchSource<Object> source = builderWithRequiredParams()
.build();
assertThat(source.name()).isEqualTo("elasticSource");
} |
public void add(Task task) {
tasks.put('/' + task.getName(), task);
TaskExecutor taskExecutor = new TaskExecutor(task);
try {
final Method executeMethod = task.getClass().getMethod("execute",
Map.class, PrintWriter.class);
if (executeMethod.isAnnotat... | @Test
void testDoNotPrintStackTrackWhenDisabled() throws Exception {
final TaskConfiguration taskConfiguration = new TaskConfiguration();
taskConfiguration.setPrintStackTraceOnError(false);
final TaskServlet servlet = new TaskServlet(metricRegistry, taskConfiguration);
servlet.add(gc... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testKin8nmQuantile() {
test(Loss.quantile(0.5), "kin8nm", Kin8nm.formula, Kin8nm.data, 0.1814);
} |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowStatement) {
return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s... | @Test
void assertCreateWithSelectNonPgCatalog() {
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class);
when(selectStatementContext.getSqlStatement()).thenReturn(new PostgreSQLSelectStatement());
assertThat(new PostgreSQLAdminExecutorCreator().create(selectState... |
public void resolveFields(SearchContext searchContext, String indexMapping) throws StarRocksConnectorException {
JSONObject jsonObject = new JSONObject(indexMapping);
// the indexName use alias takes the first mapping
Iterator<String> keys = jsonObject.keys();
String docKey = keys.next()... | @Test
public void testExtractFieldsNormal() throws Exception {
MappingPhase mappingPhase = new MappingPhase(null);
// ES version < 7.0
EsTable esTableBefore7X = fakeEsTable("fake", "test", "doc", columns);
SearchContext searchContext = new SearchContext(esTableBefore7X);
map... |
@NonNull
@Override
public FileName toProviderFileName( @NonNull ConnectionFileName pvfsFileName, @NonNull T details )
throws KettleException {
StringBuilder providerUriBuilder = new StringBuilder();
appendProviderUriConnectionRoot( providerUriBuilder, details );
// Examples:
// providerUriBu... | @Test
public void testToProviderFileNameHandlesConnectionsWithDomainAndRootPath() throws Exception {
mockDetailsWithDomain( details1, "my-domain:8080" );
mockDetailsWithRootPath( details1, "my/root/path" );
ConnectionFileName pvfsFileName = mockPvfsFileNameWithPath( "/rest/path" );
FileName provider... |
public String namespace(Namespace ns) {
return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns));
} | @Test
public void testNamespaceWithSlash() {
Namespace ns = Namespace.of("n/s");
assertThat(withPrefix.namespace(ns)).isEqualTo("v1/ws/catalog/namespaces/n%2Fs");
assertThat(withoutPrefix.namespace(ns)).isEqualTo("v1/namespaces/n%2Fs");
} |
List<Condition> run(boolean useKRaft) {
List<Condition> warnings = new ArrayList<>();
checkKafkaReplicationConfig(warnings);
checkKafkaBrokersStorage(warnings);
if (useKRaft) {
// Additional checks done for KRaft clusters
checkKRaftControllerStorage(warnings);... | @Test
public void checkKafkaJbodEphemeralStorageSingleBroker() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.editKafka()
.withConfig(Map.of(
// We want to avoid unrelated warnings
... |
public int add(Object o) {
HollowTypeMapper typeMapper = getTypeMapper(o.getClass(), null, null);
return typeMapper.write(o);
} | @Test
public void testIntPreassignedOrdinal() {
HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine);
TypeWithIntAssignedOrdinal o = new TypeWithIntAssignedOrdinal();
o.__assigned_ordinal = 1;
mapper.add(o);
// int fields are ignored
Assert.assertEqual... |
@Override
public void trace(String msg) {
logger.trace(msg);
} | @Test
void testMarkerTrace() {
jobRunrDashboardLogger.trace(marker, "trace");
verify(slfLogger).trace(marker, "trace");
} |
public String publish(TopicName topic, Map<String, String> attributes, ByteString data)
throws PubsubResourceManagerException {
checkIsUsable();
if (!createdTopics.contains(topic)) {
throw new IllegalArgumentException(
"Can not publish to a topic not managed by this instance.");
}
... | @Test
public void testPublishMessageUnmanagedTopicShouldFail() {
Map<String, String> attributes = ImmutableMap.of("key1", "value1");
ByteString data = ByteString.copyFromUtf8("valid message");
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class,
... |
public void sendCouponNewsletter() {
try {
// Retrieve the list of contacts from the "weekly-coupons-newsletter" contact
// list
// snippet-start:[sesv2.java2.newsletter.ListContacts]
ListContactsRequest contactListRequest = ListContactsRequest.builder()
.contactListName(CONTACT_LI... | @Test
public void test_sendCouponNewsletter_error_messageRejected() {
// Mock the necessary AWS SDK calls and responses
CreateEmailTemplateResponse templateResponse = CreateEmailTemplateResponse.builder().build();
when(sesClient.createEmailTemplate(any(CreateEmailTemplateRequest.class))).thenReturn(templa... |
public static void loggedMute(CheckedRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
} | @Test
void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() {
var stream = new ByteArrayOutputStream();
System.setErr(new PrintStream(stream));
Mute.loggedMute(this::methodThrowingException);
assertTrue(stream.toString().contains(MESSAGE));
} |
public static RecordBatchingStateRestoreCallback adapt(final StateRestoreCallback restoreCallback) {
Objects.requireNonNull(restoreCallback, "stateRestoreCallback must not be null");
if (restoreCallback instanceof RecordBatchingStateRestoreCallback) {
return (RecordBatchingStateRestoreCallba... | @Test
public void shouldPassRecordsThrough() {
final ArrayList<ConsumerRecord<byte[], byte[]>> actual = new ArrayList<>();
final RecordBatchingStateRestoreCallback callback = actual::addAll;
final RecordBatchingStateRestoreCallback adapted = adapt(callback);
final byte[] key1 = {1}... |
@Override
public RFuture<Boolean> removeAsync(Object o) {
String name = getRawName(o);
return commandExecutor.writeAsync(name, codec, RedisCommands.SREM_SINGLE, name, encode(o));
} | @Test
public void testRemoveAsync() throws InterruptedException, ExecutionException {
RSet<Integer> set = redisson.getSet("simple");
set.add(1);
set.add(3);
set.add(7);
Assertions.assertTrue(set.removeAsync(1).get());
Assertions.assertFalse(set.contains(1));
... |
@Override
public final long readLong() throws EOFException {
final long l = readLong(pos);
pos += LONG_SIZE_IN_BYTES;
return l;
} | @Test
public void testReadLongForPositionByteOrder() throws Exception {
long readLong1 = in.readLong(0, LITTLE_ENDIAN);
long readLong2 = in.readLong(2, BIG_ENDIAN);
long longB1 = Bits.readLong(INIT_DATA, 0, false);
long longB2 = Bits.readLong(INIT_DATA, 2, true);
assertEquals... |
@Override
public void closeRewardActivity(Long id) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(id);
if (dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 已关闭的活动,不能关闭噢
throw exception(REWARD_ACTIVITY_CLOSE_FAIL_... | @Test
public void testCloseRewardActivity() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id ... |
@Override
public boolean trySetComparator(Comparator<? super V> comparator) {
String className = comparator.getClass().getName();
String comparatorSign = className + ":" + calcClassSign(className);
Boolean res = get(commandExecutor.writeAsync(getRawName(), StringCodec.INSTANCE, RedisCommand... | @Test
public void testTrySetComparator() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
boolean setRes = set.trySetComparator(Collections.reverseOrder());
Assertions.assertTrue(setRes);
Assertions.assertTrue(set.add(1));
Assertions.assertTrue(set.add(2));
... |
public void initialize() {
if ((!(loggerFactory instanceof LoggerContext))) {
System.err.println("Unable to initialize logback. It seems that slf4j is bound to an unexpected backend " + loggerFactory.getClass().getName());
return;
}
File logbackFile = new File(configDir,... | @Test
public void shouldUseDefaultConfigFromClasspathIfUserSpecifiedConfigFileIsNotFound() {
final URL[] initializeFromPropertyResource = {null};
LogConfigurator logConfigurator = new LogConfigurator("xxx", "logging-test-logback.xml") {
@Override
protected void configureWith(... |
public UsernamePasswordAuthenticationToken getAuthentication(final String token) {
final Jws<Claims> claimsJws = Jwts.parser()
.verifyWith(tokenConfigurationParameter.getPublicKey())
.build()
.parseSignedClaims(token);
final JwsHeader jwsHeader = claimsJ... | @Test
void givenToken_whenGetAuthentication_thenReturnAuthentication() {
// Given
String token = Jwts.builder()
.claim(TokenClaims.USER_ID.getValue(), "12345")
.claim(TokenClaims.USER_TYPE.getValue(), "ADMIN")
.issuedAt(new Date())
.ex... |
public ReliableTopicConfig setReadBatchSize(int readBatchSize) {
this.readBatchSize = checkPositive("readBatchSize", readBatchSize);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setReadBatchSize_whenNegative() {
ReliableTopicConfig config = new ReliableTopicConfig("foo");
config.setReadBatchSize(-1);
} |
public PutMessageResult putMessageToSpecificQueue(MessageExtBrokerInner messageExt) {
BrokerController masterBroker = this.brokerController.peekMasterBroker();
if (masterBroker != null) {
return masterBroker.getMessageStore().putMessage(messageExt);
} else if (this.brokerController.g... | @Test
public void putMessageToSpecificQueueTest() {
// masterBroker is null
final PutMessageResult result1 = escapeBridge.putMessageToSpecificQueue(messageExtBrokerInner);
assert result1 != null;
assert PutMessageStatus.PUT_TO_REMOTE_BROKER_FAIL.equals(result1.getPutMessageStatus());... |
@Override
public T add(K name, V value) {
throw new UnsupportedOperationException("read only");
} | @Test
public void testAddStringValuesIterable() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
HEADERS.add("name", Arrays.asList("value1", "value2"));
}
});
} |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @Test
public void testCopyFromHostExtraBytes() throws Exception {
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
r, metrics, except, key, connection);
String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);
when(connection.getResponseCode()).thenR... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertTime() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("TIME").dataType("TIME").build();
Column column = DB2TypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.g... |
public static boolean isWebdavMethod(String method) {
return method != null && WEBDAV_METHOD_PATTERN.matcher(method).matches();
} | @Test
public void testIsWebdavMethod() {
for (String method : VALID_METHODS) {
Assertions.assertTrue(HttpWebdav.isWebdavMethod(method), method + " is a HttpWebdav method");
}
for (String method : INVALID_METHODS) {
Assertions.assertFalse(HttpWebdav.isWebdavMethod(meth... |
@Override
protected Object createBody() {
if (command instanceof MessageRequest) {
MessageRequest msgRequest = (MessageRequest) command;
byte[] shortMessage = msgRequest.getShortMessage();
if (shortMessage == null || shortMessage.length == 0) {
return null... | @Test
public void createBodyShouldReturnNullIfTheCommandIsNotAMessageRequest() {
AlertNotification command = new AlertNotification();
message = new SmppMessage(camelContext, command, new SmppConfiguration());
assertNull(message.createBody());
} |
public void validateTopic(Resource topic) {
validateTopic(topic.getName());
} | @Test
public void testValidateTopic() {
assertThrows(GrpcProxyException.class, () -> grpcValidator.validateTopic(""));
assertThrows(GrpcProxyException.class, () -> grpcValidator.validateTopic("rmq_sys_xxxx"));
grpcValidator.validateTopic("topicName");
} |
@Override
public void deleteProjectProperty(DbSession session, String key, String projectUuid, String projectKey,
String projectName, String qualifier) {
// do nothing
} | @Test
public void deleteProjectProperty1() {
underTest.deleteProjectProperty(dbSession, null, null, null, null, null);
assertNoInteraction();
} |
@VisibleForTesting
SocketAddress getTcpServerLocalAddress() {
return tcpChannel.localAddress();
} | @Test(timeout = 10000)
public void testIdle() throws InterruptedException, IOException {
Socket s = new Socket();
try {
s.connect(pm.getTcpServerLocalAddress());
int i = 0;
while (!s.isConnected() && i < RETRY_TIMES) {
++i;
Thread.sleep(SHORT_TIMEOUT_MILLISECONDS);
}
... |
@Nonnull
WanPublisherState getWanPublisherState(byte id) {
switch (id) {
case 0:
return WanPublisherState.REPLICATING;
case 1:
return WanPublisherState.PAUSED;
case 2:
return WanPublisherState.STOPPED;
default:
... | @Test
public void testGetWanPublisherState() {
assertEquals(WanPublisherState.REPLICATING, transformer.getWanPublisherState((byte) 0));
assertEquals(WanPublisherState.PAUSED, transformer.getWanPublisherState((byte) 1));
assertEquals(WanPublisherState.STOPPED, transformer.getWanPublisherState... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void setProperty_methods_trims_value() {
Settings underTest = new MapSettings();
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
String key = randomAlphanumeric(3);
String value = randomAlphanumeric(3);
underTest.setProper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.