focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
} | @Test
public void testIsNullOrEmpty() {
assertTrue(Tools.isNullOrEmpty(null));
assertTrue(Tools.isNullOrEmpty(Collections.emptyList()));
} |
public void forEachNormalised(BiConsumer<? super String, ? super String> entryConsumer) {
for (int i = 0; i < size(); i++) {
entryConsumer.accept(name(i), value(i));
}
} | @Test
void forEachNormalised() {
Headers headers = new Headers();
headers.add("Via", "duct");
headers.add("Cookie", "this=that");
headers.add("Cookie", "frizzle=Frazzle");
Map<String, List<String>> result = new LinkedHashMap<>();
headers.forEachNormalised((k, v) ->
... |
public String decode(byte[] val) {
return codecs[0].decode(val, 0, val.length);
} | @Test
public void testDecodeKoreanPersonName() {
assertEquals(KOREAN_PERSON_NAME,
ksx1001().decode(KOREAN_PERSON_NAME_BYTES));
} |
public static String next() {
return next(false);
} | @Test
@Disabled
public void nextTest() {
Console.log(ObjectId.next());
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
attributes.find(file, listener);
return true;
}
catch(NotfoundException e) {
... | @Test
public void testFindCommonPrefix() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
assertTrue(new GoogleStorageFindFeature(session).find(container));
final String prefix = new AlphanumericRandomStringService().... |
@VisibleForTesting
void addQueues(String args, SchedConfUpdateInfo updateInfo) {
if (args == null) {
return;
}
ArrayList<QueueConfigInfo> queueConfigInfos = new ArrayList<>();
for (String arg : args.split(";")) {
queueConfigInfos.add(getQueueConfigInfo(arg));
}
updateInfo.setAddQue... | @Test(timeout = 10000)
public void testAddQueues() {
SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo();
cli.addQueues("root.a:a1=aVal1,a2=aVal2,a3=", schedUpdateInfo);
Map<String, String> paramValues = new HashMap<>();
List<QueueConfigInfo> addQueueInfo = schedUpdateInfo.getAddQueueInfo(... |
@Override
public Set<String> initialize() {
try {
checkpointFileCache.putAll(checkpointFile.read());
} catch (final IOException e) {
throw new StreamsException("Failed to read checkpoints for global state globalStores", e);
}
final Set<String> changelogTopics... | @Test
public void shouldThrowStreamsExceptionForOldTopicPartitions() throws IOException {
final HashMap<TopicPartition, Long> expectedOffsets = new HashMap<>();
expectedOffsets.put(t1, 1L);
expectedOffsets.put(t2, 1L);
expectedOffsets.put(t3, 1L);
expectedOffsets.put(t4, 1L);... |
public static <T extends TypedSPI> T getService(final Class<T> serviceInterface, final Object type) {
return getService(serviceInterface, type, new Properties());
} | @Test
void assertGetServiceWithoutProperties() {
assertThat(TypedSPILoader.getService(TypedSPIFixture.class, "TYPED.FIXTURE"), instanceOf(TypedSPIFixtureImpl.class));
} |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseStepParameterUsingParamsToGetWorkflowParams() {
StringParameter bar =
StringParameter.builder().name("bar").expression("params.get('foo') + '-1'").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.singletonMap("foo", StringParame... |
public PaginatedList<StreamDestinationFilterRuleDTO> findPaginatedForStream(
String streamId,
String queryString,
Bson sort,
int perPage,
int page,
Predicate<String> permissionSelector
) {
final var query = parseQuery(queryString);
... | @Test
@MongoDBFixtures("StreamDestinationFilterServiceTest-2024-07-01-1.json")
void findPaginatedForStream() {
final var result = service.findPaginatedForStream("54e3deadbeefdeadbeef1000", "", Sorts.ascending("title"), 10, 1, id -> true);
assertThat(result.delegate()).hasSize(3);
} |
static boolean isEndpointAvailable(String url) {
return !RestClient.create(url, 1)
.withRequestTimeoutSeconds(1)
.withRetries(1)
.withHeader("Metadata", "True")
.get()
.getBody()
.isEmpty();
} | @Test
public void isEndpointAvailable() {
// given
String endpoint = "/some-endpoint";
String url = String.format("http://localhost:%d%s", wireMockRule.port(), endpoint);
stubFor(get(urlEqualTo(endpoint)).willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody("some-bod... |
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString... | @Test
public void shouldAbortOnError_ProducerFencedException() {
// When:
doThrow(new ProducerFencedException("Error!")).when(transactionalProducer).commitTransaction();
final KsqlStatementException e = assertThrows(
KsqlStatementException.class,
() -> distributor.execute(CONFIGURED_STATEM... |
@Override
public ConsumerConnection examineConsumerConnectionInfo(
String consumerGroup) throws InterruptedException, MQBrokerException,
RemotingException, MQClientException {
return defaultMQAdminExtImpl.examineConsumerConnectionInfo(consumerGroup);
} | @Test
public void testExamineConsumerConnectionInfo() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
ConsumerConnection consumerConnection = defaultMQAdminExt.examineConsumerConnectionInfo("default-consumer-group");
assertThat(consumerConnection.getConsumeType... |
public static WriteRequest convertToWriteRequest(Log log) {
return WriteRequest.newBuilder().setKey(log.getKey()).setGroup(log.getGroup())
.setData(log.getData())
.setType(log.getType())
.setOperation(log.getOperation())
.putAllExtendInfo(log.getEx... | @Test
void testConvertToWriteRequest() {
ByteString data = ByteString.copyFrom("data".getBytes());
Log log = Log.newBuilder().setKey("key").setGroup("group").setData(data).setOperation("o").putExtendInfo("k", "v").build();
WriteRequest writeRequest = ProtoMessageUtil.convertToWriteRequest(lo... |
public static void insert(
final UnsafeBuffer termBuffer, final int termOffset, final UnsafeBuffer packet, final int length)
{
if (0 == termBuffer.getInt(termOffset))
{
termBuffer.putBytes(termOffset + HEADER_LENGTH, packet, HEADER_LENGTH, length - HEADER_LENGTH);
te... | @Test
void shouldInsertLastFrameIntoBuffer()
{
final int frameLength = BitUtil.align(256, FRAME_ALIGNMENT);
final int srcOffset = 0;
final int tail = TERM_BUFFER_CAPACITY - frameLength;
final int termOffset = tail;
final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.a... |
@Override
public void process(Exchange exchange) throws Exception {
final String msg = exchange.getIn().getBody(String.class);
final String sendTo = exchange.getIn().getHeader(IrcConstants.IRC_SEND_TO, String.class);
if (connection == null || !connection.isConnected()) {
reconne... | @Test
public void processTestException() {
when(exchange.getIn()).thenReturn(message);
when(message.getBody(String.class)).thenReturn("PART foo");
when(message.getHeader(IrcConstants.IRC_TARGET, String.class)).thenReturn("bottest");
when(connection.isConnected()).thenReturn(false);... |
public Optional<UserDto> authenticate(HttpRequest request) {
return extractCredentialsFromHeader(request)
.flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request)));
} | @Test
public void authenticate_from_basic_http_header_with_password_containing_semi_colon() {
String password = "!ascii-only:-)@";
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(A_LOGIN + ":" + password));
when(credentialsAuthentication.authenticate(new Credentials(A_LOGIN, p... |
public String getGroup() {
return group;
} | @Test
void testGetGroup() {
String group = metadataOperation.getGroup();
assertNull(group);
} |
public static Writer writerForAppendable(Appendable appendable) {
return appendable instanceof Writer ? (Writer) appendable : new AppendableWriter(appendable);
} | @Test
public void testWriterForAppendable() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
Writer writer = Streams.writerForAppendable(stringBuilder);
writer.append('a');
writer.append('\u1234');
writer.append("test");
writer.append(null); // test custom null handling... |
@UdafFactory(description = "Compute average of column with type Long.",
aggregateSchema = "STRUCT<SUM bigint, COUNT bigint>")
public static TableUdaf<Long, Struct, Double> averageLong() {
return getAverageImplementation(
0L,
STRUCT_LONG,
(sum, newValue) -> sum.getInt64(SUM) + newValu... | @Test
public void shouldUndoSummedCountedValues() {
final TableUdaf<Long, Struct, Double> udaf = AverageUdaf.averageLong();
Struct agg = udaf.initialize();
final Long[] values = new Long[] {1L, 1L, 1L, 1L, 1L};
for (final Long thisValue : values) {
agg = udaf.aggregate(thisValue, agg);
}
... |
@Udf
public Double random() {
return Math.random();
} | @Test
public void shouldReturnDistinctValueEachInvocation() {
int capacity = 1000;
final Set<Double> outputs = new HashSet<>(capacity);
for (int i = 0; i < capacity; i++) {
outputs.add(udf.random());
}
assertThat(outputs, hasSize(capacity));
assertThat(outputs, everyItem(greaterThanOrEqu... |
void regionUnfinished(SchedulingPipelinedRegion region) {
for (ConsumerRegionGroupExecutionView executionView :
executionViewByRegion.getOrDefault(region, Collections.emptySet())) {
executionView.regionUnfinished(region);
}
} | @Test
void testUnfinishedWrongRegion() {
consumerRegionGroupExecutionViewMaintainer.regionUnfinished(producerRegion);
assertThat(consumerRegionGroupExecutionView.isFinished()).isFalse();
} |
public static String decode(InputStream in) {
StringBuilder strBuild = new StringBuilder();
Collection<? extends Certificate> certificates = readCertificates(in);
if (certificates != null) {
for (Certificate cert : certificates) {
CertificateManager certificateManager = new CertificateManager(cert);
st... | @Test
public void decodeNotCertificateFile() throws IOException {
try (InputStream in = new FileInputStream(emptyPath)) {
String result = CertificateManager.decode(in);
assertThat(result).isEmpty();
}
} |
void flush() {
producer.flush();
} | @Test
public void shouldForwardCallToFlush() {
streamsProducerWithMock.flush();
verify(mockedProducer).flush();
} |
@Override
public int inferParallelism(Context dynamicParallelismContext) {
FileEnumerator fileEnumerator;
List<HiveTablePartition> partitions;
if (dynamicFilterPartitionKeys != null) {
fileEnumerator =
new HiveSourceDynamicFileEnumerator.Provider(
... | @Test
void testDynamicParallelismInferenceWithFiltering() throws Exception {
ObjectPath tablePath = new ObjectPath("default", "hiveTbl3");
createTable(tablePath, hiveCatalog, true);
HiveSource<RowData> hiveSource =
createHiveSourceWithPartition(tablePath, new Configuration()... |
public void withLock(final List<String> e164s, final Runnable task, final Executor lockAcquisitionExecutor) {
if (e164s.isEmpty()) {
throw new IllegalArgumentException("List of e164s to lock must not be empty");
}
final List<LockItem> lockItems = new ArrayList<>(e164s.size());
try {
// Off... | @Test
void withLockTaskThrowsException() throws InterruptedException {
assertThrows(RuntimeException.class, () -> accountLockManager.withLock(List.of(FIRST_NUMBER, SECOND_NUMBER), () -> {
throw new RuntimeException();
}, executor));
verify(lockClient, times(2)).acquireLock(any());
verify(lockCl... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
super.doFilter(request, response, chain);
return;
}
final HttpServletRequest httpRequest = (HttpServletRequest) reque... | @Test
public void testWithRequestSessionIdValid() throws IOException, ServletException {
final int sessionCount = SessionListener.getSessionCount();
final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
final... |
public static void setValue( Object object, Field field, String value ) {
try {
Method setMethod = getDeclaredMethod( object.getClass(),
SET_PREFIX + StringUtils.capitalize( field.getName() ), String.class );
setMethod.invoke( object, value );
} catch ( NoSuchMethodException | InvocationTarg... | @Test
public void testSetValue() throws NoSuchFieldException {
TestConnectionWithBucketsDetailsChild testConnectionDetails = new TestConnectionWithBucketsDetailsChild();
testConnectionDetails.setPassword( PASSWORD );
testConnectionDetails.setPassword3( PASSWORD3 );
EncryptUtils.setValue( testConnectio... |
@Override
public boolean find(final Path file, final ListProgressListener listener) {
return session.getClient().existsAndIsAccessible(file.getAbsolute());
} | @Test
public void testFindFileNotFound() throws Exception {
final MantaFindFeature f = new MantaFindFeature(session);
assertFalse(f.find(new Path(
new MantaAccountHomeInfo(session.getHost().getCredentials().getUsername(), session.getHost().getDefaultPath()).getAccountPrivateRoot(),
... |
public RuntimeOptionsBuilder parse(Class<?> clazz) {
RuntimeOptionsBuilder args = new RuntimeOptionsBuilder();
for (Class<?> classWithOptions = clazz; hasSuperClass(
classWithOptions); classWithOptions = classWithOptions.getSuperclass()) {
CucumberOptions options = requireNonNul... | @Test
void create_with_snippets() {
RuntimeOptions runtimeOptions = parser().parse(Snippets.class).build();
assertThat(runtimeOptions.getSnippetType(), is(equalTo(SnippetType.CAMELCASE)));
} |
@Override
public <T> T deserialize(byte[] data, Class<T> clazz) {
return JacksonUtils.toObj(data, clazz);
} | @Test
@SuppressWarnings("checkstyle:linelength")
void testDeserialize() {
String example = "{\"adWeightMap\":{},\"defaultPushCacheMillis\":10000,\"clientBeatInterval\":5000,\"defaultCacheMillis\":3000,\"distroThreshold\":0.7,\"healthCheckEnabled\":true,\"autoChangeHealthCheckEnabled\":true,\"distroEnabl... |
@Override
public String toString() {
if (columns.isEmpty()) {
return "";
}
StringJoiner result = new StringJoiner(", ", ", ", "");
columns.forEach(result::add);
return result.toString();
} | @Test
void assertToStringWithEmptyColumn() {
assertThat(new InsertColumnsToken(0, Collections.emptyList()).toString(), is(""));
} |
public XATopicConnection xaTopicConnection(XATopicConnection connection) {
return TracingXAConnection.create(connection, this);
} | @Test void xaTopicConnection_wrapsInput() {
assertThat(jmsTracing.xaTopicConnection(mock(XATopicConnection.class)))
.isInstanceOf(TracingXAConnection.class);
} |
public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
int maximumPoolSize) {
return new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,
DateUtils.MILLISECONDS_PER_MINUTE,
TimeUnit.MILLISECONDS,
... | @Test
public void newCachedThreadPool3() throws Exception {
BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>();
RejectedExecutionHandler handler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {... |
public T maxInitialLineLength(int value) {
if (value <= 0) {
throw new IllegalArgumentException("maxInitialLineLength must be strictly positive");
}
this.maxInitialLineLength = value;
return get();
} | @Test
void maxInitialLineLength() {
checkDefaultMaxInitialLineLength(conf);
conf.maxInitialLineLength(123);
assertThat(conf.maxInitialLineLength()).as("initial line length").isEqualTo(123);
checkDefaultMaxHeaderSize(conf);
checkDefaultMaxChunkSize(conf);
checkDefaultValidateHeaders(conf);
checkDefault... |
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // TODO(b/134064106): design an alternative to no-arg check()
public final Ordered containsExactly() {
return check().about(iterableEntries()).that(checkNotNull(actual).entries()).containsExactly();
} | @Test
public void containsExactlyNoArg() {
ImmutableMultimap<Integer, String> actual = ImmutableMultimap.of();
assertThat(actual).containsExactly();
assertThat(actual).containsExactly().inOrder();
expectFailureWhenTestingThat(ImmutableMultimap.of(42, "Answer", 42, "6x7")).containsExactly();
asse... |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetStreamsConfigAdminClientProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(
Collections.singletonMap(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, 3));
final Object result = ksqlConfig.getKsqlStreamConfigProps().get(
AdminClientConfig.REQUEST_TIMEOUT_MS_CONFI... |
@Override
public Object pageListService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize,
String instancePattern, boolean ignoreEmptyService) throws NacosException {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
List<ServiceView> serviceViews =... | @Test
void testPageListService() throws NacosException {
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(Collections.singletonList(new Instance()));
Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo);
ServiceMetadata metadata = new ServiceMe... |
public void close(final boolean closeQueries) {
primaryContext.getQueryRegistry().close(closeQueries);
try {
cleanupService.stopAsync().awaitTerminated(
this.primaryContext.getKsqlConfig()
.getLong(KsqlConfig.KSQL_QUERY_CLEANUP_SHUTDOWN_TIMEOUT_MS),
TimeUnit.MILLISECONDS... | @Test
public void shouldHardDeleteSchemaOnEngineCloseForTransientQueries() throws IOException, RestClientException {
// Given:
setupKsqlEngineWithSharedRuntimeDisabled();
final QueryMetadata query = KsqlEngineTestUtil.executeQuery(
serviceContext,
ksqlEngine,
"select * from test1 E... |
@Override
public CompletableFuture<Void> asyncAddTaskExecutionLogs(List<TaskExecLog> logs) {
return CompletableFuture.runAsync(() -> addTaskExecutionLogs(logs));
} | @Test
public void asyncAddTaskExecutionLogsTest() throws Exception {
List<TaskExecLog> logs = new ArrayList<>();
logs.add(createLog(TEST_TASK_ID_2, "log1"));
logs.add(createLog(TEST_TASK_ID_2, "log2"));
logs.add(createLog(TEST_TASK_ID_2, "log3"));
dao.asyncAddTaskExecutionLogs(logs).get();
L... |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile,
String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
// 1. 执行请求
// 参考链接 https://cloud.tencent.com/document/product/382/55981
TreeMap<String, Object> bod... | @Test
public void testDoSendSms_fail() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
... |
@ConstantFunction(name = "bitShiftRight", argTypes = {TINYINT, BIGINT}, returnType = TINYINT)
public static ConstantOperator bitShiftRightTinyInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createTinyInt((byte) (first.getTinyInt() >> second.getBigint()));
} | @Test
public void bitShiftRightTinyInt() {
assertEquals(1, ScalarOperatorFunctions.bitShiftRightTinyInt(O_TI_10, O_BI_3).getTinyInt());
} |
public static LinkDescription combine(BasicLinkConfig cfg, LinkDescription descr) {
if (cfg == null) {
return descr;
}
Link.Type type = descr.type();
if (cfg.isTypeConfigured()) {
if (cfg.type() != type) {
type = cfg.type();
}
... | @Test
public void testDescOps() {
LinkDescription desc = BasicLinkOperator.combine(BLC, LD);
assertEquals(String.valueOf(NTIME), desc.annotations().value(AnnotationKeys.LATENCY));
assertEquals("true", desc.annotations().value(AnnotationKeys.DURABLE));
} |
public List<String> split(String in) {
final StringBuilder result = new StringBuilder();
final char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++) {
final char c = chars[i];
if (CHAR_OPERATORS.contains(String.valueOf(c))) {
if (i < char... | @Test
public void split1() {
List<String> tokens = parser.split("a and b");
assertEquals(Arrays.asList("a", "and", "b"), tokens);
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldResetPropertiesBetweenMigrations() throws Exception {
// Given:
command = PARSER.parse("-a");
createMigrationFile(1, NAME, migrationsDir, "SET 'cat'='pat';");
createMigrationFile(2, NAME, migrationsDir, COMMAND);
when(versionQueryResult.get()).thenReturn(ImmutableList.of())... |
static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) {
if (kafkaMirrorMaker2.getSpec() == null) {
throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource");
} else {
if (kafkaMirrorMaker2.getSpec().getClusters() == null ||... | @Test
public void testFailingValidation() {
// Missing spec
KafkaMirrorMaker2 kmm2WithoutSpec = new KafkaMirrorMaker2Builder(KMM2)
.withSpec(null)
.build();
InvalidResourceException ex = assertThrows(InvalidResourceException.class, () -> KafkaMirrorMaker2Co... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchIPDscpTest() {
Criterion criterion = Criteria.matchIPDscp((byte) 63);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@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_success() {
// mock 数据
PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
postMapper.insert(postDO);
// 准备参数
List<Long> ids = singletonList(postDO.getId());
// 调用,无需断言
postService.validatePost... |
@Override
public Throwable getException() {
return exception;
} | @Test
void testAppResponseWithNormalException() {
NullPointerException npe = new NullPointerException();
AppResponse appResponse = new AppResponse(npe);
StackTraceElement[] stackTrace = appResponse.getException().getStackTrace();
Assertions.assertNotNull(stackTrace);
Asserti... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation);
if (!LOGGED.contains(key)) {
LOGGED.add(key);
if (invoker.getUrl().getMethodParameter(RpcU... | @Test
void testDeprecatedFilter() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + DEPRECATED_KEY + "=true");
LogUtil.start();
deprecatedFilter.invoke(new MyInvoker<DemoService>(url), new MockInvocation());
assertEquals(
1,
... |
@Override
public String lock(final Path file) throws BackgroundException {
try {
return session.getClient().lock(new DAVPathEncoder().encode(file));
}
catch(SardineException e) {
throw new DAVExceptionMappingService().map("Failure to write attributes of {0}", e, file)... | @Test
public void testLockNotSupported() throws Exception {
final TransferStatus status = new TransferStatus();
final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
final byte[] content = "test".getBytes(StandardCharsets.UTF_8);... |
public static boolean isMobile(CharSequence value) {
return isMatchRegex(MOBILE, value);
} | @Test
public void isMobileTest() {
final boolean m1 = Validator.isMobile("13900221432");
assertTrue(m1);
final boolean m2 = Validator.isMobile("015100221432");
assertTrue(m2);
final boolean m3 = Validator.isMobile("+8618600221432");
assertTrue(m3);
final boolean m4 = Validator.isMobile("19312341234");
... |
public static KiePMMLExtension getKiePMMLExtension(Extension extension) {
return new KiePMMLExtension(extension.getExtender(), extension.getName(), extension.getValue(), extension.getContent());
} | @Test
void getKiePMMLExtension() {
// TODO {@gcardosi}
} |
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 shouldNotAllowParamsToBeUsedInNames() {
String content = ("""
<cruise schemaVersion='%d'>
<server />
<pipelines>
<pipeline name='dev'>
<params>
<param name='command'>ls</param>
... |
@Override
public int run(String[] args) throws Exception {
try {
webServiceClient = WebServiceClient.getWebServiceClient().createClient();
return runCommand(args);
} finally {
if (yarnClient != null) {
yarnClient.close();
}
if (webServiceClient != null) {
webServi... | @Test(timeout = 5000L)
public void testUnknownApplicationAttemptId() throws Exception {
YarnClient mockYarnClient = createMockYarnClientUnknownApp();
LogsCLI cli = new LogsCLIForTest(mockYarnClient);
cli.setConf(conf);
ApplicationId appId = ApplicationId.newInstance(0, 1);
int exitCode = cli.run(... |
public DeleteGranularity deleteGranularity() {
String valueAsString =
confParser
.stringConf()
.option(SparkWriteOptions.DELETE_GRANULARITY)
.tableProperty(TableProperties.DELETE_GRANULARITY)
.defaultValue(TableProperties.DELETE_GRANULARITY_DEFAULT)
... | @Test
public void testDeleteGranularityTableProperty() {
Table table = validationCatalog.loadTable(tableIdent);
table
.updateProperties()
.set(TableProperties.DELETE_GRANULARITY, DeleteGranularity.FILE.toString())
.commit();
SparkWriteConf writeConf = new SparkWriteConf(spark, ta... |
public static InRawPredicateEvaluator newRawValueBasedEvaluator(InPredicate inPredicate, DataType dataType) {
switch (dataType) {
case INT: {
int[] intValues = inPredicate.getIntValues();
IntSet matchingValues = new IntOpenHashSet(HashUtil.getMinHashSetSize(intValues.length));
for (int... | @Test
void canBeVisited() {
// Given a visitor
MultiValueVisitor<Integer> valueLengthVisitor = Mockito.spy(createValueLengthVisitor());
// When int predicate is used
InPredicate predicate = new InPredicate(ExpressionContext.forIdentifier("ident"), Lists.newArrayList("1", "2"));
InPredicateEvalua... |
public int doWork(final long nowMs)
{
return delegateResolver.doWork(nowMs);
} | @Test
void doWorkShouldCallActualMethod()
{
final NameResolver delegateResolver = mock(NameResolver.class);
final NanoClock clock = mock(NanoClock.class);
final DutyCycleTracker maxTime = mock(DutyCycleTracker.class);
final TimeTrackingNameResolver resolver = new TimeTrackingName... |
@Override
protected ServerSocketFactory getServerSocketFactory() throws Exception {
if (socketFactory == null) {
SSLContext sslContext = getSsl().createContext(this);
SSLParametersConfiguration parameters = getSsl().getParameters();
parameters.setContext(getContext());
socketFactory = new ... | @Test
public void testGetServerSocketFactory() throws Exception {
ServerSocketFactory socketFactory = receiver.getServerSocketFactory();
assertNotNull(socketFactory);
assertTrue(ssl.isContextCreated());
assertTrue(parameters.isContextInjected());
} |
@Override
public QuoteCharacter getQuoteCharacter() {
return QuoteCharacter.QUOTE;
} | @Test
void assertGetQuoteCharacter() {
assertThat(dialectDatabaseMetaData.getQuoteCharacter(), is(QuoteCharacter.QUOTE));
} |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testNonForwardedInvalidTypes5() {
String[] nonForwardedFields = {"int1"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsSingleFromString(
... |
public static Object applyLogicalType(Schema.Field field, Object value) {
if (field == null || field.schema() == null) {
return value;
}
Schema fieldSchema = resolveUnionSchema(field.schema());
return applySchemaTypeLogic(fieldSchema, value);
} | @Test
public void testApplyLogicalTypeReturnsSameValueWhenFieldIsNull() {
String value = "d7738003-1472-4f63-b0f1-b5e69c8b93e9";
Object result = AvroSchemaUtil.applyLogicalType(null, value);
Assert.assertTrue(result instanceof String);
Assert.assertSame(value, result);
} |
@Override
public void validate(Context context) {
if (!context.deployState().isHosted() || context.deployState().zone().system().isPublic()) return;
if (context.deployState().getProperties().allowDisableMtls()) return;
context.model().getContainerClusters().forEach((id, cluster) -> {
... | @Test
public void validator_warns_excludes_in_cloud() throws IOException, SAXException {
StringBuffer logOutput = new StringBuffer();
DeployState deployState = createDeployState(zone(CloudName.YAHOO, SystemName.main), logOutput, false);
VespaModel model = new VespaModel(
MapC... |
@Override
public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test)
{
return mapMatchingPrestoException(queryException, CONTROL_CHECKSUM, ImmutableSet.of(COMPILER_ERROR, GENERATED_BYTECODE_TOO_LARGE),
e -> O... | @Test
public void testResolveGeneratedBytecodeTooLarge()
{
assertEquals(
getFailureResolver().resolveQueryFailure(
CONTROL_QUERY_STATS,
new PrestoQueryException(
new RuntimeException(),
... |
@Override
public Object getKey() {
return serializationService.toObject(key);
} | @Test
public void getKey_caching() {
QueryableEntry entry = createEntry("key", "value");
assertThat(entry.getKey()).isNotSameAs(entry.getKey());
} |
@Override
public MapTileArea computeFromSource(final MapTileArea pSource, final MapTileArea pReuse) {
final MapTileArea out = pReuse != null ? pReuse : new MapTileArea();
if (pSource.size() == 0) {
out.reset();
return out;
}
final int sourceZoom = pSource.getZ... | @Test
public void testWorld() {
final MapTileArea src = new MapTileArea();
final MapTileArea dst = new MapTileArea();
long size;
int mapTileUpperBound;
for (int zoom = 0; zoom <= TileSystem.getMaximumZoomLevel(); zoom++) {
mapTileUpperBound = getMapTileUpperBound(... |
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
... | @Test
void testNeverWriteYesterday() {
clock.pin(Instant.ofEpochMilli(today));
final Device device = oldAccount.getDevices().stream().findFirst().get();
accountAuthenticator.updateLastSeen(oldAccount, device);
verify(accountsManager).updateDeviceLastSeen(eq(oldAccount), eq(device), anyLong());
... |
@Override
public void start() throws Exception {
LOG.debug("Start leadership runner for job {}.", getJobID());
leaderElection.startLeaderElection(this);
} | @Test
void testJobInformationOperationsDuringInitialization() throws Exception {
final JobManagerRunner jobManagerRunner =
newJobMasterServiceLeadershipRunnerBuilder()
.withSingleJobMasterServiceProcess(
TestingJobMasterServiceProcess.... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_object() {
Object original = new SerializableObject("value");
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
public static String getDefaultServerPort() {
return serverPort;
} | @Test
void testGetDefaultServerPort() {
String actual = ParamUtil.getDefaultServerPort();
assertEquals("8848", actual);
} |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() +
mxBean.getNonHeapMemoryUsage().getInit());
gauges.put("total.used", (Gauge<Long>) () -... | @Test
public void hasAGaugeForWeirdMemoryPoolCommitted() {
final Gauge gauge = (Gauge) gauges.getMetrics().get("pools.Weird-Pool.committed");
assertThat(gauge.getValue())
.isEqualTo(100L);
} |
@Subscribe
public void inputCreated(InputCreated inputCreatedEvent) {
final String inputId = inputCreatedEvent.id();
LOG.debug("Input created: {}", inputId);
final Input input;
try {
input = inputService.find(inputId);
} catch (NotFoundException e) {
L... | @Test
public void inputCreatedStartsGlobalInputOnOtherNode() throws Exception {
final String inputId = "input-id";
final Input input = mock(Input.class);
when(inputService.find(inputId)).thenReturn(input);
when(input.getNodeId()).thenReturn(OTHER_NODE_ID);
when(input.isGlobal... |
public static Builder in(Table table) {
return new Builder(table);
} | @TestTemplate
public void testBasicBehavior() {
table.newAppend().appendFile(FILE_A).appendFile(FILE_B).commit();
Iterable<DataFile> files = FindFiles.in(table).collect();
assertThat(pathSet(files)).isEqualTo(pathSet(FILE_A, FILE_B));
} |
public static DataPermission get() {
return DATA_PERMISSIONS.get().peekLast();
} | @Test
public void testGet() {
// mock 方法
DataPermission dataPermission01 = mock(DataPermission.class);
DataPermissionContextHolder.add(dataPermission01);
DataPermission dataPermission02 = mock(DataPermission.class);
DataPermissionContextHolder.add(dataPermission02);
... |
@SuppressWarnings("JavaUtilDate")
protected LocalDate convertDateValue(Object value) {
if (value instanceof Number) {
int days = ((Number) value).intValue();
return DateTimeUtil.dateFromDays(days);
} else if (value instanceof String) {
return LocalDate.parse((String) value);
} else if (v... | @Test
public void testDateConversion() {
Table table = mock(Table.class);
when(table.schema()).thenReturn(SIMPLE_SCHEMA);
RecordConverter converter = new RecordConverter(table, config);
LocalDate expected = LocalDate.of(2023, 11, 15);
List<Object> inputList =
ImmutableList.of(
... |
public synchronized BeamFnStateClient forApiServiceDescriptor(
ApiServiceDescriptor apiServiceDescriptor) throws IOException {
// We specifically are synchronized so that we only create one GrpcStateClient at a time
// preventing a race where multiple GrpcStateClient objects might be constructed at the sa... | @Test
public void testRequestResponses() throws Exception {
BeamFnStateClient client = clientCache.forApiServiceDescriptor(apiServiceDescriptor);
CompletableFuture<StateResponse> successfulResponse =
client.handle(StateRequest.newBuilder().setInstructionId(SUCCESS));
CompletableFuture<StateRespon... |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testMissingRulesConfiguration() throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
createArgumentHandler();
argumentHandler.parseAndConvert(getDefaultArgumentsAsArray());
} |
public static double longitudeToPixelX(double longitude, byte zoomLevel, int tileSize) {
long mapSize = getMapSize(zoomLevel, tileSize);
return (longitude + 180) / 360 * mapSize;
} | @Test
public void longitudeToPixelXTest() {
for (int tileSize : TILE_SIZES) {
for (byte zoomLevel = ZOOM_LEVEL_MIN; zoomLevel <= ZOOM_LEVEL_MAX; ++zoomLevel) {
long mapSize = MercatorProjection.getMapSize(zoomLevel, tileSize);
double pixelX = MercatorProjection.lo... |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamMa... | @Test
public void testWorkflowParamRunParamsUpstreamInitiatorRestartMerge() {
Map<String, ParamDefinition> restartParams =
singletonMap(
"TARGET_RUN_DATE",
ParamDefinition.buildParamDefinition("TARGET_RUN_DATE", 1001).toBuilder()
.mode(ParamMode.MUTABLE)
... |
@Nullable
public static <T> T getWithoutException(CompletableFuture<T> future) {
if (isCompletedNormally(future)) {
try {
return future.get();
} catch (InterruptedException | ExecutionException ignored) {
}
}
return null;
} | @Test
void testGetWithoutExceptionWithoutFinishing() {
final CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
assertThat(FutureUtils.getWithoutException(completableFuture)).isNull();
} |
public static Time parseTime(final String str) {
try {
return new Time(LocalTime.parse(str).toNanoOfDay() / 1000000);
} catch (DateTimeParseException e) {
throw new KsqlException("Failed to parse time '" + str
+ "': " + e.getMessage()
+ TIME_HELP_MESSAGE,
e
);
... | @Test
public void shouldNotParseTime() {
// When:
final KsqlException e = assertThrows(
KsqlException.class,
() -> SqlTimeTypes.parseTime("foo")
);
// Then
assertThat(e.getMessage(), containsString(
"Required format is: \"HH:mm:ss.SSS\""));
} |
public static final String getTrimTypeCode( int i ) {
if ( i < 0 || i >= trimTypeCode.length ) {
return trimTypeCode[0];
}
return trimTypeCode[i];
} | @Test
public void testGetTrimTypeCode() {
assertEquals( ValueMetaBase.getTrimTypeCode( ValueMetaInterface.TRIM_TYPE_NONE ), "none" );
assertEquals( ValueMetaBase.getTrimTypeCode( ValueMetaInterface.TRIM_TYPE_LEFT ), "left" );
assertEquals( ValueMetaBase.getTrimTypeCode( ValueMetaInterface.TRIM_TYPE_RIGHT ... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertBoolean() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.BOOLEAN_TYPE)
.nullable(true)
.defaultValue(true)
.com... |
@Override
public PackageRevision responseMessageForLatestRevisionSince(String responseBody) {
return toPackageRevision(responseBody);
} | @Test
public void shouldBuildPackageRevisionFromLatestRevisionSinceResponse() throws Exception {
String responseBody = "{\"revision\":\"abc.rpm\",\"timestamp\":\"2011-07-14T19:43:37.100Z\",\"user\":\"some-user\",\"revisionComment\":\"comment\"," +
"\"trackbackUrl\":\"http:\\\\localhost:9999\... |
public static String buildWhereConditionByPKs(List<String> pkNameList, int rowSize, String dbType)
throws SQLException {
return buildWhereConditionByPKs(pkNameList, rowSize, dbType, MAX_IN_SIZE);
} | @Test
void testBuildWhereConditionByPKs() throws SQLException {
List<String> pkNameList=new ArrayList<>();
pkNameList.add("id");
pkNameList.add("name");
String result = SqlGenerateUtils.buildWhereConditionByPKs(pkNameList,4,"mysql",2);
Assertions.assertEquals("(id,name) in ( ... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test
public void testSubstVarsVariableNotClosed() {
String noSubst = "testing if ${v1 works";
try {
@SuppressWarnings("unused")
String result = OptionHelper.substVars(noSubst, context);
fail();
} catch (IllegalArgumentException e) {
//ok
}
} |
public static QueryDataType toHazelcastType(RelDataType relDataType) {
if (relDataType.getSqlTypeName() != OTHER) {
return toHazelcastTypeFromSqlTypeName(relDataType.getSqlTypeName());
}
final RelDataTypeFamily typeFamily = relDataType.getFamily();
if (typeFamily instanceof ... | @Test
public void testCalciteToHazelcast() {
assertSame(QueryDataType.JSON, HazelcastTypeUtils.toHazelcastType(HazelcastJsonType.TYPE));
assertSame(QueryDataType.JSON, HazelcastTypeUtils.toHazelcastType(HazelcastJsonType.TYPE_NULLABLE));
assertSame(QueryDataType.VARCHAR, HazelcastTypeUtils.... |
@Override
public void rotate(IndexSet indexSet) {
indexRotator.rotate(indexSet, this::shouldRotate);
} | @Test
public void testDontRotate() {
when(indices.getStoreSizeInBytes("name")).thenReturn(Optional.of(1000L));
when(indexSet.getNewestIndex()).thenReturn("name");
when(indexSet.getConfig()).thenReturn(indexSetConfig);
when(indexSetConfig.rotationStrategyConfig()).thenReturn(SizeBased... |
public void flushToServer() {
if (buffer.isEmpty()) {
return;
}
List sent = new ArrayList();
try {
synchronized (buffer) {
while (!buffer.isEmpty()) {
sent.add(buffer.remove());
}
}
Strin... | @Test
public void shouldNotFlushToServerWhenBufferIsEmpty() throws Exception {
transmitter.flushToServer();
verify(consoleAppender, never()).append(any(String.class));
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(0L == status.getLength()) {
return new NullInputStream(0L);
}
final Storage.Objects.Get request = sessi... | @Test
@Ignore
public void testReadRangeUnknownLength() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, String.format("%s %s", new AlphanumericRandomStringService().random(), new Alph... |
void apply(Metrics.MetricsBuilder metricsBuilder) {
metricsBuilder.topicBytesInPerSec(bytesInFifteenMinuteRate);
metricsBuilder.topicBytesOutPerSec(bytesOutFifteenMinuteRate);
metricsBuilder.brokerBytesInPerSec(brokerBytesInFifteenMinuteRate);
metricsBuilder.brokerBytesOutPerSec(brokerBytesOutFifteenMin... | @Test
void appliesInnerStateToMetricsBuilder() {
//filling per topic io rates
wellKnownMetrics.bytesInFifteenMinuteRate.put("topic", new BigDecimal(1));
wellKnownMetrics.bytesOutFifteenMinuteRate.put("topic", new BigDecimal(2));
//filling per broker io rates
wellKnownMetrics.brokerBytesInFifteenM... |
@Override
public void post(Event event) {
if (!getDispatcher(event).add(event)) {
log.error("Unable to post event {}", event);
}
} | @Test
public void postEventWithBadSink() throws Exception {
gooSink.latch = new CountDownLatch(1);
dispatcher.post(new Goo("boom"));
gooSink.latch.await(100, TimeUnit.MILLISECONDS);
validate(gooSink, "boom");
validate(prickleSink);
} |
@Udf(description = "Returns the inverse (arc) tangent of an INT value")
public Double atan(
@UdfParameter(
value = "value",
description = "The value to get the inverse tangent of."
) final Integer value
) {
return atan(value == null ? null : value.doubleVa... | @Test
public void shouldHandleNegative() {
assertThat(udf.atan(-0.43), closeTo(-0.40609805831761564, 0.000000000000001));
assertThat(udf.atan(-0.5), closeTo(-0.4636476090008061, 0.000000000000001));
assertThat(udf.atan(-1.0), closeTo(-0.7853981633974483, 0.000000000000001));
assertThat(udf.atan(-1), c... |
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final InferableFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor());
} | @Test
public void testNestedPolymorphicInferableFunction() throws Exception {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline
.apply(Create.of(1, 2, 3))
.apply("Polymorphic Identity", MapElements.via(new NestedPolymorphicInferableFunction<>()))
.apply(
"Test Consu... |
@Override
public final boolean cancel(String errMsg) {
isCancelling.set(true);
try {
// If waitingCreatingReplica == false, we will assume that
// cancel thread will get the object lock very quickly.
if (waitingCreatingReplica.get()) {
Precondition... | @Test
public void testCancelPendingJob() throws IOException {
TabletInvertedIndex invertedIndex = GlobalStateMgr.getCurrentState().getTabletInvertedIndex();
schemaChangeJob.cancel("test");
Assert.assertEquals(AlterJobV2.JobState.CANCELLED, schemaChangeJob.getJobState());
// test canc... |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetArray1() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(new Object[] {}, -1);
});
} |
void notifyPendingReceivedCallback(final Message<T> message, Exception exception) {
if (pendingReceives.isEmpty()) {
return;
}
// fetch receivedCallback from queue
final CompletableFuture<Message<T>> receivedFuture = nextPendingReceive();
if (receivedFuture == null) ... | @Test(invocationTimeOut = 1000)
public void testNotifyPendingReceivedCallback_CompleteWithException() {
CompletableFuture<Message<byte[]>> receiveFuture = new CompletableFuture<>();
consumer.pendingReceives.add(receiveFuture);
Exception exception = new PulsarClientException.InvalidMessageExc... |
public String encode(String name, String value) {
return encode(new DefaultCookie(name, value));
} | @Test
public void testEncodingMultipleClientCookies() {
String c1 = "myCookie=myValue";
String c2 = "myCookie2=myValue2";
String c3 = "myCookie3=myValue3";
Cookie cookie1 = new DefaultCookie("myCookie", "myValue");
cookie1.setDomain(".adomainsomewhere");
cookie1.setMa... |
@Override
public void populateContainer(TaskContainer container) {
ComputationSteps steps = new ReportComputationSteps(container);
container.add(SettingsLoader.class);
container.add(task);
container.add(steps);
container.add(componentClasses());
for (ReportAnalysisComponentProvider componentPr... | @Test
public void item_is_added_to_the_container() {
ListTaskContainer container = new ListTaskContainer();
underTest.populateContainer(container);
assertThat(container.getAddedComponents()).contains(task);
} |
public boolean isOnos() {
return Arrays.equals(this.oui(), ONOS.oui());
} | @Test
public void testIsOnos() throws Exception {
assertFalse(MAC_NORMAL.isOnos());
assertFalse(MAC_BCAST.isOnos());
assertFalse(MAC_MCAST.isOnos());
assertFalse(MAC_MCAST_2.isOnos());
assertFalse(MAC_LLDP.isOnos());
assertFalse(MAC_LLDP_2.isOnos());
assertFal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.