focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void close() {
if (CONTAINER_DATASOURCE_NAMES.contains(dataSource.getClass().getSimpleName())) {
close(dataSource);
} else {
xaTransactionManagerProvider.removeRecoveryResource(resourceName, xaDataSource);
}
enlistedTransactions.remove();
... | @Test
void assertCloseHikariDataSource() {
DataSource dataSource = DataSourceUtils.build(HikariDataSource.class, TypedSPILoader.getService(DatabaseType.class, "H2"), "ds1");
XATransactionDataSource transactionDataSource = new XATransactionDataSource(TypedSPILoader.getService(DatabaseType.class, "H2"... |
@Override
public int compare(String version1, String version2) {
if(ObjectUtil.equal(version1, version2)) {
return 0;
}
if (version1 == null && version2 == null) {
return 0;
} else if (version1 == null) {// null或""视为最小版本,排在前
return -1;
} else if (version2 == null) {
return 1;
}
return Compar... | @Test
public void versionComparatorTest1() {
int compare = VersionComparator.INSTANCE.compare("1.2.1", "1.12.1");
assertTrue(compare < 0);
// 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1", "1.2.1");
assertTrue(compare > 0);
} |
@Override
public void execute(ComputationStep.Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) {
@Override
public void visitProject(Component project) {
executeForProject(project);
}
}).visit(tree... | @Test
void new_measures_have_ERROR_level_if_at_least_one_updated_measure_has_ERROR_level() {
int rawValue = 3;
Condition equalsOneErrorCondition = createLessThanCondition(INT_METRIC_1, "4");
Condition equalsOneOkCondition = createLessThanCondition(INT_METRIC_2, "2");
Measure rawMeasure = newMeasureBui... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> objects = new AttributedList<>();
Marker marker = new Marker(null, null);
final String containerId = fileid.... | @Test
public void testDisplayFolderInBucketMissingPlaceholder() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(
new Path(String.format("test-%s", new AsciiRandomStringService().... |
@Override
public void updateIndices(SegmentDirectory.Writer segmentWriter)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter);
if (columnOperationsMap.isEmpty()) {
return;
}
for (Map.Entry<String, List<Operation>> entry : columnOperation... | @Test
public void testAddOtherIndexWhenForwardIndexDisabledAndInvertedIndexOrDictionaryDisabled()
throws Exception {
SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory);
SegmentDirectory segmentLocalFSDirectory =
new SegmentLocalFSDirectory(_segmentDirectory,... |
@Override
public UsersSearchRestResponse toUsersForResponse(List<UserInformation> userInformations, PaginationInformation paginationInformation) {
List<UserRestResponse> usersForResponse = toUsersForResponse(userInformations);
PageRestResponse pageRestResponse = new PageRestResponse(paginationInformation.page... | @Test
public void toUsersForResponse_whenAdmin_mapsAllFields() {
when(userSession.isLoggedIn()).thenReturn(true);
when(userSession.isSystemAdministrator()).thenReturn(true);
PaginationInformation paging = forPageIndex(1).withPageSize(2).andTotal(3);
UserInformation userInformation1 = mockSearchResul... |
@SuppressWarnings({"checkstyle:ParameterNumber"})
public static Pod createStatefulPod(
Reconciliation reconciliation,
String name,
String namespace,
Labels labels,
String strimziPodSetName,
String serviceAccountName,
PodTemplate tem... | @Test
public void testCreateStatefulPodWithNullValuesAndNullTemplate() {
Pod pod = WorkloadUtils.createStatefulPod(
Reconciliation.DUMMY_RECONCILIATION,
NAME + "-0", // => Pod name
NAMESPACE,
LABELS,
NAME, // => Workload n... |
public synchronized ResultSet fetchResults(FetchOrientation orientation, int maxFetchSize) {
long token;
switch (orientation) {
case FETCH_NEXT:
token = currentToken;
break;
case FETCH_PRIOR:
token = currentToken - 1;
... | @Test
void testFetchResultWithToken() {
ResultFetcher fetcher =
buildResultFetcher(Collections.singletonList(data.iterator()), data.size());
Long nextToken = 0L;
List<RowData> actual = new ArrayList<>();
ResultSet resultSetBefore = null;
while (nextToken != nu... |
@Override
public void doRun() {
doRun(false);
} | @Test
void scheduledExecutionIsSkippedWhenServerIsNotRunning() {
when(serverStatus.getLifecycle()).thenReturn(Lifecycle.HALTING);
periodical.doRun();
verifyNoInteractions(cluster);
} |
public static List<DataTypes.Field> getFields(DataType dataType) {
final List<String> names = getFieldNames(dataType);
final List<DataType> dataTypes = getFieldDataTypes(dataType);
return IntStream.range(0, names.size())
.mapToObj(i -> DataTypes.FIELD(names.get(i), dataTypes.get(... | @Test
void testGetFields() {
assertThat(
DataType.getFields(
ROW(
FIELD("c0", BOOLEAN()),
FIELD("c1", DOUBLE()),
FIELD("c2", INT()))... |
public static CronPattern of(String pattern) {
return new CronPattern(pattern);
} | @Test
public void matchAllTest() {
CronPattern pattern;
// 任何时间匹配
pattern = CronPattern.of("* * * * * *");
assertMatch(pattern, DateUtil.now());
} |
@Transactional(readOnly = true)
public AuthFindDto.FindUsernameRes findUsername(String phone) {
User user = readGeneralSignUpUser(phone);
return AuthFindDto.FindUsernameRes.of(user);
} | @DisplayName("휴대폰 번호로 유저를 찾았으나 OAuth 유저일 때 AuthFinderException을 발생시킨다.")
@Test
void findUsernameIfUserIsOAuth() {
// given
String phone = "010-1234-5678";
User user = UserFixture.OAUTH_USER.toUser();
given(userService.readUserByPhone(phone)).willReturn(Optional.of(user));
... |
public static java.nio.file.Path relativizePath(
java.nio.file.Path basePath, java.nio.file.Path pathToRelativize) {
if (pathToRelativize.isAbsolute()) {
return basePath.relativize(pathToRelativize);
} else {
return pathToRelativize;
}
} | @Test
void testRelativizeOfAbsolutePath() throws IOException {
final java.nio.file.Path absolutePath =
TempDirUtils.newFolder(temporaryFolder).toPath().toAbsolutePath();
final java.nio.file.Path rootPath = temporaryFolder.getRoot();
final java.nio.file.Path relativePath = Fi... |
@DoNotSub public int size()
{
return sizeOfArrayValues + (containsMissingValue ? 1 : 0);
} | @Test
void sizeIncrementsWithNumberOfAddedElements()
{
addTwoElements(testSet);
assertEquals(2, testSet.size());
} |
@Override
public String getSessionId() {
return sessionID;
} | @Test
public void testUnLockRequest() {
log.info("Starting unlock async");
assertNotNull("Incorrect sessionId", session1.getSessionId());
try {
assertTrue("NETCONF unlock request failed", session1.unlock());
} catch (NetconfException e) {
e.printStackTrace();
... |
NewCookie createAuthenticationCookie(SessionResponse token, ContainerRequestContext requestContext) {
return makeCookie(token.getAuthenticationToken(), token.validUntil(), requestContext);
} | @Test
void pathFromRequest() {
containerRequest.getHeaders().put(HttpConfiguration.OVERRIDE_HEADER,
List.of("http://graylog.local/path/from/request/"));
final CookieFactory cookieFactory = new CookieFactory(new HttpConfiguration());
final NewCookie cookie = cookieFactory.cre... |
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER)
.setSince("6.6")
.setDescription("Manage branch");
Arrays.stream(actions).forEach(action -> action.define(controller));
controller.done();
} | @Test
public void define_ws() {
BranchesWs underTest = new BranchesWs(new BranchWsAction() {
@Override
public void define(WebService.NewController context) {
context.createAction("foo").setHandler(this);
}
@Override
public void handle(Request request, Response response) {
... |
public static List<RlpType> asRlpValues(
RawTransaction rawTransaction, Sign.SignatureData signatureData) {
return rawTransaction.getTransaction().asRlpValues(signatureData);
} | @Test
public void testContractAsRlpValues() {
List<RlpType> rlpStrings =
TransactionEncoder.asRlpValues(createContractTransaction(), null);
assertEquals(rlpStrings.size(), (6));
assertEquals(rlpStrings.get(3), (RlpString.create("")));
} |
public @CheckForNull R search(final int n, final Direction d) {
switch (d) {
case EXACT:
return getByNumber(n);
case ASC:
for (int m : numberOnDisk) {
if (m < n) {
// TODO could be made more efficient with numberOnDisk.find
... | @Test
public void unloadableData() throws IOException {
FakeMap m = localBuilder.add(1).addUnloadable(3).add(5).make();
assertNull(m.search(3, Direction.EXACT));
m.search(3, Direction.DESC).asserts(1);
m.search(3, Direction.ASC).asserts(5);
} |
@Override
public boolean open(final Local file) {
synchronized(NSWorkspace.class) {
if(!workspace.openFile(file.getAbsolute())) {
log.warn(String.format("Error opening file %s", file));
return false;
}
return true;
}
} | @Test
public void testOpen() throws Exception {
new WorkspaceApplicationLauncher().open(new NullLocal("t"));
final NullLocal file = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
LocalTouchFactory.get().touch(file);
new WorkspaceApplicationLauncher... |
@Override
protected Result[] run(String value) {
final Map<String, Object> extractedJson;
try {
extractedJson = extractJson(value);
} catch (IOException e) {
throw new ExtractorException(e);
}
final List<Result> results = new ArrayList<>(extractedJson.... | @Test
public void testRunWithWhitespaceInNestedKey() throws Exception {
final String value = "{\"foo\":{\"b a r\":{\"b a z\": 42}}}";
final JsonExtractor jsonExtractor = new JsonExtractor(
new MetricRegistry(),
"json",
"title",
0L,
... |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
// Automatically detect the character encoding
try (AutoDetectReader reader = new AutoDetectReader(CloseShieldInpu... | @Test
public void testUseIncomingCharsetAsHint() throws Exception {
// Could be ISO 8859-1 or ISO 8859-15 or ...
// u00e1 is latin small letter a with acute
final String test2 = "the name is \u00e1ndre";
Metadata metadata = new Metadata();
parser.parse(new ByteArrayInputStre... |
public static String reformatParam(@Nullable Object param) {
if (param == null) {
return PARAM_NULL;
}
String abbreviated = abbreviate(param.toString(), PARAM_MAX_WIDTH);
return NEWLINE_PATTERN.matcher(abbreviated).replaceAll("\\\\n");
} | @Test
public void reformatParam_escapes_newlines() {
assertThat(SqlLogFormatter.reformatParam("foo\n bar\nbaz")).isEqualTo("foo\\n bar\\nbaz");
} |
static int run(File buildResult, Path root) throws IOException {
// parse included dependencies from build output
final Map<String, Set<Dependency>> modulesWithBundledDependencies =
combineAndFilterFlinkDependencies(
ShadeParser.parseShadeOutput(buildResult.toPath... | @Test
void testRunIncludesBundledNonDeployedModules() throws IOException {
final Map<String, Set<Dependency>> bundledDependencies = new HashMap<>();
final Map<String, Optional<NoticeContents>> notices = new HashMap<>();
// a module that is not deployed but bundles another dependency with an... |
@Override
public void close() throws Exception {
this.timer.close();
this.persister.stop();
} | @Test
public void testCloseSharePartitionManager() throws Exception {
Timer timer = Mockito.mock(SystemTimerReaper.class);
Persister persister = Mockito.mock(Persister.class);
SharePartitionManager sharePartitionManager = SharePartitionManagerBuilder.builder()
.withTimer(time... |
@Override
public <T> void delete(T attachedObject) {
addExpireListener(commandExecutor);
Set<String> deleted = new HashSet<String>();
delete(attachedObject, deleted);
} | @Test
public void testDeleteNotExisted() {
RLiveObjectService service = redisson.getLiveObjectService();
assertThat(service.delete(Customer.class, "id")).isZero();
} |
public static Serializer getDefault() {
return SERIALIZER_MAP.get(defaultSerializer);
} | @Test
void testMapSerialize() {
Serializer serializer = SerializeFactory.getDefault();
Map<Integer, Integer> logsMap = new HashMap<>();
for (int i = 0; i < 4; i++) {
logsMap.put(i, i);
}
byte[] data = serializer.serialize(logsMap);
assertNotEquals(0, data.... |
@Override
protected void refresh(final List<MetaData> data) {
if (CollectionUtils.isEmpty(data)) {
LOG.info("clear all metaData cache");
metaDataSubscribers.forEach(MetaDataSubscriber::refresh);
} else {
data.forEach(metaData -> metaDataSubscribers.forEach(subscri... | @Test
public void testRefreshCoverage() {
final MetaDataRefresh metaDataRefresh = mockMetaDataRefresh;
MetaData metaData = new MetaData();
List<MetaData> metaDataList = new ArrayList<>();
metaDataRefresh.refresh(metaDataList);
metaDataList.add(metaData);
metaDataRefre... |
public FEELFnResult<List<Object>> invoke(@ParameterName( "ctx" ) EvaluationContext ctx,
@ParameterName("list") List list,
@ParameterName("precedes") FEELFunction function) {
if ( function == null ) {
return inv... | @Test
void invokeList() {
FunctionTestUtil.assertResultList(sortFunction.invoke(Arrays.asList(10, 4, 5, 12)), Arrays.asList(4, 5, 10, 12));
FunctionTestUtil.assertResultList(sortFunction.invoke(Arrays.asList("a", "c", "b")), Arrays.asList("a", "b", "c"));
} |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void shouldPrintConnectorsList() {
// Given:
final KsqlEntityList entities = new KsqlEntityList(ImmutableList.of(
new ConnectorList(
"statement",
ImmutableList.of(),
ImmutableList.of(
new SimpleConnectorInfo("foo", ConnectorType.SOURCE, ... |
@Override
public DeleteConsumerGroupOffsetsResult deleteConsumerGroupOffsets(
String groupId,
Set<TopicPartition> partitions,
DeleteConsumerGroupOffsetsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, Errors>> future =
DeleteCons... | @Test
public void testDeleteConsumerGroupOffsetsFindCoordinatorNonRetriableErrors() throws Exception {
// Non-retriable FindCoordinatorResponse errors throw an exception
final TopicPartition tp1 = new TopicPartition("foo", 0);
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mo... |
static TupleIdentifier createTupleIdentifierById(String id) {
return new TupleIdentifier(id, generateNameFromId(id));
} | @Test
void createTupleIdentifierById() {
String id = "123124";
TupleIdentifier retrieved = TupleIdentifier.createTupleIdentifierById(id);
assertThat(retrieved).isNotNull();
assertThat(retrieved.getId()).isEqualTo(id);
assertThat(retrieved.getName()).isNotNull();
} |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertMapMessageToAmqpMessage() throws Exception {
ActiveMQMapMessage outbound = createMapMessage();
outbound.setString("property-1", "string");
outbound.setInt("property-2", 1);
outbound.setBoolean("property-3", true);
outbound.onSend();
outbou... |
@Override
String getFileName(double lat, double lon) {
int intKey = calcIntKey(lat, lon);
String str = areas.get(intKey);
if (str == null)
return null;
int minLat = Math.abs(down(lat));
int minLon = Math.abs(down(lon));
str += "/";
if (lat >= 0)
... | @Disabled
@Test
public void testDownloadIssue_1274() {
instance = new SRTMProvider();
// The file is incorrectly named on the sever: N55W061hgt.zip (it should be N55W061.hgt.zip)
assertEquals("North_America/N55W061", instance.getFileName(55.055,-60.541));
assertEquals(204, instan... |
public boolean shouldShow(@NonNull PublicNotices ime) {
final View candidate = ime.getInputViewContainer().getCandidateView();
return candidate != null && candidate.getVisibility() == View.VISIBLE;
} | @Test
@SuppressWarnings("ResultOfMethodCallIgnored")
public void testHappyPath() {
CandidateViewShowingHelper helper = new CandidateViewShowingHelper();
final PublicNotices ime = Mockito.mock(PublicNotices.class);
final KeyboardViewContainerView container = Mockito.mock(KeyboardViewContainerView.class)... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldEscapeQuotesInStringLiteralQuote() {
// Given:
final Expression expression = new StringLiteral("\\\"");
// When:
final String javaExpression = sqlToJavaVisitor.process(expression);
// Then:
assertThat(javaExpression, equalTo("\"\\\\\\\"\""));
} |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReport29DaysFor29Days23Hours59Minutes29Seconds() throws Exception {
assertEquals(TimeConverter.ABOUT_X_DAYS_AGO.argument(29), timeConverter
.getConvertedTime(30 * TimeConverter.DAY_IN_SECONDS - 31));
} |
public static String generateWsRemoteAddress(HttpServletRequest request) {
if (request == null) {
throw new IllegalArgumentException("HttpServletRequest must not be null.");
}
StringBuilder remoteAddress = new StringBuilder();
String scheme = request.getScheme();
rem... | @Test(expected=IllegalArgumentException.class)
public void testNullHttpServleRequest() {
HttpTransportUtils.generateWsRemoteAddress(null);
} |
@CanIgnoreReturnValue
public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
// TODO(kak): Possible enhancement: Include "[1 copy]" if... | @Test
public void containsAtLeastRejectsNull() {
ImmutableMultimap<Integer, String> multimap =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
try {
assertThat(multimap).containsAtLeastEntriesIn(null);
fail("Should have thrown.");
} catch (NullPointerExceptio... |
@Override
public Iterable<DefaultLogicalResult> getProducedResults() {
return jobVertex.getProducedDataSets().stream()
.map(IntermediateDataSet::getId)
.map(resultRetriever)
.collect(Collectors.toList());
} | @Test
public void testGetProducedResults() {
assertResultsEquals(results, upstreamLogicalVertex.getProducedResults());
} |
public static LeaderElectionManagerConfig fromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(LeaderElectionManagerConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return ne... | @Test
public void testSomeRequiredValuesNotNull() {
Map<String, String> envVars = new HashMap<>();
envVars.put(LeaderElectionManagerConfig.ENV_VAR_LEADER_ELECTION_LEASE_NAMESPACE.key(), "my-namespace");
envVars.put(LeaderElectionManagerConfig.ENV_VAR_LEADER_ELECTION_IDENTITY.key(), "my-pod")... |
@Override
public V computeIfPresent(String key, BiFunction<? super String, ? super V, ? extends V> remappingFunction) {
return Map.super.computeIfPresent(key.toLowerCase(), remappingFunction);
} | @Test
void computeIfPresent() {
Map<String, Object> map = new LowerCaseLinkHashMap<>(lowerCaseLinkHashMap);
Object result = map.computeIfPresent("key", (key,value)-> key.toUpperCase());
Assertions.assertEquals("KEY", result);
Assertions.assertEquals("KEY", map.get("key"));
r... |
@Override
@SuppressWarnings("unchecked")
public int run() throws IOException {
Preconditions.checkArgument(targets != null && targets.size() == 1, "A data file is required.");
String source = targets.get(0);
CodecFactory codecFactory = Codecs.avroCodec(compressionCodecName);
final Schema schema;
... | @Test
public void testToAvroCommandFromJson() throws IOException {
final File jsonInputFile = folder.newFile("sample.json");
final File avroOutputFile = folder.newFile("sample.avro");
// Write the json to the file, so we can read it again.
final String inputJson = "{\"id\": 1, \"name\": \"Alice\"}\n"... |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
... | @Test
public void testList() {
cli.command("list", existingStoreConfig);
// contents of the existing store is a-z for both the key and value
for (int i = 65; i <= 90; i++) {
String expected = new String(new byte[]{(byte) i});
assertListed(expected.toLowerCase());
... |
@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 autoDetectsMemoryUsageBeanAndMemoryPools() {
assertThat(new MemoryUsageGaugeSet().getMetrics().keySet())
.isNotEmpty();
} |
@SuppressWarnings("unchecked")
public static <T> T getObjectWithKey(String key, RequestContext requestContext, Class<T> clazz)
{
final Object object = requestContext.getLocalAttr(key);
return (clazz.isInstance(object)) ? (T) object : null;
} | @Test
public void testGetObjectWithKeySuperclass()
{
final ArrayList<String> value = new ArrayList<>();
_requestContext.putLocalAttr(KEY, value);
Assert.assertEquals(RequestContextUtil.getObjectWithKey(KEY, _requestContext, List.class), value);
} |
public TaskRunScheduler getTaskRunScheduler() {
return taskRunScheduler;
} | @Test
public void testTaskRunMergePriorityFirst2() {
TaskRunManager taskRunManager = new TaskRunManager();
Task task = new Task("test");
task.setDefinition("select 1");
long taskId = 1;
TaskRun taskRun1 = TaskRunBuilder
.newBuilder(task)
.se... |
public synchronized boolean isValid(int maxAllowedWindowsWithExtrapolation) {
int currentArrayIndex = arrayIndex(currentWindowIndex());
// The total number of valid window indices should exclude the current window index.
int numValidIndicesAdjustment = _validity.get(currentArrayIndex) ? 1 : 0;
boolean a... | @Test
public void testIsValid() {
RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS);
rawValues.updateOldestWindowIndex(0);
MetricSample<String, IntegerEntity> m = getMetricSample(10, 10, 10);
for (int i = 0; i < NUM_WINDOWS_TO_KEEP; i++) {
... |
@Override
public TransformResultMetadata getResultMetadata() {
return _resultMetadata;
} | @Test
public void testCaseTransformFunctionWithoutCastForFloatValues() {
boolean[] predicateResults = new boolean[1];
Arrays.fill(predicateResults, true);
int[] expectedValues = new int[1];
int index = -1;
for (int i = 0; i < NUM_ROWS; i++) {
if (Double.compare(_floatSVValues[i], Double.pars... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
} |
@Override
public void fulfillFinishedTaskStatus(Map<OperatorID, OperatorState> operatorStates) {
if (!mayHaveFinishedTasks) {
return;
}
Map<JobVertexID, ExecutionJobVertex> partlyFinishedVertex = new HashMap<>();
for (Execution task : finishedTasks) {
JobVert... | @Test
void testFulfillFinishedStates() throws Exception {
JobVertexID fullyFinishedVertexId = new JobVertexID();
JobVertexID finishedOnRestoreVertexId = new JobVertexID();
JobVertexID partiallyFinishedVertexId = new JobVertexID();
OperatorID fullyFinishedOperatorId = new OperatorID()... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldExtractUnaliasedDataSources() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getFrom(), is(new AliasedRelation(TEST1, TEST1_NAME)));
} |
@Override
public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) throws Exception {
response = discovery.discoverNodes();
List<Address> addresses = response.getPrivateMemberAddresses();
listenerRunner.onPossibleAddressesCollected(addresses);
return new... | @Test
public void testLoadAddresses_withTpc() throws Exception {
setUpWithTpc();
ViridianAddressProvider provider = new ViridianAddressProvider(createDiscovery());
ClientConnectionProcessListenerRegistry listener = createListenerRunner();
Addresses addresses = provider.loadAddresses(... |
public CompletableFuture<JobClient> submitJob(
JobGraph jobGraph, ClassLoader userCodeClassloader) throws Exception {
MiniClusterConfiguration miniClusterConfig =
getMiniClusterConfig(jobGraph.getMaximumParallelism());
MiniCluster miniCluster = miniClusterFactory.apply(miniCl... | @Test
void testJobClientInteractionAfterShutdown() throws Exception {
PerJobMiniClusterFactory perJobMiniClusterFactory = initializeMiniCluster();
JobClient jobClient =
perJobMiniClusterFactory
.submitJob(getNoopJobGraph(), ClassLoader.getSystemClassLoader())
... |
public static void checkContextPath(String contextPath) {
if (contextPath == null) {
return;
}
Matcher matcher = CONTEXT_PATH_MATCH.matcher(contextPath);
if (matcher.find()) {
throw new IllegalArgumentException("Illegal url path expression");
}
} | @Test
void testContextPathIllegal2() {
assertThrows(IllegalArgumentException.class, () -> {
String contextPath2 = "/nacos//";
ValidatorUtils.checkContextPath(contextPath2);
});
} |
@Override
public SchemaTransform from(PubsubReadSchemaTransformConfiguration configuration) {
if (configuration.getSubscription() == null && configuration.getTopic() == null) {
throw new IllegalArgumentException(
"To read from Pubsub, a subscription name or a topic name must be provided");
}
... | @Test
public void testInvalidConfigInvalidFormat() {
PCollectionRowTuple begin = PCollectionRowTuple.empty(p);
assertThrows(
IllegalArgumentException.class,
() ->
begin.apply(
new PubsubReadSchemaTransformProvider()
.from(
... |
public static ThriftType.StructType toStructType(Class<? extends TBase<?, ?>> thriftClass) {
final TStructDescriptor struct = TStructDescriptor.getInstance(thriftClass);
return toStructType(struct);
} | @Test
public void testToThriftType() throws Exception {
final StructType converted = ThriftSchemaConverter.toStructType(AddressBook.class);
final String json = converted.toJSON();
final ThriftType fromJSON = StructType.fromJSON(json);
assertEquals(json, fromJSON.toJSON());
} |
@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 testFindFileNotFound() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final GoogleStorageFindFeature f = new GoogleStorageFindFeature(session);
assertFalse(f.find(new Path(container, UUID.randomUUI... |
@JsonCreator
public static ContentPackInstallationRequest create(
@JsonProperty("parameters") @Nullable Map<String, ValueReference> parameters,
@JsonProperty("comment") @Nullable String comment) {
final Map<String, ValueReference> parameterMap = parameters == null ? Collections.empty... | @Test
public void testDeserialisation() throws IOException {
final String json = "{"
+ "\"parameters\":{"
+ " \"param1\":{\"@type\":\"string\",\"@value\":\"string\"},"
+ " \"param2\":{\"@type\":\"integer\",\"@value\":42},"
+ " \"param3\":{\"... |
@Override
public ControlledShutdownResponse getErrorResponse(int throttleTimeMs, Throwable e) {
ControlledShutdownResponseData data = new ControlledShutdownResponseData()
.setErrorCode(Errors.forException(e).code());
return new ControlledShutdownResponse(data);
} | @Test
public void testGetErrorResponse() {
for (short version : CONTROLLED_SHUTDOWN.allVersions()) {
ControlledShutdownRequest.Builder builder = new ControlledShutdownRequest.Builder(
new ControlledShutdownRequestData().setBrokerId(1), version);
ControlledShutdown... |
@Override
public ValidationResult validate(Object value) {
ValidationResult result = super.validate(value);
if (result instanceof ValidationResult.ValidationPassed) {
final String sValue = (String) value;
if (sValue != null && sValue.length() > maxLength) {
r... | @Test
public void testValidateNoString() {
assertThat(new LimitedOptionalStringValidator(1).validate(123))
.isInstanceOf(ValidationResult.ValidationFailed.class);
} |
@SuppressWarnings({"dereference.of.nullable", "argument"})
public static PipelineResult run(DataTokenizationOptions options) {
SchemasUtils schema = null;
try {
schema = new SchemasUtils(options.getDataSchemaPath(), StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("Failed to retrie... | @Test
public void testFileSystemIOReadJSON() throws IOException {
PCollection<Row> jsons = fileSystemIORead(JSON_FILE_PATH, FORMAT.JSON);
assertRows(jsons);
testPipeline.run();
} |
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (!left.getSchema().getName().equals(right.ge... | @Test
public void shouldProvideCollisionGuaranteesForIntegerCollisions_onObjects() {
IntTypeState1 intTypeState1 = new IntTypeState1();
intTypeState1.intA = 15;
intTypeState1.intB = 5;
writer1.reset();
mapper1.writeFlat(intTypeState1, writer1);
FlatRecord rec1 = writ... |
public static List<ParameterMarkerExpressionSegment> getParameterMarkerExpressions(final Collection<ExpressionSegment> expressions) {
List<ParameterMarkerExpressionSegment> result = new ArrayList<>();
extractParameterMarkerExpressions(result, expressions);
return result;
} | @Test
void assertExtractGetParameterMarkerExpressions() {
FunctionSegment functionSegment = new FunctionSegment(0, 0, "IF", "IF(number + 1 <= ?, 1, -1)");
BinaryOperationExpression param1 = new BinaryOperationExpression(0, 0,
new BinaryOperationExpression(0, 0, new ColumnSegment(0, 0... |
public AbilityStatus getConnectionAbility(AbilityKey abilityKey) {
if (currentConnection != null) {
return currentConnection.getConnectionAbility(abilityKey);
}
// return null if connection is not ready
return null;
} | @Test
void testGetConnectionAbilityWithNullConnection() {
AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1);
assertNull(abilityStatus);
} |
@Override
public int getID() {
return this.id;
} | @Test
public void checkCategoryIDs() {
Assert.assertEquals(0, this.fastFood.getID());
Assert.assertEquals(1, this.bars.getID());
Assert.assertEquals(2, this.restaurants.getID());
Assert.assertEquals(3, this.electronics.getID());
Assert.assertEquals(4, this.clothes.getID());
... |
public static GenericRecord rewriteRecord(GenericRecord oldRecord, Schema newSchema) {
GenericRecord newRecord = new GenericData.Record(newSchema);
boolean isSpecificRecord = oldRecord instanceof SpecificRecordBase;
for (Schema.Field f : newSchema.getFields()) {
if (!(isSpecificRecord && isMetadataFie... | @Test
public void testNonNullableFieldWithoutDefault() {
GenericRecord rec = new GenericData.Record(new Schema.Parser().parse(EXAMPLE_SCHEMA));
rec.put("_row_key", "key1");
rec.put("non_pii_col", "val1");
rec.put("pii_col", "val2");
rec.put("timestamp", 3.5);
assertThrows(SchemaCompatibilityEx... |
public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) {
JsonNode oldConfiguration = node.getConfiguration();
int configurationVersion = node.getConfigurationVersion();
int currentVersion = nodeInfo.getCurrentVersion();
var configClass = nodeInfo.ge... | @Test
public void testUpgradeRuleNodeConfigurationWithNonNullConfig() throws Exception {
// GIVEN
var node = new RuleNode();
var nodeInfo = mock(RuleNodeClassInfo.class);
var nodeConfigClazz = TbGetAttributesNodeConfiguration.class;
var annotation = mock(org.thingsboard.rule.... |
@Override
public Mono<TagVo> getByName(String name) {
return client.fetch(Tag.class, name)
.map(TagVo::from);
} | @Test
void getByName() throws JSONException {
when(client.fetch(eq(Tag.class), eq("t1")))
.thenReturn(Mono.just(tag(1)));
TagVo tagVo = tagFinder.getByName("t1").block();
tagVo.getMetadata().setCreationTimestamp(null);
JSONAssert.assertEquals("""
{
... |
public static <T> Read<T> read() {
return new AutoValue_JdbcIO_Read.Builder<T>()
.setFetchSize(DEFAULT_FETCH_SIZE)
.setOutputParallelization(true)
.build();
} | @Test
public void testReadWithSingleStringParameter() {
PCollection<TestRow> rows =
pipeline.apply(
JdbcIO.<TestRow>read()
.withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION)
.withQuery(String.format("select name,id from %s where name = ?", READ_TABLE_NAME))... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testTemporossNoPb()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Subdued in <col=ef1020>7:40</col>. Personal best: 5:38.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your Tempoross kill count is: <col=f... |
@Override
public TypeSerializer<T> createSerializer(SerializerConfig config) {
return new AvroSerializer<>(getTypeClass());
} | @Test
void testAvroByDefault() {
final TypeSerializer<User> serializer =
new AvroTypeInfo<>(User.class).createSerializer(new SerializerConfigImpl());
assertThat(serializer).isInstanceOf(AvroSerializer.class);
} |
public int getAttributesToNodesFailedRetrieved() {
return numGetAttributesToNodesFailedRetrieved.value();
} | @Test
public void testGetAttributesToNodesRetrievedFailed() {
long totalBadBefore = metrics.getAttributesToNodesFailedRetrieved();
badSubCluster.getAttributesToNodesFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getAttributesToNodesFailedRetrieved());
} |
@UdafFactory(description = "collect distinct values of a Bigint field into a single Array")
public static <T> Udaf<T, List<T>, List<T>> createCollectSetT() {
return new Collect<>();
} | @Test
public void shouldRespectSizeLimitString() {
final Udaf<Integer, List<Integer>, List<Integer>> udaf = CollectSetUdaf.createCollectSetT();
((Configurable) udaf).configure(ImmutableMap.of(CollectSetUdaf.LIMIT_CONFIG, "1000"));
List<Integer> runningList = udaf.initialize();
for (int i = 1; i < 2500... |
public void execute(final PrioritizableRunnable runnable) {
_queue.add(runnable);
// Guarantees that execution loop is scheduled only once to the underlying executor.
// Also makes sure that all memory effects of last Runnable are visible to the next Runnable
// in case value returned by decrementAndGet... | @Test(dataProvider = "draining")
public void testRejectOnFirstExecute(boolean draining) throws InterruptedException {
// First fill up the underlying executor service so that a subsequent
// submission of an execution loop by the serial executor will fail.
_executorService.execute(new NeverEndingRunnable(... |
public static List<String> computeNameParts(String loggerName) {
List<String> partList = new ArrayList<String>();
int fromIndex = 0;
while (true) {
int index = getSeparatorIndexOf(loggerName, fromIndex);
if (index == -1) {
partList.add(loggerName.substrin... | @Test
public void supportNestedClassesAtBeginning() {
List<String> witnessList = new ArrayList<String>();
witnessList.add("foo");
witnessList.add("Nested");
witnessList.add("bar");
List<String> partList = LoggerNameUtil.computeNameParts("foo$Nested.bar");
assertEqual... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (bizConfig.isAdminServiceAccessControlEnabled()) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res... | @Test
public void testWithAccessControlEnabledWithTokenSpecifiedWithNoTokenPassed() throws Exception {
String someValidToken = "someValidToken";
when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true);
when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someValidToken);
when(servle... |
@Override
public Iterator<Path> iterator() {
return new NameIterator(fs, !bucket.isEmpty(), bucketAndObject());
} | @Test
public void testIterator() {
GcsPath a = GcsPath.fromComponents("bucket", "a/b/c");
Iterator<Path> it = a.iterator();
assertTrue(it.hasNext());
assertEquals("gs://bucket/", it.next().toString());
assertTrue(it.hasNext());
assertEquals("a", it.next().toString());
assertTrue(it.hasNex... |
public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
// We don't have any input fields here in "r" as they are all info fields.
// So we just me... | @Test
public void testGetFieldsEmptyInput() throws Exception {
RowMeta outputRowMeta = new RowMeta();
MergeJoinMeta meta = new MergeJoinMeta();
RowMeta inputRow1 = new RowMeta();
ValueMetaInteger field1_row1 = new ValueMetaInteger( "field1" );
field1_row1.setOrigin( "inputStep1" );
inputRow1.... |
@Override
public Hedge hedge(final String name) {
return hedge(name, getDefaultConfig(), emptyMap());
} | @Test
public void hedgePositive() {
HedgeRegistry registry = HedgeRegistry.builder().withDefaultConfig(config).build();
Hedge firstHedge = registry.hedge("test");
Hedge anotherLimit = registry.hedge("test1");
Hedge sameAsFirst = registry.hedge("test");
then(firstHedge).isEq... |
@Override
@Nullable
public String readString(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, UTF, super::readString);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadUTF_IncompatibleClass() throws Exception {
reader.readString("byte");
} |
@Override
public void start(EdgeExplorer explorer, int startNode) {
SimpleIntDeque fifo = new SimpleIntDeque();
GHBitSet visited = createBitSet();
visited.add(startNode);
fifo.push(startNode);
int current;
while (!fifo.isEmpty()) {
current = fifo.pop();
... | @Test
public void testBFS() {
BreadthFirstSearch bfs = new BreadthFirstSearch() {
@Override
protected GHBitSet createBitSet() {
return new GHTBitSet();
}
@Override
public boolean goFurther(int v) {
counter++;
... |
public boolean isLaunchIntentOfNotification(Intent intent) {
return intent.getBooleanExtra(LAUNCH_FLAG_KEY_NAME, false);
} | @Test
public void isLaunchIntentOfNotification_hasFlagInBundle_returnTrue() throws Exception {
Intent intent = mock(Intent.class);
when(intent.getBooleanExtra(eq(LAUNCHED_FROM_NOTIF_BOOLEAN_EXTRA_NAME), eq(false))).thenReturn(true);
final AppLaunchHelper uut = getUUT();
boolean resu... |
@Override
@Transactional(rollbackFor = Exception.class)
@LogRecord(type = SYSTEM_USER_TYPE, subType = SYSTEM_USER_UPDATE_SUB_TYPE, bizNo = "{{#updateReqVO.id}}",
success = SYSTEM_USER_UPDATE_SUCCESS)
public void updateUser(UserSaveReqVO updateReqVO) {
updateReqVO.setPassword(null); // 特殊... | @Test
public void testUpdateUser_success() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO(o -> o.setPostIds(asSet(1L, 2L)));
userMapper.insert(dbUser);
userPostMapper.insert(new UserPostDO().setUserId(dbUser.getId()).setPostId(1L));
userPostMapper.insert(new UserPostDO()... |
static public JobConf createJob(String[] argv) throws IOException {
StreamJob job = new StreamJob();
job.argv_ = argv;
job.init();
job.preProcessArgs();
job.parseArgv();
job.postProcessArgs();
job.setJobConf();
return job.jobConf_;
} | @Test
public void testCreateJob() throws IOException {
JobConf job;
ArrayList<String> dummyArgs = new ArrayList<String>();
dummyArgs.add("-input"); dummyArgs.add("dummy");
dummyArgs.add("-output"); dummyArgs.add("dummy");
dummyArgs.add("-mapper"); dummyArgs.add("dummy");
dummyArgs.add("-reduce... |
@VisibleForTesting
RoleDO validateRoleForUpdate(Long id) {
RoleDO role = roleMapper.selectById(id);
if (role == null) {
throw exception(ROLE_NOT_EXISTS);
}
// 内置角色,不允许删除
if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) {
throw exception(ROLE_C... | @Test
public void testValidateUpdateRole_systemRoleCanNotBeUpdate() {
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.SYSTEM.getType()));
roleMapper.insert(roleDO);
// 准备参数
Long id = roleDO.getId();
assertServiceException(() -> roleService.validateRoleFo... |
@Override
public boolean updateGlobalWhiteAddrsConfig(List<String> globalWhiteAddrsList) {
return aclPlugEngine.updateGlobalWhiteAddrsConfig(globalWhiteAddrsList);
} | @Test
public void testUpdateSpecifiedAclFileGlobalWhiteAddrsConfig() throws IOException {
String folder = "update_global_white_addr";
File home = AclTestHelper.copyResources(folder);
System.setProperty("rocketmq.home.dir", home.getAbsolutePath());
System.setProperty("rocketmq.acl.pla... |
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, Dimension... dimensions) ... | @Test
void testString() {
testGeneric(Flags.defineStringFlag("string-id", "default value", List.of("owner"), "1970-01-01", "2100-01-01", "description",
"modification effect", Dimension.ZONE_ID, Dimension.HOSTNAME),
"other value");
} |
public String getName() {
return type.name;
} | @Test
void qualifiedName() {
Arrays.stream(Type.values()).forEach((Type t) -> {
final Schema.Name name = new Schema.Name(t.getName(), "space");
assertEquals("space." + t.getName(), name.getQualified("space"));
assertEquals("space." + t.getName(), name.getQualified("otherdefault"));
});
f... |
static ULabeledStatement create(CharSequence label, UStatement statement) {
return new AutoValue_ULabeledStatement(StringName.of(label), (USimpleStatement) statement);
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(ULabeledStatement.create("foo", USkip.INSTANCE));
} |
@Override
public ObjectNode encode(OpenstackVtapCriterion entity, CodecContext context) {
String protoStr = getProtocolStringFromType(entity.ipProtocol());
return context.mapper().createObjectNode()
.put(SRC_IP, entity.srcIpPrefix().address().toString())
.put(DST_IP,... | @Test
public void testOpenstackVtapCriterionEncode() {
OpenstackVtapCriterion criterion = DefaultOpenstackVtapCriterion.builder()
.srcIpPrefix(IpPrefix.valueOf(IpAddress.valueOf("10.10.10.10"), 32))
.dstIpPrefix(IpPrefix.valueOf(IpAddress.valueOf("20.20.20.20"), 32))
... |
@Override
public void collectSizeStats(StateObjectSizeStatsCollector collector) {
final StateObjectLocation location;
if (NOT_LOCAL_FILER.matcher(filePath.toUri().toString()).matches()) {
location = StateObjectLocation.REMOTE;
} else {
location = StateObjectLocation.L... | @Test
void testCollectSizeStats() throws Exception {
final long stateSize = 123L;
StateObject.StateObjectSizeStatsCollector statsCollector =
StateObject.StateObjectSizeStatsCollector.create();
FileStateHandle handle =
new FileStateHandle(new Path(new URI("fil... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
return doSharding(availableTargetNames, Range.singleton(sh... | @Test
void assertPreciseDoShardingByQuarter() {
assertThat(shardingAlgorithmByQuarter.doSharding(availableTablesForQuarterDataSources,
new PreciseShardingValue<>("t_order", "create_time", DATA_NODE_INFO, "2020-01-01 00:00:01")), is("t_order_202001"));
assertThat(shardingAlgorithmByQu... |
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(String topic, long offset, int queueId, String brokerName, boolean deCompressBody) {
MessageStore messageStore = brokerController.getMessageStoreByBrokerName(brokerName);
if (messageStore != null) {
return messageS... | @Test
public void getMessageAsyncTest_localStore_getMessageAsync_null() {
when(brokerController.getMessageStoreByBrokerName(any())).thenReturn(defaultMessageStore);
when(defaultMessageStore.getMessageAsync(anyString(), anyString(), anyInt(), anyLong(), anyInt(), any()))
.thenReturn(C... |
@Override
public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
process(deviceId, forwardingObjective);
} | @Test
public void forwardTimeout() {
final AtomicInteger counter = new AtomicInteger(0);
ForwardingObjective fwdTimeout = buildFwdObjective(S1, NID2).add(new ObjectiveContext() {
@Override
public void onError(Objective objective, ObjectiveError error) {
if (Ob... |
public void setSaslMechanism(String saslMechanism) {
this.saslMechanism = saslMechanism;
} | @Test
public void testSetSaslMechanism() {
Properties props = getLog4jConfig(false);
props.put("log4j.appender.KAFKA.SaslMechanism", "PLAIN");
PropertyConfigurator.configure(props);
MockKafkaLog4jAppender mockKafkaLog4jAppender = getMockKafkaLog4jAppender();
assertEquals(mo... |
@SuppressWarnings("unchecked")
public Set<String> getStreamIds() {
Collection<String> streamField;
try {
streamField = getFieldAs(Collection.class, FIELD_STREAMS);
} catch (ClassCastException e) {
LOG.trace("Couldn't cast {} to List", FIELD_STREAMS, e);
st... | @Test
public void testGetStreamIds() throws Exception {
message.addField("streams", Lists.newArrayList("stream-id"));
assertThat(message.getStreamIds()).containsOnly("stream-id");
} |
@Override
public boolean remove(Object o) {
if (o instanceof Pair) {
Object first = ((Pair<?, ?>) o).first();
Object second = ((Pair<?, ?>) o).second();
if (first instanceof Integer && (second == null || second instanceof StructLike)) {
return remove((Integer) first, (StructLike) second)... | @Test
public void testRemove() {
PartitionSet set = PartitionSet.create(SPECS);
set.add(BY_DATA_SPEC.specId(), Row.of("a"));
set.add(UNPARTITIONED_SPEC.specId(), null);
set.add(UNPARTITIONED_SPEC.specId(), Row.of());
set.add(BY_DATA_CATEGORY_BUCKET_SPEC.specId(), CustomRow.of("a", 1));
assert... |
@Override
public OverlayData createOverlayData(ComponentName remoteApp) {
final OverlayData original = mOriginal.createOverlayData(remoteApp);
if (original.isValid() || mFixInvalid) {
final int backgroundLuminance = luminance(original.getPrimaryColor());
final int diff = backgroundLuminance - lumi... | @Test
public void testReturnsOriginalIfInvalid() {
OverlayData original = setupOriginal(Color.GRAY, Color.GRAY, Color.GRAY);
final OverlayData fixed = mUnderTest.createOverlayData(mTestComponent);
Assert.assertSame(original, fixed);
Assert.assertFalse(fixed.isValid());
} |
public static String createRpcId() {
return UUID.randomUUID().toString();
} | @Test
public void createRpcId() throws Exception {
String first = IdUtils.createRpcId();
assertTrue(!first.isEmpty());
String second = IdUtils.createRpcId();
assertTrue(!second.isEmpty());
assertNotEquals(first, second);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.