focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@SuppressWarnings("nullness")
@VisibleForTesting
public ProcessContinuation run(
PartitionMetadata partition,
RestrictionTracker<TimestampRange, Timestamp> tracker,
OutputReceiver<DataChangeRecord> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
BundleFinalizer bundleFi... | @Test
public void testQueryChangeStreamWithHeartbeatRecord() {
final Struct rowAsStruct = mock(Struct.class);
final ChangeStreamResultSetMetadata resultSetMetadata =
mock(ChangeStreamResultSetMetadata.class);
final ChangeStreamResultSet resultSet = mock(ChangeStreamResultSet.class);
final Hear... |
@Override
public ClusterClientProvider<ApplicationId> deployApplicationCluster(
final ClusterSpecification clusterSpecification,
final ApplicationConfiguration applicationConfiguration)
throws ClusterDeploymentException {
checkNotNull(clusterSpecification);
checkN... | @Test
void testDeployApplicationClusterWithDeploymentTargetNotCorrectlySet() {
final Configuration flinkConfig = new Configuration();
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("file:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, YarnD... |
@Override
public void accept(MeterEntity entity, Long value) {
setEntityId(entity.id());
setServiceId(entity.serviceId());
setTotal(getTotal() + value);
} | @Test
public void testAccept() {
long time1 = 1597113318673L;
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), time1);
function.calculate();
assertThat(function.getValue()).isEqualTo(time1);
long time2 = 1597113447737L;
function.accept(MeterEnti... |
@Udf
public String extractFragment(
@UdfParameter(
value = "input",
description = "a valid URL to extract a fragment from")
final String input) {
return UrlParser.extract(input, URI::getFragment);
} | @Test
public void shouldExtractFragmentIfPresent() {
assertThat(extractUdf.extractFragment("https://docs.confluent.io/current/ksql/docs/syntax-reference.html#scalar-functions"), equalTo("scalar-functions"));
} |
public Optional<Violation> validate(IndexSetConfig newConfig) {
// Don't validate prefix conflicts in case of an update
if (Strings.isNullOrEmpty(newConfig.id())) {
final Violation prefixViolation = validatePrefix(newConfig);
if (prefixViolation != null) {
return... | @Test
public void validateWhenAlreadyManaged() {
final String prefix = "graylog_index";
final IndexSetConfig newConfig = mock(IndexSetConfig.class);
when(indexSetRegistry.isManagedIndex("graylog_index_0")).thenReturn(true);
when(newConfig.indexPrefix()).thenReturn(prefix);
... |
@Override
public <KEY> URIMappingResult<KEY> mapUris(List<URIKeyPair<KEY>> requestUriKeyPairs)
throws ServiceUnavailableException
{
if (requestUriKeyPairs == null || requestUriKeyPairs.isEmpty())
{
return new URIMappingResult<>(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap... | @Test
public void testSameHostSupportingMultiplePartitions() throws ServiceUnavailableException
{
int partitionCount = 10;
int requestPerPartition = 100;
// one host supporting 10 partitions
URI host = createHostURI(0, 0);
List<Ring<URI>> rings = IntStream.range(0, partitionCount)
.boxe... |
public String compress(String compressorName, String uncompressedString) throws IOException {
Checks.notNull(uncompressedString, "uncompressedString cannot be null");
Compressor compressor =
getCompressor(compressorName == null ? DEFAULT_COMPRESSOR_NAME : compressorName);
return base64Encode(compres... | @Test
public void compressShouldThrowExceptionIfCompressorNotFound() {
AssertHelper.assertThrows(
"compress should throw exception if compressor not found",
NullPointerException.class,
"unknown compressorName: abcd",
() -> stringCodec.compress("abcd", "testValue"));
} |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(file.attributes().getLink() != DescriptiveUrl.EMPTY) {
list.add(file.attributes().getLink());
}
return list;
} | @Test
public void testToUrl() throws Exception {
final DriveUrlProvider provider = new DriveUrlProvider();
final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
assertNotNull(provider.toUrl(test));
assertTrue(prov... |
public static SchemaKStream<?> buildSource(
final PlanBuildContext buildContext,
final DataSource dataSource,
final QueryContext.Stacker contextStacker
) {
final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed();
switch (dataSource.getDataSourceType()) {
case KST... | @Test
public void shouldReplaceWindowedStreamSourceWithMatchingPseudoColumnVersion() {
// Given:
givenWindowedStream();
givenExistingQueryWithOldPseudoColumnVersion(windowedStreamSource);
// When:
final SchemaKStream<?> result = SchemaKSourceFactory.buildSource(
buildContext,
data... |
@Override
public ExplodedPlugin explode(PluginInfo plugin) {
File toDir = new File(fs.getDeployedPluginsDir(), plugin.getKey());
try {
forceMkdir(toDir);
org.sonar.core.util.FileUtils.cleanDirectory(toDir);
File jarTarget = new File(toDir, plugin.getNonNullJarFile().getName());
FileU... | @Test
public void copy_all_classloader_files_to_dedicated_directory() throws Exception {
File deployDir = temp.newFolder();
when(fs.getDeployedPluginsDir()).thenReturn(deployDir);
File sourceJar = TestProjectUtils.jarOf("test-libs-plugin");
PluginInfo info = PluginInfo.create(sourceJar);
Exploded... |
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
ShenyuContext shenyuContext = builder.build(exchange);
exchange.getAttributes().put(Constants.CONTEXT, shenyuContext);
return chain.execute(exchange);
} | @Test
public void testExecuted() {
this.globalPlugin.execute(this.exchange, this.chain);
assertNotNull(this.exchange.getAttributes().get(Constants.CONTEXT));
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080/http")
.remoteAddress(new ... |
@Override
public Object result(RpcException e) {
// javax dependency judge
if (violationDependency()) {
// ConstraintViolationException judge
if (ConstraintViolationExceptionConvert.needConvert(e)) {
return ConstraintViolationExceptionConvert.handleConstrain... | @Test
void testNormalException() {
RpcException rpcException = new RpcException();
Object response = exceptionMapper.result(rpcException);
assertThat(response, not(nullValue()));
assertThat(response, instanceOf(String.class));
} |
static long[] getMemoryUsage(VespaService service) {
BufferedReader br;
int pid = service.getPid();
try {
br = new BufferedReader(new FileReader("/proc/" + pid + "/smaps"));
} catch (FileNotFoundException ex) {
service.setAlive(false);
return new long... | @Ignore
@Test
public void benchmarkSmapsParsing() throws IOException {
for (int i=0; i < 100000; i++) {
BufferedReader br = new BufferedReader(new StringReader(smaps));
long[] memusage = SystemPoller.getMemoryUsage(br);
assertEquals(913408L, memusage[0]);
... |
@Override
public ConfigErrors errors() {
return configErrors;
} | @Test
public void validate_shouldMakeSureParamNameIsOfNameType() {
assertThat(createAndValidate("name").errors().isEmpty(), is(true));
ConfigErrors errors = createAndValidate(".name").errors();
assertThat(errors.isEmpty(), is(false));
assertThat(errors.on(ParamConfig.NAME), is("Inval... |
public abstract int status(HttpServletResponse response); | @Test void servlet25_status_doesntParseLocalTypes() {
// while looks nice, this will overflow our cache
class LocalResponse extends HttpServletResponseImpl {
}
assertThat(servlet25.status(new LocalResponse()))
.isZero();
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendAudio() {
Message message = bot.execute(new SendAudio(chatId, audioFileId)
.caption("caption").captionEntities(new MessageEntity(MessageEntity.Type.italic, 0, 7))
).message();
MessageTest.checkMessage(message);
AudioTest.checkAudio(message.audio(... |
InvocationCallback queuePoll() {
InvocationCallback element;
synchronized (this) {
if (tail != head) {
element = elements[head & mask];
head++;
} else {
element = null;
frozen = true;
}
}
return element;
} | @Test(dataProvider = "offsets")
public void testExpandCapacity(int splitOffset) throws Throwable {
CompletableFuture<Object> future = new CompletableFuture<>();
QueueAsyncInvocationStage stage =
new QueueAsyncInvocationStage(null, null, future, makeCallback(0));
assertCallback(0, stage.... |
public Set<Analysis.AliasedDataSource> extractDataSources(final AstNode node) {
new Visitor().process(node, null);
return getAllSources();
} | @Test
public void shouldExtractUnaliasedJoinDataSources() {
// Given:
final AstNode stmt = givenQuery("SELECT * FROM TEST1 JOIN TEST2"
+ " ON test1.col1 = test2.col1;");
// When:
extractor.extractDataSources(stmt);
// Then:
assertContainsAlias(TEST1, TEST2);
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testNonExistantField() {
StreamRule rule = getSampleRule();
Message msg = getSampleMessage();
msg.addField("someother", "foo");
StreamRuleMatcher matcher = getMatcher(rule);
assertFalse(matcher.match(msg, rule));
} |
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
if (defaultTrustManager != null) {
defaultTrustManager.checkServerTrusted(chain, authType);
}
} catch (CertificateException ce) {
// If the certificate chain ... | @Test(expected = Exception.class)
public void testCustomX509TrustManagerWithUnrecognizedCertificate() throws CertificateException {
customTrustManager.checkServerTrusted(
new X509Certificate[] {unrecognizedSelfSignedCertificate}, "RSA");
} |
TaskSpec rebaseTaskSpecTime(TaskSpec spec) throws Exception {
ObjectNode node = JsonUtil.JSON_SERDE.valueToTree(spec);
node.set("startMs", new LongNode(Math.max(time.milliseconds(), spec.startMs())));
return JsonUtil.JSON_SERDE.treeToValue(node, TaskSpec.class);
} | @Test
public void testAgentExecWithNormalExit() throws Exception {
Agent agent = createAgent(Scheduler.SYSTEM);
SampleTaskSpec spec = new SampleTaskSpec(0, 120000,
Collections.singletonMap("node01", 1L), "");
TaskSpec rebasedSpec = agent.rebaseTaskSpecTime(spec);
testExec... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testGroupByWithRowExpression()
{
// TODO: verify output
analyze("SELECT (a, b) FROM t1 GROUP BY a, b");
} |
public static VisionModel V2S() {
return V2S("model/EfficientNet/efficientnet_v2_s.pt");
} | @Test
public void train() throws IOException {
Device device = Device.CUDA((byte) 1);
device.setDefaultDevice();
// half precision to lower memory usage.
var dtype = ScalarType.BFloat16;
var model = EfficientNet.V2S();
model.to(device, dtype);
var transform... |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
void testAcceptEndpoint() {
assertTrue(GooglePubSubMessageConsumptionTask.acceptEndpoint("googlepubsub://my-own-project-id/my-topic"));
} |
public static boolean validMagicNumbers( final BufferedInputStream bin ) throws IOException
{
final List<String> validMagicBytesCollection = JiveGlobals.getListProperty( "plugins.upload.magic-number.values.expected-value", Arrays.asList( "504B0304", "504B0506", "504B0708" ) );
for ( final String ent... | @Test
public void testJARMagicBytes() throws Exception
{
// Setup test fixture.
try (final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("hello.jar")) {
assert inputStream != null;
try (final BufferedInputStream in = new BufferedInputStream(inp... |
public boolean setGap(DefaultIssue issue, @Nullable Double d, IssueChangeContext context) {
if (!Objects.equals(d, issue.gap())) {
issue.setGap(d);
issue.setUpdateDate(context.date());
issue.setChanged(true);
// Do not send notifications to prevent spam when installing the SQALE plugin,
... | @Test
void not_set_gap_to_fix_if_unchanged() {
issue.setGap(3.14);
boolean updated = underTest.setGap(issue, 3.14, context);
assertThat(updated).isFalse();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.gap()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
} |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testOffsetAssignmentAfterUpConversionV1ToV2NonCompressed() {
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V1, RecordBatch.NO_TIMESTAMP, Compression.NONE);
checkOffsets(records, 0);
long offset = 1234567;
checkOffsets(new LogValidator(
... |
@Override
public long getSetOperationCount() {
throw new UnsupportedOperationException("Set operation on replicated maps is not supported.");
} | @Test(expected = UnsupportedOperationException.class)
public void testSetOperationCount() {
localReplicatedMapStats.getSetOperationCount();
} |
public void convertQueueHierarchy(FSQueue queue) {
List<FSQueue> children = queue.getChildQueues();
final String queueName = queue.getName();
emitChildQueues(queueName, children);
emitMaxAMShare(queueName, queue);
emitMaxParallelApps(queueName, queue);
emitMaxAllocations(queueName, queue);
... | @Test
public void testQueueMinimumCapacity() {
converter = builder.build();
converter.convertQueueHierarchy(rootQueue);
verify(ruleHandler, times(2)).handleMinResources();
} |
@Override
public void shutdown() throws PulsarClientException {
try {
// We will throw the last thrown exception only, though logging all of them.
Throwable throwable = null;
if (lookup != null) {
try {
lookup.close();
}... | @Test
public void testInitializeWithoutTimer() throws Exception {
ClientConfigurationData conf = new ClientConfigurationData();
conf.setServiceUrl("pulsar://localhost:6650");
PulsarClientImpl client = new PulsarClientImpl(conf);
HashedWheelTimer timer = mock(HashedWheelTimer.class);... |
public String createULID(Message message) {
checkTimestamp(message.getTimestamp().getMillis());
try {
return createULID(message.getTimestamp().getMillis(), message.getSequenceNr());
} catch (Exception e) {
LOG.error("Exception while creating ULID.", e);
return... | @Test
public void doesNotAcceptTooLargeTimestamp() {
final MessageULIDGenerator generator = new MessageULIDGenerator(new ULID());
final DateTime largeDate = DateTime.parse("+10889-08-02T05:31:50.656Z");
final Message message = messageFactory.createMessage("foo", "source", largeDate);
... |
public static <T> WithTimestamps<T> of(SerializableFunction<T, Instant> fn) {
return new WithTimestamps<>(fn, Duration.ZERO);
} | @Test
@Category(NeedsRunner.class)
public void withTimestampsBackwardsInTimeShouldThrow() {
SerializableFunction<String, Instant> timestampFn = input -> new Instant(Long.valueOf(input));
SerializableFunction<String, Instant> backInTimeFn =
input -> new Instant(Long.valueOf(input)).minus(Duration.mi... |
public CacheStats minus(CacheStats other) {
return CacheStats.of(
Math.max(0L, hitCount - other.hitCount),
Math.max(0L, missCount - other.missCount),
Math.max(0L, loadSuccessCount - other.loadSuccessCount),
Math.max(0L, loadFailureCount - other.loadFailureCount),
Math.max(0L,... | @Test
public void minus() {
var one = CacheStats.of(11, 13, 17, 19, 23, 27, 54);
var two = CacheStats.of(53, 47, 43, 41, 37, 31, 62);
var diff = two.minus(one);
checkStats(diff, 76, 42, 42.0 / 76, 34, 34.0 / 76,
26, 22, 22.0 / 48, 26 + 22, 14, 14.0 / (26 + 22), 4, 8);
assertThat(one.minus... |
KafkaSourceConsumerFn(
Class<?> connectorClass,
SourceRecordMapper<T> fn,
Integer maxRecords,
Long milisecondsToRun) {
this.connectorClass = (Class<? extends SourceConnector>) connectorClass;
this.fn = fn;
this.maxRecords = maxRecords;
this.milisecondsToRun = milisecondsToRun;
... | @Test
public void testKafkaSourceConsumerFn() {
Map<String, String> config =
ImmutableMap.of(
"from", "1",
"to", "10",
"delay", "0.4",
"topic", "any");
Pipeline pipeline = Pipeline.create();
PCollection<Integer> counts =
pipeline
... |
public long getNum_blocks() {
return num_blocks;
} | @Test
public void testGetNum_blocks() {
assertEquals(TestParameters.VP_UNKNOWN_NUM_BLOCKS, chmItspHeader.getNum_blocks());
} |
public static Write write() {
// 1000 for batch size is good enough in many cases,
// ex: if document size is large, around 10KB, the request's size will be around 10MB
// if document size is small, around 1KB, the request's size will be around 1MB
return new AutoValue_SolrIO_Write.Builder().setMaxBatch... | @Test
public void testWriteWithMaxBatchSize() throws Exception {
SolrIO.Write write =
SolrIO.write()
.withConnectionConfiguration(connectionConfiguration)
.to(SOLR_COLLECTION)
.withMaxBatchSize(BATCH_SIZE);
// write bundles size is the runner decision, we cannot for... |
public static TableIdentifier fromJson(String json) {
Preconditions.checkArgument(
json != null, "Cannot parse table identifier from invalid JSON: null");
Preconditions.checkArgument(
!json.isEmpty(), "Cannot parse table identifier from invalid JSON: ''");
return JsonUtil.parse(json, TableId... | @Test
public void testFailWhenFieldsHaveInvalidValues() {
String invalidNamespace = "{\"namespace\":\"accounting.tax\",\"name\":\"paid\"}";
assertThatThrownBy(() -> TableIdentifierParser.fromJson(invalidNamespace))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse JSON ar... |
public static DataMap getAnnotationsMap(Annotation[] as)
{
return annotationsToData(as, true);
} | @Test(description = "Unsafe call: RestSpecAnnotation annotation with short array member",
expectedExceptions = NullPointerException.class)
public void failsOnRestSpecAnnotationShortArrayMember()
{
@UnsupportedShortArray
class LocalClass {
}
final Annotation[] annotations = LocalClass.class.ge... |
public static String name(final String path) {
if(String.valueOf(Path.DELIMITER).equals(path)) {
return path;
}
if(!StringUtils.contains(path, Path.DELIMITER)) {
return path;
}
if(StringUtils.endsWith(path, String.valueOf(Path.DELIMITER))) {
re... | @Test
public void testName() {
assertEquals("p", PathNormalizer.name("/p"));
assertEquals("n", PathNormalizer.name("/p/n"));
assertEquals("p", PathNormalizer.name("p"));
assertEquals("n", PathNormalizer.name("p/n"));
} |
public static Expression[] parseExpressions(String template, EvaluationContext context, String expressionPrefix,
String expressionSuffix) throws ParseException {
// Prepare an array for results.
List<Expression> expressions = new ArrayList<>();
int startIdx = 0;
while (startIdx < templ... | @Test
void testRedirectParseExpressions() {
String template = "Hello {{ guid() > put(id) }} world! This is my {{ id }}";
// Build a suitable context.
EvaluationContext context = new EvaluationContext();
context.registerFunction("guid", UUIDELFunction.class);
context.registerFunction("p... |
public static <K> ShardedKey<K> of(K key, byte[] shardId) {
checkArgument(key != null, "Key should not be null!");
checkArgument(shardId != null, "Shard id should not be null!");
return new ShardedKey<K>(key, shardId);
} | @Test
public void testDecodeEncodeEqual() throws Exception {
Coder<ShardedKey<String>> coder = ShardedKey.Coder.of(StringUtf8Coder.of());
CoderProperties.coderDecodeEncodeEqual(coder, ShardedKey.of(KEY, SHARD));
CoderProperties.coderDecodeEncodeEqual(coder, ShardedKey.of(KEY, EMPTY_SHARD));
CoderPrope... |
@UdafFactory(description = "sum int values in a list into a single int")
public static TableUdaf<List<Integer>, Integer, Integer> sumIntList() {
return new TableUdaf<List<Integer>, Integer, Integer>() {
@Override
public Integer initialize() {
return 0;
}
@Override
public In... | @Test
public void shouldASumZeroes() {
final TableUdaf<List<Integer>, Integer, Integer> udaf = ListSumUdaf.sumIntList();
final Integer[] values = new Integer[] {0, 0, 0, 0, 0};
final List<Integer> list = Arrays.asList(values);
final Integer sum = udaf.aggregate(list, 0);
assertThat(0, equalTo(su... |
public static int getNewNodeId() {
return ID_COUNTER.incrementAndGet();
} | @Test
void testGetNewNodeIdIsThreadSafe() throws Exception {
final int numThreads = 10;
final int numIdsPerThread = 100;
final List<CheckedThread> threads = new ArrayList<>();
final OneShotLatch startLatch = new OneShotLatch();
final List<List<Integer>> idLists = Collectio... |
public List<Date> parse(String language)
{
return parse(language, new Date());
} | @Test
public void testParseYesterday()
{
Calendar yesterday = Calendar.getInstance();
yesterday.setTime(new Date());
yesterday.add(Calendar.DAY_OF_MONTH, -1);
List<Date> parse = new PrettyTimeParser().parse("yesterday");
Assert.assertFalse(parse.isEmpty());
Calendar parsedDat... |
@Override
public void process(HttpResponse response, HttpContext context) throws
HttpException, IOException {
List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList());
response.remov... | @Test
public void testInterceptorMultipleHeaderFilteredWarning2() throws IOException, HttpException {
ElasticsearchFilterDeprecationWarningsInterceptor interceptor = new ElasticsearchFilterDeprecationWarningsInterceptor();
HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new Protoc... |
public void addMessageListener(ReleaseMessageListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
} | @Test
public void testScanMessageWithGapAndNotifyMessageListener() throws Exception {
String someMessage = "someMessage";
long someId = 1;
ReleaseMessage someReleaseMessage = assembleReleaseMessage(someId, someMessage);
String someMissingMessage = "someMissingMessage";
long someMissingId = 2;
... |
@Override
public DataSink createDataSink(Context context) {
FactoryHelper.createFactoryHelper(this, context)
.validateExcept(TABLE_CREATE_PROPERTIES_PREFIX, SINK_PROPERTIES_PREFIX);
StarRocksSinkOptions sinkOptions =
buildSinkConnectorOptions(context.getFactoryConfig... | @Test
void testUnsupportedOption() {
DataSinkFactory sinkFactory =
FactoryDiscoveryUtils.getFactoryByIdentifier("starrocks", DataSinkFactory.class);
Assertions.assertThat(sinkFactory).isInstanceOf(StarRocksDataSinkFactory.class);
Configuration conf =
Configur... |
public Mono<Void> createStreamAppAcl(KafkaCluster cluster, CreateStreamAppAclDTO request) {
return adminClientService.get(cluster)
.flatMap(ac -> createAclsWithLogging(ac, createStreamAppBindings(request)))
.then();
} | @Test
void createsStreamAppDependantAcls() {
ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class);
when(adminClientMock.createAcls(createdCaptor.capture()))
.thenReturn(Mono.empty());
var principal = UUID.randomUUID().toString();
var host = UUID.ran... |
@Override
public void close() {
} | @Test
public void shouldSucceed_remoteNodeExceptionWithRetry() throws ExecutionException, InterruptedException {
// Given:
final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>(
ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemote));
final PushRouting routing = new PushRouting(sqr -> nodes.g... |
static boolean fieldMatch(Object repoObj, Object filterObj) {
return filterObj == null || repoObj.equals(filterObj);
} | @Test
public void testFieldMatchWithNonStringObjectsShouldReturnFalse() {
assertFalse(Utilities.fieldMatch(42, "42"));
} |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test
public void testVersion() {
Ip4Prefix ipPrefix;
// IPv4
ipPrefix = Ip4Prefix.valueOf("0.0.0.0/0");
assertThat(ipPrefix.version(), is(IpAddress.Version.INET));
} |
public static byte[] parseMAC(String value) {
final byte[] machineId;
final char separator;
switch (value.length()) {
case 17:
separator = value.charAt(2);
validateMacSeparator(separator);
machineId = new byte[EUI48_MAC_ADDRESS_LENGTH];... | @Test
public void testParseMacEUI48() {
assertArrayEquals(new byte[]{0, (byte) 0xaa, 0x11, (byte) 0xbb, 0x22, (byte) 0xcc},
parseMAC("00-AA-11-BB-22-CC"));
assertArrayEquals(new byte[]{0, (byte) 0xaa, 0x11, (byte) 0xbb, 0x22, (byte) 0xcc},
parseMAC("00:AA:11:BB:22:CC"... |
public static Pair<String, String> encryptHandler(String dataId, String content) {
if (!checkCipher(dataId)) {
return Pair.with("", content);
}
Optional<String> algorithmName = parseAlgorithmName(dataId);
Optional<EncryptionPluginService> optional = algorithmName.flatMap(
... | @Test
void testEncrypt() {
String dataId = "cipher-mockAlgo-application";
String content = "content";
String sec = mockEncryptionPluginService.generateSecretKey();
Pair<String, String> pair = EncryptionHandler.encryptHandler(dataId, content);
assertNotNull(pair);
asse... |
public Consumer getConsumerByConsumerId(long consumerId) {
return consumerRepository.findById(consumerId).orElse(null);
} | @Test
public void testGetConsumerByConsumerId() throws Exception {
long someConsumerId = 1;
Consumer someConsumer = mock(Consumer.class);
when(consumerRepository.findById(someConsumerId)).thenReturn(Optional.of(someConsumer));
assertEquals(someConsumer, consumerService.getConsumerByConsumerId(someCo... |
protected boolean isMatch(String invokerId) {
if (allEffective) {
return true;
} else {
//如果没有排除,那么只生效指定id,其余不生效。
if (excludeId.size() == 0) {
return effectiveId.contains(invokerId);
//如果有排除,那么除排除id外,其余都生效。
} else {
... | @Test
public void testIsMatch() {
TestCustomizeFilter testCustomizeFilter = new TestCustomizeFilter();
Assert.assertTrue(testCustomizeFilter.isMatch(""));
testCustomizeFilter = new TestCustomizeFilter();
testCustomizeFilter.setIdRule("AAA,BBB");
AbstractInterfaceConfig conf... |
@Override
public List<Column> getPartitionColumns(Map<ColumnId, Column> idToColumn) {
List<Column> columns = MetaUtils.getColumnsByColumnIds(idToColumn, partitionColumnIds);
for (int i = 0; i < columns.size(); i++) {
Expr expr = partitionExprs.get(i).convertToColumnNameExpr(idToColumn);
... | @Test
public void testInitUseSlotRef() {
Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATETIME), true, null, "", "");
SlotRef slotRef = new SlotRef(tableName, "k1");
partitionExprs.add(ColumnIdExpr.create(slotRef));
List<Column> schema = Collections.singletonList(k1);
... |
public static HeaderTemplate create(String name, Iterable<String> values) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("name is required.");
}
if (values == null) {
throw new IllegalArgumentException("values are required");
}
return new HeaderTemplate(name... | @Test
void it_should_throw_exception_when_name_is_empty() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> HeaderTemplate.create("", Collections.singletonList("test")));
assertThat(exception.getMessage()).isEqualTo("name is required.");
} |
@JsonProperty("rootPath")
public void setJerseyRootPath(String jerseyRootPath) {
this.jerseyRootPath = Optional.ofNullable(jerseyRootPath);
} | @Test
void usesYamlDefinedPattern() {
serverFactory.setJerseyRootPath(YAML_SET_PATTERN);
jerseyEnvironment.setUrlPattern(RUN_SET_PATTERN);
serverFactory.build(environment);
assertThat(jerseyEnvironment.getUrlPattern()).isEqualTo(YAML_SET_PATTERN);
} |
@Override
public boolean support(AnnotatedElement annotatedEle) {
return annotatedEle instanceof Method;
} | @Test
public void supportTest() {
AnnotationScanner scanner = new MethodAnnotationScanner();
assertTrue(scanner.support(ReflectUtil.getMethod(Example.class, "test")));
assertFalse(scanner.support(null));
assertFalse(scanner.support(Example.class));
assertFalse(scanner.support(ReflectUtil.getField(Example.cla... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testAnalyzeGemspec() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/rails-4.1.15/vendor/bundle/ruby/2.2.0/specifications/dalli-2.7.5.gemspec"));
analyzer.analyze(result, null);
fina... |
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (StringUtils.isNotBlank(protocol)) {
b.append(protocol);
b.append("://");
}
if (StringUtils.isNotBlank(host)) {
b.append(host);
}
if (!isPortDefault() &&... | @Test
public void testNullOrBlankURLs() {
s = null;
t = "";
assertEquals(t, new HttpURL(s).toString());
s = "";
t = "";
assertEquals(t, new HttpURL(s).toString());
s = " ";
t = "";
assertEquals(t, new HttpURL(s).toString());
} |
public static PrestoSparkRowBatchBuilder builder(int partitionCount, int targetAverageRowSizeInBytes)
{
checkArgument(partitionCount > 0, "partitionCount must be greater then zero: %s", partitionCount);
int targetSizeInBytes = partitionCount * targetAverageRowSizeInBytes;
targetSizeInBytes =... | @Test
public void testBuilderFull()
{
PrestoSparkRowBatchBuilder builder = PrestoSparkRowBatch.builder(
10,
5,
10,
NO_TARGET_ENTRY_SIZE_REQUIREMENT,
UNLIMITED_MAX_ENTRY_SIZE,
UNLIMITED_MAX_ENTRY_ROW_COUNT);
... |
@Converter
public static InputStream toInputStream(IoBuffer buffer) {
return buffer.asInputStream();
} | @Test
public void testToInputStream() throws Exception {
byte[] in = "Hello World".getBytes();
IoBuffer bb = IoBuffer.wrap(in);
try (InputStream is = MinaConverter.toInputStream(bb)) {
for (byte b : in) {
int out = is.read();
assertEquals(b, out);... |
@VisibleForTesting
protected Map<String, Object> read(String json) {
final Object result = jsonPath.read(json);
final Map<String, Object> fields = Maps.newHashMap();
if (result instanceof Integer || result instanceof Double || result instanceof Long) {
fields.put("result", resu... | @Test
public void testReadResultingInDouble() throws Exception {
String json = "{\"url\":\"https://api.github.com/repos/Graylog2/graylog2-server/releases/assets/22660\",\"some_double\":0.50,\"id\":22660,\"name\":\"graylog2-server-0.20.0-preview.1.tgz\",\"label\":\"graylog2-server-0.20.0-preview.1.tgz\",\"co... |
static Segment fromString(String segmentString) {
return parseFromString(segmentString);
} | @Test
public void fromString_allEmptyTokens_returnsNullSegment() {
assertThat(Segment.fromString("...")).isEqualTo(Segment.NULL);
} |
@Override
public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) {
if (lockConfiguration.getLockAtMostFor().compareTo(minimalLockAtMostFor) < 0) {
throw new IllegalArgumentException(
"Can not use KeepAliveLockProvider with lockAtMostFor shorter than " + minimal... | @Test
void shouldCancelIfCanNotExtend() {
mockExtension(originalLock, Optional.empty());
Optional<SimpleLock> lock = provider.lock(lockConfiguration);
assertThat(lock).isNotNull();
tickMs(1_500);
verify(originalLock).extend(lockConfiguration.getLockAtMostFor(), ofMillis(500)... |
@Override
public void removeConfigInfo(final String dataId, final String group, final String tenant, final String srcIp,
final String srcUser) {
tjt.execute(new TransactionCallback<Boolean>() {
final Timestamp time = new Timestamp(System.currentTimeMillis());
... | @Test
void testRemoveConfigInfo() {
String dataId = "dataId4567";
String group = "group3456789";
String tenant = "tenant4567890";
//mock exist config info
ConfigInfoWrapper configInfoWrapperOld = new ConfigInfoWrapper();
configInfoWrapperOld.setDataId(dataId)... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testHavingSettersGettersFromSeparateInterfacesIsValid() {
PipelineOptionsFactory.as(CombinedObject.class);
} |
@Udf
public <T extends Comparable<? super T>> T arrayMax(@UdfParameter(
description = "Array of values from which to find the maximum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldReturnNullForNullInput() {
assertThat(udf.arrayMax((List<String>) null), is(nullValue()));
} |
@Override
public boolean nullPlusNonNullIsNull() {
return false;
} | @Test
void assertNullPlusNonNullIsNull() {
assertFalse(metaData.nullPlusNonNullIsNull());
} |
@Override
public void goToFinished(ArchivedExecutionGraph archivedExecutionGraph) {
transitionToState(new Finished.Factory(this, archivedExecutionGraph, LOG));
} | @Test
void testGoToFinished() throws Exception {
final AdaptiveScheduler scheduler =
new AdaptiveSchedulerBuilder(
createJobGraph(),
mainThreadExecutor,
EXECUTOR_RESOURCE.getExecutor())
... |
static <T extends Comparable<? super T>> int compareListWithFillValue(
List<T> left, List<T> right, T fillValue) {
int longest = Math.max(left.size(), right.size());
for (int i = 0; i < longest; i++) {
T leftElement = fillValue;
T rightElement = fillValue;
if (i < left.size()) {
... | @Test
public void compareWithFillValue_nonEmptyListSameSizeEqualValue_returnsZero() {
assertThat(
ComparisonUtility.compareListWithFillValue(
Lists.newArrayList(1, 2, 3), Lists.newArrayList(1, 2, 3), 100))
.isEqualTo(0);
} |
@Override
public KiePMMLDroolsModelWithSources getKiePMMLModelWithSources(final CompilationDTO<T> compilationDTO) {
logger.trace("getKiePMMLModelWithSources {} {} {}", compilationDTO.getPackageName(),
compilationDTO.getFields(), compilationDTO.getModel());
try {
fina... | @Test
void getKiePMMLModelWithSources() {
final CommonCompilationDTO<Scorecard> compilationDTO =
CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmml,
... |
public static EventPublisher getPublisher(Class<? extends Event> topic) {
if (ClassUtils.isAssignableFrom(SlowEvent.class, topic)) {
return INSTANCE.sharePublisher;
}
return INSTANCE.publisherMap.get(topic.getCanonicalName());
} | @Test
void testGetPublisher() {
assertEquals(NotifyCenter.getSharePublisher(), NotifyCenter.getPublisher(TestSlowEvent.class));
assertTrue(NotifyCenter.getPublisher(TestEvent.class) instanceof DefaultPublisher);
} |
@Override
public void createNode(K8sNode node) {
checkNotNull(node, ERR_NULL_NODE);
K8sNode intNode;
K8sNode extNode;
K8sNode localNode;
K8sNode tunNode;
if (node.intgBridge() == null) {
String deviceIdStr = genDpid(deviceIdCounter.incrementAndGet());
... | @Test(expected = NullPointerException.class)
public void testCreateNullNode() {
target.createNode(null);
} |
@Override
public RedisClusterNode clusterGetNodeForSlot(int slot) {
Iterable<RedisClusterNode> res = clusterGetNodes();
for (RedisClusterNode redisClusterNode : res) {
if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) {
return redisCluster... | @Test
public void testClusterGetNodeForSlot() {
RedisClusterNode node1 = connection.clusterGetNodeForSlot(1);
RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000);
assertThat(node1.getId()).isNotEqualTo(node2.getId());
} |
@Override
public void execute(Runnable command) {
if (shutdown.get()) {
throw new RejectedExecutionException("Executor[" + name + "] was shut down.");
}
if (!taskQ.offer(command)) {
throw new RejectedExecutionException("Executor[" + name + "] is overloaded!");
... | @Test
public void execute() {
final int taskCount = 10;
ManagedExecutorService executorService = newManagedExecutorService(1, taskCount);
final CountDownLatch latch = new CountDownLatch(taskCount);
for (int i = 0; i < taskCount; i++) {
executorService.execute(latch::coun... |
public static String saslName(String username) {
String replace1 = EQUAL.matcher(username).replaceAll(Matcher.quoteReplacement("=3D"));
return COMMA.matcher(replace1).replaceAll(Matcher.quoteReplacement("=2C"));
} | @Test
public void saslName() {
String[] usernames = {"user1", "123", "1,2", "user=A", "user==B", "user,1", "user 1", ",", "=", ",=", "=="};
for (String username : usernames) {
String saslName = ScramFormatter.saslName(username);
// There should be no commas in saslName (comma... |
public static List<TierFactory> initializeTierFactories(Configuration configuration) {
String externalTierFactoryClass =
configuration.get(
NettyShuffleEnvironmentOptions
.NETWORK_HYBRID_SHUFFLE_EXTERNAL_REMOTE_TIER_FACTORY_CLASS_NAME);
... | @Test
void testInitEphemeralTiers() {
Configuration configuration = new Configuration();
List<TierFactory> tierFactories =
TierFactoryInitializer.initializeTierFactories(configuration);
assertThat(tierFactories).hasSize(2);
assertThat(tierFactories.get(0)).isInstanceO... |
@PostMapping(value = "/artifact/download")
public ResponseEntity<String> importArtifact(@RequestParam(value = "url", required = true) String url,
@RequestParam(value = "mainArtifact", defaultValue = "true") boolean mainArtifact,
@RequestParam(value = "secretName", required = false) String secretNam... | @Test
void shouldReturnNoContentWhenTheServiceHasNotBeenCreated() throws MockRepositoryImportException {
// arrange
Mockito.when(serviceService.importServiceDefinition(Mockito.any(File.class), Mockito.any(ReferenceResolver.class),
Mockito.any(ArtifactInfo.class))).thenReturn(Collections.empty... |
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 testSplitStringStringTrueWithLeadingComplexSplitCharacters() {
// Test leading split characters
assertThat(JOrphanUtils.split(" , ,a ,bc", " ,", true), CoreMatchers.equalTo(new String[]{"a", "bc"}));
} |
@Override
public boolean hasAnySuperAdmin(Collection<Long> ids) {
if (CollectionUtil.isEmpty(ids)) {
return false;
}
RoleServiceImpl self = getSelf();
return ids.stream().anyMatch(id -> {
RoleDO role = self.getRoleFromCache(id);
return role != null... | @Test
public void testHasAnySuperAdmin_true() {
try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(RoleServiceImpl.class)))
.thenReturn(roleService);
// mock 数据
... |
public Date getEndOfNextNthPeriod(Date now, int numPeriods) {
Calendar cal = this;
cal.setTime(now);
roundDownTime(cal, this.datePattern);
switch (this.periodicityType) {
case TOP_OF_MILLISECOND:
cal.add(Calendar.MILLISECOND, numPeriods);
break;
case TOP_OF_SECOND:
... | @Test
public void roundsDateWithMissingTimeUnits() throws ParseException {
final Date REF_DATE = parseDate("yyyy-MM-dd HH:mm:ss.SSS", "2000-12-25 09:30:49.876");
Calendar cal = getEndOfNextNthPeriod("yyyy-MM-dd-ss", REF_DATE, -1);
assertEquals(2000, cal.get(Calendar.YEAR));
assertEquals(Calendar.DECE... |
@Override
public Future<RestResponse> restRequest(RestRequest request)
{
return restRequest(request, new RequestContext());
} | @Test(dataProvider = "isD2Async")
public void testRequest(boolean isD2Async) throws Exception
{
AtomicReference<ServiceProperties> serviceProperties = new AtomicReference<>();
serviceProperties.set(createServiceProperties(null));
BackupRequestsClient client = createClient(serviceProperties::get, isD2Asy... |
public boolean liveness() {
if (!Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(webServerStatusNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(ceStatusNodeCheck.check().getStatu... | @Test
public void success_when_db_web_ce_es_succeed() {
when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN);
when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN);
when(ceStatusNodeCheck.check()).thenReturn(Health.GREEN);
when(esStatusNodeCheck.check()).thenReturn(Health.GREEN);
... |
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) {
// Start of evaluate
boolean retval = false;
// If we have 0 items in the list, evaluate the current condition
// Otherwise, evaluate all sub-conditions
//
try {
if ( isAtomic() ) {
if ( function == FUNC_TRUE ) {
... | @Test
public void testZeroSmallerOrEqualsThanNull() {
String left = "left";
String right = "right";
Long leftValue = 0L;
Long rightValue = null;
RowMetaInterface rowMeta = new RowMeta();
rowMeta.addValueMeta( new ValueMetaInteger( left ) );
rowMeta.addValueMeta( new ValueMetaInteger( rig... |
public void replay(TopicRecord record) {
Uuid existingUuid = topicsByName.put(record.name(), record.topicId());
if (existingUuid != null) {
// We don't currently support sending a second TopicRecord for the same topic name...
// unless, of course, there is a RemoveTopicRecord in ... | @Test
public void testDuplicateTopicIdReplay() {
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build();
ReplicationControlManager replicationControl = ctx.replicationControl;
replicationControl.replay(new TopicRecord().
setName("foo").
... |
@Override
public Set<Entry<CharSequence, V>> entrySet() {
Set<Entry<CharSequence, V>> entrySet = Sets.newHashSet();
for (Entry<CharSequenceWrapper, V> entry : wrapperMap.entrySet()) {
entrySet.add(new CharSequenceEntry<>(entry));
}
return entrySet;
} | @Test
public void testEntrySet() {
CharSequenceMap<String> map = CharSequenceMap.create();
map.put("key1", "value1");
map.put(new StringBuilder("key2"), "value2");
assertThat(map.entrySet()).hasSize(2);
} |
@Override
protected void processRecord(RowData row) {
synchronized (resultLock) {
boolean isInsertOp =
row.getRowKind() == RowKind.INSERT || row.getRowKind() == RowKind.UPDATE_AFTER;
// Always set the RowKind to INSERT, so that we can compare rows correctly (RowKi... | @Test
void testLimitedSnapshot() {
final ResolvedSchema schema =
ResolvedSchema.physical(
new String[] {"f0", "f1"},
new DataType[] {DataTypes.STRING(), DataTypes.INT()});
@SuppressWarnings({"unchecked", "rawtypes"})
final Data... |
public static String getClientIp(ServerHttpRequest request) {
for (String header : IP_HEADER_NAMES) {
String ipList = request.getHeaders().getFirst(header);
if (StringUtils.hasText(ipList) && !UNKNOWN.equalsIgnoreCase(ipList)) {
String[] ips = ipList.trim().split("[,;]");... | @Test
void testGetUnknownIPAddressWhenRemoteAddressIsNull() {
var request = MockServerHttpRequest.get("/").build();
var actual = IpAddressUtils.getClientIp(request);
assertEquals(IpAddressUtils.UNKNOWN, actual);
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testStateParameterDuplicate() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("duplicate");
thrown.expectMessage("my-id");
thrown.expectMessage("myProcessElement");
thrown.expectMessage("index 2");
thrown.expectMessage(not(mentionsTimers... |
public static Locale createLocale( String localeCode ) {
if ( Utils.isEmpty( localeCode ) ) {
return null;
}
StringTokenizer parser = new StringTokenizer( localeCode, "_" );
if ( parser.countTokens() == 2 ) {
return new Locale( parser.nextToken(), parser.nextToken() );
}
if ( parser.... | @Test
public void createLocale_DoubleCode_Variant() throws Exception {
assertEquals( new Locale( "no", "NO", "NY" ), EnvUtil.createLocale( "no_NO_NY" ) );
} |
public static ListenableFuture<CustomerId> findEntityIdAsync(TbContext ctx, EntityId originator) {
switch (originator.getEntityType()) {
case CUSTOMER:
return Futures.immediateFuture((CustomerId) originator);
case USER:
return toCustomerIdAsync(ctx, ctx.ge... | @Test
public void givenUserEntityType_whenFindEntityIdAsync_thenOK() throws ExecutionException, InterruptedException {
// GIVEN
var user = new User(new UserId(UUID.randomUUID()));
var expectedCustomerId = new CustomerId(UUID.randomUUID());
user.setCustomerId(expectedCustomerId);
... |
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
// Load the URL
//
setUrl( rep.getStepAttributeString( id_step, "wsUrl" ) );
// Load the operation
//
setOperationName( rep.getStepAttributeString( id_step, "wsOp... | @Test
public void testReadRep() throws Exception {
Repository rep = mock( Repository.class );
IMetaStore metastore = mock( IMetaStore.class );
DatabaseMeta dbMeta = mock( DatabaseMeta.class );
StringObjectId id_step = new StringObjectId( "oid" );
when( rep.getStepAttributeString( id_step, "wsOper... |
@Override
public AgentMetadataDTO toDTO(AgentMetadata agentMetadata) {
return new AgentMetadataDTO(agentMetadata.elasticAgentId(), agentMetadata.agentState(), agentMetadata.buildState(), agentMetadata.configState());
} | @Test
public void fromDTO_shouldConvertToAgentMetadataDTOFromAgentMetadata() {
final AgentMetadata agentMetadata = new AgentMetadata("agent-id", "Idle", "Building", "Enabled");
final AgentMetadataDTO agentMetadataDTO = new AgentMetadataConverterV4().toDTO(agentMetadata);
assertThat(agentMe... |
@Override
public void receiveConfigInfo(String configInfo) {
if (StringUtils.isEmpty(configInfo)) {
return;
}
Properties properties = new Properties();
try {
properties.load(new StringReader(configInfo));
innerReceive(properties);
... | @Test
void testReceiveConfigInfoIsNotProperties() {
final Deque<Properties> q2 = new ArrayDeque<Properties>();
PropertiesListener a = new PropertiesListener() {
@Override
public void innerReceive(Properties properties) {
q2.offer(properties);
}
... |
@VisibleForTesting
int formatSchedulerConf(String webAppAddress, WebResource resource)
throws Exception {
ClientResponse response = null;
resource = (resource != null) ? resource :
initializeWebResource(webAppAddress);
try {
Builder builder;
if (UserGroupInformation.isSecurityEna... | @Test(timeout = 10000)
public void testFormatSchedulerConf() throws Exception {
try {
super.setUp();
GuiceServletConfig.setInjector(
Guice.createInjector(new WebServletModule()));
ResourceScheduler scheduler = rm.getResourceScheduler();
MutableConfigurationProvider provider =
... |
public String convertInt(int i) {
return convert(i);
} | @Test
public void withBackslash() {
FileNamePattern pp = new FileNamePattern("c:\\foo\\bar.%i", context);
assertEquals("c:/foo/bar.3", pp.convertInt(3));
} |
public static Builder builder() {
return new Builder();
} | @Test
void throwsFeignExceptionIncludingBody() {
server.enqueue(new MockResponse().setBody("success!"));
TestInterface api = Feign.builder().decoder((response, type) -> {
throw new IOException("timeout");
})
.target(TestInterface.class, "http://localhost:" + server.getPort());
try {
... |
public static TopicPath topicPathFromName(String projectId, String topicName) {
return new TopicPath(String.format("projects/%s/topics/%s", projectId, topicName));
} | @Test
public void topicPathFromNameWellFormed() {
TopicPath path = PubsubClient.topicPathFromName("test", "something");
assertEquals("projects/test/topics/something", path.getPath());
assertEquals("/topics/test/something", path.getFullPath());
assertEquals(ImmutableList.of("test", "something"), path.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.