focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override public TraceContext context() {
return context;
} | @Test void hasRealContext() {
assertThat(span.context().spanId()).isNotZero();
} |
public static void warn(final Logger logger, final String format, final Supplier<Object> supplier) {
if (logger.isWarnEnabled()) {
logger.warn(format, supplier.get());
}
} | @Test
public void testAtLeastOnceWarn() {
when(logger.isWarnEnabled()).thenReturn(true);
LogUtils.warn(logger, supplier);
verify(supplier, atLeastOnce()).get();
} |
public void addMapStatistics(DwrfProto.KeyInfo key, ColumnStatistics columnStatistics)
{
requireNonNull(key, "key is null");
requireNonNull(columnStatistics, "columnStatistics is null");
hasEntries = true;
if (collectKeyStats) {
entries.add(new MapStatisticsEntry(key, col... | @Test(dataProvider = "keySupplier")
public void testAddMapStatistics(KeyInfo[] keys)
{
KeyInfo key1 = keys[0];
KeyInfo key2 = keys[1];
ColumnStatistics columnStatistics1 = new ColumnStatistics(3L, null, null, null);
ColumnStatistics columnStatistics2 = new ColumnStatistics(5L, n... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testOffsetCommitsSensor() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Create an empty group.
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup(
"foo",
true
... |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testAllowedTypeCastingIntoString() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
ParamsMergeHelperTest.this.parseParamDefMap(
"{'tomerge': {'type': 'STRING','value': '', 'name': 'tomerge'}}");
Map<String, ParamDefinition> paramsToMerge =
... |
public static SemanticVersion parse(String version) {
try {
var matcher = VERSION_PARSE_PATTERN.matcher(version);
matcher.find();
var semver = new SemanticVersion();
semver.setMajor(Integer.parseInt(matcher.group("major")));
semver.setMinor(Integer.pa... | @Test
public void testParseInvalidVersion() {
var exception = assertThrows(RuntimeException.class, () -> SemanticVersion.parse("9.2"));
assertEquals("Invalid semantic version. See https://semver.org/.", exception.getMessage());
} |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @Test
public void testCopyFromHostWait() throws Exception {
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
r, metrics, except, key, connection);
String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);
when(connection.getResponseCode()).thenRet... |
@Override
public Query normalizeQuery(final Query query, final ParameterProvider parameterProvider) {
return query.toBuilder()
.query(ElasticsearchQueryString.of(this.queryStringDecorators.decorate(query.query().queryString(), parameterProvider, query)))
.filter(normalizeFilt... | @Test
void decoratesQueryStrings() {
final Query query = Query.builder()
.query(ElasticsearchQueryString.of("action:index"))
.build();
final Query normalizedQuery = decorateQueryStringsNormalizer.normalizeQuery(query, name -> Optional.empty());
final String... |
public AuthenticationRequest startAuthenticationProcess(HttpServletRequest httpRequest) throws ComponentInitializationException, MessageDecodingException, SamlValidationException, SharedServiceClientException, DienstencatalogusException, SamlSessionException {
BaseHttpServletRequestXMLMessageDecoder decoder = d... | @Test
protected void parseAuthenticationSuccessfulEntranceTest() throws SamlSessionException, SharedServiceClientException, DienstencatalogusException, ComponentInitializationException, SamlValidationException, MessageDecodingException, UnsupportedEncodingException, SamlParseException {
String samlRequest =... |
public void write(ImageWriter writer, ImageWriterOptions options) {
if (options.metadataVersion().isDelegationTokenSupported()) {
for (Entry<String, DelegationTokenData> entry : tokens.entrySet()) {
writer.write(0, entry.getValue().toRecord());
}
} else {
... | @Test
public void testImage1withInvalidIBP() {
ImageWriterOptions imageWriterOptions = new ImageWriterOptions.Builder().
setMetadataVersion(MetadataVersion.IBP_3_5_IV2).build();
RecordListWriter writer = new RecordListWriter();
try {
IMAGE1.write(writer, imageWrit... |
@SuppressWarnings("MethodMayBeStatic")
@Udf(description = "The 2 input points should be specified as (lat, lon) pairs, measured"
+ " in decimal degrees. An optional fifth parameter allows to specify either \"MI\" (miles)"
+ " or \"KM\" (kilometers) as the desired unit for the output measurement. Default i... | @Test
public void shouldComputeDistanceBetweenLocationsWithNullUnitsUsingKM() {
assertEquals(8634.6528,
(double) distanceUdf.geoDistance(37.4439, -122.1663, 51.5257, -0.1122, null), 0.5);
} |
@NonNull
@Override
public FileName toProviderFileName( @NonNull ConnectionFileName pvfsFileName, @NonNull T details )
throws KettleException {
StringBuilder providerUriBuilder = new StringBuilder();
appendProviderUriConnectionRoot( providerUriBuilder, details );
// Examples:
// providerUriBu... | @Test
public void testToProviderFileNameHandlesConnectionsWithDomain() throws Exception {
mockDetailsWithDomain( details1, "my-domain:8080" );
ConnectionFileName pvfsFileName = mockPvfsFileNameWithPath( "/rest/path" );
FileName providerFileName = transformer.toProviderFileName( pvfsFileName, details1 )... |
public static String toSymbolCase(CharSequence str, char symbol) {
if (str == null) {
return null;
}
final int length = str.length();
final StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < length; i++) {
c = str.charAt(i);
... | @Test
public void toSymbolCase() {
String string = "str";
String s = StringUtil.toSymbolCase(string, StringUtil.UNDERLINE);
Assert.assertEquals("str", s);
} |
public Status currentStatus(FetchRequest request) {
final DocumentStatus ds = fetchStatus(request);
if (MUStatusType.ACTIEF == ds.getStatusMu() || ds.getDocType() == DocTypeType.NI) {
switch (ds.getStatus()) {
case GEACTIVEERD:
return Status.ACTIVE;
... | @Test
public void getActiveStatusWithSuccessTest() {
final DocumentStatus dummyDocumentStatus = new DocumentStatus();
dummyDocumentStatus.setId(1L);
dummyDocumentStatus.setSequenceNo("SSSSSSSSSSSSS");
dummyDocumentStatus.setDocType(DocTypeType.NL_RIJBEWIJS);
dummyDocumentStat... |
public boolean isUnqualifiedShorthandProjection() {
if (1 != projections.size()) {
return false;
}
Projection projection = projections.iterator().next();
return projection instanceof ShorthandProjection && !((ShorthandProjection) projection).getOwner().isPresent();
} | @Test
void assertUnqualifiedShorthandProjection() {
Projection projection = new ShorthandProjection(null, Collections.emptyList());
ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, true, Collections.singleton(projection));
assertTrue(projectionsContext.isUnqualifiedShorth... |
@VisibleForTesting
ExportResult<PhotosContainerResource> exportOneDrivePhotos(
TokensAndUrlAuthData authData,
Optional<IdOnlyContainerResource> albumData,
Optional<PaginationData> paginationData,
UUID jobId)
throws IOException {
Optional<String> albumId = Optional.empty();
if (al... | @Test
public void exportAlbumAndPhotoWithNextPage() throws IOException {
// Setup
MicrosoftDriveItem folderItem = setUpSingleAlbum();
MicrosoftDriveItem photoItem = setUpSinglePhoto(IMAGE_URI, PHOTO_ID);
when(driveItemsResponse.getDriveItems())
.thenReturn(new MicrosoftDriveItem[] {folderItem... |
@Override
public Map<Headers, String> getHeaders() {
return Collections.unmodifiableMap(headers);
} | @Test
void testGetHeaders() {
final var message = new SimpleMessage();
assertNotNull(message.getHeaders());
assertTrue(message.getHeaders().isEmpty());
final var senderName = "test";
message.addHeader(Message.Headers.SENDER, senderName);
assertNotNull(message.getHeaders());
assertFalse(me... |
public static Set<String> validateScopes(String scopeClaimName, Collection<String> scopes) throws ValidateException {
if (scopes == null)
throw new ValidateException(String.format("%s value must be non-null", scopeClaimName));
Set<String> copy = new HashSet<>();
for (String scope :... | @Test
public void testValidateScopesResultThrowsExceptionOnMutation() {
SortedSet<String> callerSet = new TreeSet<>(Arrays.asList("a", "b", "c"));
Set<String> scopes = ClaimValidationUtils.validateScopes("scope", callerSet);
assertThrows(UnsupportedOperationException.class, scopes::clear);
... |
public boolean containsCustomMappingForField(final String fieldName) {
return stream().anyMatch(m -> m.fieldName().equals(fieldName));
} | @Test
void testContainsMappingForFieldWorksCorrectly() {
CustomFieldMappings mapping = new CustomFieldMappings(List.of(
new CustomFieldMapping("field1", "string"),
new CustomFieldMapping("field2", "long")
));
assertTrue(mapping.containsCustomMappingForField("... |
@Override
public void upgrade() {
try {
streamService.load(Stream.DEFAULT_STREAM_ID);
} catch (NotFoundException ignored) {
createDefaultStream();
}
} | @Test
public void upgradeWithoutDefaultIndexSet() throws Exception {
when(streamService.load("000000000000000000000001")).thenThrow(NotFoundException.class);
when(indexSetRegistry.getDefault()).thenThrow(IllegalStateException.class);
expectedException.expect(IllegalStateException.class);
... |
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception { // NOPMD
// cette méthode est appelée par le conteneur ejb grâce à l'annotation AroundInvoke
if (DISABLED || !EJB_COUNTER.isDisplayed()) {
return context.proceed();
}
// nom identifiant la requête
final String requestName ... | @Test
public void testMonitoringAsynchronousCdi() throws Exception {
final Counter ejbCounter = MonitoringProxy.getEjbCounter();
ejbCounter.clear();
final MonitoringAsynchronousCdiInterceptor interceptor = new MonitoringAsynchronousCdiInterceptor();
ejbCounter.setDisplayed(true);
interceptor.intercept(new I... |
@Override
public boolean remove(Object o)
{
return _map.remove(o) == PRESENT;
} | @Test
public void testRemove()
{
final CowSet<String> set = new CowSet<>();
set.add("test");
Assert.assertTrue(set.remove("test"));
Assert.assertFalse(set.contains("test"));
Assert.assertEquals(set.size(), 0);
Assert.assertFalse(set.remove("test"));
Assert.assertFalse(set.contains("tes... |
@Override
public void execute(CommandLine commandLine, Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
... | @Test
public void testExecute() {
DeleteAccessConfigSubCommand cmd = new DeleteAccessConfigSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-a unit-test", "-c default-cluster"};
final CommandLine commandLine =
... |
public String getDiscriminatingValue(ILoggingEvent event) {
// http://jira.qos.ch/browse/LBCLASSIC-213
Map<String, String> mdcMap = event.getMDCPropertyMap();
if (mdcMap == null) {
return defaultValue;
}
String mdcValue = mdcMap.get(key);
if (mdcValue == null)... | @Test
public void smoke() {
logbackMDCAdapter.put(key, value);
event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
String discriminatorValue = discriminator.getDiscriminatingValue(event);
assertEquals(value, discriminatorValue);
} |
public static double var(int[] array) {
if (array.length < 2) {
throw new IllegalArgumentException("Array length is less than 2.");
}
double sum = 0.0;
double sumsq = 0.0;
for (int xi : array) {
sum += xi;
sumsq += xi * xi;
}
... | @Test
public void testVar_doubleArr() {
System.out.println("var");
double[] data = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
assertEquals(7.5, MathEx.var(data), 1E-6);
} |
public static <T> Stream<T> stream(Enumeration<T> e) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(
new Iterator<T>() {
public T next() {
return e.nextElement();
}... | @Test
public void test_stream_from_empty_enumeration() {
Enumeration<Integer> someEnumeration = Collections.enumeration(Collections.emptyList());
assertThat(EnumerationUtil.stream(someEnumeration).collect(Collectors.toList())).isEmpty();
} |
public RecordReader getRecordReader(InputSplit split, JobConf job,
Reporter reporter) throws IOException {
FileSplit fileSplit = (FileSplit) split;
FileSystem fs = FileSystem.get(fileSplit.getPath().toUri(), job);
FSDataInputStream is = fs.open(fileSplit.getPath());
byte[] header = new byte[3];
... | @SuppressWarnings( { "unchecked", "deprecation" })
@Test
public void testFormat() throws IOException {
JobConf job = new JobConf(conf);
FileSystem fs = FileSystem.getLocal(conf);
Path dir = new Path(System.getProperty("test.build.data", ".") + "/mapred");
Path txtFile = new Path(dir, "auto.txt");
... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldDropExistingType() {
// Given:
metaStore.registerType("type", SqlTypes.STRING);
// When:
final DdlCommandResult result = cmdExec.execute(SQL_TEXT, dropType, false, NO_QUERY_SOURCES);
// Then:
assertThat(metaStore.resolveType("type").isPresent(), is(false));
assert... |
@Override
public Image call() throws LayerPropertyNotFoundException {
try (ProgressEventDispatcher ignored =
progressEventDispatcherFactory.create("building image format", 1);
TimerEventDispatcher ignored2 =
new TimerEventDispatcher(buildContext.getEventHandlers(), DESCRIPTION)) {
... | @Test
public void test_basicCase() {
Image image =
new BuildImageStep(
mockBuildContext,
mockProgressEventDispatcherFactory,
baseImage,
baseImageLayers,
applicationLayers)
.call();
Assert.assertEquals("root", i... |
@Override
public <K> HostToKeyMapper<K> getPartitionInformation(URI serviceUri, Collection<K> keys,
int limitHostPerPartition,
int hash)
throws ServiceUnavailableException
{
if (limitHostPer... | @Test
public void testGetAllPartitionMultipleHostsOrdering()
throws Exception
{
String serviceName = "articles";
String clusterName = "cluster";
String path = "path";
String strategyName = "degrader";
//setup partition
Map<URI,Map<Integer, PartitionData>> partitionDescriptions = new H... |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_expired() {
// 准备参数
String code = "test_code";
// mock 数据
OAuth2CodeDO codeDO = randomPojo(OAuth2CodeDO.class).setCode(code)
.setExpiresTime(LocalDateTime.now().minusDays(1));
oauth2CodeMapper.insert(codeDO);
... |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test
public void of_equalityDifferentTypes() {
String urnA = "urn:hzScheduledTaskHandler:39ffc539-a356-444c-bec7-6f644462c208 -1 Scheduler Task";
String urnB = "urn:hzScheduledTaskHandler:- 2 Scheduler Task";
assertNotEquals(ScheduledTaskHandler.of(urnA), ScheduledTaskHandler.of(urnB));
... |
public static void setEnvFromInputProperty(Map<String, String> env,
String propName, String defaultPropValue, Configuration conf,
String classPathSeparator) {
String envString = conf.get(propName, defaultPropValue);
// Get k,v pairs from string into a tmp env. Note that we don't want
// to exp... | @Test
void testSetEnvFromInputPropertyNull() {
Configuration conf = new Configuration(false);
Map<String, String> env = new HashMap<>();
String propName = "mapreduce.map.env";
String defaultPropName = "mapreduce.child.env";
// Setup environment input properties
conf.set(propName, "env1=env1_va... |
public static boolean isBean(Type type) {
return isBean(TypeRef.of(type));
} | @Test
public void isBeanTest() {
Assert.assertTrue(TypeUtils.isBean(BeanA.class));
Assert.assertFalse(TypeUtils.isBean(Object.class));
} |
@Override
@SneakyThrows
public String createFile(String name, String path, byte[] content) {
// 计算默认的 path 名
String type = FileTypeUtils.getMineType(content, name);
if (StrUtil.isEmpty(path)) {
path = FileUtils.generatePath(content, name);
}
// 如果 name 为空,则使用 ... | @Test
public void testCreateFile_success() throws Exception {
// 准备参数
String path = randomString();
byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
// mock Master 文件客户端
FileClient client = mock(FileClient.class);
when(fileConfigService.getMasterFileClient... |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testRoundDecimalNullLiteral() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("round_decimal(null)", INT_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transformFuncti... |
public ValidationResult isRepositoryConfigurationValid(String pluginId, final RepositoryConfiguration repositoryConfiguration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_REPOSITORY_CONFIGURATION, new DefaultPluginInteractionCallback<>() {
@Override
public Strin... | @Test
public void shouldTalkToPluginToCheckIfRepositoryConfigurationIsValid() throws Exception {
String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}}";
String expectedResponseBody = "[{\"key\":\"key-one\",\"messag... |
public int getSubpartitionId() {
return subpartitionId;
} | @Test
void testGetSubpartitionId() {
Buffer buffer = BufferBuilderTestUtils.buildSomeBuffer(0);
int bufferIndex = 0;
int subpartitionId = 1;
NettyPayload nettyPayload = NettyPayload.newBuffer(buffer, bufferIndex, subpartitionId);
assertThat(nettyPayload.getSubpartitionId()).i... |
@Override
public void persist(final String key, final String value) {
try {
if (isExisted(key)) {
update(key, value);
return;
}
String tempPrefix = "";
String parent = SEPARATOR;
String[] paths = Arrays.stream(key.sp... | @Test
void assertPersistFailureDuringUpdate() throws SQLException {
final String key = "key";
when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement);
when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
when(moc... |
public static Integer parseRestBindPortFromWebInterfaceUrl(String webInterfaceUrl) {
if (webInterfaceUrl != null) {
final int lastColon = webInterfaceUrl.lastIndexOf(':');
if (lastColon == -1) {
return -1;
} else {
try {
re... | @Test
void testParseRestBindPortFromWebInterfaceUrlWithInvalidSchema() {
assertThat(ResourceManagerUtils.parseRestBindPortFromWebInterfaceUrl("localhost:8080//"))
.isEqualTo(-1);
} |
public static boolean isMaskBitValid(int maskBit) {
return MaskBit.get(maskBit) != null;
} | @Test
public void isMaskBitInvalidTest() {
final boolean maskBitValid = Ipv4Util.isMaskBitValid(33);
assertFalse(maskBitValid);
} |
@Override
public void validateConnectorConfig(Map<String, String> connectorProps, Callback<ConfigInfos> callback) {
validateConnectorConfig(connectorProps, callback, true);
} | @Test
public void testConfigValidationMissingName() {
final Class<? extends Connector> connectorClass = SampleSourceConnector.class;
AbstractHerder herder = createConfigValidationHerder(connectorClass, noneConnectorClientConfigOverridePolicy);
Map<String, String> config = Collections.single... |
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
String originalString = values[0].execute();
String mode = null; // default
if (values.length > 1) {
mode = values[1].execute();
}
if(StringUtils... | @Test
public void testEmptyMode() throws Exception {
String returnValue = execute("ab-CD eF", "");
assertEquals("AB-CD EF", returnValue);
} |
public void writeInfinity() {
writeTrailingBytes(INFINITY_ENCODED);
} | @Test
public void testWriteInfinity() {
OrderedCode orderedCode = new OrderedCode();
try {
orderedCode.readInfinity();
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException e) {
// expected
}
orderedCode.writeInfinity();
assertTrue(orderedCode.readInfi... |
@Override
public void start() throws PulsarServerException {
try {
// At this point, the ports will be updated with the real port number that the server was assigned
Map<String, String> protocolData = pulsar.getProtocolDataToAdvertise();
lastData = new LocalBrokerData(pu... | @Test
public void testOwnBrokerZnodeByMultipleBroker() throws Exception {
ServiceConfiguration config = new ServiceConfiguration();
config.setLoadManagerClassName(ModularLoadManagerImpl.class.getName());
config.setClusterName("use");
config.setWebServicePort(Optional.of(PortManager.... |
@Override
public RetrievableStateHandle<T> addAndLock(String pathInZooKeeper, T state)
throws PossibleInconsistentStateException, Exception {
checkNotNull(pathInZooKeeper, "Path in ZooKeeper");
checkNotNull(state, "State");
final String path = normalizePath(pathInZooKeeper);
... | @Test
void testAddAndLock() throws Exception {
final TestingLongStateHandleHelper longStateStorage = new TestingLongStateHandleHelper();
ZooKeeperStateHandleStore<TestingLongStateHandleHelper.LongStateHandle> store =
new ZooKeeperStateHandleStore<>(getZooKeeperClient(), longStateStor... |
public void validateReadPermission(String serverUrl, String personalAccessToken) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos");
doGet(personalAccessToken, url, body -> buildGson().fromJson(body, RepositoryList.class));
} | @Test
public void fail_validate_url_on_non_json_result_log_correctly_the_response() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setResponseCode(500)
.setBody("not json"));
String serverUrl = server.url("/").toString();
assertThatThro... |
public static void checkValid(boolean isValid, String argName) {
checkArgument(isValid, "'%s' is invalid.", argName);
} | @Test
public void testCheckValid() throws Exception {
// Should not throw.
Validate.checkValid(true, "arg");
// Verify it throws.
ExceptionAsserts.assertThrows(
IllegalArgumentException.class,
"'arg' is invalid",
() -> Validate.checkValid(false, "arg"));
} |
@Nullable
public static TraceContextOrSamplingFlags parseB3SingleFormat(CharSequence b3) {
return parseB3SingleFormat(b3, 0, b3.length());
} | @Test void parseB3SingleFormat_spanIdsNotYetSampled128() {
assertThat(parseB3SingleFormat(traceIdHigh + traceId + "-" + spanId).context())
.isEqualToComparingFieldByField(TraceContext.newBuilder()
.traceIdHigh(Long.parseUnsignedLong(traceIdHigh, 16))
.traceId(Long.parseUnsignedLong(traceId, 16... |
public static GetResourceProfileResponse mergeClusterResourceProfileResponse(
Collection<GetResourceProfileResponse> responses) {
GetResourceProfileResponse profileResponse =
Records.newRecord(GetResourceProfileResponse.class);
Resource resource = Resource.newInstance(0, 0);
for (GetResourcePr... | @Test
public void testMergeResourceProfile() {
// normal response1
Resource resource1 = Resource.newInstance(1024, 1);
GetResourceProfileResponse response1 =
Records.newRecord(GetResourceProfileResponse.class);
response1.setResource(resource1);
// normal response2
Resource resource2 =... |
public static Collection<PValue> nonAdditionalInputs(AppliedPTransform<?, ?, ?> application) {
ImmutableList.Builder<PValue> mainInputs = ImmutableList.builder();
PTransform<?, ?> transform = application.getTransform();
for (Map.Entry<TupleTag<?>, PCollection<?>> input : application.getInputs().entrySet()) ... | @Test
public void nonAdditionalInputsWithMultipleNonAdditionalInputsSucceeds() {
Map<TupleTag<?>, PCollection<?>> allInputs = new HashMap<>();
PCollection<Integer> mainInts = pipeline.apply("MainInput", Create.of(12, 3));
allInputs.put(new TupleTag<Integer>() {}, mainInts);
PCollection<Void> voids = p... |
protected String stripBasePath(String requestPath, ContainerConfig config) {
if (!config.isStripBasePath()) {
return requestPath;
}
if (requestPath.startsWith(config.getServiceBasePath())) {
String newRequestPath = requestPath.replaceFirst(config.getServiceBasePath(), ""... | @Test
void requestReader_doubleBasePath() {
ContainerConfig config = ContainerConfig.defaultConfig();
config.setStripBasePath(true);
config.setServiceBasePath(BASE_PATH_MAPPING);
String finalPath = requestReader.stripBasePath("/" + BASE_PATH_MAPPING + "/" + BASE_PATH_MAPPING, config... |
@Deactivate
public void deactivate() {
cfgService.unregisterProperties(getClass(), false);
providerRegistry.unregister(this);
mastershipService.removeListener(mastershipListener);
deviceService.removeListener(deviceListener);
alarmsExecutor.shutdown();
providerService... | @Test
public void deactivate() throws Exception {
provider.deactivate();
assertEquals("Device listener should be removed", 0, deviceListeners.size());
assertEquals("Mastership listener should be removed", 0, mastershipListeners.size());
assertFalse("Provider should not be registered"... |
public static String toSnakeCase(String camelCase) {
if (camelCase == null || camelCase.isEmpty()) {
return camelCase;
}
StringBuilder result = new StringBuilder();
result.append(camelCase.substring(0, 1).toLowerCase()); // 将首字母转小写并添加到结果
for (int i = 1; i < camelCas... | @Test
void toSnakeCase() {
String str = StringUtils.toSnakeCase("TeacherStatics");
assertEquals("teacher_statics", str);
} |
public static void checkResourcePerms(List<String> resources) {
if (resources == null || resources.isEmpty()) {
return;
}
for (String resource : resources) {
String[] items = StringUtils.split(resource, "=");
if (items.length != 2) {
throw new... | @Test(expected = AclException.class)
public void checkResourcePermsExceptionTest2() {
Permission.checkResourcePerms(Arrays.asList("topicA="));
} |
public static byte[] floatToBytesLE(float f, byte[] bytes, int off) {
return intToBytesLE(Float.floatToIntBits(f), bytes, off);
} | @Test
public void testFloatToBytesLE() {
assertArrayEquals(FLOAT_PI_LE ,
ByteUtils.floatToBytesLE((float) Math.PI, new byte[4], 0));
} |
public void handleUpdatedHostInfo(NodeInfo node, HostInfo hostInfo) {
if ( ! node.isDistributor()) return;
final int hostVersion;
if (hostInfo.getClusterStateVersionOrNull() == null) {
// TODO: Consider logging a warning in the future (>5.36).
// For now, a missing clust... | @Test
void testStateVersionMismatch() {
when(nodeInfo.isDistributor()).thenReturn(true);
when(clusterState.getVersion()).thenReturn(101);
clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("22"));
verify(statsAggregator, never()).updateForDistributor(anyInt(), any());
... |
@Deprecated
public static <K, V>
PTransform<PCollection<? extends KV<K, TimestampedValue<V>>>, PCollection<KV<K, V>>>
extractFromValues() {
return new ExtractTimestampsFromValues<>();
} | @Test
@Category(ValidatesRunner.class)
public void extractFromValuesWhenValueTimestampedLaterSucceeds() {
PCollection<KV<String, TimestampedValue<Integer>>> preified =
pipeline.apply(
Create.timestamped(
TimestampedValue.of(
KV.of("foo", TimestampedValue.o... |
@Override
public boolean contains(Object o) {
for (Set<QueryableEntry> otherIndexedResult : indexedResults) {
if (otherIndexedResult.contains(o)) {
return true;
}
}
return false;
} | @Test
public void contains() {
int size = 100000;
Set<QueryableEntry> entries1 = generateEntries(size);
Set<QueryableEntry> entries2 = generateEntries(size);
List<Set<QueryableEntry>> indexedResults = new ArrayList<>();
indexedResults.add(entries1);
indexedResults.add... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetProof() throws Exception {
web3j.ethGetProof(
"0x7F0d15C7FAae65896648C8273B6d7E43f58Fa842",
Arrays.asList(
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"),
... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @TestTemplate
public void testPartitionedHours() throws Exception {
createPartitionedTable(spark, tableName, "hours(ts)");
SparkScanBuilder builder = scanBuilder();
HoursFunction.TimestampToHoursFunction function = new HoursFunction.TimestampToHoursFunction();
UserDefinedScalarFunc udf = toUDF(funct... |
public void start() {
start(false);
} | @Test
@Disabled
public void tailWithLinesTest() {
Tailer tailer = new Tailer(FileUtil.file("f:/test/test.log"), Tailer.CONSOLE_HANDLER, 2);
tailer.start();
} |
@Override
public <T extends Recorder> RetryContext<T> context() {
return new RetryContextImpl<>();
} | @Test
public void contextTest() throws Exception {
final Retry retry = Retry.create(build("context", false));
final RetryContext<Recorder> context = retry.context();
final Recorder recorder = Mockito.mock(Recorder.class);
context.onBefore(recorder);
Mockito.verify(recorder, M... |
public Host lookup(final String uuid) {
return this.stream().filter(h -> h.getUuid().equals(uuid)).findFirst().orElse(null);
} | @Test
public void testLookup() {
final AbstractHostCollection c = new AbstractHostCollection() {
};
final Host bookmark = new Host(new TestProtocol());
assertFalse(c.find(new AbstractHostCollection.HostComparePredicate(bookmark)).isPresent());
assertNull(c.lookup(bookmark.get... |
@Override
public int permitMaximum() {
return maxConnections;
} | @Test
void permitMaximum() {
builder.maxConnections(2);
Http2AllocationStrategy strategy = builder.build();
assertThat(strategy.maxConcurrentStreams()).isEqualTo(DEFAULT_MAX_CONCURRENT_STREAMS);
assertThat(strategy.permitMaximum()).isEqualTo(2);
assertThat(strategy.permitMinimum()).isEqualTo(DEFAULT_MIN_CONN... |
@PostMapping("")
public ShenyuAdminResult createSelector(@Valid @RequestBody final SelectorDTO selectorDTO) {
selectorService.createOrUpdate(selectorDTO);
return ShenyuAdminResult.success(ShenyuResultMessage.CREATE_SUCCESS, selectorDTO.getId());
} | @Test
public void createSelector() throws Exception {
SelectorDTO selectorDTO = SelectorDTO.builder()
.id("123")
.name("test123")
.continued(true)
.type(1)
.loged(true)
.enabled(true)
.matchRestfu... |
void remove(int brokerId) {
BrokerHeartbeatState broker = brokers.remove(brokerId);
if (broker != null) {
untrack(broker);
}
} | @Test
public void testBrokerHeartbeatStateList() {
BrokerHeartbeatStateList list = new BrokerHeartbeatStateList();
assertNull(list.first());
BrokerHeartbeatStateIterator iterator = list.iterator();
assertFalse(iterator.hasNext());
BrokerHeartbeatState broker0 = new BrokerHear... |
public void popMessageAsync(
final String brokerName, final String addr, final PopMessageRequestHeader requestHeader,
final long timeoutMillis, final PopCallback popCallback
) throws RemotingException, InterruptedException {
final RemotingCommand request = RemotingCommand.createRequestComman... | @Test
public void testPopMessageAsync_Success() throws Exception {
final long popTime = System.currentTimeMillis();
final int invisibleTime = 10 * 1000;
doAnswer((Answer<Void>) mock -> {
InvokeCallback callback = mock.getArgument(3);
RemotingCommand request = mock.get... |
public HashMap<String, String> parseInfoToGetUUID(String output, String queryURL, SAXBuilder builder) {
HashMap<String, String> uidToUrlMap = new HashMap<>();
try {
Document document = builder.build(new StringReader(output));
Element root = document.getRootElement();
... | @Test
public void shouldParseSvnInfoOutputToConstructUrlToRemoteUUIDMapping() {
final SvnLogXmlParser svnLogXmlParser = new SvnLogXmlParser();
final String svnInfoOutput = """
<?xml version="1.0"?>
<info>
<entry
kind="dir"
... |
public static String simplyEnvNameIfOverLimit(String envName) {
if (StringUtils.isNotBlank(envName) && envName.length() > MAX_ENV_NAME_LENGTH) {
return envName.substring(0, MAX_ENV_NAME_LENGTH) + MD5Utils.md5Hex(envName, "UTF-8");
}
return envName;
} | @Test
void testSimplyEnvNameIfOverLimit() {
StringBuilder envNameOverLimitBuilder = new StringBuilder("test");
for (int i = 0; i < 50; i++) {
envNameOverLimitBuilder.append(i);
}
String envName = envNameOverLimitBuilder.toString();
String actual = ParamUtil.simply... |
public static Future<Void> unregisterNodes(
Reconciliation reconciliation,
Vertx vertx,
AdminClientProvider adminClientProvider,
PemTrustSet pemTrustSet,
PemAuthIdentity pemAuthIdentity,
List<Integer> nodeIdsToUnregister
) {
try {
... | @Test
void testUnregistration(VertxTestContext context) {
Admin mockAdmin = ResourceUtils.adminClient();
UnregisterBrokerResult ubr = mock(UnregisterBrokerResult.class);
when(ubr.all()).thenReturn(KafkaFuture.completedFuture(null));
ArgumentCaptor<Integer> unregisteredNodeIdCaptor =... |
@Override
public void removeIndex(String columnName, IndexType<?, ?, ?> indexType) {
// Text index is kept in its own files, thus can be removed directly.
if (indexType == StandardIndexes.text()) {
TextIndexUtils.cleanupTextIndex(_segmentDirectory, columnName);
return;
}
if (indexType == S... | @Test
public void testRemoveIndex()
throws IOException, ConfigurationException {
try (SingleFileIndexDirectory sfd = new SingleFileIndexDirectory(TEMP_DIR, _segmentMetadata, ReadMode.mmap)) {
sfd.newBuffer("col1", StandardIndexes.dictionary(), 1024);
sfd.removeIndex("col1", StandardIndexes.dicti... |
public IntArray(int capacity) {
elementData = new int[capacity];
} | @Test
public void testIntArray() {
IntArray array = new IntArray(10);
for (int i = 0; i < 10; i++) {
array.add(i * 2);
}
assertEquals(array.elementData, IntStream.range(0, 10).map(i -> i * 2).toArray());
int[] elementData = array.elementData;
array.add(1);
assertNotSame(elementData, ... |
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize) throws NacosException {
return getServicesOfServer(pageNo, pageSize, Constants.DEFAULT_GROUP);
} | @Test
void testGetServicesOfServer3() throws NacosException {
//given
int pageNo = 1;
int pageSize = 10;
AbstractSelector selector = new AbstractSelector("aaa") {
@Override
public String getType() {
return super.getType();
}
... |
public static String getLineSeparator() {
return System.getProperty("line.separator");
} | @Test
void testGetLineSeparator() {
String lineSeparator = DiskCache.getLineSeparator();
assertTrue(lineSeparator.length() > 0);
} |
@Udf
public <T extends Comparable<? super T>> T arrayMin(@UdfParameter(
description = "Array of values from which to find the minimum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldFindDecimalMin() {
final List<BigDecimal> input =
Arrays.asList(BigDecimal.valueOf(1.2), BigDecimal.valueOf(1.3), BigDecimal.valueOf(-1.2));
assertThat(udf.arrayMin(input), is(BigDecimal.valueOf(-1.2)));
} |
public static boolean isBigDecimalEquals(final BigDecimal one, final BigDecimal another) {
BigDecimal decimalOne;
BigDecimal decimalTwo;
if (one.scale() == another.scale()) {
decimalOne = one;
decimalTwo = another;
} else {
if (one.scale() > another.sc... | @Test
void assertIsBigDecimalEquals() {
BigDecimal one = BigDecimal.valueOf(3322L, 1);
BigDecimal another = BigDecimal.valueOf(33220L, 2);
assertTrue(DataConsistencyCheckUtils.isBigDecimalEquals(one, another));
} |
public Set<String> groups(String clusterName) {
return clusterNodes.computeIfAbsent(clusterName, k -> new ConcurrentHashMap<>()).keySet();
} | @Test
public void testGroups() {
Assertions.assertDoesNotThrow(() -> metadata.groups("cluster"));
} |
public static Result label(long durationInMillis) {
double nbSeconds = durationInMillis / 1000.0;
double nbMinutes = nbSeconds / 60;
double nbHours = nbMinutes / 60;
double nbDays = nbHours / 24;
double nbYears = nbDays / 365;
return getMessage(nbSeconds, nbMinutes, nbHours, nbDays, nbYears);
... | @Test
public void age_in_hours() {
long hours = 3;
DurationLabel.Result result = DurationLabel.label(now() - ago(hours * HOUR));
assertThat(result.key()).isEqualTo("duration.hours");
assertThat(result.value()).isEqualTo(hours);
} |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
List<KeyValue<String, Object>> templateParams) throws Throwable {
Assert.notBlank(properties.getSignature(), "短信签名不能为空");
// 1. 执行请求
// 参考链接 https://api.aliyun.com/d... | @Test
public void tesSendSms_fail() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
... |
public Map<String, Integer> releaseHistoryRetentionSizeOverride() {
String overrideString = getValue("apollo.release-history.retention.size.override");
Map<String, Integer> releaseHistoryRetentionSizeOverride = Maps.newHashMap();
if (!Strings.isNullOrEmpty(overrideString)) {
releaseHistoryRetentionSiz... | @Test
public void testReleaseHistoryRetentionSizeOverride() {
int someOverrideLimit = 10;
String overrideValueString = "{'a+b+c+b':10}";
when(environment.getProperty("apollo.release-history.retention.size.override")).thenReturn(overrideValueString);
int overrideValue = bizConfig.releaseHistoryRetenti... |
public QueueConfig setAsyncBackupCount(int asyncBackupCount) {
this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setAsyncBackupCount_whenItsNegative() {
queueConfig.setAsyncBackupCount(-1);
} |
@Override
public RequestFuture requestFuture(Request request) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
final ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
return new RequestFuture() {
@... | @Test
void testRequestFutureFailure() throws Exception {
assertThrows(NacosException.class, () -> {
when(future.get()).thenReturn(errorResponsePayload);
RequestFuture requestFuture = connection.requestFuture(new HealthCheckRequest());
assertTrue(requestFuture.isDone());
... |
public static NetFlowV5Packet parsePacket(ByteBuf bb) {
final int readableBytes = bb.readableBytes();
final NetFlowV5Header header = parseHeader(bb.slice(bb.readerIndex(), HEADER_LENGTH));
final int packetLength = HEADER_LENGTH + header.count() * RECORD_LENGTH;
if (header.count() <= 0 |... | @Test
public void testParse2() throws IOException {
final byte[] b = Resources.toByteArray(Resources.getResource("netflow-data/netflow-v5-2.dat"));
NetFlowV5Packet packet = NetFlowV5Parser.parsePacket(Unpooled.wrappedBuffer(b));
assertNotNull(packet);
NetFlowV5Header h = packet.head... |
public boolean containsMapping(String tableName, Mappings mappings) {
if (Objects.isNull(mappings) ||
CollectionUtils.isEmpty(mappings.getProperties())) {
return true;
}
return mappingStructures.containsKey(tableName)
&& mappingStructures.get(tableName)
... | @Test
public void containsMapping() {
IndexStructures structures = new IndexStructures();
HashMap<String, Object> properties = new HashMap<>();
properties.put("a", "b");
properties.put("c", "d");
properties.put("f", "g");
structures.putStructure("test", Mappings.build... |
@Override
public void setConfigAttributes(Object attributes) {
clear();
if (attributes == null) {
return;
}
List<Map> attrList = (List<Map>) attributes;
for (Map attrMap : attrList) {
String type = (String) attrMap.get("artifactTypeValue");
... | @Test
public void setConfigAttributes_shouldSetConfigurationAsIsIfPluginIdIsBlank() throws CryptoException {
Map<Object, Object> imageMap = new HashMap<>();
imageMap.put("value", new GoCipher().encrypt("some-encrypted-value"));
imageMap.put("isSecure", "true");
Map<Object, Object> t... |
public static void checkState(boolean isValid, String message) throws IllegalStateException {
if (!isValid) {
throw new IllegalStateException(message);
}
} | @Test
public void testCheckStateWithThreeArguments() {
try {
Preconditions.checkState(true, "Test message %s %s %s", 12, null, "column");
} catch (IllegalStateException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkState(false, "Test... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof NiciraSetNshSi) {
NiciraSetNshSi that = (NiciraSetNshSi) obj;
return Objects.equals(nshSi, that.nshSi);
}
return false;
} | @Test
public void testEquals() {
new EqualsTester().addEqualityGroup(nshSi1, sameAsNshSi1).addEqualityGroup(nshSi2).testEquals();
} |
@Override
public void deleteTenant(Long id) {
// 校验存在
validateUpdateTenant(id);
// 删除
tenantMapper.deleteById(id);
} | @Test
public void testDeleteTenant_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> tenantService.deleteTenant(id), TENANT_NOT_EXISTS);
} |
@Override
public void useSmsCode(SmsCodeUseReqDTO reqDTO) {
// 检测验证码是否有效
SmsCodeDO lastSmsCode = validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene());
// 使用验证码
smsCodeMapper.updateById(SmsCodeDO.builder().id(lastSmsCode.getId())
.used(true).usedTi... | @Test
public void testUseSmsCode_success() {
// 准备参数
SmsCodeUseReqDTO reqDTO = randomPojo(SmsCodeUseReqDTO.class, o -> {
o.setMobile("15601691300");
o.setScene(randomEle(SmsSceneEnum.values()).getScene());
});
// mock 数据
SqlConstants.init(DbType.MYSQL)... |
public void awaitSynchronous() {
List<CompletableFuture<Void>> futures = pending.get();
if (futures.isEmpty()) {
return;
}
try {
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
} catch (CompletionException e) {
logger.log(Level.WARNING, "", e);
} fina... | @Test
public void awaitSynchronous_failure() {
var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run);
var future = new CompletableFuture<Void>();
future.completeExceptionally(new RuntimeException());
dispatcher.pending.get().add(future);
dispatcher.awaitSynchronous();
assertTh... |
@Override
public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Er... | @Test
public void testListenersGetNotifiedOfMemberEpochUpdatesOnlyIfItChanges() {
ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup();
MemberStateListener listener = mock(MemberStateListener.class);
membershipManager.registerStateListener(listener);
in... |
public CompletableFuture<Void> handlePullQuery(
final ServiceContext serviceContext,
final PullPhysicalPlan pullPhysicalPlan,
final ConfiguredStatement<Query> statement,
final RoutingOptions routingOptions,
final PullQueryWriteStream pullQueryQueue,
final CompletableFuture<Void> shou... | @Test
public void shouldCallRouteQuery_couldNotFindHost() {
// Given:
location1 = new PartitionLocation(Optional.empty(), 1, ImmutableList.of());
locate(location1, location2, location3, location4);
// When:
final Exception e = assertThrows(
MaterializationException.class,
() -> ha... |
@Override
public int readInt(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0;
}
switch (fd.getType()) {
case INT:
return super.readInt(fieldName);
case BYTE:
... | @Test
public void testReadInt() throws Exception {
int aByte = reader.readInt("byte");
int aShort = reader.readInt("short");
int aChar = reader.readInt("char");
int aInt = reader.readInt("int");
assertEquals(1, aByte);
assertEquals(3, aShort);
assertEquals(2,... |
@Override
public Optional<BlobDescriptor> handleResponse(Response response) throws RegistryErrorException {
long contentLength = response.getContentLength();
if (contentLength < 0) {
throw new RegistryErrorExceptionBuilder(getActionDescription())
.addReason("Did not receive Content-Length head... | @Test
public void testHandleResponse() throws RegistryErrorException {
Mockito.when(mockResponse.getContentLength()).thenReturn(0L);
BlobDescriptor expectedBlobDescriptor = new BlobDescriptor(0, fakeDigest);
BlobDescriptor blobDescriptor = testBlobChecker.handleResponse(mockResponse).get();
Assert.a... |
public static void preserve(FileSystem targetFS, Path path,
CopyListingFileStatus srcFileStatus,
EnumSet<FileAttribute> attributes,
boolean preserveRawXattrs) throws IOException {
// strip out those attributes we don't need a... | @Test
public void testPreserveGroupOnFile() throws IOException {
FileSystem fs = FileSystem.get(config);
EnumSet<FileAttribute> attributes = EnumSet.of(FileAttribute.GROUP);
Path dst = new Path("/tmp/dest2");
Path src = new Path("/tmp/src2");
createFile(fs, src);
createFile(fs, dst);
fs... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertVarchar() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("varchar")
.dataType("varchar")
.build();
Column column = ... |
public FEELFnResult<BigDecimal> invoke(@ParameterName("list") List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "the list cannot be null"));
}
if (list.isEmpty()) {
return FEELFnResult.ofResult(null); // DMN ... | @Test
void invokeArrayParamContainsUnsupportedType() {
FunctionTestUtil.assertResultError(sumFunction.invoke(new Object[]{10, "test", 2}),
InvalidParametersEvent.class);
} |
public static Metric metric(String name) {
return MetricsImpl.metric(name, Unit.COUNT);
} | @Test
public void metricInFusedStages() {
int inputSize = 100_000;
Integer[] inputs = new Integer[inputSize];
Arrays.setAll(inputs, i -> i);
pipeline.readFrom(TestSources.items(inputs))
.filter(l -> {
Metrics.metric("onlyInFilter").increment();
... |
private RemotingCommand getTopicStatsInfo(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetTopicStatsInfoRequestHeader requestHeader =
(GetTopicStatsInfoRequest... | @Test
public void testGetTopicStatsInfo() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPIC_STATS_INFO, null);
request.addExtField("topic", "topicTest");
RemotingCommand response = adminBrokerProcessor.processRequest(handle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.