focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public ImmutableList<PluginDefinition> getAllPlugins() {
try {
if (checkHealthWithBackoffs()) {
logger.atInfo().log("Getting language server plugins...");
var listPluginsResponse =
service
.listPluginsWithDeadline(ListPluginsRequest.getDefaultInstance(),... | @Test
public void getAllPlugins_withServingServer_returnsSuccessfulList() throws Exception {
registerHealthCheckWithStatus(ServingStatus.SERVING);
var plugin = createSinglePluginDefinitionWithName("test");
RemoteVulnDetector pluginToTest = getNewRemoteVulnDetectorInstance();
serviceRegistry.addServ... |
public static <K, V> RedistributeByKey<K, V> byKey() {
return new RedistributeByKey<>(false);
} | @Test
@Category(ValidatesRunner.class)
public void testJustRedistribute() {
PCollection<KV<String, Integer>> input =
pipeline.apply(
Create.of(ARBITRARY_KVS).withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())));
PCollection<KV<String, Integer>> output = input.apply(Redistribu... |
@Override
public int compareTo(@NotNull Evidence o) {
return new CompareToBuilder()
.append(this.source == null ? null : this.source.toLowerCase(), o.source == null ? null : o.source.toLowerCase())
.append(this.name == null ? null : this.name.toLowerCase(), o.name == null ? n... | @Test
public void testCompareTo() {
Evidence that0 = new Evidence("file", "name", "guice-3.0", Confidence.HIGHEST);
Evidence that1 = new Evidence("jar", "package name", "dependency", Confidence.HIGHEST);
Evidence that2 = new Evidence("jar", "package name", "google", Confidence.HIGHEST);
... |
public HttpRequest inject(HttpRequest request) {
Map<String, List<String>> map = new HashMap<>();
if (manager.activeSpan() == null) {
return request;
}
map.put(ApolloAuditConstants.TRACE_ID,
Collections.singletonList(manager.activeSpan().traceId()));
map.put(ApolloAuditConstants.SPAN_I... | @Test
public void testInjectCaseActiveSpanIsNull() {
HttpRequest mockRequest = Mockito.mock(HttpRequest.class);
{
Mockito.when(manager.activeSpan()).thenReturn(null);
Mockito.when(mockRequest.getHeaders()).thenReturn(new HttpHeaders());
}
HttpRequest injected = tracer.inject(mockRequest);
... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void sessionWindowedCogroupedZeroArgCountWithTopologyConfigShouldPreserveTopologyStructure() {
// override the default store into in-memory
final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY));
builder.stream("input-topic")
... |
static <T extends Comparable<? super T>> int compareListWithFillValue(
List<T> left, List<T> right, T fillValue) {
int longest = Math.max(left.size(), right.size());
for (int i = 0; i < longest; i++) {
T leftElement = fillValue;
T rightElement = fillValue;
if (i < left.size()) {
... | @Test
public void compareWithFillValue_nonEmptyListVariedSizeWithPositiveFillValue_returnsPositive() {
assertThat(
ComparisonUtility.compareListWithFillValue(
Lists.newArrayList(1, 2), Lists.newArrayList(1, 2, 3), 100))
.isGreaterThan(0);
} |
@SuppressWarnings("MethodLength")
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header)
{
messageHeaderDecoder.wrap(buffer, offset);
final int templateId = messageHeaderDecoder.templateId();
final int schemaId = messageHeaderDecoder.s... | @Test
void onFragmentShouldInvokeOnAdminResponseCallbackIfSessionIdMatches()
{
final int offset = 24;
final long clusterSessionId = 18;
final long correlationId = 3274239749237498239L;
final AdminRequestType type = AdminRequestType.SNAPSHOT;
final AdminResponseCode respon... |
static int getIndexInsensitive(CharSequence name, CharSequence value) {
if (value.length() == 0) {
HeaderNameIndex entry = getEntry(name);
return entry == null || !entry.emptyValue ? NOT_FOUND : entry.index;
}
int bucket = headerBucket(value);
HeaderIndex header =... | @Test
public void testExistingHeaderNameAndValueSecondMatch() {
assertEquals(7, HpackStaticTable.getIndexInsensitive(
AsciiString.cached(":scheme"), AsciiString.cached("https")));
} |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void testBuildWithIllegalCoreThreadPoolSize() {
ThreadPoolBulkheadConfig.custom()
.coreThreadPoolSize(-1)
.build();
} |
@Override
public boolean addAll(Collection<? extends R> c) {
throw new UnsupportedOperationException("LazySet is not modifiable");
} | @Test(expected = UnsupportedOperationException.class)
public void testAddAll_throwsException() {
set.addAll(Collections.emptyList());
} |
public boolean rollbackClusterState(UUID txnId) {
clusterServiceLock.lock();
try {
final LockGuard currentLock = getStateLock();
if (!currentLock.allowsUnlock(txnId)) {
return false;
}
logger.fine("Rolling back cluster state transaction: "... | @Test(expected = NullPointerException.class)
public void test_unlockClusterState_nullTransactionId() {
clusterStateManager.rollbackClusterState(null);
} |
@Override
public ApiResult<TopicPartition, DeletedRecords> handleResponse(
Node broker,
Set<TopicPartition> keys,
AbstractResponse abstractResponse
) {
DeleteRecordsResponse response = (DeleteRecordsResponse) abstractResponse;
Map<TopicPartition, DeletedRecords> completed... | @Test
public void testHandleSuccessfulResponse() {
AdminApiHandler.ApiResult<TopicPartition, DeletedRecords> result =
handleResponse(createResponse(emptyMap(), recordsToDelete.keySet()));
assertResult(result, recordsToDelete.keySet(), emptyMap(), emptyList(), emptySet());
} |
@GetMapping
public String getHealth() {
// TODO UP DOWN WARN
StringBuilder sb = new StringBuilder();
String dbStatus = dataSourceService.getHealth();
boolean addressServerHealthy = isAddressServerHealthy();
if (dbStatus.contains(HEALTH_UP) && addressServerHealthy && ServerMem... | @Test
void testGetHealthWhenTheLoopUpInfoParseError() throws Exception {
when(dataSourceService.getHealth()).thenReturn("UP");
when(memberManager.getLookup()).thenReturn(memberLookup);
when(memberLookup.useAddressServer()).thenReturn(true);
final HashMap<String, Object> info... |
public final void doesNotContainKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).doesNotContain(key);
} | @Test
public void doesNotContainKeyFailure() {
ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever");
expectFailureWhenTestingThat(multimap).doesNotContainKey("kurt");
assertFailureKeys("value of", "expected not to contain", "but was", "multimap was");
assertFailureValue... |
public synchronized void lostNodeFound(Address address) {
Preconditions.checkNotNull(address, "address should not be null");
mLostNodes.remove(address);
for (Runnable function : mChangeListeners) {
function.run();
}
} | @Test
public void lostNodeFound() {
ConfigurationStore configStore = createConfigStore();
configStore.handleNodeLost(mAddressOne);
configStore.handleNodeLost(mAddressTwo);
Map<Address, List<ConfigRecord>> confMap = configStore.getConfMap();
assertFalse(confMap.containsKey(mAddressOne));
asse... |
public RecordAppendResult append(String topic,
int partition,
long timestamp,
byte[] key,
byte[] value,
Header[] headers,
... | @Test
public void testSplitFrequency() throws InterruptedException {
long seed = System.currentTimeMillis();
Random random = new Random();
random.setSeed(seed);
final int batchSize = 1024;
final int numMessages = 1000;
RecordAccumulator accum = createTestRecordAccumu... |
@VisibleForTesting
static Duration parseToDuration(String timeStr) {
final Matcher matcher = Pattern.compile("(?<value>\\d+)\\s*(?<time>[dhms])").matcher(timeStr);
if (!matcher.matches()) {
throw new IllegalArgumentException("Expected a time specification in the form <number>[d,h,m,s], e... | @Test
public void testParseToDurationSuccessfullyParseExpectedFormats() {
assertEquals(Duration.of(4, ChronoUnit.DAYS), AbstractPipelineExt.parseToDuration("4d"));
assertEquals(Duration.of(3, ChronoUnit.HOURS), AbstractPipelineExt.parseToDuration("3h"));
assertEquals(Duration.of(2, ChronoUni... |
public static UserOperatorConfig buildFromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(UserOperatorConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return new UserOperatorC... | @Test
public void testFromMapInvalidLabelsStringThrows() {
Map<String, String> envVars = new HashMap<>(UserOperatorConfigTest.ENV_VARS);
envVars.put(UserOperatorConfig.LABELS.key(), ",label1=");
assertThrows(InvalidConfigurationException.class, () -> UserOperatorConfig.buildFromMap(envVars... |
RuleDto createNewRule(RulesRegistrationContext context, RulesDefinition.Rule ruleDef) {
RuleDto newRule = createRuleWithSimpleFields(ruleDef, uuidFactory.create(), system2.now());
ruleDescriptionSectionsGeneratorResolver.generateFor(ruleDef).forEach(newRule::addRuleDescriptionSectionDto);
context.created(ne... | @Test
public void createNewRule_whenRuleDefinitionDoesHaveCleanCodeAttributeAndIsSecurityHotspot_shouldReturnNull() {
RulesDefinition.Rule ruleDef = getDefaultRule(CleanCodeAttribute.TESTED, RuleType.SECURITY_HOTSPOT);
RuleDto newRuleDto = underTest.createNewRule(context, ruleDef);
assertThat(newRuleDto.... |
@Override
public Predicate visit(OrPredicate orPredicate, IndexRegistry indexes) {
Predicate[] originalInnerPredicates = orPredicate.predicates;
if (originalInnerPredicates == null || originalInnerPredicates.length < MINIMUM_NUMBER_OF_OR_TO_REPLACE) {
return orPredicate;
}
... | @Test
public void whenThresholdExceeded_noEnoughCandidatesFound_thenReturnItself() {
// (age != 1 or age != 2 or age != 3 or age != 4 or age != 5)
Predicate p1 = equal("age", 1);
Predicate p2 = equal("age", 2);
Predicate p3 = equal("age", 3);
Predicate p4 = equal("age", 4);
... |
public static void addLockOptions(String basePath, TypedProperties props) {
if (!props.containsKey(HoodieLockConfig.LOCK_PROVIDER_CLASS_NAME.key())) {
props.putAll(FileSystemBasedLockProvider.getLockConfig(basePath));
}
} | @Test
void testAddLockOptions() {
TypedProperties props1 = new TypedProperties();
UtilHelpers.addLockOptions("path1", props1);
assertEquals(FileSystemBasedLockProvider.class.getName(), props1.getString(HoodieLockConfig.LOCK_PROVIDER_CLASS_NAME.key()));
TypedProperties props2 = new TypedProperties();
... |
@Override
public void onReceived() throws InvalidNotificationException {
if (!mAppLifecycleFacade.isAppVisible()) {
postNotification(null);
notifyReceivedBackgroundToJS();
} else {
notifyReceivedToJS();
}
} | @Test
public void onReceived_validDataForBackgroundApp_postNotificationAndNotifyJs() throws Exception {
// Arrange
setUpBackgroundApp();
// Act
final PushNotification uut = createUUT();
uut.onReceived();
// Assert
ArgumentCaptor<Notification> notification... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesIntegerUsingJavaTypeLongPrimitiveWhenMaximumGreaterThanIntegerMax() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "integer");
... |
@Override
public Exchange add(CamelContext camelContext, String key, Exchange oldExchange, Exchange newExchange)
throws OptimisticLockingException {
if (!optimistic) {
throw new UnsupportedOperationException();
}
LOG.trace("Adding an Exchange with ID {} for key {} in... | @Test
public void checkOptimisticAddOfNewExchange() throws Exception {
JCacheAggregationRepository repoOne = createRepository(true);
JCacheAggregationRepository repoTwo = createRepository(true);
repoOne.start();
repoTwo.start();
try {
final String testBody = "Th... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldNotMatchGenericMethodWithAlreadyReservedTypes() {
// Given:
final GenericType generic = GenericType.of("A");
givenFunctions(
function(EXPECTED, -1, generic, generic)
);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> udfInd... |
public static List<List<String>> getTabletDistribution(AdminShowReplicaDistributionStmt stmt) throws DdlException {
return getTabletDistribution(stmt.getDbName(), stmt.getTblName(), stmt.getPartitionNames());
} | @Test
public void testGetTabletDistribution()
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Object[] args = new Object[] {CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME, null};
List<List<String>> result = (List<List<String>>) getTabletDistr... |
public MatchResult match(MatchResult reuse, byte[] sequence, int start, int length, int node) {
if (node == 0) {
reuse.reset(MatchResult.NO_MATCH, start, node);
return reuse;
}
final FST fst = _fst;
final int end = start + length;
for (int i = start; i < end; i++) {
final int arc ... | @Test
public void testMatch()
throws IOException {
File file = new File("./src/test/resources/data/abc.native.fst");
FST fst = FST.read(new FileInputStream(file), false, new DirectMemoryManager(FSTTraversalTest.class.getName()));
FSTTraversal traversalHelper = new FSTTraversal(fst);
MatchResult... |
@VisibleForTesting
void validateExperienceOutRange(List<MemberLevelDO> list, Long id, Integer level, Integer experience) {
for (MemberLevelDO levelDO : list) {
if (levelDO.getId().equals(id)) {
continue;
}
if (levelDO.getLevel() < level) {
... | @Test
public void testCreateLevel_experienceOutRange() {
// 准备参数
int level = 10;
int experience = 10;
String name = randomString();
// mock 数据
memberlevelMapper.insert(randomLevelDO(o -> {
o.setLevel(level);
o.setExperience(experience);
... |
@Override
public boolean checkClass(ClassResolver classResolver, String className) {
try {
lock.readLock().lock();
return check(className);
} finally {
lock.readLock().unlock();
}
} | @Test
public void testCheckClass() {
{
Fury fury = Fury.builder().requireClassRegistration(false).build();
AllowListChecker checker = new AllowListChecker(AllowListChecker.CheckLevel.STRICT);
fury.getClassResolver().setClassChecker(checker);
assertThrows(InsecureException.class, () -> fury... |
@Override
public String version() {
return TSDBUtils.version(address, username, password);
} | @Test
public void testVersion() {
String version = new TSDBConnection(TSDB_ADDRESS,null,null,null).version();
Assert.assertNotNull(version);
} |
@Override
public Boolean getNullableResult(final ResultSet resultSet, final String columnName) throws SQLException {
return resultSet.getBoolean(columnName);
} | @Test
public void getNullableResultTest() {
final PostgreSQLBooleanHandler postgreSQLBooleanHandler = new PostgreSQLBooleanHandler();
final ResultSet resultSet = mock(ResultSet.class);
Assertions.assertDoesNotThrow(() -> postgreSQLBooleanHandler.getNullableResult(resultSet, 1));
Asse... |
@Override
protected IMetaStoreClient newClient() {
try {
try {
return GET_CLIENT.invoke(hiveConf, (HiveMetaHookLoader) tbl -> null, HiveMetaStoreClient.class.getName());
} catch (RuntimeException e) {
// any MetaException would be wrapped into RuntimeException during reflection, so le... | @Test
public void testGetTablesFailsForNonReconnectableException() throws Exception {
HiveMetaStoreClient hmsClient = Mockito.mock(HiveMetaStoreClient.class);
Mockito.doReturn(hmsClient).when(clients).newClient();
Mockito.doThrow(new MetaException("Another meta exception"))
.when(hmsClient)
... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));... | @Test
void invokeNumberWithoutDecimalPart() {
FunctionTestUtil.assertResult(numberFunction.invoke("9876", null, null), BigDecimal.valueOf(9876));
} |
@Override
public long getLargestSequence() {
long startNanos = Timer.nanos();
try {
return delegate.getLargestSequence();
} finally {
getLargestSequenceProbe.recordValue(Timer.nanosElapsed(startNanos));
}
} | @Test
public void getLargestSequence() {
long largestSequence = 100L;
when(delegate.getLargestSequence()).thenReturn(largestSequence);
long result = ringbufferStore.getLargestSequence();
assertEquals(largestSequence, result);
assertProbeCalledOnce("getLargestSequence");
... |
@VisibleForTesting
static boolean isValidUrlFormat(String url) {
Matcher matcher = URL_PATTERN.matcher(url);
if (matcher.find()) {
String host = matcher.group(2);
return InetAddresses.isInetAddress(host) || InternetDomainName.isValid(host);
}
return false;
} | @Test
public void testMissingURLProtocol() {
assertFalse(SplunkEventWriter.isValidUrlFormat("test-url"));
} |
public List<DataRecord> merge(final List<DataRecord> dataRecords) {
Map<DataRecord.Key, DataRecord> result = new HashMap<>();
dataRecords.forEach(each -> {
if (PipelineSQLOperationType.INSERT == each.getType()) {
mergeInsert(each, result);
} else if (PipelineSQLOp... | @Test
void assertUpdateBeforeDelete() {
DataRecord beforeDataRecord = mockUpdateDataRecord(1, 10, 50);
DataRecord afterDataRecord = mockDeleteDataRecord(1, 10, 50);
Collection<DataRecord> actual = groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRecord));
assertThat(actual.... |
public Optional<RouteContext> loadRouteContext(final OriginSQLRouter originSQLRouter, final QueryContext queryContext, final RuleMetaData globalRuleMetaData,
final ShardingSphereDatabase database, final ShardingCache shardingCache, final ConfigurationProperties props,
... | @Test
void assertCreateRouteContextWithCacheHit() {
QueryContext queryContext =
new QueryContext(sqlStatementContext, "insert into t values (?, ?)", Arrays.asList(0, 1), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class));
when(shardingCache.getConfig... |
@Override
public NativeEntity<Collector> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("0"))
.type(ModelTypes.SIDECAR_COLLECTOR_V1)
.data(objectMapper.convertValue(SidecarCollectorEntity.create(
ValueReference.of("filebeat"),
... |
@Override
public void run() {
if (!redoService.isConnected()) {
LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task");
return;
}
try {
redoForInstances();
redoForSubscribes();
} catch (Exception e) {
... | @Test
void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<InstanceRedoData> mockData = generateMockInstanceData(false, false, true);
when(redoService.findInstanceRedoData()).thenReturn(mockData);
redoTask.ru... |
@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 testReturnsFixedIfTextIsTooClose() {
OverlayData original = setupOriginal(Color.GRAY, Color.DKGRAY, Color.LTGRAY);
final OverlayData fixed = mUnderTest.createOverlayData(mTestComponent);
Assert.assertSame(original, fixed);
Assert.assertTrue(fixed.isValid());
Assert.assertEquals(C... |
TopicFilter topicFilter() {
return getConfiguredInstance(TOPIC_FILTER_CLASS, TopicFilter.class);
} | @Test
public void testAllTopics() {
MirrorSourceConfig config = new MirrorSourceConfig(makeProps("topics", ".*"));
assertTrue(config.topicFilter().shouldReplicateTopic("topic1"),
"topic1 created from wildcard should exist");
assertTrue(config.topicFilter().shouldReplicateTopi... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendMediaGroupDocuments() {
MessagesResponse response = bot.execute(new SendMediaGroup(chatId,
new InputMediaDocument(docFile),
new InputMediaDocument(docBytes).fileName("test.pdf").contentType("application/pdf")
));
assertTrue(response.isOk(... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testDisplayDataMissingPipelineOptionsRegistration() throws Exception {
HasClassOptions options = PipelineOptionsFactory.as(HasClassOptions.class);
options.setClassOption(ProxyInvocationHandlerTest.class);
PipelineOptions deserializedOptions = serializeDeserialize(PipelineOptions.class, ... |
public static String getFormattedDate() {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
} | @Test
public void testFormatter() {
String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$";
String dateString = Formatter.getFormattedDate();
assertTrue(Pattern
.matches(dateRegex1, dateString... |
static Map<String, String> parseAgentArgs(final String agentArgs)
{
if (Strings.isEmpty(agentArgs))
{
throw new IllegalArgumentException("cannot parse empty value");
}
final Map<String, String> values = new HashMap<>();
int optionIndex = -1;
do
{... | @Test
void shouldParseAgentArgsAsAConfigOptionsMap()
{
final Map<String, String> expectedOptions = new HashMap<>();
expectedOptions.put(LOG_FILENAME, "log.out");
expectedOptions.put(READER_CLASSNAME, "my reader");
expectedOptions.put(ENABLED_DRIVER_EVENT_CODES, "all");
ex... |
public boolean isSecured() {
return getBaseUrl().startsWith("https://");
} | @Test
public void is_secured_on_https_server() {
settings.setProperty("sonar.core.serverBaseURL", "https://mydomain.com");
assertThat(underTest().isSecured()).isTrue();
} |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testLessThanEqualsOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg = builder.startAnd().lessThanEquals("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
UnboundPredicate expected = Expressions.lessThanOrEqual("salary", 3000L);
... |
public Upstream choose(final String serviceId, final String selectorId,
final String ip, final String loadbalancer) {
// load service instance by serviceId
List<ServiceInstance> available = this.getServiceInstance(serviceId);
if (CollectionUtils.isEmpty(available)) {
... | @Test
public void testChoose() {
final String ip = "0.0.0.0";
final String selectorId = "1";
final String loadbalancer = "roundRobin";
// serviceInstance is null
Upstream upstreamIsNull = serviceChooser.choose("test", selectorId, ip, loadbalancer);
Assertions.assertN... |
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getData();
switch (metric.getType().getValueType()) {
case ... | @Test
public void toMeasure_returns_absent_for_null_argument() {
assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent();
} |
public static void printHelp(PrintStream out) {
checkNotNull(out);
out.println("The set of registered options are:");
Set<Class<? extends PipelineOptions>> sortedOptions =
new TreeSet<>(ClassNameComparator.INSTANCE);
sortedOptions.addAll(CACHE.get().registeredOptions);
for (Class<? extends P... | @Test
public void testProgrammaticPrintHelp() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PipelineOptionsFactory.printHelp(new PrintStream(baos));
String output = new String(baos.toByteArray(), StandardCharsets.UTF_8);
assertThat(output, containsString("The set of registered options ar... |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test
public void of_equalityDifferentAddress() {
String urnA = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler Task";
String urnB = "urn:hzScheduledTaskHandler:20e4f0f8-52bf-47e5-b541-e1924b83cc9b -1 Scheduler Task";
assertNotEquals(ScheduledTaskHandler.of(urnA... |
public abstract IsmPrefixReaderIterator overKeyComponents(List<?> keyComponents)
throws IOException; | @Test
public void testReadMissingKeysBypassingBloomFilter() throws Exception {
File tmpFile = tmpFolder.newFile();
List<IsmRecord<byte[]>> data = new ArrayList<>();
data.add(IsmRecord.<byte[]>of(ImmutableList.of(EMPTY, new byte[] {0x04}), EMPTY));
data.add(IsmRecord.<byte[]>of(ImmutableList.of(EMPTY, ... |
public ShareFetch<K, V> collect(final ShareFetchBuffer fetchBuffer) {
ShareFetch<K, V> fetch = ShareFetch.empty();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
final ShareCompletedFetch nextInLineFetch = fetchBuffer.nextInLi... | @Test
public void testFetchWithCorruptMessage() {
buildDependencies();
subscribeAndAssign(topicAPartition0);
ShareCompletedFetch completedFetch = completedFetchBuilder
.error(Errors.CORRUPT_MESSAGE)
.build();
fetchBuffer.add(completedFetch);
a... |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = true,通过 + token
public void testApproveOrDeny_autoApproveWithToken() {
// 准备参数
String responseType = "token";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = "https://www.iocoder.cn";
S... |
@Override
public <T> void delete(T attachedObject) {
addExpireListener(commandExecutor);
Set<String> deleted = new HashSet<String>();
delete(attachedObject, deleted);
} | @Test
public void testDelete() {
Customer customer = new Customer("12");
Order order = new Order(customer);
order = redisson.getLiveObjectService().persist(order);
assertThat(redisson.getKeys().count()).isEqualTo(3);
Customer persistedCustomer = order.getCustomer();
... |
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) {
return ConfigInstanceUtil.getNewInstance(clazz, configId, this);
} | @Test
public void non_existent_array_of_struct_in_payload_is_ignored() {
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("non_existent_arr");
array.addObject().setString("name", "val");
StructtypesConfig config = new ConfigPayload(slime).toInstance(StructtypesCon... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void renameNestedInMapFields() {
Schema nestedSchema = Schema.builder().addStringField("field1").addInt32Field("field2").build();
Schema schema =
Schema.builder()
.addMapField("map", Schema.FieldType.STRING, Schema.FieldType.row(nestedSchema))
... |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void fpOrWontFixIssues_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = FPOrAcceptedNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
} |
public static SerializableFunction<Row, Mutation> beamRowToMutationFn(
Mutation.Op operation, String table) {
return (row -> {
switch (operation) {
case INSERT:
return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row);
case DELETE:
return... | @Test
public void testCreateInsertMutationFromRowWithNulls() {
Mutation expectedMutation = createMutationNulls(Mutation.Op.INSERT);
Mutation mutation = beamRowToMutationFn(Mutation.Op.INSERT, TABLE).apply(WRITE_ROW_NULLS);
assertEquals(expectedMutation, mutation);
} |
@Override
public boolean match(Message msg, StreamRule rule) {
Double msgVal = getDouble(msg.getField(rule.getField()));
if (msgVal == null) {
return false;
}
Double ruleVal = getDouble(rule.getValue());
if (ruleVal == null) {
return false;
}
... | @Test
public void testMissedInvertedMatchWithMissingField() {
StreamRule rule = getSampleRule();
rule.setValue("23");
rule.setInverted(true);
Message msg = getSampleMessage();
msg.addField("someother", "42");
StreamRuleMatcher matcher = getMatcher(rule);
ass... |
void checkPerm(PlainAccessResource needCheckedAccess, PlainAccessResource ownedAccess) {
permissionChecker.check(needCheckedAccess, ownedAccess);
} | @Test(expected = AclException.class)
public void checkErrorPermDefaultValueNotMatch() {
plainAccessResource = new PlainAccessResource();
plainAccessResource.addResourceAndPerm("topicF", Permission.PUB);
plainPermissionManager.checkPerm(plainAccessResource, subPlainAccessResource);
} |
public String createULID(Message message) {
checkTimestamp(message.getTimestamp().getMillis());
try {
return createULID(message.getTimestamp().getMillis(), message.getSequenceNr());
} catch (Exception e) {
LOG.error("Exception while creating ULID.", e);
return... | @Test
public void uintMaxGenerate() {
final MessageULIDGenerator generator = new MessageULIDGenerator(new ULID());
final long ts = Tools.nowUTC().getMillis();
final int uIntMaxValue = ~0;
ULID.Value parsedULID = ULID.parseULID(generator.createULID(ts, uIntMaxValue));
asser... |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testHoursAgoDefaultReference() throws Exception
{
PrettyTime t = new PrettyTime();
Assert.assertEquals("3 hours ago", t.format(now.minusHours(3)));
} |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (boolean.class == type) {
return resultSet.getBoolean(columnIndex);
}
if (byte.class == type) {
return resultSet.getByte(columnIndex);
}
if (short.cla... | @Test
void assertGetValueByTimestamp() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getTimestamp(1)).thenReturn(new Timestamp(0L));
assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, Timestamp.class), is(new Timestamp(0L)));
} |
public static <T> void chainFuture(
CompletableFuture<? extends T> sourceFuture,
CompletableFuture<T> destinationFuture
) {
sourceFuture.whenComplete((BiConsumer<T, Throwable>) (val, throwable) -> {
if (throwable != null) {
destinationFuture.completeExceptionally(... | @Test
public void testChainFutureExceptionally() {
CompletableFuture<Integer> sourceFuture = new CompletableFuture<>();
CompletableFuture<Number> destinationFuture = new CompletableFuture<>();
FutureUtils.chainFuture(sourceFuture, destinationFuture);
sourceFuture.completeExceptionall... |
public static Map<List<RowExpression>, Boolean> getExpressionsPartitionedByCSE(Collection<? extends RowExpression> expressions, int expressionGroupSize)
{
if (expressions.isEmpty()) {
return ImmutableMap.of();
}
CommonSubExpressionCollector expressionCollector = new CommonSubExp... | @Test
void testGetExpressionsWithCSE()
{
List<RowExpression> expressions = ImmutableList.of(rowExpression("x + y"), rowExpression("(x + y) * 2"), rowExpression("x + 2"), rowExpression("y * (x + 2)"), rowExpression("x * y"));
Map<List<RowExpression>, Boolean> expressionsWithCSE = getExpressionsPa... |
static void validateCertificate(String clusterName, String clientId, X509Certificate cert, BiConsumer<String, Throwable> reporter, DeployState state) {
try {
var extensions = TBSCertificate.getInstance(cert.getTBSCertificate()).getExtensions();
if (extensions == null) return; // Certific... | @Test
void logs_deployment_warning_on_certificate_with_empty_sequence_of_extensions() {
var logger = new DeployLoggerStub();
var state = new DeployState.Builder().deployLogger(logger).build();
var cert = readTestCertificate("cert-with-empty-sequence-of-extensions.pem");
CloudClientsV... |
@Override
public Messages process(Messages messages) {
for (final MessageFilter filter : filterRegistry) {
for (Message msg : messages) {
final String timerName = name(filter.getClass(), "executionTime");
final Timer timer = metricRegistry.timer(timerName);
... | @Test
public void testHandleMessage() {
MessageFilter filterOnlyFirst = new MessageFilter() {
private boolean filterOut = true;
@Override
public boolean filter(Message msg) {
if (filterOut) {
msg.setFilterOut(true);
... |
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides)
{
Map<String, String> sessionProperties;
if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) {
sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride());
}
else... | @Test
public void testSessionPropertyRemoval()
{
overrides.setSessionPropertiesToRemove("property_2");
overrides.setSessionPropertiesOverrideStrategy(NO_ACTION);
QueryConfiguration removed = new QueryConfiguration(
CATALOG_OVERRIDE,
SCHEMA_OVERRIDE,
... |
@Override
public boolean isActive() {
return isActive;
} | @Test(timeOut = 30000)
public void testSubscribeTimeout() throws Exception {
resetChannel();
setChannelConnected();
// Delay the topic creation in a deterministic way
CompletableFuture<Runnable> openTopicTask = new CompletableFuture<>();
doAnswer(invocationOnMock -> {
... |
@Deprecated
@Override
public Boolean hasAppendsOnly(org.apache.hadoop.hive.ql.metadata.Table hmsTable, SnapshotContext since) {
TableDesc tableDesc = Utilities.getTableDesc(hmsTable);
Table table = IcebergTableUtil.getTable(conf, tableDesc.getProperties());
return hasAppendsOnly(table.snapshots(), since... | @Test
public void testHasAppendsOnlyFalseWhenGivenSnapShotIsNullButHasNonAppend() {
HiveIcebergStorageHandler storageHandler = new HiveIcebergStorageHandler();
Boolean result = storageHandler.hasAppendsOnly(asList(appendSnapshot, deleteSnapshot), null);
assertThat(result, is(false));
} |
public void updateEventQueueProcessingTime(long durationMs) {
eventQueueProcessingTimeUpdater.accept(durationMs);
} | @Test
public void testUpdateEventQueueProcessingTime() {
MetricsRegistry registry = new MetricsRegistry();
MockTime time = new MockTime();
try (QuorumControllerMetrics metrics = new QuorumControllerMetrics(Optional.of(registry), time, false)) {
metrics.updateEventQueueProcessingT... |
public void shutdown(final Duration duration) {
for (final TaskExecutor t: taskExecutors) {
t.requestShutdown();
}
signalTaskExecutors();
for (final TaskExecutor t: taskExecutors) {
t.awaitShutdown(duration);
}
} | @Test
public void shouldShutdownTaskExecutors() {
final Duration duration = mock(Duration.class);
taskManager.shutdown(duration);
verify(taskExecutor).requestShutdown();
verify(taskExecutor).awaitShutdown(duration);
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeGeneratedColumns() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByExpression("two", "one + 1")
.build();
List<SqlNode> derivedColumns =
Array... |
public synchronized ListenableFuture<?> waitForMinimumCoordinatorSidecars()
{
if (currentCoordinatorSidecarCount == 1 || !isCoordinatorSidecarEnabled) {
return immediateFuture(null);
}
SettableFuture<?> future = SettableFuture.create();
coordinatorSidecarSizeFutures.add(... | @Test(timeOut = 60_000)
public void testWaitForMinimumCoordinatorSidecars()
throws InterruptedException
{
ListenableFuture<?> coordinatorSidecarsFuture = waitForMinimumCoordinatorSidecars();
assertFalse(monitor.hasRequiredCoordinatorSidecars());
assertFalse(coordinatorSidecar... |
public int separate(File starTreeOutputDir, StarTreeV2BuilderConfig builderConfig)
throws IOException {
int treeIndex = _builderConfigList.indexOf(builderConfig);
if (treeIndex == -1) {
LOGGER.info("No existing star-tree found for config: {}", builderConfig);
return -1;
}
LOGGER.info("... | @Test
public void testSeparate()
throws Exception {
URL segmentUrl = getClass().getClassLoader().getResource(SEGMENT_PATH);
assertNotNull(segmentUrl);
File segmentDir = new File(segmentUrl.getFile());
try (StarTreeIndexSeparator separator = new StarTreeIndexSeparator(
new File(segmentDir... |
public String filterNamespaceName(String namespaceName) {
if (namespaceName.toLowerCase().endsWith(".properties")) {
int dotIndex = namespaceName.lastIndexOf(".");
return namespaceName.substring(0, dotIndex);
}
return namespaceName;
} | @Test
public void testFilterNamespaceName() throws Exception {
String someName = "a.properties";
assertEquals("a", namespaceUtil.filterNamespaceName(someName));
} |
public boolean shouldExecute(DefaultPostJobDescriptor descriptor) {
if (!settingsCondition(descriptor)) {
LOG.debug("'{}' skipped because one of the required properties is missing", descriptor.name());
return false;
}
return true;
} | @Test
public void should_run_analyzer_with_no_metadata() {
DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor();
optimizer = new PostJobOptimizer(settings.asConfig());
assertThat(optimizer.shouldExecute(descriptor)).isTrue();
} |
public static void main(String[] args) throws Exception
{
try
{
final CommandLineParser parser = new GnuParser();
CommandLine cl = parser.parse(OPTIONS, args);
if (cl.hasOption('h'))
{
help();
System.exit(0);
}
String sourceFormat = cl.getOptionValue('s', ... | @Test(dataProvider = "fullClassName")
public void testTranslatePdscToPdl(String packageName, String className) throws Exception
{
String temp = Files.createTempDirectory("restli").toFile().getAbsolutePath();
SchemaFormatTranslator.main(new String[]{"-o", RESOLVER_DIR, SOURCE_ROOT, temp});
MultiFormatDat... |
public static boolean isLmq(String lmqMetaData) {
return lmqMetaData != null && lmqMetaData.startsWith(LMQ_PREFIX);
} | @Test
public void testIsLmq() {
String testLmq = null;
assertThat(MixAll.isLmq(testLmq)).isFalse();
testLmq = "lmq";
assertThat(MixAll.isLmq(testLmq)).isFalse();
testLmq = "%LMQ%queue123";
assertThat(MixAll.isLmq(testLmq)).isTrue();
testLmq = "%LMQ%GID_TEST";
... |
public ShareFetchContext newContext(String groupId, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData,
List<TopicIdPartition> toForget, ShareRequestMetadata reqMetadata, Boolean isAcknowledgeDataPresent) {
ShareFetchContext context;
// Top... | @Test
public void testNewContext() {
Time time = new MockTime();
ShareSessionCache cache = new ShareSessionCache(10, 1000);
SharePartitionManager sharePartitionManager = SharePartitionManagerBuilder.builder()
.withCache(cache).withTime(time).build();
Map<Uuid, String>... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_error_and_display_stack_trace() {
// Given
String query = "@consistency=THREE\n" +
"SELECT * FROM zeppelin.users LIMIT 3;";
// When
final InterpreterResult actual = interpreter.interpret(query, intrContext);
// Then
assertEquals(Code.ERROR, actual.code());
assert... |
public static NettySourceConfig load(Map<String, Object> map) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(mapper.writeValueAsString(map), NettySourceConfig.class);
} | @Test
public void testNettyTcpConfigLoadWithMap() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("type", TCP);
map.put("host", LOCALHOST);
map.put("port", 10999);
map.put("numberOfThreads", 1);
NettySourceConfig nettySourceConfig = NettySourc... |
public static long readUint32BE(ByteBuffer buf) throws BufferUnderflowException {
return Integer.toUnsignedLong(buf.order(ByteOrder.BIG_ENDIAN).getInt());
} | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32BEThrowsException3() {
ByteUtils.readUint32BE(new byte[]{1, 2, 3, 4, 5}, -1);
} |
@Override
// add synchronized to avoid process 2 or more stmts at same time
public synchronized ShowResultSet process(List<AlterClause> alterClauses, Database dummyDb,
OlapTable dummyTbl) throws UserException {
Preconditions.checkArgument(alterClauses.size()... | @Test
public void testDecommissionBackendsReplicasRequirement() throws UserException {
List<String> hostAndPorts = Lists.newArrayList("host1:123");
DecommissionBackendClause decommissionBackendClause = new DecommissionBackendClause(hostAndPorts);
Analyzer.analyze(new AlterSystemStmt(decommis... |
@Override
@Nullable
public int[] readIntArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, INT_ARRAY, super::readIntArray);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadIntArray_IncompatibleClass() throws Exception {
reader.readIntArray("byte");
} |
@Override
public RefreshSuperUserGroupsConfigurationResponse refreshSuperUserGroupsConfiguration(
RefreshSuperUserGroupsConfigurationRequest request)
throws StandbyException, YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRefreshSuperUserGro... | @Test
public void testSC1RefreshSuperUserGroupsConfiguration() throws Exception {
// case 1, test the existing subCluster (SC-1).
String existSubCluster = "SC-1";
RefreshSuperUserGroupsConfigurationRequest request =
RefreshSuperUserGroupsConfigurationRequest.newInstance(existSubCluster);
Refr... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testPuma8nhLAD() {
test(Loss.lad(), "puma8nh", Puma8NH.formula, Puma8NH.data, 3.2486);
} |
@Override
public synchronized List<PrivilegedOperation> postComplete(
ContainerId containerId) throws ResourceHandlerException {
gpuAllocator.unassignGpus(containerId);
cGroupsHandler.deleteCGroup(CGroupsHandler.CGroupController.DEVICES,
containerId.toString());
return null;
} | @Test
public void testAllocation() throws Exception {
initializeGpus();
//Start container 1, asks 3 containers --> Only device=4 will be blocked.
startContainerWithGpuRequests(1, 3);
verifyDeniedDevices(getContainerId(1),
Collections.singletonList(new GpuDevice(3, 4)));
/* Start containe... |
public static DenseSparseMatrix createDiagonal(SGDVector diagonal) {
int dimension = diagonal.size();
SparseVector[] newValues = new SparseVector[dimension];
for (int i = 0; i < dimension; i++) {
newValues[i] = new SparseVector(dimension, new int[]{i}, new double[]{diagonal.get(i)});... | @Test
public void testCreateDiagonal() {
DenseSparseMatrix diagonal = DenseSparseMatrix.createDiagonal(new DenseVector(new double[] {1.0, 2.0}));
assertMatrixEquals(new DenseMatrix(new double[][]{new double[]{1.0, 0.0}, new double[]{0.0, 2.0}}),diagonal);
diagonal = DenseSparseMatrix.createD... |
@CanIgnoreReturnValue
public GsonBuilder disableJdkUnsafe() {
this.useJdkUnsafe = false;
return this;
} | @Test
public void testDisableJdkUnsafe() {
Gson gson = new GsonBuilder().disableJdkUnsafe().create();
var e =
assertThrows(
JsonIOException.class, () -> gson.fromJson("{}", ClassWithoutNoArgsConstructor.class));
assertThat(e)
.hasMessageThat()
.isEqualTo(
"U... |
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) {
Objects.requireNonNull(pred, "pred cannot be null");
Objects.requireNonNull(columns, "columns cannot be null");
return pred.accept(new StatisticsFilter(columns));
} | @Test
public void testOr() {
FilterPredicate yes = eq(intColumn, 9);
FilterPredicate no = eq(doubleColumn, 50D);
assertTrue(canDrop(or(yes, yes), columnMetas));
assertFalse(canDrop(or(yes, no), columnMetas));
assertFalse(canDrop(or(no, yes), columnMetas));
assertFalse(canDrop(or(no, no), colum... |
@Override
public InternalLogger newInstance(String name) {
return new Log4J2Logger(LogManager.getLogger(name));
} | @Test
public void testCreation() {
InternalLogger logger = Log4J2LoggerFactory.INSTANCE.newInstance("foo");
assertTrue(logger instanceof Log4J2Logger);
assertEquals("foo", logger.name());
} |
public static String executeDockerCommand(DockerCommand dockerCommand,
String containerId, Map<String, String> env,
PrivilegedOperationExecutor privilegedOperationExecutor,
boolean disableFailureLogging, Context nmContext)
throws ContainerExecutionException {
PrivilegedOperation dockerOp = d... | @Test
public void testExecuteDockerKillSIGQUIT() throws Exception {
DockerKillCommand dockerKillCommand =
new DockerKillCommand(MOCK_CONTAINER_ID)
.setSignal(ContainerExecutor.Signal.QUIT.name());
DockerCommandExecutor.executeDockerCommand(dockerKillCommand,
MOCK_CONTAINER_ID, env,... |
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
LOGGER.log(Level.FINE, e.toString(), e);
}
} | @Test
public void closeQuietlyTest() {
IOUtils.closeQuietly(null);
DummyCloseable dummyCloseable = new DummyCloseable();
IOUtils.closeQuietly(dummyCloseable);
Assert.assertTrue(dummyCloseable.closed);
IOUtils.closeQuietly(dummyCloseable);
} |
public static void validate(TableConfig tableConfig, @Nullable Schema schema) {
validate(tableConfig, schema, null);
} | @Test
public void validateDimensionTableConfig() {
// dimension table with REALTIME type (should be OFFLINE)
Schema schema = new Schema.SchemaBuilder().setSchemaName(TABLE_NAME)
.addSingleValueDimension(TIME_COLUMN, FieldSpec.DataType.STRING).build();
TableConfig tableConfig = new TableConfigBuild... |
public Canvas canvas() {
Canvas canvas = new Canvas(getLowerBound(), getUpperBound());
canvas.add(this);
if (name != null) {
canvas.setTitle(name);
}
return canvas;
} | @Test
public void testHeart() throws Exception {
System.out.println("Heart");
double[][] heart = new double[200][2];
for (int i = 0; i < 200; i++) {
double t = PI * (i - 100) / 100;
heart[i][0] = 16 * pow(sin(t), 3);
heart[i][1] = 13 * cos(t) - 5 * cos(2*... |
public synchronized void synchronizeConnections( DatabaseMeta database ) {
synchronizeConnections( database, database.getName() );
} | @Test
public void synchronizeConnections() throws Exception {
final String databaseName = "SharedDB";
DatabaseMeta sharedDB0 = createDatabaseMeta( databaseName, true );
saveSharedObjects( SHARED_OBJECTS_FILE, sharedDB0 );
JobMeta job1 = createJobMeta();
spoonDelegates.jobs.addJob( job1 );
J... |
static Boolean surrogateOperator(Boolean aBoolean, Boolean aBoolean2) {
logger.trace("surrogateOperator {} {}", aBoolean, aBoolean2);
return aBoolean != null ? aBoolean : aBoolean2;
} | @Test
void surrogateOperator() {
Boolean aBoolean = null;
boolean aBoolean2 = true;
assertThat(KiePMMLCompoundPredicate.surrogateOperator(aBoolean, aBoolean2)).isTrue();
aBoolean2 = false;
assertThat(KiePMMLCompoundPredicate.surrogateOperator(aBoolean, aBoolean2)).isFalse();... |
@Override
public void define(Context context) {
NewController controller = context.createController("api/plugins");
controller.setDescription("Manage the plugins on the server, including installing, uninstalling, and upgrading.")
.setSince("5.2");
for (PluginsWsAction action : actions) {
acti... | @Test
public void defines_controller_and_binds_PluginsWsActions() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/plugins");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.