focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T extends SearchablePlugin> List<T> search(Collection<T> searchablePlugins, String query)
{
return searchablePlugins.stream()
.filter(plugin -> Text.matchesSearchTerms(SPLITTER.split(query.toLowerCase()), plugin.getKeywords()))
.sorted(comparator(query))
.collect(Collectors.toList());
} | @Test
public void searchReturnsMatchingPlugins()
{
List<SearchablePlugin> results = PluginSearch.search(plugins.values(), "sTATus");
assertThat(results, hasSize(2));
assertThat(results, containsInAnyOrder(plugins.get("Discord"), plugins.get("Status Bars")));
} |
public static JobDataNodeEntry unmarshal(final String text) {
List<String> segments = Splitter.on(":").splitToList(text);
String logicTableName = segments.get(0);
List<DataNode> dataNodes = new LinkedList<>();
for (String each : Splitter.on(",").omitEmptyStrings().splitToList(segments.ge... | @Test
void assertUnmarshalWithSchema() {
JobDataNodeEntry actual = JobDataNodeEntry.unmarshal("t_order:ds_0.public.t_order_0,ds_1.test.t_order_1");
assertThat(actual.getLogicTableName(), is("t_order"));
assertNotNull(actual.getDataNodes());
assertThat(actual.getDataNodes().size(), is... |
public static <S> S load(Class<S> service, ClassLoader loader) throws EnhancedServiceNotFoundException {
return InnerEnhancedServiceLoader.getServiceLoader(service).load(loader, true);
} | @Test
public void testLoadByClassAndActivateName() {
Hello englishHello = EnhancedServiceLoader.load(Hello.class, "EnglishHello");
assertThat(englishHello.say()).isEqualTo("hello!");
} |
@Override
public VectorCollectionConfig setName(String name) {
validateName(name);
this.name = name;
return this;
} | @Test
public void setNameValidation_failed() {
assertThatThrownBy(() -> new VectorCollectionConfig().setName("asd*^"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The name of the vector collection should "
+ "only consist of letters, num... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testNotNullInJoinClause()
{
analyze("SELECT * FROM (VALUES (1)) a (x) JOIN (VALUES (2)) b ON a.x IS NOT NULL");
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatSimpleCaseExpressionWithDefaultValue() {
final SimpleCaseExpression expression = new SimpleCaseExpression(
new StringLiteral("operand"),
Collections.singletonList(
new WhenClause(new StringLiteral("foo"),
new LongLiteral(1))),
Optio... |
public static Schema schemaFromJavaBeanClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedCollection() {
Schema schema =
JavaBeanUtils.schemaFromJavaBeanClass(
new TypeDescriptor<NestedCollectionBean>() {}, GetterTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_COLLECTION_BEAN_SCHEMA, schema);
} |
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !DatasourceConfiguration.isEmbeddedStorage();
} | @Test
void testMatches() {
MockedStatic<DatasourceConfiguration> mockedStatic = Mockito.mockStatic(DatasourceConfiguration.class);
mockedStatic.when(DatasourceConfiguration::isEmbeddedStorage).thenReturn(true);
assertFalse(conditionOnExternalStorage.matches(context, metadata));
... |
public BufferPool get() {
WeakReference<BufferPool> ref = threadLocal.get();
if (ref == null) {
BufferPool pool = bufferPoolFactory.create(serializationService);
ref = new WeakReference<>(pool);
strongReferences.put(Thread.currentThread(), pool);
threadLoc... | @Test
public void get_whenDifferentThreadLocals_thenDifferentInstances() {
BufferPoolThreadLocal bufferPoolThreadLocal2 = new BufferPoolThreadLocal(
serializationService, new BufferPoolFactoryImpl(), null);
BufferPool pool1 = bufferPoolThreadLocal.get();
BufferPool pool2 = b... |
public static String getNamenodeNameServiceId(Configuration conf) {
return getNameServiceId(conf, DFS_NAMENODE_RPC_ADDRESS_KEY);
} | @Test
public void getNameNodeNameServiceId() {
Configuration conf = setupAddress(DFS_NAMENODE_RPC_ADDRESS_KEY);
assertEquals("nn1", DFSUtil.getNamenodeNameServiceId(conf));
} |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testConsistentWithEqualsBytesField() throws Exception {
Schema schema = Schema.of(Schema.Field.of("f1", FieldType.BYTES));
Row row1 = Row.withSchema(schema).addValue(new byte[] {1, 2, 3, 4}).build();
Row row2 = Row.withSchema(schema).addValue(new byte[] {1, 2, 3, 4}).build();
RowCode... |
private void watch() {
try {
AclFileWatchService aclFileWatchService = new AclFileWatchService(defaultAclDir, defaultAclFile, new AclFileWatchService.Listener() {
@Override
public void onFileChanged(String aclFileName) {
load(aclFileName);
... | @Test
public void testWatch() throws IOException, IllegalAccessException, InterruptedException {
String fileName = Joiner.on(File.separator).join(new String[]{System.getProperty("rocketmq.home.dir"), "conf", "acl", "plain_acl_test.yml"});
File transport = new File(fileName);
transport.delet... |
public static Builder newBuilder(double cpuCores, int taskHeapMemoryMB) {
return new Builder(new CPUResource(cpuCores), MemorySize.ofMebiBytes(taskHeapMemoryMB));
} | @Test
void testSerializable() throws Exception {
ResourceSpec rs1 =
ResourceSpec.newBuilder(1.0, 100)
.setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 1.1))
.build();
ResourceSpec rs2 = CommonTestUtils.createCopySerial... |
public TopicPartition registeredChangelogPartitionFor(final String storeName) {
final StateStoreMetadata storeMetadata = stores.get(storeName);
if (storeMetadata == null) {
throw new IllegalStateException("State store " + storeName
+ " for which the registered changelog parti... | @Test
public void shouldThrowIfStateStoreIsNotRegistered() {
final ProcessorStateManager stateMgr = getStateManager(Task.TaskType.ACTIVE);
assertThrows(IllegalStateException.class,
() -> stateMgr.registeredChangelogPartitionFor(persistentStoreName),
"State store " + persiste... |
public void addDescription(String path, String description)
throws IOException, InvalidTokenException {
Map<String, String[]> tags = new LinkedHashMap<>();
tags.put("description", new String[] {description});
Map<String, Object> body = new LinkedHashMap<>();
body.put("tags", tags);
String url... | @Test
public void testAddDescriptionError() {
server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error"));
Exception caughtExc =
assertThrows(
KoofrClientIOException.class,
() -> client.addDescription("/path/to/folder", "Test description"));
assertNo... |
public static String buildBasicAuthValue(String username, String password) {
String credentials = join(":", username, password);
return format("Basic %s", Util.encodeToBase64(credentials));
} | @Test
public void testBuildBasicAuthValue() {
String username = "testUser";
String password = "testPassword";
String expectedHeaderValue = "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk";
String actualHeaderValue = CruiseControlUtil.buildBasicAuthValue(username, password);
assertEquals(... |
@Udf(description = "Returns the natural logarithm (base e) of an INT value.")
public Double ln(
@UdfParameter(
value = "value",
description = "the value get the natual logarithm of."
) final Integer value
) {
return ln(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleNegative() {
assertThat(Double.isNaN(udf.ln(-1.0)), is(true));
} |
public boolean shouldOverwriteHeaderWithName(String headerName) {
notNull(headerName, "Header name");
return headersToOverwrite.get(headerName.toUpperCase());
} | @Test public void
content_type_header_is_overwritable_by_default() {
HeaderConfig headerConfig = new HeaderConfig();
assertThat(headerConfig.shouldOverwriteHeaderWithName("content-type"), is(true));
} |
Database getDatabase(@NotNull String dbName) throws TException {
return client.get_database(dbName);
} | @Test
public void getDatabase() throws TException {
Database db = client.getDatabase(TEST_DATABASE);
MatcherAssert.assertThat(db.getName(), Matchers.equalToIgnoringCase(TEST_DATABASE));
MatcherAssert.assertThat(db.getDescription(), Matchers.equalTo(TEST_DATABASE_DESCRIPTION));
MatcherAssert.assertThat... |
public void publishArtifacts(List<ArtifactPlan> artifactPlans, EnvironmentVariableContext environmentVariableContext) {
final File pluggableArtifactFolder = publishPluggableArtifacts(artifactPlans, environmentVariableContext);
try {
final List<ArtifactPlan> mergedPlans = artifactPlanFilter.g... | @Test
public void shouldContinueWithOtherPluginWhenPublishArtifactCallFailsForOnePlugin() {
final ArtifactStore s3ArtifactStore = new ArtifactStore("s3", "cd.go.s3", create("access_key", false, "some-key"));
final ArtifactStore dockerArtifactStore = new ArtifactStore("docker", "cd.go.docker", create... |
static Slice shiftLeft(Slice decimal, int leftShifts)
{
Slice result = Slices.copyOf(decimal);
shiftLeftDestructive(result, leftShifts);
return result;
} | @Test
public void testShiftLeft()
{
assertEquals(shiftLeft(wrappedLongArray(0x1234567890ABCDEFL, 0xEFDCBA0987654321L), 0), wrappedLongArray(0x1234567890ABCDEFL, 0xEFDCBA0987654321L));
assertEquals(shiftLeft(wrappedLongArray(0x1234567890ABCDEFL, 0xEFDCBA0987654321L), 1), wrappedLongArray(0x2468AC... |
@VisibleForTesting
public SmsChannelDO validateSmsChannel(Long channelId) {
SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId);
if (channelDO == null) {
throw exception(SMS_CHANNEL_NOT_EXISTS);
}
if (CommonStatusEnum.isDisable(channelDO.getStatus())) {
... | @Test
public void testValidateSmsChannel_disable() {
// 准备参数
Long channelId = randomLongId();
// mock 方法
SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> {
o.setId(channelId);
o.setStatus(CommonStatusEnum.DISABLE.getStatus()); // 保证 status 禁用,触发失败
... |
public static boolean isNotEmpty(@Nullable String string) {
return string != null && !string.isEmpty();
} | @Test
public void testNull() {
assertThat(StringUtils.isNotEmpty(null)).isFalse();
} |
@Override
public void warn(String msg) {
logger.warn(msg);
} | @Test
public void testWarn() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.getName()).thenReturn("foo");
InternalLogger logger = new Slf4JLogger(mockLogger);
logger.warn("a");
verify(mockLogger).getName();
verify(mockLogger).warn("a");
} |
public void complete(T value) {
try {
if (value instanceof RuntimeException)
throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException");
if (!result.compareAndSet(INCOMPLETE_SENTINEL, value))
throw new Illega... | @Test
public void invokeExceptionAfterSuccess() {
RequestFuture<Void> future = new RequestFuture<>();
future.complete(null);
assertThrows(IllegalStateException.class, future::exception);
} |
public static void tar(@NotNull File source, @NotNull File dest) throws IOException {
if (!source.exists()) {
throw new IllegalArgumentException("No source file or folder exists: " + source.getAbsolutePath());
}
if (dest.exists()) {
throw new IllegalArgumentException("Des... | @Test
public void testNoSource() throws Exception {
try {
CompressBackupUtil.tar(new File(randName + ".txt"), dest);
} catch (IllegalArgumentException e) {
return;
}
Assert.fail("No source file/folder exists. Should have thrown an exception.");
} |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldNotLoadAPluginWhenTargetedGocdVersionIsIncorrect() throws Exception {
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
copyPluginToTheDirectory(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
final GoPluginDescriptor pluginDescriptor1 = getPluginDescriptor("some.o... |
@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 testDisableForwardIndexForRawAndInvertedIndexDisabledColumns()
throws Exception {
Set<String> forwardIndexDisabledColumns = new HashSet<>(SV_FORWARD_INDEX_DISABLED_COLUMNS);
forwardIndexDisabledColumns.addAll(MV_FORWARD_INDEX_DISABLED_COLUMNS);
forwardIndexDisabledColumns.addAll(MV... |
public CompletableFuture<Boolean> isAllowAutoTopicCreationAsync(final String topic) {
TopicName topicName = TopicName.get(topic);
return isAllowAutoTopicCreationAsync(topicName);
} | @Test
public void testIsSystemTopicAllowAutoTopicCreationAsync() throws Exception {
BrokerService brokerService = pulsar.getBrokerService();
assertFalse(brokerService.isAllowAutoTopicCreationAsync(
ServiceUnitStateChannelImpl.TOPIC).get());
assertTrue(brokerService.isAllowAut... |
@Override
public PageResult<SmsTemplateDO> getSmsTemplatePage(SmsTemplatePageReqVO pageReqVO) {
return smsTemplateMapper.selectPage(pageReqVO);
} | @Test
public void testGetSmsTemplatePage() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomPojo(SmsTemplateDO.class, o -> { // 等会查询到
o.setType(SmsTemplateTypeEnum.PROMOTION.getType());
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setCode("tudou");
... |
public static ByteBuffer allocateAndConfigureBuffer(int bufferSize) {
ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
buffer.order(ByteOrder.nativeOrder());
return buffer;
} | @Test
void testAllocateAndConfigureBuffer() {
final int bufferSize = 16;
ByteBuffer buffer = FileRegionWriteReadUtils.allocateAndConfigureBuffer(bufferSize);
assertThat(buffer.capacity()).isEqualTo(16);
assertThat(buffer.limit()).isEqualTo(16);
assertThat(buffer.position()).i... |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
public static YamlSequence asSequence(YamlNode node) {
if (node != null && !(node instanceof YamlSequence)) {
String nodeName = node.nodeName();
throw new YamlException(String.format("Child %s is not a sequence, it's actual type is %s",
nodeName, node.getClass()));
... | @Test(expected = YamlException.class)
public void asSequenceThrowsIfNonSequencePassed() {
YamlNode genericNode = new YamlMappingImpl(null, "mapping");
YamlUtil.asSequence(genericNode);
} |
@Override
public OptionalLong apply(OptionalLong previousSendTimeNs) {
long delayNs;
if (previousGlobalFailures > 0) {
// If there were global failures (like a response timeout), we want to wait for the
// full backoff period.
delayNs = backoff.backoff(previousGlo... | @Test
public void applyBackoffInterval() {
assertEquals(OptionalLong.of(BACKOFF.initialInterval() * 2),
new AssignmentsManagerDeadlineFunction(BACKOFF, 0, 1, false, 12).
apply(OptionalLong.empty()));
} |
public boolean setLocations(DefaultIssue issue, @Nullable Object locations) {
if (!locationsEqualsIgnoreHashes(locations, issue.getLocations())) {
issue.setLocations(locations);
issue.setChanged(true);
issue.setLocationsChanged(true);
return true;
}
return false;
} | @Test
void do_not_change_locations_if_secondary_hash_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().se... |
public synchronized Topology addSource(final String name,
final String... topics) {
internalTopologyBuilder.addSource(null, name, null, null, null, topics);
return this;
} | @Test
public void testPatternMatchesAlreadyProvidedTopicSource() {
topology.addSource("source-1", "foo");
try {
topology.addSource("source-2", Pattern.compile("f.*"));
fail("Should have thrown TopologyException for overlapping pattern with already registered topic");
... |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfByteArrayNegativePrefixLengthIPv4() {
Ip4Prefix ipPrefix;
byte[] value;
value = new byte[] {1, 2, 3, 4};
ipPrefix = Ip4Prefix.valueOf(value, -1);
} |
static RequestConfigElement parse(String property, String key, Object value) throws RequestConfigKeyParsingException {
RequestConfigKeyParsingErrorListener errorListener = new RequestConfigKeyParsingErrorListener();
ANTLRInputStream input = new ANTLRInputStream(key);
RequestConfigKeyLexer lexer = new Reques... | @Test(expectedExceptions = {RequestConfigKeyParsingException.class})
public void testParsingInvalidKey() throws RequestConfigKeyParsingException {
RequestConfigElement.parse("timeoutMs", "greetings.POST/greetings.DELETE/timeoutMs", 100L);
} |
@Override
public List<ParsedStatement> parse(final String sql) {
return primaryContext.parse(sql);
} | @Test
public void shouldBeAbleToPrepareTerminateAndDrop() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
givenSqlAlreadyExecuted("CREATE STREAM FOO AS SELECT * FROM TEST1;");
final List<ParsedStatement> parsed = ksqlEngine.parse(
"TERMINATE CSAS_FOO_0;"
+ "DROP STREAM FOO;... |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
@Nullable
public static Field findPropertyField(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
return null;
}
if (!Modifier.isPublic(field.getModifiers()) || Modifier.isStat... | @Test
public void when_findPropertyField_public_then_returnsIt() {
assertNotNull(findPropertyField(JavaFields.class, "publicField"));
} |
public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) {
final String configuredPoolingType = MetastoreConf.getVar(hdpConfig,
MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE);
return Iterables.tryFind(FACTORIES, factory -> {
String poolingType = factory.getPoolingT... | @Test
public void testSetHikariCpNumberProperty() throws SQLException {
MetastoreConf.setVar(conf, ConfVars.CONNECTION_POOLING_TYPE, HikariCPDataSourceProvider.HIKARI);
conf.set(HikariCPDataSourceProvider.HIKARI + ".idleTimeout", "59999");
conf.set(HikariCPDataSourceProvider.HIKARI + ".initializationFail... |
public static File getSourceJarFile(URL classesJarFileUrl) throws IOException {
final String file = classesJarFileUrl.getFile();
if (file.endsWith(".jar")) {
final File sources = new File(file.replace(".jar", "-sources.jar"));
if (sources.exists()) {
return sources;
}
}
final byte[] pomProperties =... | @Test
public void testGetSourceJarFile() throws ClassNotFoundException, IOException {
final File storageDirectory = Parameters
.getStorageDirectory(Parameters.getCurrentApplication());
rmdir(new File(storageDirectory, "poms"));
rmdir(new File(storageDirectory, "sources"));
final Class<?> clazz = Class.for... |
public Float asFloat(Map<String, ValueReference> parameters) {
switch (valueType()) {
case FLOAT:
if (value() instanceof Number) {
return ((Number) value()).floatValue();
}
throw new IllegalStateException("Expected value reference o... | @Test
public void asFloat() {
assertThat(ValueReference.of(1.0f).asFloat(Collections.emptyMap())).isEqualTo(1.0f);
assertThatThrownBy(() -> ValueReference.of("Test").asFloat(Collections.emptyMap()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Expected valu... |
public ProviderBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
} | @Test
void Wait() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.wait(Integer.valueOf(1000));
Assertions.assertEquals(1000, builder.build().getWait());
} |
static GeneratedClassResource getGeneratedClassResource(String fullClassName) {
return new GeneratedClassResource(fullClassName);
} | @Test
void getGeneratedIntermediateResource() {
String className = "className";
GeneratedClassResource retrieved = CompilationManagerUtils.getGeneratedClassResource(className);
assertThat(retrieved).isNotNull();
assertThat(retrieved.getFullClassName()).isEqualTo(className);
} |
public static <ID, T> TaskDispatcher<ID, T> createNonBatchingTaskDispatcher(String id,
int maxBufferSize,
int workerCount,
... | @Test
public void testSingleTaskDispatcher() throws Exception {
dispatcher = TaskDispatchers.createNonBatchingTaskDispatcher(
"TEST",
MAX_BUFFER_SIZE,
1,
MAX_BATCHING_DELAY_MS,
SERVER_UNAVAILABLE_SLEEP_TIME_MS,
R... |
@Override
public Map<String, String> convertToEntityAttribute(String dbData) {
return GSON.fromJson(dbData, TYPE);
} | @Test
void convertToEntityAttribute_null() {
assertNull(this.converter.convertToEntityAttribute(null));
assertNull(this.converter.convertToEntityAttribute("null"));
} |
public int distanceOf(PartitionTableView partitionTableView) {
int distance = 0;
for (int i = 0; i < partitions.length; i++) {
distance += distanceOf(partitions[i], partitionTableView.partitions[i]);
}
return distance;
} | @Test
public void testDistanceIsZero_whenSame() throws Exception {
// distanceOf([A, B, C], [A, B, C]) == 0
PartitionTableView table1 = createRandomPartitionTable();
InternalPartition[] partitions = extractPartitions(table1);
PartitionTableView table2 = new PartitionTableView(partit... |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldNotAllowMoreThanOneOnCancelTaskWhenDefined() {
String xml = ("""
<cruise schemaVersion='%d'>
<server>
<artifacts>
<artifactsDir>artifactsDir</artifactsDir>
</artifacts>
</server>
... |
public static String getSourceIpForGrpcRequest(RequestMeta meta) {
String sourceIp = getSourceIp();
// If can't get from request context, get from grpc request meta.
if (StringUtils.isBlank(sourceIp)) {
sourceIp = meta.getClientIp();
}
return sourceIp;
} | @Test
void getSourceIpForGrpcRequest() {
when(meta.getClientIp()).thenReturn("3.3.3.3");
assertEquals("2.2.2.2", NamingRequestUtil.getSourceIpForGrpcRequest(meta));
RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp(null);
assertEquals("1.1.1.1", Nami... |
public static long readVLong(ByteData arr, long position) {
byte b = arr.get(position++);
if(b == (byte) 0x80)
throw new RuntimeException("Attempting to read null value as long");
long value = b & 0x7F;
while ((b & 0x80) != 0) {
b = arr.get(position++);
... | @Test(expected = EOFException.class)
public void testReadVLongEmptyInputStream() throws IOException {
InputStream is = new ByteArrayInputStream(BYTES_EMPTY);
VarInt.readVLong(is);
} |
@Override
public NSImage folderIcon(final Integer size) {
NSImage folder = this.iconNamed("NSFolder", size);
if(null == folder) {
return this.iconNamed("NSFolder", size);
}
return folder;
} | @Test
public void testFolderIcon512() {
final NSImage icon = new NSImageIconCache().folderIcon(512);
assertNotNull(icon);
assertTrue(icon.isValid());
assertFalse(icon.isTemplate());
assertEquals(512, icon.size().width.intValue());
assertEquals(512, icon.size().height.... |
@Override
public List<OAuth2ApproveDO> getApproveList(Long userId, Integer userType, String clientId) {
List<OAuth2ApproveDO> approveDOs = oauth2ApproveMapper.selectListByUserIdAndUserTypeAndClientId(
userId, userType, clientId);
approveDOs.removeIf(o -> DateUtils.isExpired(o.getExpi... | @Test
public void testGetApproveList() {
// 准备参数
Long userId = 10L;
Integer userType = UserTypeEnum.ADMIN.getValue();
String clientId = randomString();
// mock 数据
OAuth2ApproveDO approve = randomPojo(OAuth2ApproveDO.class).setUserId(userId)
.setUserTyp... |
public Properties apply(final Properties properties) {
if (properties == null) {
throw new IllegalArgumentException("properties must not be null");
} else {
if (properties.isEmpty()) {
return new Properties();
} else {
final Properties filtered = new Properties();
for (... | @Test
public void doesNotAcceptNullInput() {
// Given
Properties nullProperties = null;
Filter f = new Filter();
// When/Then
try {
f.apply(nullProperties);
fail("IllegalArgumentException expected because input is null");
} catch (IllegalArgumentException e) {
// ignore
... |
public static Properties getProperties(Set<ClassLoader> classLoaders) {
String path = System.getProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
if (StringUtils.isEmpty(path)) {
path = System.getenv(CommonConstants.DUBBO_PROPERTIES_KEY);
if (StringUtils.isEmpty(path)) {
... | @Test
void testGetProperties2() throws Exception {
System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY);
Properties p = ConfigUtils.getProperties(Collections.emptySet());
assertThat((String) p.get("dubbo"), equalTo("properties"));
} |
public boolean sendProvisioningMessage(final ProvisioningAddress address, final byte[] body) {
final PubSubProtos.PubSubMessage pubSubMessage = PubSubProtos.PubSubMessage.newBuilder()
.setType(PubSubProtos.PubSubMessage.Type.DELIVER)
.setContent(ByteString.copyFrom(body))
.build();
fina... | @Test
void sendProvisioningMessage() {
final ProvisioningAddress address = ProvisioningAddress.create("address");
final byte[] content = TestRandomUtil.nextBytes(16);
@SuppressWarnings("unchecked") final Consumer<PubSubProtos.PubSubMessage> subscribedConsumer = mock(Consumer.class);
provisioningMan... |
public static List<DynamicMessage> buildJsonMessageList(final Map<String, Object> jsonParamMap) {
ParamCheckUtils.checkParamsLength(jsonParamMap.size(), GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NUM);
JsonArray jsonParams = (JsonArray) jsonParamMap.get(GrpcConstants.JSON_DESCRIPTOR_PROTO_FIELD_NAME);
... | @Test
public void testBuildJsonMessageList() {
String jsonParam = "{\"data\":[{\"text\":\"hello\"}, {\"text\":\"world\"}]}\n";
List<DynamicMessage> jsonMessageList = JsonMessage.buildJsonMessageList(GsonUtils.getInstance().toObjectMap(jsonParam));
assertEquals(2, jsonMessageList.size());
... |
public static String humanReadableByteCountSI(long bytes) {
if (-1000 < bytes && bytes < 1000) {
if (bytes == 1) {
return bytes + " byte";
}
return bytes + " bytes";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
... | @Test
public void humanReadableByteCountSI_returns_tbs() {
assertThat(FileUtils.humanReadableByteCountSI(1_234_000_000_000L)).isEqualTo("1.2 TB");
} |
public static void main(String[] argv) {
//Use JCommander to parse the CLI args into a useful class
CommandLineArgs args = parseCommandLineArgs(argv);
execute(
args.dataFile,
configFromYaml(args.yamlConfig)
);
} | @Disabled
@Test
public void mainMethodProcessesOneFile() throws IOException {
// This test tasks about 10 minutes to run (it processes, 1.2M RH messages)
// Ideally it would be classified as a "large test" and be run less often (e.g. pre-PR but not in the main-development loop)
String[]... |
@Override
public int compareTo(AlluxioURI other) {
return mUri.compareTo(other.mUri);
} | @Test
public void compareToTests() {
AlluxioURI[] uris =
new AlluxioURI[] {new AlluxioURI("file://127.0.0.0:8081/a/b/c.txt"),
new AlluxioURI("glusterfs://127.0.0.0:8081/a/b/c.txt"),
new AlluxioURI("hdfs://127.0.0.0:8081/a/b/c.txt"),
new AlluxioURI("hdfs://127.0.0.1:8081... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("eue.listing.chunksize"));
} | @Test
public void testListRoot() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path root = new Path("/", EnumSet.of(directory));
final Path folder = new EueDirectoryFeature(session, fileid).mkdir(
new Path(root, new Alphanum... |
@Override
public void filterProducer(Exchange exchange, WebServiceMessage response) {
if (exchange != null) {
processHeaderAndAttachments(exchange.getIn(AttachmentMessage.class), response);
}
} | @Test
public void producerWithHeader() throws Exception {
// foo is already in the header.in from the parent ExchangeTestSupport
exchange.getIn().getHeaders().put("headerAttributeKey", "testAttributeValue");
exchange.getIn().getHeaders().put("headerAttributeElement", new QName("http://should... |
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) {
if (partitions == null || partitions.isEmpty()) {
return Collections.emptyMap();
}
Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> Off... | @Test
public void endOffsetsShouldReturnEmptyMapWhenPartitionsSetIsNull() {
String topicName = "myTopic";
Cluster cluster = createCluster(1, topicName, 1);
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(new MockTime(), cluster)) {
TopicAdmin admin = new TopicAdmin(e... |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
public void testAcceptEndpoint() {
assertTrue(WebSocketMessageConsumptionTask.acceptEndpoint("ws://localhost:4000/"));
assertTrue(WebSocketMessageConsumptionTask.acceptEndpoint("ws://localhost:4000/websocket"));
assertTrue(WebSocketMessageConsumptionTask
.acceptEndpoint("ws://mi... |
public void setOrganization(String organization) {
this.organization = organization;
} | @Test
public void testSetOrganization() {
String organization = "apache";
Model instance = new Model();
instance.setOrganization(organization);
assertEquals("apache", instance.getOrganization());
} |
@VisibleForTesting
public static Map<String, ColumnStats> convertToColumnStatsMap(
Map<String, CatalogColumnStatisticsDataBase> columnStatisticsData) {
Map<String, ColumnStats> columnStatsMap = new HashMap<>();
for (Map.Entry<String, CatalogColumnStatisticsDataBase> entry :
... | @Test
void testConvertToColumnStatsMapWithNullColumnStatisticsData() {
Map<String, CatalogColumnStatisticsDataBase> columnStatisticsDataBaseMap = new HashMap<>();
columnStatisticsDataBaseMap.put(
"first", new CatalogColumnStatisticsDataString(10L, 5.2, 3L, 100L));
columnStati... |
public static int calculateFor(final ConnectionSession connectionSession) {
int result = 0;
result |= connectionSession.isAutoCommit() ? MySQLStatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue() : 0;
result |= connectionSession.getTransactionStatus().isInTransaction() ? MySQLStatusFlag.SERVER_STATUS_I... | @Test
void assertAutoCommitNotInTransaction() {
when(connectionSession.isAutoCommit()).thenReturn(true);
assertThat(ServerStatusFlagCalculator.calculateFor(connectionSession), is(MySQLStatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue()));
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM)
{
return;
}
if (event.getMessage().startsWith("You retrieve a bar of"))
{
if (session == null)
{
session = new SmeltingSession();
}
session.increaseBarsSmelted();
}
else if (event.g... | @Test
public void testCannonballsAmmoMould()
{
ChatMessage chatMessageAmmoMould = new ChatMessage(null, ChatMessageType.SPAM, "", SMELT_CANNONBALL_AMMO_MOULD, "", 0);
smeltingPlugin.onChatMessage(chatMessageAmmoMould);
ChatMessage chatMessageDone = new ChatMessage(null, ChatMessageType.SPAM, "", SMELT_CANNONBAL... |
void doImportCheckpoint(FSNamesystem target) throws IOException {
Collection<URI> checkpointDirs =
FSImage.getCheckpointDirs(conf, null);
List<URI> checkpointEditsDirs =
FSImage.getCheckpointEditsDirs(conf, null);
if (checkpointDirs == null || checkpointDirs.isEmpty()) {
throw new IOExcep... | @Test
public void testImportCheckpoint() throws Exception{
Configuration conf = new Configuration();
conf.set(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_EDITS_DIR_KEY, "");
try(MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build()){
cluster.waitActive();
FSNamesystem fsn = cluster.getNa... |
Object[] findValues(int ordinal) {
return getAllValues(ordinal, type, 0);
} | @Test
public void testListObjectReference() throws Exception {
ListObjectReference listType = new ListObjectReference();
SimpleValue val1 = new SimpleValue();
val1.id = 1;
SimpleValue val2 = new SimpleValue();
val2.id = 2;
listType.intValues = Arrays.asList(val1, val... |
@Override
public ObjectNode encode(Instruction instruction, CodecContext context) {
checkNotNull(instruction, "Instruction cannot be null");
return new EncodeInstructionCodecHelper(instruction, context).encode();
} | @Test
public void modIPDstInstructionTest() {
final Ip4Address ip = Ip4Address.valueOf("1.2.3.4");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3Dst(ip);
final ObjectNode i... |
@Override
public boolean isInputConsumable(
SchedulingExecutionVertex executionVertex,
Set<ExecutionVertexID> verticesToDeploy,
Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) {
for (ConsumedPartitionGroup consumedPartitionGroup :
executionVert... | @Test
void testNotFinishedHybridInput() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
final List<TestingSchedulingExecutionVertex> producers =
topology.addExecutionVertices().withParallelism(2).finish();
final List<TestingSchedulingExecutionV... |
@Override
public PageResult<MailLogDO> getMailLogPage(MailLogPageReqVO pageVO) {
return mailLogMapper.selectPage(pageVO);
} | @Test
public void testGetMailLogPage() {
// mock 数据
MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> { // 等会查询到
o.setUserId(1L);
o.setUserType(UserTypeEnum.ADMIN.getValue());
o.setToMail("768@qq.com");
o.setAccountId(10L);
o.setTemplateId(10... |
public static org.slf4j.Logger getLogger(String name, String appname) {
//从"com/alipay/sofa/rpc/log"中获取 rpc 的日志配置并寻找对应logger对象,log 为默认添加的后缀
if (name == null || name.isEmpty()) {
return null;
}
Map<String, String> properties = new HashMap<String, String>();
properties... | @Test
public void getLogger() throws Exception {
Assert.assertNull(RpcLoggerFactory.getLogger(null, "appname1"));
Logger logger1 = RpcLoggerFactory.getLogger("xxx", "appname1");
Assert.assertNotNull(logger1);
Logger logger2 = RpcLoggerFactory.getLogger("xxx", "appname1");
As... |
public void onGlobalPropertyChange(String key, @Nullable String value) {
GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create(key, value);
for (GlobalPropertyChangeHandler changeHandler : changeHandlers) {
changeHandler.onChange(change);
}
} | @Test
public void no_handlers() {
SettingsChangeNotifier notifier = new SettingsChangeNotifier();
assertThat(notifier.changeHandlers).isEmpty();
// does not fail
notifier.onGlobalPropertyChange("foo", "bar");
} |
public static <T> AggregateOperation1<T, ArrayList<T>, List<T>> sorting(
@Nonnull ComparatorEx<? super T> comparator
) {
checkSerializable(comparator, "comparator");
return AggregateOperation
.withCreate(ArrayList<T>::new)
.<T>andAccumulate(ArrayList::add)... | @Test
public void when_sorting() {
validateOpWithoutDeduct(
sorting(naturalOrder()),
identity(),
2,
1,
singletonList(2),
asList(2, 1),
asList(1, 2)
);
} |
@Override
public void uncaughtException(@NonNull Thread thread, Throwable ex) {
ex.printStackTrace();
Logger.e(TAG, "Caught an unhandled exception!!!", ex);
// https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
// https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/433
final Strin... | @Test
public void testCallsPreviousHandler() {
final AtomicReference<Pair<Thread, Throwable>> receiver = new AtomicReference<>();
final Thread.UncaughtExceptionHandler handler = (t, e) -> receiver.set(Pair.create(t, e));
TestableChewbaccaUncaughtExceptionHandler underTest =
new TestableChewbaccaU... |
public static Result find(List<Path> files, Consumer<LogEvent> logger) {
List<String> mainClasses = new ArrayList<>();
for (Path file : files) {
// Makes sure classFile is valid.
if (!Files.exists(file)) {
logger.accept(LogEvent.debug("MainClassFinder: " + file + " does not exist; ignoring")... | @Test
public void testFindMainClass_importedMethods() throws URISyntaxException, IOException {
Path rootDirectory =
Paths.get(Resources.getResource("core/class-finder-tests/imported-methods").toURI());
MainClassFinder.Result mainClassFinderResult =
MainClassFinder.find(new DirectoryWalker(root... |
@InvokeOnHeader(Web3jConstants.ETH_NEW_FILTER)
void ethNewFilter(Message message) throws IOException {
DefaultBlockParameter fromBlock = toDefaultBlockParameter(
message.getHeader(Web3jConstants.FROM_BLOCK, configuration::getFromBlock, String.class));
DefaultBlockParameter toBlock
... | @Test
public void ethNewFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.O... |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData,
MusicContainerResource data)
throws Exception {
if (data == null) {
// Nothing to do
re... | @Test
public void testImportPlaylistTracksFailure() throws Exception {
MusicPlaylistItem item1 = createTestPlaylistItem(randomString(), 1);
List<MusicPlaylistItem> musicPlaylistItems = List.of(item1);
setUpImportPlaylistTracksBatchResponse(musicPlaylistItems.stream().collect(
... |
@Override
public Boolean exists(final String key) {
try {
KV kvClient = etcdClient.getKVClient();
GetOption option = GetOption.newBuilder().isPrefix(true).withCountOnly(true).build();
GetResponse response = kvClient.get(bytesOf(key), option).get();
return resp... | @Test
void testExists() throws ExecutionException, InterruptedException {
final String key = "key";
final KV kvClient = mock(KV.class);
when(etcdClient.getKVClient()).thenReturn(kvClient);
final GetResponse getResponse = mock(GetResponse.class);
when(getResponse.getCount()).... |
public static void closeQuietly(Closeable closeable) {
try {
if (null == closeable) {
return;
}
closeable.close();
} catch (Exception e) {
log.error("Close closeable error", e);
}
} | @Test
public void testCloseQuietly() throws FileNotFoundException {
InputStream ins = IOKitTest.class.getResourceAsStream("/application.properties");
IOKit.closeQuietly(ins);
IOKit.closeQuietly(null);
} |
public void reset() {
removeShutdownHook();
getLifeCycleManager().reset();
propertyMap.clear();
objectMap.clear();
} | @Test
public void resetTest() {
context.setName("hello");
context.putProperty("keyA", "valA");
context.putObject("keyA", "valA");
Assertions.assertEquals("valA", context.getProperty("keyA"));
Assertions.assertEquals("valA", context.getObject("keyA"));
MockLifeCycleCom... |
@ApiOperation(value = "Delete the Dashboard (deleteDashboard)",
notes = "Delete the Dashboard." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/dashboard/{dashboardId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
... | @Test
public void testDeleteDashboard() throws Exception {
Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
Mockito.reset(tbClusterService, auditLogService);
doDelete(... |
@SqlNullable
@Description("Returns an array of geometries in the specified collection")
@ScalarFunction("ST_Geometries")
@SqlType("array(" + GEOMETRY_TYPE_NAME + ")")
public static Block stGeometries(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
Geometry geometry = deserialize(input);
... | @Test
public void testSTGeometries()
{
assertFunction("ST_Geometries(ST_GeometryFromText('POINT EMPTY'))", new ArrayType(GEOMETRY), null);
assertSTGeometries("POINT (1 5)", "POINT (1 5)");
assertSTGeometries("LINESTRING (77.29 29.07, 77.42 29.26, 77.27 29.31, 77.29 29.07)", "LINESTRING (... |
@Override
public String getSource() {
return source;
} | @Test
public void testGetSource() {
assertEquals("source", localCacheWideEventData.getSource());
} |
public static Version fromString(String versionString) {
checkArgument(!Strings.isNullOrEmpty(versionString));
Version version = builder().setVersionType(Type.NORMAL).setVersionString(versionString).build();
if (!EPOCH_PATTERN.matcher(versionString).matches()) {
versionString = "0:" + versionString;
... | @Test
public void create_whnNormalVersionAndValueIsEmpty_throwsExceptionIfStringIsNull() {
assertThrows(IllegalArgumentException.class, () -> Version.fromString(""));
} |
public static HCatFieldSchema getHCatFieldSchema(FieldSchema fs) throws HCatException {
String fieldName = fs.getName();
TypeInfo baseTypeInfo = TypeInfoUtils.getTypeInfoFromTypeString(fs.getType());
return getHCatFieldSchema(fieldName, baseTypeInfo, fs.getComment());
} | @Test
public void testHCatFieldSchemaConversion() throws Exception {
FieldSchema stringFieldSchema = new FieldSchema("name1", serdeConstants.STRING_TYPE_NAME, "comment1");
HCatFieldSchema stringHCatFieldSchema = HCatSchemaUtils.getHCatFieldSchema(stringFieldSchema);
assertEquals(stringHCatFieldSchema.getName... |
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) {
// First check whether rpc addresses are explicitly configured.
if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) {
return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES));
}
// Fall b... | @Test
public void getMasterRpcAddressesDefault() {
AlluxioConfiguration conf = createConf(Collections.emptyMap());
String host = NetworkAddressUtils.getLocalHostName(5 * Constants.SECOND_MS);
assertEquals(Arrays.asList(InetSocketAddress.createUnresolved(host, 19998)),
ConfigurationUtils.getMasterR... |
public boolean areWithin(Distance altitudeProximityReq, Distance lateralProximityReq) {
//test the altitudeDelta first to reduce the number of calls to lateralDistance()
return altitudeDelta().isLessThanOrEqualTo(altitudeProximityReq)
&& lateralDistance().isLessThanOrEqualTo(lateralProximity... | @Test
public void verifyLateralDistanceIsIgnoredIfAltitudeIsTooDifferent() {
Distance requiredAltitudeProximity = Distance.ofFeet(500);
//alt = 2400
Point p1 = NopHit.from("[RH],STARS,A80_B,02/12/2018,18:36:46.667,JIA5545,CRJ9,E,5116,024,157,270,033.63143,-084.33913,1334,5116,22.4031,27.668... |
final WorkAttempt performWork() {
try {
LOG.debug("[Agent Loop] Trying to retrieve work.");
agentUpgradeService.checkForUpgradeAndExtraProperties();
sslInfrastructureService.registerIfNecessary(getAgentAutoRegistrationProperties());
if (pluginJarLocationMonitor.h... | @Test
void shouldNotTryWorkIfPluginMonitorHasNotRun() {
when(pluginJarLocationMonitor.hasRunAtLeastOnce()).thenReturn(false);
assertThat(agentController.performWork()).isEqualTo(WorkAttempt.FAILED);
verify(pluginJarLocationMonitor).hasRunAtLeastOnce();
} |
@Override
public PageData<AlarmCommentInfo> findAlarmComments(TenantId tenantId, AlarmId id, PageLink pageLink) {
log.trace("Try to find alarm comments by alarm id using [{}]", id);
return DaoUtil.toPageData(
alarmCommentRepository.findAllByAlarmId(id.getId(), DaoUtil.toPageable(page... | @Test
public void testFindAlarmCommentsByAlarmId() {
log.info("Current system time in millis = {}", System.currentTimeMillis());
UUID tenantId = UUID.randomUUID();
UUID userId = UUID.randomUUID();
UUID alarmId1 = UUID.randomUUID();
UUID alarmId2 = UUID.randomUUID();
U... |
@Override
public T getValue() {
return value;
} | @Test
public void newSettableGaugeWithoutDefaultReturnsNull() {
DefaultSettableGauge<String> gauge = new DefaultSettableGauge<>();
assertThat(gauge.getValue()).isNull();
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBigint() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("bigint")
.dataType("bigint")
.build();
Column column = Xug... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldSupportExplicitEmitFinalForInsertInto() {
// Given:
final SingleStatementContext stmt =
givenQuery("INSERT INTO TEST1 SELECT * FROM TEST2 EMIT FINAL;");
// When:
final Query result = ((QueryContainer) builder.buildStatement(stmt)).getQuery();
// Then:
assertTh... |
public static <T> T getAnnotationValue(AnnotatedElement annotationEle, Class<? extends Annotation> annotationType) throws UtilException {
return getAnnotationValue(annotationEle, annotationType, "value");
} | @Test
public void getAnnotationValueTest2() {
final String[] names = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest::names);
assertTrue(names.length == 1 && names[0].isEmpty() || ArrayUtil.equals(names, new String[]{"测试1", "测试2"}));
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testParseNewStyleResourceVcoresNegative() throws Exception {
expectNegativeValueOfResource("vcores");
parseResourceConfigValue("memory-mb=5120,vcores=-2");
} |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testSingleStringSetUpdates() throws IOException {
AppliedPTransform<?, ?, ?> myStep = mock(AppliedPTransform.class);
when(myStep.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNames.put(myStep, ... |
public <InputT, OutputT, CollectionT extends PCollection<? extends InputT>>
DataStream<OutputT> applyBeamPTransform(
DataStream<InputT> input, PTransform<CollectionT, PCollection<OutputT>> transform) {
return (DataStream)
getNonNull(
applyBeamPTransformInternal(
I... | @Test
public void testApplyPreservesInputTimestamps() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
DataStream<Long> input =
env.fromCollection(ImmutableList.of(1L, 2L, 12L))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.