focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{
PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name()));
if (userSession.hasSession() && userSession.isLoggedIn()
&& userSession.isSystemAdministrator() && riskConsent == REQUIRED) {
redirectTo(response, request.getContextPath() + PLUGINS_RISK_CONSENT_PATH);
}
chain.doFilter(request, response);
} | @Test
public void doFilter_givenNoUserSession_dontRedirect() throws Exception {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
when(userSession.hasSession()).thenReturn(true);
consentFilter.doFilter(request, response, chain);
verify(response, times(0)).sendRedirect(Mockito.anyString());
} |
static TypeName getNativeType(TypeName typeName) {
if (typeName instanceof ParameterizedTypeName) {
return getNativeType((ParameterizedTypeName) typeName);
}
String simpleName = ((ClassName) typeName).simpleName();
if (simpleName.equals(Address.class.getSimpleName())) {
return TypeName.get(String.class);
} else if (simpleName.startsWith("Uint")) {
return TypeName.get(BigInteger.class);
} else if (simpleName.equals(Utf8String.class.getSimpleName())) {
return TypeName.get(String.class);
} else if (simpleName.startsWith("Bytes") || simpleName.equals("DynamicBytes")) {
return TypeName.get(byte[].class);
} else if (simpleName.startsWith("Bool")) {
return TypeName.get(java.lang.Boolean.class);
// boolean cannot be a parameterized type
} else if (simpleName.equals(Byte.class.getSimpleName())) {
return TypeName.get(java.lang.Byte.class);
} else if (simpleName.equals(Char.class.getSimpleName())) {
return TypeName.get(Character.class);
} else if (simpleName.equals(Double.class.getSimpleName())) {
return TypeName.get(java.lang.Double.class);
} else if (simpleName.equals(Float.class.getSimpleName())) {
return TypeName.get(java.lang.Float.class);
} else if (simpleName.equals(Int.class.getSimpleName())) {
return TypeName.get(Integer.class);
} else if (simpleName.equals(Long.class.getSimpleName())) {
return TypeName.get(java.lang.Long.class);
} else if (simpleName.equals(Short.class.getSimpleName())) {
return TypeName.get(java.lang.Short.class);
} else if (simpleName.startsWith("Int")) {
return TypeName.get(BigInteger.class);
} else {
throw new UnsupportedOperationException(
"Unsupported type: " + typeName + ", no native type mapping exists.");
}
} | @Test
public void testGetNativeType() {
assertEquals(getNativeType(TypeName.get(Address.class)), (TypeName.get(String.class)));
assertEquals(getNativeType(TypeName.get(Uint256.class)), (TypeName.get(BigInteger.class)));
assertEquals(getNativeType(TypeName.get(Int256.class)), (TypeName.get(BigInteger.class)));
assertEquals(getNativeType(TypeName.get(Utf8String.class)), (TypeName.get(String.class)));
assertEquals(getNativeType(TypeName.get(Bool.class)), (TypeName.get(Boolean.class)));
assertEquals(getNativeType(TypeName.get(Bytes32.class)), (TypeName.get(byte[].class)));
assertEquals(getNativeType(TypeName.get(DynamicBytes.class)), (TypeName.get(byte[].class)));
} |
public static String stringBlankAndThenExecute(String source, Callable<String> callable) {
if (StringUtils.isBlank(source)) {
try {
return callable.call();
} catch (Exception e) {
LogUtils.NAMING_LOGGER.error("string empty and then execute cause an exception.", e);
}
}
return source == null ? null : source.trim();
} | @Test
void testStringBlankAndThenExecuteException() throws Exception {
Callable callable = mock(Callable.class);
when(callable.call()).thenThrow(new RuntimeException("test"));
String actual = TemplateUtils.stringBlankAndThenExecute(null, callable);
assertNull(actual);
} |
public ModuleBuilder monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
} | @Test
void monitor() {
MonitorConfig monitor = new MonitorConfig();
ModuleBuilder builder = ModuleBuilder.newBuilder();
builder.monitor(monitor);
Assertions.assertSame(monitor, builder.build().getMonitor());
} |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(source.getParent()).test(target.getParent())) {
// Rename only
return proxy.move(source, target, status, callback, connectionCallback);
}
}
if(new SDSTripleCryptEncryptorFeature(session, nodeid).isEncrypted(source) ^ new SDSTripleCryptEncryptorFeature(session, nodeid).isEncrypted(containerService.getContainer(target))) {
// Moving into or from an encrypted room
final Copy copy = new SDSDelegatingCopyFeature(session, nodeid, new SDSCopyFeature(session, nodeid));
if(log.isDebugEnabled()) {
log.debug(String.format("Move %s to %s using copy feature %s", source, target, copy));
}
final Path c = copy.copy(source, target, status, connectionCallback, new DisabledStreamListener());
// Delete source file after copy is complete
final Delete delete = new SDSDeleteFeature(session, nodeid);
if(delete.isSupported(source)) {
log.warn(String.format("Delete source %s copied to %s", source, target));
delete.delete(Collections.singletonMap(source, status), connectionCallback, callback);
}
return c;
}
else {
return proxy.move(source, target, status, callback, connectionCallback);
}
} | @Test
public void testMoveDifferentDataRoom() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room1 = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path room2 = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path test = new Path(room1, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new SDSTouchFeature(session, nodeid).touch(test, new TransferStatus());
final Path target = new Path(room2, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new SDSDelegatingMoveFeature(session, nodeid, new SDSMoveFeature(session, nodeid)).move(test, target, new TransferStatus(), new Delete.DisabledCallback(), new DisabledConnectionCallback());
test.attributes().setVersionId(null);
assertFalse(new SDSFindFeature(session, nodeid).find(test));
assertTrue(new SDSFindFeature(session, nodeid).find(target));
assertEquals(0, session.getMetrics().get(Copy.class));
new SDSDeleteFeature(session, nodeid).delete(Arrays.asList(room1, room2), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
@Override
public UltraLogLog getInitialAggregatedValue(Object rawValue) {
UltraLogLog initialValue;
if (rawValue instanceof byte[]) {
byte[] bytes = (byte[]) rawValue;
initialValue = deserializeAggregatedValue(bytes);
} else {
initialValue = UltraLogLog.create(_p);
addObjectToSketch(rawValue, initialValue);
}
return initialValue;
} | @Test
public void initialShouldCreateSingleItemULL() {
DistinctCountULLValueAggregator agg = new DistinctCountULLValueAggregator(Collections.emptyList());
assertEquals(
Math.round(agg.getInitialAggregatedValue("hello world").getDistinctCountEstimate()),
1.0);
} |
public ApplicationBuilder logger(String logger) {
this.logger = logger;
return getThis();
} | @Test
void logger() {
ApplicationBuilder builder = new ApplicationBuilder();
builder.logger("log4j");
Assertions.assertEquals("log4j", builder.build().getLogger());
} |
ProducerListeners listeners() {
return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0]));
} | @Test
public void fireProducerRestoreStartDontStopWhenOneFails() {
long version = 31337;
HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class);
Mockito.when(readState.getVersion()).thenReturn(version);
Mockito.doThrow(RuntimeException.class).when(listener).onProducerRestoreStart(version);
Status.RestoreStageBuilder b = new Status.RestoreStageBuilder();
listenerSupport.listeners().fireProducerRestoreComplete(b);
ArgumentCaptor<Status> status = ArgumentCaptor.forClass(
Status.class);
ArgumentCaptor<Long> desired = ArgumentCaptor.forClass(
long.class);
ArgumentCaptor<Long> reached = ArgumentCaptor.forClass(
long.class);
ArgumentCaptor<Duration> elapsed = ArgumentCaptor.forClass(
Duration.class);
Mockito.verify(listener).onProducerRestoreComplete(status.capture(), desired.capture(), reached.capture(), elapsed.capture());
Assert.assertNotNull(status.getValue());
Assert.assertNotNull(elapsed.getValue());
} |
@GetMapping(params = "checkNamespaceIdExist=true")
public Boolean checkNamespaceIdExist(@RequestParam("customNamespaceId") String namespaceId) {
if (StringUtils.isBlank(namespaceId)) {
return false;
}
return (namespacePersistService.tenantInfoCountByTenantId(namespaceId) > 0);
} | @Test
void testCheckNamespaceIdExist() throws Exception {
when(namespacePersistService.tenantInfoCountByTenantId("public")).thenReturn(1);
when(namespacePersistService.tenantInfoCountByTenantId("123")).thenReturn(0);
assertFalse(namespaceController.checkNamespaceIdExist(""));
assertTrue(namespaceController.checkNamespaceIdExist("public"));
assertFalse(namespaceController.checkNamespaceIdExist("123"));
} |
public double get(int index) {
return nonzeros[index];
} | @Test
public void testGet() {
System.out.println("get");
assertEquals(0.9, sparse.get(0, 0), 1E-7);
assertEquals(0.8, sparse.get(2, 2), 1E-7);
assertEquals(0.5, sparse.get(1, 1), 1E-7);
assertEquals(0.0, sparse.get(2, 0), 1E-7);
assertEquals(0.0, sparse.get(0, 2), 1E-7);
assertEquals(0.4, sparse.get(0, 1), 1E-7);
} |
public static Expression create(final String value) {
/* remove the start and end braces */
final String expression = stripBraces(value);
if (expression == null || expression.isEmpty()) {
throw new IllegalArgumentException("an expression is required.");
}
/* Check if the expression is too long */
if (expression.length() > MAX_EXPRESSION_LENGTH) {
throw new IllegalArgumentException(
"expression is too long. Max length: " + MAX_EXPRESSION_LENGTH);
}
/* create a new regular expression matcher for the expression */
String variableName = null;
String variablePattern = null;
String operator = null;
Matcher matcher = EXPRESSION_PATTERN.matcher(value);
if (matcher.matches()) {
/* grab the operator */
operator = matcher.group(2).trim();
/* we have a valid variable expression, extract the name from the first group */
variableName = matcher.group(3).trim();
if (variableName.contains(":")) {
/* split on the colon and ensure the size of parts array must be 2 */
String[] parts = variableName.split(":", 2);
variableName = parts[0];
variablePattern = parts[1];
}
/* look for nested expressions */
if (variableName.contains("{")) {
/* nested, literal */
return null;
}
}
/* check for an operator */
if (PATH_STYLE_OPERATOR.equalsIgnoreCase(operator)) {
return new PathStyleExpression(variableName, variablePattern);
}
/* default to simple */
return SimpleExpression.isSimpleExpression(value)
? new SimpleExpression(variableName, variablePattern)
: null; // Return null if it can't be validated as a Simple Expression -- Probably a Literal
} | @Test
void simpleExpression() {
Expression expression = Expressions.create("{foo}");
assertThat(expression).isNotNull();
String expanded = expression.expand(Collections.singletonMap("foo", "bar"), false);
assertThat(expanded).isEqualToIgnoringCase("foo=bar");
} |
public Connection connection(Connection connection) {
// It is common to implement both interfaces
if (connection instanceof XAConnection) {
return xaConnection((XAConnection) connection);
}
return TracingConnection.create(connection, this);
} | @Test void connection_doesntDoubleWrap() {
Connection wrapped = jmsTracing.connection(mock(Connection.class));
assertThat(jmsTracing.connection(wrapped))
.isSameAs(wrapped);
} |
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void findRecurringJobAnnotationsAndScheduleThem(RecorderContext recorderContext, CombinedIndexBuildItem index, BeanContainerBuildItem beanContainer, JobRunrRecurringJobRecorder recorder, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) throws NoSuchMethodException {
if (jobRunrBuildTimeConfiguration.jobScheduler().enabled()) {
new RecurringJobsFinder(recorderContext, index, beanContainer, recorder).findRecurringJobsAndScheduleThem();
}
} | @Test
void producesNoJobRunrRecurringJobsFinderIfJobSchedulerIsNotEnabled() throws NoSuchMethodException {
RecorderContext recorderContext = mock(RecorderContext.class);
CombinedIndexBuildItem combinedIndex = mock(CombinedIndexBuildItem.class);
BeanContainerBuildItem beanContainer = mock(BeanContainerBuildItem.class);
JobRunrRecurringJobRecorder recurringJobRecorder = mock(JobRunrRecurringJobRecorder.class);
when(jobSchedulerConfiguration.enabled()).thenReturn(false);
jobRunrExtensionProcessor.findRecurringJobAnnotationsAndScheduleThem(recorderContext, combinedIndex, beanContainer, recurringJobRecorder, jobRunrBuildTimeConfiguration);
verifyNoInteractions(recorderContext);
} |
@Override
public CompletableFuture<List<ConsumerGroupDescribeResponseData.DescribedGroup>> consumerGroupDescribe(
RequestContext context,
List<String> groupIds
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(ConsumerGroupDescribeRequest.getErrorDescribedGroupList(
groupIds,
Errors.COORDINATOR_NOT_AVAILABLE
));
}
final List<CompletableFuture<List<ConsumerGroupDescribeResponseData.DescribedGroup>>> futures =
new ArrayList<>(groupIds.size());
final Map<TopicPartition, List<String>> groupsByTopicPartition = new HashMap<>();
groupIds.forEach(groupId -> {
if (isGroupIdNotEmpty(groupId)) {
groupsByTopicPartition
.computeIfAbsent(topicPartitionFor(groupId), __ -> new ArrayList<>())
.add(groupId);
} else {
futures.add(CompletableFuture.completedFuture(Collections.singletonList(
new ConsumerGroupDescribeResponseData.DescribedGroup()
.setGroupId(null)
.setErrorCode(Errors.INVALID_GROUP_ID.code())
)));
}
});
groupsByTopicPartition.forEach((topicPartition, groupList) -> {
CompletableFuture<List<ConsumerGroupDescribeResponseData.DescribedGroup>> future =
runtime.scheduleReadOperation(
"consumer-group-describe",
topicPartition,
(coordinator, lastCommittedOffset) -> coordinator.consumerGroupDescribe(groupIds, lastCommittedOffset)
).exceptionally(exception -> handleOperationException(
"consumer-group-describe",
groupList,
exception,
(error, __) -> ConsumerGroupDescribeRequest.getErrorDescribedGroupList(groupList, error)
));
futures.add(future);
});
return FutureUtils.combineFutures(futures, ArrayList::new, List::addAll);
} | @Test
public void testConsumerGroupDescribe() throws InterruptedException, ExecutionException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
new GroupCoordinatorMetrics(),
createConfigManager()
);
int partitionCount = 2;
service.startup(() -> partitionCount);
ConsumerGroupDescribeResponseData.DescribedGroup describedGroup1 = new ConsumerGroupDescribeResponseData.DescribedGroup()
.setGroupId("group-id-1");
ConsumerGroupDescribeResponseData.DescribedGroup describedGroup2 = new ConsumerGroupDescribeResponseData.DescribedGroup()
.setGroupId("group-id-2");
List<ConsumerGroupDescribeResponseData.DescribedGroup> expectedDescribedGroups = Arrays.asList(
describedGroup1,
describedGroup2
);
when(runtime.scheduleReadOperation(
ArgumentMatchers.eq("consumer-group-describe"),
ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
ArgumentMatchers.any()
)).thenReturn(CompletableFuture.completedFuture(Collections.singletonList(describedGroup1)));
CompletableFuture<Object> describedGroupFuture = new CompletableFuture<>();
when(runtime.scheduleReadOperation(
ArgumentMatchers.eq("consumer-group-describe"),
ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 1)),
ArgumentMatchers.any()
)).thenReturn(describedGroupFuture);
CompletableFuture<List<ConsumerGroupDescribeResponseData.DescribedGroup>> future =
service.consumerGroupDescribe(requestContext(ApiKeys.CONSUMER_GROUP_DESCRIBE), Arrays.asList("group-id-1", "group-id-2"));
assertFalse(future.isDone());
describedGroupFuture.complete(Collections.singletonList(describedGroup2));
assertEquals(expectedDescribedGroups, future.get());
} |
@Override
public double p(int k) {
if (k < 0 || k > n) {
return 0.0;
} else {
return Math.floor(0.5 + exp(lfactorial(n) - lfactorial(k) - lfactorial(n - k))) * Math.pow(p, k) * Math.pow(1.0 - p, n - k);
}
} | @Test
public void testP() {
System.out.println("p");
BinomialDistribution instance = new BinomialDistribution(100, 0.3);
instance.rand();
assertEquals(3.234477e-16, instance.p(0), 1E-20);
assertEquals(1.386204e-14, instance.p(1), 1E-18);
assertEquals(1.170418e-06, instance.p(10), 1E-10);
assertEquals(0.007575645, instance.p(20), 1E-7);
assertEquals(0.08678386, instance.p(30), 1E-7);
assertEquals(5.153775e-53, instance.p(100), 1E-58);
} |
@Nonnull
public static String limit(@Nonnull String text, int max) {
return limit(text, null, max);
} | @Test
void testLimit() {
assertEquals("abcdefg", StringUtil.limit("abcdefg", 999));
assertEquals("abc", StringUtil.limit("abcdefg", 3));
assertEquals("", StringUtil.limit("abcdefg", 0));
assertEquals("", StringUtil.limit("abcdefg", -1));
assertEquals("abc...", StringUtil.limit("abcdefg", "...", 3));
} |
@Override
public boolean isTrusted(Address address) {
if (address == null) {
return false;
}
if (trustedInterfaces.isEmpty()) {
return true;
}
String host = address.getHost();
if (matchAnyInterface(host, trustedInterfaces)) {
return true;
} else {
if (logger.isFineEnabled()) {
logger.fine(
"Address %s doesn't match any trusted interface", host);
}
return false;
}
} | @Test
public void testIntervalRange() throws UnknownHostException {
AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.110-115.*"), logger);
assertTrue(joinMessageTrustChecker.isTrusted(createAddress("127.0.110.1")));
assertTrue(joinMessageTrustChecker.isTrusted(createAddress("127.0.112.1")));
assertTrue(joinMessageTrustChecker.isTrusted(createAddress("127.0.115.255")));
assertFalse(joinMessageTrustChecker.isTrusted(createAddress("127.0.116.255")));
assertFalse(joinMessageTrustChecker.isTrusted(createAddress("127.0.1.1")));
joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.110-115.1-2"), logger);
assertTrue(joinMessageTrustChecker.isTrusted(createAddress("127.0.110.2")));
assertFalse(joinMessageTrustChecker.isTrusted(createAddress("127.0.110.3")));
assertFalse(joinMessageTrustChecker.isTrusted(createAddress("127.0.109.2")));
} |
public void create() {
checkFilesAccessibility(bundledPlugins, externalPlugins);
reset();
MessageDigest md5Digest = DigestUtils.getMd5Digest();
try (ZipOutputStream zos = new ZipOutputStream(new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
for (GoPluginBundleDescriptor agentPlugins : agentPlugins()) {
String zipEntryPrefix = "external/";
if (agentPlugins.isBundledPlugin()) {
zipEntryPrefix = "bundled/";
}
zos.putNextEntry(new ZipEntry(zipEntryPrefix + new File(agentPlugins.bundleJARFileLocation()).getName()));
Files.copy(new File(agentPlugins.bundleJARFileLocation()).toPath(), zos);
zos.closeEntry();
}
} catch (Exception e) {
LOG.error("Could not create zip of plugins for agent to download.", e);
}
md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
} | @Test
void shouldCreateAZipWithOneCopyOfEachJar_ForAPluginBundleWithMultiplePluginsInIt() throws IOException {
File bundledPluginJarLocation = createPluginFile(bundledPluginsDir, "bundled-multi-plugin-1.jar", "Bundled1");
File externalPluginJarLocation = createPluginFile(externalPluginsDir, "external-multi-plugin-1.jar", "External1");
bundledTaskPlugin = new GoPluginBundleDescriptor(
getPluginDescriptor("bundled-plugin-1", bundledPluginJarLocation, true),
getPluginDescriptor("bundled-plugin-2", bundledPluginJarLocation, true)
);
externalTaskPlugin = new GoPluginBundleDescriptor(
getPluginDescriptor("external-plugin-1", externalPluginJarLocation, false),
getPluginDescriptor("external-plugin-2", externalPluginJarLocation, false)
);
when(pluginManager.plugins()).thenReturn(List.of(
bundledTaskPlugin.descriptors().get(0),
bundledTaskPlugin.descriptors().get(1),
externalTaskPlugin.descriptors().get(0),
externalTaskPlugin.descriptors().get(1)
));
when(pluginManager.isPluginOfType("task", "bundled-plugin-1")).thenReturn(true);
when(pluginManager.isPluginOfType("scm", "bundled-plugin-2")).thenReturn(true);
when(pluginManager.isPluginOfType("task", "external-plugin-1")).thenReturn(true);
when(pluginManager.isPluginOfType("artifact", "external-plugin-2")).thenReturn(true);
pluginsZip = spy(new PluginsZip(systemEnvironment, pluginManager));
pluginsZip.create();
try (ZipFile zipFile = new ZipFile(expectedZipPath)) {
assertThat(new File(expectedZipPath).exists()).as(expectedZipPath + " should exist").isTrue();
assertThat(EnumerationUtils.toList(zipFile.entries()).size()).isEqualTo(2);
assertThat(zipFile.getEntry("bundled/bundled-multi-plugin-1.jar")).isNotNull();
assertThat(zipFile.getEntry("external/external-multi-plugin-1.jar")).isNotNull();
}
} |
public static PointList sample(PointList input, double maxDistance, DistanceCalc distCalc, ElevationProvider elevation) {
PointList output = new PointList(input.size() * 2, input.is3D());
if (input.isEmpty()) return output;
int nodes = input.size();
double lastLat = input.getLat(0), lastLon = input.getLon(0), lastEle = input.getEle(0),
thisLat, thisLon, thisEle;
for (int i = 0; i < nodes; i++) {
thisLat = input.getLat(i);
thisLon = input.getLon(i);
thisEle = input.getEle(i);
if (i > 0) {
double segmentLength = distCalc.calcDist3D(lastLat, lastLon, lastEle, thisLat, thisLon, thisEle);
int segments = (int) Math.round(segmentLength / maxDistance);
// for small distances, we use a simple and fast approximation to interpolate between points
// for longer distances (or when crossing international date line) we use great circle interpolation
boolean exact = segmentLength > GREAT_CIRCLE_SEGMENT_LENGTH || distCalc.isCrossBoundary(lastLon, thisLon);
for (int segment = 1; segment < segments; segment++) {
double ratio = (double) segment / segments;
double lat, lon;
if (exact) {
GHPoint point = distCalc.intermediatePoint(ratio, lastLat, lastLon, thisLat, thisLon);
lat = point.getLat();
lon = point.getLon();
} else {
lat = lastLat + (thisLat - lastLat) * ratio;
lon = lastLon + (thisLon - lastLon) * ratio;
}
double ele = elevation.getEle(lat, lon);
if (!Double.isNaN(ele)) {
output.add(lat, lon, ele);
}
}
}
output.add(thisLat, thisLon, thisEle);
lastLat = thisLat;
lastLon = thisLon;
lastEle = thisEle;
}
return output;
} | @Test
public void addsExtraPointAboveThreshold() {
PointList in = new PointList(2, true);
in.add(0, 0, 0);
in.add(0.8, 0, 0);
PointList out = EdgeSampling.sample(
in,
DistanceCalcEarth.METERS_PER_DEGREE / 2,
new DistanceCalcEarth(),
elevation
);
assertEquals("(0.0,0.0,0.0), (0.4,0.0,10.0), (0.8,0.0,0.0)", round(out).toString());
} |
@Override
public ImmutableMap<K, V> removed(K key) {
return new PCollectionsImmutableMap<>(underlying().minus(key));
} | @Test
public void testDelegationOfRemoved() {
new PCollectionsHashMapWrapperDelegationChecker<>()
.defineMockConfigurationForFunctionInvocation(mock -> mock.minus(eq(this)), SINGLETON_MAP)
.defineWrapperFunctionInvocationAndMockReturnValueTransformation(wrapper -> wrapper.removed(this), identity())
.expectWrapperToWrapMockFunctionReturnValue()
.doFunctionDelegationCheck();
} |
public static void copyDirectory(File srcDir, File destDir) throws IOException {
FileUtils.copyDirectory(srcDir, destDir);
} | @Test
void testCopyDirectory() throws IOException {
Path srcPath = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString());
DiskUtils.forceMkdir(srcPath.toString());
File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut");
Path destPath = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString());
DiskUtils.copyDirectory(srcPath.toFile(), destPath.toFile());
File file = Paths.get(destPath.toString(), nacos.getName()).toFile();
assertTrue(file.exists());
DiskUtils.deleteDirectory(srcPath.toString());
DiskUtils.deleteDirectory(destPath.toString());
} |
@Override
public void applySchemaChange(SchemaChangeEvent schemaChangeEvent)
throws SchemaEvolveException {
if (!isOpened) {
isOpened = true;
catalog.open();
}
SchemaChangeEventVisitor.visit(
schemaChangeEvent,
addColumnEvent -> {
applyAddColumn(addColumnEvent);
return null;
},
alterColumnTypeEvent -> {
applyAlterColumnType(alterColumnTypeEvent);
return null;
},
createTableEvent -> {
applyCreateTable(createTableEvent);
return null;
},
dropColumnEvent -> {
applyDropColumn(dropColumnEvent);
return null;
},
dropTableEvent -> {
throw new UnsupportedSchemaChangeEventException(dropTableEvent);
},
renameColumnEvent -> {
applyRenameColumn(renameColumnEvent);
return null;
},
truncateTableEvent -> {
throw new UnsupportedSchemaChangeEventException(truncateTableEvent);
});
} | @Test
public void testCreateTable() throws Exception {
TableId tableId = TableId.parse("test.tbl1");
Schema schema =
Schema.newBuilder()
.physicalColumn("col1", new IntType())
.physicalColumn("col2", new BooleanType())
.physicalColumn("col3", new TimestampType())
.primaryKey("col1")
.build();
CreateTableEvent createTableEvent = new CreateTableEvent(tableId, schema);
metadataApplier.applySchemaChange(createTableEvent);
StarRocksTable actualTable =
catalog.getTable(tableId.getSchemaName(), tableId.getTableName()).orElse(null);
assertNotNull(actualTable);
List<StarRocksColumn> columns = new ArrayList<>();
columns.add(
new StarRocksColumn.Builder()
.setColumnName("col1")
.setOrdinalPosition(0)
.setDataType("int")
.setNullable(true)
.build());
columns.add(
new StarRocksColumn.Builder()
.setColumnName("col2")
.setOrdinalPosition(1)
.setDataType("boolean")
.setNullable(true)
.build());
columns.add(
new StarRocksColumn.Builder()
.setColumnName("col3")
.setOrdinalPosition(2)
.setDataType("datetime")
.setNullable(true)
.build());
StarRocksTable expectTable =
new StarRocksTable.Builder()
.setDatabaseName(tableId.getSchemaName())
.setTableName(tableId.getTableName())
.setTableType(StarRocksTable.TableType.PRIMARY_KEY)
.setColumns(columns)
.setTableKeys(schema.primaryKeys())
.setDistributionKeys(schema.primaryKeys())
.setNumBuckets(10)
.setTableProperties(Collections.singletonMap("replication_num", "5"))
.build();
assertEquals(expectTable, actualTable);
} |
public static WebService.NewParam createQualifiersParameter(WebService.NewAction action, QualifierParameterContext context) {
return createQualifiersParameter(action, context, getAllQualifiers(context.getResourceTypes()));
} | @Test
public void test_createQualifiersParameter() {
when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2));
when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam);
when(newParam.setDescription(startsWith("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. "
+ "Possible values are:"
+ "<ul><li>Q1 - null</li>"
+ "<li>Q2 - null</li></ul>"))).thenReturn(newParam);
when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam);
NewParam newParam = WsParameterBuilder
.createQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes));
assertThat(newParam).isNotNull();
} |
@Udf(description = "Returns the tangent of an INT value")
public Double tan(
@UdfParameter(
value = "value",
description = "The value in radians to get the tangent of."
) final Integer value
) {
return tan(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleMoreThanPositive2Pi() {
assertThat(udf.tan(9.1), closeTo(-0.33670052643287396, 0.000000000000001));
assertThat(udf.tan(6.3), closeTo(0.016816277694182057, 0.000000000000001));
assertThat(udf.tan(7), closeTo(0.8714479827243188, 0.000000000000001));
assertThat(udf.tan(7L), closeTo(0.8714479827243188, 0.000000000000001));
} |
@Override
public Deserializer deserializer(String topic, Target type) {
return switch (type) {
case KEY -> keyDeserializer();
case VALUE -> valueDeserializer();
};
} | @Test
void deserializesMessagesMadeByConsumerActivity() {
var serde = new ConsumerOffsetsSerde();
var keyDeserializer = serde.deserializer(TOPIC, Serde.Target.KEY);
var valueDeserializer = serde.deserializer(TOPIC, Serde.Target.VALUE);
try (var consumer = createConsumer(consumerGroupName + "-check")) {
consumer.subscribe(List.of(ConsumerOffsetsSerde.TOPIC));
List<Tuple2<DeserializeResult, DeserializeResult>> polled = new ArrayList<>();
Awaitility.await()
.pollInSameThread()
.atMost(Duration.ofMinutes(1))
.untilAsserted(() -> {
for (var rec : consumer.poll(Duration.ofMillis(200))) {
DeserializeResult key = rec.key() != null
? keyDeserializer.deserialize(null, rec.key().get())
: null;
DeserializeResult val = rec.value() != null
? valueDeserializer.deserialize(null, rec.value().get())
: null;
if (key != null && val != null) {
polled.add(Tuples.of(key, val));
}
}
assertThat(polled).anyMatch(t -> isCommitMessage(t.getT1(), t.getT2()));
assertThat(polled).anyMatch(t -> isGroupMetadataMessage(t.getT1(), t.getT2()));
});
}
} |
@Override
public void queuePermissionSyncTask(String submitterUuid, String componentUuid, String projectUuid) {
findManagedProjectService()
.ifPresent(managedProjectService -> managedProjectService.queuePermissionSyncTask(submitterUuid, componentUuid, projectUuid));
} | @Test
public void queuePermissionSyncTask_whenManagedNoInstanceServices_doesNotFail() {
assertThatNoException().isThrownBy(() -> NO_MANAGED_SERVICES.queuePermissionSyncTask("userUuid", "componentUuid", "projectUuid"));
} |
void writeInput(
JobVertexID jobVertexID, int subtaskIndex, InputChannelInfo info, Buffer buffer) {
try {
if (isDone()) {
return;
}
ChannelStatePendingResult pendingResult =
getChannelStatePendingResult(jobVertexID, subtaskIndex);
write(
pendingResult.getInputChannelOffsets(),
info,
buffer,
!pendingResult.isAllInputsReceived(),
"ChannelStateCheckpointWriter#writeInput");
} finally {
buffer.recycleBuffer();
}
} | @Test
void testRecyclingBuffers() {
ChannelStateCheckpointWriter writer = createWriter(new ChannelStateWriteResult());
NetworkBuffer buffer =
new NetworkBuffer(
MemorySegmentFactory.allocateUnpooledSegment(10),
FreeingBufferRecycler.INSTANCE);
writer.writeInput(JOB_VERTEX_ID, SUBTASK_INDEX, new InputChannelInfo(1, 2), buffer);
assertThat(buffer.isRecycled()).isTrue();
} |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
OptionParser optParser = new OptionParser();
OptionSpec<Long> offsetOpt = optParser.accepts("offset", "offset for reading input").withRequiredArg()
.ofType(Long.class).defaultsTo(Long.valueOf(0));
OptionSpec<Long> limitOpt = optParser.accepts("limit", "maximum number of records in the outputfile")
.withRequiredArg().ofType(Long.class).defaultsTo(Long.MAX_VALUE);
OptionSpec<Double> fracOpt = optParser.accepts("samplerate", "rate at which records will be collected")
.withRequiredArg().ofType(Double.class).defaultsTo(Double.valueOf(1));
OptionSet opts = optParser.parse(args.toArray(new String[0]));
List<String> nargs = (List<String>) opts.nonOptionArguments();
if (nargs.size() < 2) {
printHelp(out);
return 0;
}
inFiles = Util.getFiles(nargs.subList(0, nargs.size() - 1));
System.out.println("List of input files:");
for (Path p : inFiles) {
System.out.println(p);
}
currentInput = -1;
nextInput();
OutputStream output = out;
String lastArg = nargs.get(nargs.size() - 1);
if (nargs.size() > 1 && !lastArg.equals("-")) {
output = Util.createFromFS(lastArg);
}
writer = new DataFileWriter<>(new GenericDatumWriter<>());
String codecName = reader.getMetaString(DataFileConstants.CODEC);
CodecFactory codec = (codecName == null) ? CodecFactory.fromString(DataFileConstants.NULL_CODEC)
: CodecFactory.fromString(codecName);
writer.setCodec(codec);
for (String key : reader.getMetaKeys()) {
if (!DataFileWriter.isReservedMeta(key)) {
writer.setMeta(key, reader.getMeta(key));
}
}
writer.create(schema, output);
long offset = opts.valueOf(offsetOpt);
long limit = opts.valueOf(limitOpt);
double samplerate = opts.valueOf(fracOpt);
sampleCounter = 1;
totalCopied = 0;
reuse = null;
if (limit < 0) {
System.out.println("limit has to be non-negative");
this.printHelp(out);
return 1;
}
if (offset < 0) {
System.out.println("offset has to be non-negative");
this.printHelp(out);
return 1;
}
if (samplerate < 0 || samplerate > 1) {
System.out.println("samplerate has to be a number between 0 and 1");
this.printHelp(out);
return 1;
}
skip(offset);
writeRecords(limit, samplerate);
System.out.println(totalCopied + " records written.");
writer.flush();
writer.close();
Util.close(out);
return 0;
} | @Test
void offsetBiggerThanInput() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), "--offset", String.valueOf(ROWS_IN_INPUT_FILES + 1),
output.getAbsolutePath());
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(0, numRowsInFile(output), "output is not empty");
} |
@Override
public void deleteRewardActivity(Long id) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(id);
if (!dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 未关闭的活动,不能删除噢
throw exception(REWARD_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED);
}
// 删除
rewardActivityMapper.deleteById(id);
} | @Test
public void testDeleteRewardActivity_success() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbRewardActivity.getId();
// 调用
rewardActivityService.deleteRewardActivity(id);
// 校验数据不存在了
assertNull(rewardActivityMapper.selectById(id));
} |
public static String convertOperationName(RpcMessage rpcMessage) {
String requestSimpleName = rpcMessage.getBody().getClass().getSimpleName();
if (SeataPluginConfig.Plugin.SEATA.SERVER) {
return ComponentsDefine.SEATA.getName() + "/TC/" + requestSimpleName;
}
if (SWSeataConstants.isTransactionManagerOperationName(requestSimpleName)) {
return ComponentsDefine.SEATA.getName() + "/TM/" + requestSimpleName;
}
return ComponentsDefine.SEATA.getName() + "/RM/" + requestSimpleName;
} | @Test
public void testConvertOperationName() {
{
RpcMessage rpcMessage = new RpcMessage();
AbstractMessage abstractMessage = new GlobalBeginRequest();
rpcMessage.setBody(abstractMessage);
Assertions.assertEquals(SWSeataUtils.convertOperationName(rpcMessage), "Seata/TM/GlobalBeginRequest");
}
{
RpcMessage rpcMessage = new RpcMessage();
AbstractMessage abstractMessage = new RegisterRMRequest();
rpcMessage.setBody(abstractMessage);
Assertions.assertEquals(SWSeataUtils.convertOperationName(rpcMessage), "Seata/RM/RegisterRMRequest");
}
{
SeataPluginConfig.Plugin.SEATA.SERVER = true;
RpcMessage rpcMessage = new RpcMessage();
AbstractMessage abstractMessage = new RegisterRMResponse();
rpcMessage.setBody(abstractMessage);
Assertions.assertEquals(SWSeataUtils.convertOperationName(rpcMessage), "Seata/TC/RegisterRMResponse");
}
} |
public synchronized void ensureParentZNode()
throws IOException, InterruptedException, KeeperException {
Preconditions.checkState(!wantToBeInElection,
"ensureParentZNode() may not be called while in the election");
if (zkClient == null) {
createConnection();
}
String pathParts[] = znodeWorkingDir.split("/");
Preconditions.checkArgument(pathParts.length >= 1 &&
pathParts[0].isEmpty(),
"Invalid path: %s", znodeWorkingDir);
StringBuilder sb = new StringBuilder();
for (int i = 1; i < pathParts.length; i++) {
sb.append("/").append(pathParts[i]);
String prefixPath = sb.toString();
LOG.debug("Ensuring existence of " + prefixPath);
try {
createWithRetries(prefixPath, new byte[]{}, zkAcl, CreateMode.PERSISTENT);
} catch (KeeperException e) {
if (isNodeExists(e.code())) {
// Set ACLs for parent node, if they do not exist or are different
try {
setAclsWithRetries(prefixPath);
} catch (KeeperException e1) {
throw new IOException("Couldn't set ACLs on parent ZNode: " +
prefixPath, e1);
}
} else {
throw new IOException("Couldn't create " + prefixPath, e);
}
}
}
LOG.info("Successfully created " + znodeWorkingDir + " in ZK.");
} | @Test
public void testEnsureBaseNodeFails() throws Exception {
Mockito.doThrow(new KeeperException.ConnectionLossException())
.when(mockZK).create(
Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(),
Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT));
try {
elector.ensureParentZNode();
Assert.fail("Did not throw!");
} catch (IOException ioe) {
if (!(ioe.getCause() instanceof KeeperException.ConnectionLossException)) {
throw ioe;
}
}
// Should have tried three times
Mockito.verify(mockZK, Mockito.times(3)).create(
Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(),
Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT));
} |
@SuppressWarnings("unchecked")
public static <N> ImmutableGraph<N> emptyUndirectedGraph() {
return EMPTY_UNDIRECTED_GRAPH;
} | @Test
public void emptyUndirectedGraph() {
final ImmutableGraph<String> emptyGraph = Graphs.emptyUndirectedGraph();
assertThat(emptyGraph.isDirected()).isFalse();
assertThat(emptyGraph.nodes()).isEmpty();
assertThat(emptyGraph.edges()).isEmpty();
} |
public static <K, V> Write<K, V> write() {
return new AutoValue_KafkaIO_Write.Builder<K, V>()
.setWriteRecordsTransform(writeRecords())
.build();
} | @Test
public void testValuesSink() throws Exception {
// similar to testSink(), but use values()' interface.
int numElements = 1000;
try (MockProducerWrapper producerWrapper = new MockProducerWrapper(new LongSerializer())) {
ProducerSendCompletionThread completionThread =
new ProducerSendCompletionThread(producerWrapper.mockProducer).start();
String topic = "test";
p.apply(mkKafkaReadTransform(numElements, new ValueAsTimestampFn()).withoutMetadata())
.apply(Values.create()) // there are no keys
.apply(
KafkaIO.<Integer, Long>write()
.withBootstrapServers("none")
.withTopic(topic)
.withValueSerializer(LongSerializer.class)
.withProducerFactoryFn(new ProducerFactoryFn(producerWrapper.producerKey))
.values());
p.run();
completionThread.shutdown();
verifyProducerRecords(producerWrapper.mockProducer, topic, numElements, true, false);
}
} |
@Nullable static String getPropertyIfString(Message message, String name) {
try {
Object o = message.getObjectProperty(name);
if (o instanceof String) return o.toString();
return null;
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting property {0} from message {1}", name, message);
return null;
}
} | @Test void getPropertyIfString() throws Exception {
message.setStringProperty("b3", "1");
assertThat(MessageProperties.getPropertyIfString(message, "b3"))
.isEqualTo("1");
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
try {
if (statement.getStatement() instanceof CreateSource) {
final ConfiguredStatement<CreateSource> createStatement =
(ConfiguredStatement<CreateSource>) statement;
return (ConfiguredStatement<T>) forCreateStatement(createStatement).orElse(createStatement);
} else {
final ConfiguredStatement<CreateAsSelect> createStatement =
(ConfiguredStatement<CreateAsSelect>) statement;
return (ConfiguredStatement<T>) forCreateAsStatement(createStatement).orElse(
createStatement);
}
} catch (final KsqlStatementException e) {
throw e;
} catch (final KsqlException e) {
throw new KsqlStatementException(
ErrorMessageUtil.buildErrorMessage(e),
statement.getMaskedStatementText(),
e.getCause());
}
} | @Test
public void shouldThrowIfCsasKeyTableElementsNotCompatibleReorderedValue() {
// Given:
givenFormatsAndProps("kafka", "avro",
ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42)));
givenDDLSchemaAndFormats(LOGICAL_SCHEMA_VALUE_REORDERED, "kafka", "avro",
SerdeFeature.UNWRAP_SINGLES, SerdeFeature.UNWRAP_SINGLES);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> injector.inject(csasStatement)
);
// Then:
assertThat(e.getMessage(),
containsString("The following value columns are changed, missing or reordered: "
+ "[`bigIntField` BIGINT, `intField` INTEGER]. Schema from schema registry is ["
+ "`intField` INTEGER, "
+ "`bigIntField` BIGINT, "
+ "`doubleField` DOUBLE, "
+ "`stringField` STRING, "
+ "`booleanField` BOOLEAN, "
+ "`arrayField` ARRAY<INTEGER>, "
+ "`mapField` MAP<STRING, BIGINT>, "
+ "`structField` STRUCT<`s0` BIGINT>, "
+ "`decimalField` DECIMAL(4, 2)]"
)
);
} |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.getNodeInfos()) {
final NodeState nodeState = computeEffectiveNodeState(nodeInfo, params, nodeStateReasons);
workingState.setNodeState(nodeInfo.getNode(), nodeState);
}
takeDownGroupsWithTooLowAvailability(workingState, nodeStateReasons, params);
final Optional<ClusterStateReason> reasonToBeDown = clusterDownReason(workingState, params);
if (reasonToBeDown.isPresent()) {
workingState.setClusterState(State.DOWN);
}
workingState.setDistributionBits(inferDistributionBitCount(cluster, workingState, params));
return new AnnotatedClusterState(workingState, reasonToBeDown, nodeStateReasons);
} | @Test
void unstable_retired_node_should_be_marked_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(3, State.RETIRED);
final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 3));
nodeInfo.setPrematureCrashCount(11);
final AnnotatedClusterState state = ClusterStateGenerator.generatedStateFrom(params);
assertThat(state.toString(), equalTo("distributor:5 storage:5 .3.s:d"));
} |
@Override
public void unsubscribe() {
acquireAndEnsureOpen();
try {
fetchBuffer.retainAll(Collections.emptySet());
Timer timer = time.timer(Long.MAX_VALUE);
UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
applicationEventHandler.add(unsubscribeEvent);
log.info("Unsubscribing all topics or patterns and assigned partitions {}",
subscriptions.assignedPartitions());
try {
processBackgroundEvents(unsubscribeEvent.future(), timer);
log.info("Unsubscribed all topics or patterns and assigned partitions");
} catch (TimeoutException e) {
log.error("Failed while waiting for the unsubscribe event to complete");
}
resetGroupMetadata();
} catch (Exception e) {
log.error("Unsubscribe failed", e);
throw e;
} finally {
release();
}
} | @Test
public void testUnsubscribeWithoutGroupId() {
consumer = newConsumerWithoutGroupId();
completeUnsubscribeApplicationEventSuccessfully();
consumer.unsubscribe();
verify(applicationEventHandler).add(ArgumentMatchers.isA(UnsubscribeEvent.class));
} |
public static boolean haveSameId(Note note, Note currentNote) {
return currentNote != null
&& currentNote.get_id() != null
&& currentNote.get_id().equals(note.get_id());
} | @Test
public void haveSameIdShouldFail() {
var note1 = getNote(1L, "test title", "test content");
var note2 = getNote(2L, "test title", "test content");
assertFalse(NotesHelper.haveSameId(note1, note2));
} |
public static <N> ImmutableGraph<N> singletonDirectedGraph(N node) {
final MutableGraph<N> graph = GraphBuilder.directed().build();
graph.addNode(node);
return ImmutableGraph.copyOf(graph);
} | @Test
public void singletonDirectedGraph() {
final ImmutableGraph<String> singletonGraph = Graphs.singletonDirectedGraph("Test");
assertThat(singletonGraph.isDirected()).isTrue();
assertThat(singletonGraph.nodes()).containsExactly("Test");
assertThat(singletonGraph.edges()).isEmpty();
} |
public String vote(Set<String> candidates) {
for (JoinGroupRequestProtocol protocol : supportedProtocols) {
if (candidates.contains(protocol.name())) {
return protocol.name();
}
}
throw new IllegalArgumentException("Member does not support any of the candidate protocols");
} | @Test
public void testVoteForPreferredProtocol() {
JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestProtocolCollection();
protocols.add(new JoinGroupRequestProtocol()
.setName("range")
.setMetadata(new byte[0]));
protocols.add(new JoinGroupRequestProtocol()
.setName("roundrobin")
.setMetadata(new byte[0]));
ClassicGroupMember member = new ClassicGroupMember(
"member",
Optional.of("group-instance-id"),
"client-id",
"client-host",
10,
4500,
"generic",
protocols,
EMPTY_ASSIGNMENT
);
Set<String> expectedProtocolNames = new HashSet<>();
expectedProtocolNames.add("range");
expectedProtocolNames.add("roundrobin");
assertEquals("range", member.vote(expectedProtocolNames));
expectedProtocolNames.clear();
expectedProtocolNames.add("unknown");
expectedProtocolNames.add("roundrobin");
assertEquals("roundrobin", member.vote(expectedProtocolNames));
} |
@Override
public Integer call() throws Exception {
super.call();
try(DefaultHttpClient client = client()) {
MutableHttpRequest<Object> request = HttpRequest
.GET(apiUri("/flows/export/by-query") + (namespace != null ? "?namespace=" + namespace : ""))
.accept(MediaType.APPLICATION_OCTET_STREAM);
HttpResponse<byte[]> response = client.toBlocking().exchange(this.requestOptions(request), byte[].class);
Path zipFile = Path.of(directory.toString(), DEFAULT_FILE_NAME);
zipFile.toFile().createNewFile();
Files.write(zipFile, response.body());
stdOut("Exporting flow(s) for namespace '" + namespace + "' successfully done !");
} catch (HttpClientResponseException e) {
FlowValidateCommand.handleHttpException(e, "flow");
return 1;
}
return 0;
} | @Test
void run() throws IOException {
URL directory = FlowExportCommandTest.class.getClassLoader().getResource("flows");
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class);
embeddedServer.start();
// we use the update command to add flows to extract
String[] updateArgs = {
"--server",
embeddedServer.getURL().toString(),
"--user",
"myuser:pass:word",
"io.kestra.cli",
directory.getPath(),
};
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, updateArgs);
assertThat(out.toString(), containsString("3 flow(s)"));
// then we export them
String[] exportArgs = {
"--server",
embeddedServer.getURL().toString(),
"--user",
"myuser:pass:word",
"--namespace",
"io.kestra.cli",
"/tmp",
};
PicocliRunner.call(FlowExportCommand.class, ctx, exportArgs);
File file = new File("/tmp/flows.zip");
assertThat(file.exists(), is(true));
ZipFile zipFile = new ZipFile(file);
// When launching the test in a suite, there is 4 flows but when lauching individualy there is only 3
assertThat(zipFile.stream().count(), greaterThanOrEqualTo(3L));
file.delete();
}
} |
@Override
public int hashCode() {
return Objects.hash(supportJraft);
} | @Test
void testHashCode() throws JsonProcessingException {
ServerNamingAbility expected = new ServerNamingAbility();
expected.setSupportJraft(true);
String serializeJson = jacksonMapper.writeValueAsString(expected);
ServerNamingAbility actual = jacksonMapper.readValue(serializeJson, ServerNamingAbility.class);
assertEquals(expected, actual);
actual = new ServerNamingAbility();
assertNotEquals(expected, actual);
actual.setSupportJraft(true);
assertEquals(expected.hashCode(), actual.hashCode());
} |
@Override
public CompletableFuture<JoinGroupResponseData> joinGroup(
RequestContext context,
JoinGroupRequestData request,
BufferSupplier bufferSupplier
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(new JoinGroupResponseData()
.setMemberId(request.memberId())
.setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
);
}
if (!isGroupIdNotEmpty(request.groupId())) {
return CompletableFuture.completedFuture(new JoinGroupResponseData()
.setMemberId(request.memberId())
.setErrorCode(Errors.INVALID_GROUP_ID.code())
);
}
if (request.sessionTimeoutMs() < config.classicGroupMinSessionTimeoutMs() ||
request.sessionTimeoutMs() > config.classicGroupMaxSessionTimeoutMs()) {
return CompletableFuture.completedFuture(new JoinGroupResponseData()
.setMemberId(request.memberId())
.setErrorCode(Errors.INVALID_SESSION_TIMEOUT.code())
);
}
CompletableFuture<JoinGroupResponseData> responseFuture = new CompletableFuture<>();
runtime.scheduleWriteOperation(
"classic-group-join",
topicPartitionFor(request.groupId()),
Duration.ofMillis(config.offsetCommitTimeoutMs()),
coordinator -> coordinator.classicGroupJoin(context, request, responseFuture)
).exceptionally(exception -> {
if (!responseFuture.isDone()) {
responseFuture.complete(handleOperationException(
"classic-group-join",
request,
exception,
(error, __) -> new JoinGroupResponseData().setErrorCode(error.code())
));
}
return null;
});
return responseFuture;
} | @Test
public void testJoinGroupWhenNotStarted() throws ExecutionException, InterruptedException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
new GroupCoordinatorMetrics(),
createConfigManager()
);
JoinGroupRequestData request = new JoinGroupRequestData()
.setGroupId("foo");
CompletableFuture<JoinGroupResponseData> future = service.joinGroup(
requestContext(ApiKeys.JOIN_GROUP),
request,
BufferSupplier.NO_CACHING
);
assertEquals(
new JoinGroupResponseData()
.setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
future.get()
);
} |
@Override
public Type classify(final Throwable e) {
final Type type = SchemaRegistryUtil.isAuthErrorCode(e) ? Type.USER : Type.UNKNOWN;
if (type == Type.USER) {
LOG.info(
"Classified error as USER error based on missing SR subject access rights. "
+ "Query ID: {} Exception: {}",
queryId,
e);
}
return type;
} | @Test
public void shouldClassifySRAuthenticationErrorCodeAsUserError() {
// Given:
final Exception e = new RestClientException("foo", 401, 403101);
// When:
final QueryError.Type type = new SchemaAuthorizationClassifier("").classify(e);
// Then:
assertThat(type, is(QueryError.Type.USER));
} |
public static boolean isUnclosedQuote(final String line) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
int quoteStart = -1;
for (int i = 0; i < line.length(); ++i) {
if (quoteStart < 0 && isQuoteChar(line, i)) {
quoteStart = i;
} else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !isEscaped(line, i)) {
// Together, two quotes are effectively an escaped quote and don't act as a quote character.
// Skip the next quote char, since it's coupled with the first.
i++;
} else if (quoteStart >= 0 && isQuoteChar(line, i) && !isEscaped(line, i)) {
quoteStart = -1;
}
}
final int commentInd = line.indexOf(COMMENT);
if (commentInd < 0) {
return quoteStart >= 0;
} else if (quoteStart < 0) {
return false;
} else {
return commentInd > quoteStart;
}
} | @Test
public void shouldFindUnclosedQuote_twoQuote() {
// Given:
final String line = "some line 'this is in a quote''";
// Then:
assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(true));
} |
@SuppressWarnings("checkstyle:MissingSwitchDefault")
@Override
protected void doCommit(TableMetadata base, TableMetadata metadata) {
int version = currentVersion() + 1;
CommitStatus commitStatus = CommitStatus.FAILURE;
/* This method adds no fs scheme, and it persists in HTS that way. */
final String newMetadataLocation = rootMetadataFileLocation(metadata, version);
HouseTable houseTable = HouseTable.builder().build();
try {
// Now that we have metadataLocation we stamp it in metadata property.
Map<String, String> properties = new HashMap<>(metadata.properties());
failIfRetryUpdate(properties);
String currentTsString = String.valueOf(Instant.now(Clock.systemUTC()).toEpochMilli());
properties.put(getCanonicalFieldName("lastModifiedTime"), currentTsString);
if (base == null) {
properties.put(getCanonicalFieldName("creationTime"), currentTsString);
}
properties.put(
getCanonicalFieldName("tableVersion"),
properties.getOrDefault(
getCanonicalFieldName("tableLocation"), CatalogConstants.INITIAL_VERSION));
properties.put(getCanonicalFieldName("tableLocation"), newMetadataLocation);
String serializedSnapshotsToPut = properties.remove(CatalogConstants.SNAPSHOTS_JSON_KEY);
String serializedSnapshotRefs = properties.remove(CatalogConstants.SNAPSHOTS_REFS_KEY);
boolean isStageCreate =
Boolean.parseBoolean(properties.remove(CatalogConstants.IS_STAGE_CREATE_KEY));
logPropertiesMap(properties);
TableMetadata updatedMetadata = metadata.replaceProperties(properties);
if (serializedSnapshotsToPut != null) {
List<Snapshot> snapshotsToPut =
SnapshotsUtil.parseSnapshots(fileIO, serializedSnapshotsToPut);
Pair<List<Snapshot>, List<Snapshot>> snapshotsDiff =
SnapshotsUtil.symmetricDifferenceSplit(snapshotsToPut, updatedMetadata.snapshots());
List<Snapshot> appendedSnapshots = snapshotsDiff.getFirst();
List<Snapshot> deletedSnapshots = snapshotsDiff.getSecond();
snapshotInspector.validateSnapshotsUpdate(
updatedMetadata, appendedSnapshots, deletedSnapshots);
Map<String, SnapshotRef> snapshotRefs =
serializedSnapshotRefs == null
? new HashMap<>()
: SnapshotsUtil.parseSnapshotRefs(serializedSnapshotRefs);
updatedMetadata =
maybeAppendSnapshots(updatedMetadata, appendedSnapshots, snapshotRefs, true);
updatedMetadata = maybeDeleteSnapshots(updatedMetadata, deletedSnapshots);
}
final TableMetadata updatedMtDataRef = updatedMetadata;
metricsReporter.executeWithStats(
() ->
TableMetadataParser.write(updatedMtDataRef, io().newOutputFile(newMetadataLocation)),
InternalCatalogMetricsConstant.METADATA_UPDATE_LATENCY);
houseTable = houseTableMapper.toHouseTable(updatedMetadata);
if (!isStageCreate) {
houseTableRepository.save(houseTable);
} else {
/**
* Refresh current metadata for staged tables from newly created metadata file and disable
* "forced refresh" in {@link OpenHouseInternalTableOperations#commit(TableMetadata,
* TableMetadata)}
*/
refreshFromMetadataLocation(newMetadataLocation);
}
commitStatus = CommitStatus.SUCCESS;
} catch (InvalidIcebergSnapshotException e) {
throw new BadRequestException(e, e.getMessage());
} catch (CommitFailedException e) {
throw e;
} catch (HouseTableCallerException
| HouseTableNotFoundException
| HouseTableConcurrentUpdateException e) {
throw new CommitFailedException(e);
} catch (Throwable persistFailure) {
// Try to reconnect and determine the commit status for unknown exception
log.error(
"Encounter unexpected error while updating metadata.json for table:" + tableIdentifier,
persistFailure);
commitStatus = checkCommitStatus(newMetadataLocation, metadata);
switch (commitStatus) {
case SUCCESS:
log.debug("Calling doCommit succeeded");
break;
case FAILURE:
// logging error and exception-throwing co-existence is needed, given the exception
// handler in
// org.apache.iceberg.BaseMetastoreCatalog.BaseMetastoreCatalogTableBuilder.create swallow
// the
// nested exception information.
log.error("Exception details:", persistFailure);
throw new CommitFailedException(
persistFailure,
String.format(
"Persisting metadata file %s at version %s for table %s failed while persisting to house table",
newMetadataLocation, version, GSON.toJson(houseTable)));
case UNKNOWN:
throw new CommitStateUnknownException(persistFailure);
}
} finally {
switch (commitStatus) {
case FAILURE:
metricsReporter.count(InternalCatalogMetricsConstant.COMMIT_FAILED_CTR);
break;
case UNKNOWN:
metricsReporter.count(InternalCatalogMetricsConstant.COMMIT_STATE_UNKNOWN);
break;
default:
break; /*should never happen, kept to silence SpotBugs*/
}
}
} | @Test
void testDoCommitExceptionHandling() {
TableMetadata base = BASE_TABLE_METADATA;
TableMetadata metadata =
BASE_TABLE_METADATA.replaceProperties(ImmutableMap.of("random", "value"));
when(mockHouseTableRepository.save(Mockito.any(HouseTable.class)))
.thenThrow(HouseTableCallerException.class);
Assertions.assertThrows(
CommitFailedException.class,
() -> openHouseInternalTableOperations.doCommit(base, metadata));
when(mockHouseTableRepository.save(Mockito.any(HouseTable.class)))
.thenThrow(HouseTableConcurrentUpdateException.class);
Assertions.assertThrows(
CommitFailedException.class,
() -> openHouseInternalTableOperations.doCommit(base, metadata));
when(mockHouseTableRepository.save(Mockito.any(HouseTable.class)))
.thenThrow(HouseTableNotFoundException.class);
Assertions.assertThrows(
CommitFailedException.class,
() -> openHouseInternalTableOperations.doCommit(base, metadata));
when(mockHouseTableRepository.save(Mockito.any(HouseTable.class)))
.thenThrow(HouseTableRepositoryStateUnkownException.class);
Assertions.assertThrows(
CommitStateUnknownException.class,
() -> openHouseInternalTableOperations.doCommit(base, metadata));
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherValue) {
return 0;
}
if (null == thisValue) {
return NullsOrderType.FIRST == nullsOrderType ? -1 : 1;
}
if (null == otherValue) {
return NullsOrderType.FIRST == nullsOrderType ? 1 : -1;
}
if (!caseSensitive && thisValue instanceof String && otherValue instanceof String) {
return compareToCaseInsensitiveString((String) thisValue, (String) otherValue, orderDirection);
}
return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue);
} | @Test
void assertCompareToWhenFirstValueIsNullForOrderByDescAndNullsLast() {
assertThat(CompareUtils.compareTo(null, 1, OrderDirection.DESC, NullsOrderType.LAST, caseSensitive), is(1));
} |
public double getCenterX() {
return (this.left + this.right) / 2;
} | @Test
public void getCenterXTest() {
Rectangle rectangle = create(1, 2, 3, 4);
Assert.assertEquals(2, rectangle.getCenterX(), 0);
} |
@Override
public boolean support(AnnotatedElement annotatedEle) {
return ObjectUtil.isNotNull(annotatedEle);
} | @Test
public void getAnnotationsTest() {
final ElementAnnotationScanner scanner = new ElementAnnotationScanner();
final Field field = ReflectUtil.getField(FieldAnnotationScannerTest.Example.class, "id");
assertNotNull(field);
assertTrue(scanner.support(field));
List<Annotation> annotations = scanner.getAnnotations(field);
assertEquals(1, annotations.size());
assertEquals(AnnotationForScannerTest.class, CollUtil.getFirst(annotations).annotationType());
} |
@Override
public List<DictTypeDO> getDictTypeList() {
return dictTypeMapper.selectList();
} | @Test
public void testGetDictTypeList() {
// 准备参数
DictTypeDO dictTypeDO01 = randomDictTypeDO();
dictTypeMapper.insert(dictTypeDO01);
DictTypeDO dictTypeDO02 = randomDictTypeDO();
dictTypeMapper.insert(dictTypeDO02);
// mock 方法
// 调用
List<DictTypeDO> dictTypeDOList = dictTypeService.getDictTypeList();
// 断言
assertEquals(2, dictTypeDOList.size());
assertPojoEquals(dictTypeDO01, dictTypeDOList.get(0));
assertPojoEquals(dictTypeDO02, dictTypeDOList.get(1));
} |
@Override
public CompletableFuture<AckResult> changeInvisibleTime(ProxyContext ctx, ReceiptHandle handle, String messageId,
ChangeInvisibleTimeRequestHeader requestHeader, long timeoutMillis) {
SimpleChannel channel = channelManager.createChannel(ctx);
ChannelHandlerContext channelHandlerContext = channel.getChannelHandlerContext();
RemotingCommand command = LocalRemotingCommand.createRequestCommand(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, requestHeader, ctx.getLanguage());
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
try {
RemotingCommand response = brokerController.getChangeInvisibleTimeProcessor()
.processRequest(channelHandlerContext, command);
future.complete(response);
} catch (Exception e) {
log.error("Fail to process changeInvisibleTime command", e);
future.completeExceptionally(e);
}
return future.thenApply(r -> {
ChangeInvisibleTimeResponseHeader responseHeader = (ChangeInvisibleTimeResponseHeader) r.readCustomHeader();
AckResult ackResult = new AckResult();
if (ResponseCode.SUCCESS == r.getCode()) {
ackResult.setStatus(AckStatus.OK);
} else {
ackResult.setStatus(AckStatus.NO_EXIST);
}
ackResult.setPopTime(responseHeader.getPopTime());
ackResult.setExtraInfo(ReceiptHandle.builder()
.startOffset(handle.getStartOffset())
.retrieveTime(responseHeader.getPopTime())
.invisibleTime(responseHeader.getInvisibleTime())
.reviveQueueId(responseHeader.getReviveQid())
.topicType(handle.getTopicType())
.brokerName(handle.getBrokerName())
.queueId(handle.getQueueId())
.offset(handle.getOffset())
.build()
.encode());
return ackResult;
});
} | @Test
public void testChangeInvisibleTime() throws Exception {
String messageId = "messageId";
long popTime = System.currentTimeMillis();
long invisibleTime = 3000L;
int reviveQueueId = 1;
ReceiptHandle handle = ReceiptHandle.builder()
.startOffset(0L)
.retrieveTime(popTime)
.invisibleTime(invisibleTime)
.reviveQueueId(reviveQueueId)
.topicType(ReceiptHandle.NORMAL_TOPIC)
.brokerName(brokerName)
.queueId(queueId)
.offset(queueOffset)
.build();
RemotingCommand remotingCommand = RemotingCommand.createResponseCommand(ChangeInvisibleTimeResponseHeader.class);
remotingCommand.setCode(ResponseCode.SUCCESS);
remotingCommand.setRemark("");
long newPopTime = System.currentTimeMillis();
long newInvisibleTime = 5000L;
int newReviveQueueId = 2;
ChangeInvisibleTimeResponseHeader responseHeader = (ChangeInvisibleTimeResponseHeader) remotingCommand.readCustomHeader();
responseHeader.setReviveQid(newReviveQueueId);
responseHeader.setInvisibleTime(newInvisibleTime);
responseHeader.setPopTime(newPopTime);
Mockito.when(changeInvisibleTimeProcessorMock.processRequest(Mockito.any(SimpleChannelHandlerContext.class), Mockito.argThat(argument -> {
boolean first = argument.getCode() == RequestCode.CHANGE_MESSAGE_INVISIBLETIME;
boolean second = argument.readCustomHeader() instanceof ChangeInvisibleTimeRequestHeader;
return first && second;
}))).thenReturn(remotingCommand);
ChangeInvisibleTimeRequestHeader requestHeader = new ChangeInvisibleTimeRequestHeader();
CompletableFuture<AckResult> future = localMessageService.changeInvisibleTime(proxyContext, handle, messageId,
requestHeader, 1000L);
AckResult ackResult = future.get();
assertThat(ackResult.getStatus()).isEqualTo(AckStatus.OK);
assertThat(ackResult.getPopTime()).isEqualTo(newPopTime);
assertThat(ackResult.getExtraInfo()).isEqualTo(ReceiptHandle.builder()
.startOffset(0L)
.retrieveTime(newPopTime)
.invisibleTime(newInvisibleTime)
.reviveQueueId(newReviveQueueId)
.topicType(ReceiptHandle.NORMAL_TOPIC)
.brokerName(brokerName)
.queueId(queueId)
.offset(queueOffset)
.build()
.encode());
} |
public static void executeAction( DatabaseMeta databaseMeta, Consumer<Database> dbAction ) {
CompletableFuture.supplyAsync( () -> internalExec( databaseMeta, dbAction, new LoggingObject( databaseMeta ) ) )
.acceptEither( timeout(), r -> {
// no-op
} );
// ^ this trick is used to enforce a timeout on the async thread in Java8.
// With Java 9+ we can use the .orTimeout() method.
} | @Test
public void executeAction() throws InterruptedException, ExecutionException, TimeoutException {
CompletableFuture<List<Object[]>> rowMetaCompletion = new CompletableFuture<>();
AsyncDatabaseAction.executeAction( dbMeta, database -> {
try {
rowMetaCompletion.complete( database.getFirstRows( "BAR", 2 ) );
} catch ( KettleDatabaseException e ) {
throw new IllegalStateException( e );
}
} );
List<Object[]> rows = rowMetaCompletion.get( COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS );
assertThat( rows.size(), equalTo( 1 ) );
assertThat( rows.get( 0 )[ 0 ], equalTo( 123L ) );
assertThat( rows.get( 0 )[ 1 ], equalTo( 321L ) );
} |
private static Map<String, Set<Dependency>> checkOptionalFlags(
Map<String, Set<Dependency>> bundledDependenciesByModule,
Map<String, DependencyTree> dependenciesByModule) {
final Map<String, Set<Dependency>> allViolations = new HashMap<>();
for (String module : bundledDependenciesByModule.keySet()) {
LOG.debug("Checking module '{}'.", module);
if (!dependenciesByModule.containsKey(module)) {
throw new IllegalStateException(
String.format(
"Module %s listed by shade-plugin, but not dependency-plugin.",
module));
}
final Collection<Dependency> bundledDependencies =
bundledDependenciesByModule.get(module);
final DependencyTree dependencyTree = dependenciesByModule.get(module);
final Set<Dependency> violations =
checkOptionalFlags(module, bundledDependencies, dependencyTree);
if (violations.isEmpty()) {
LOG.info("OK: {}", module);
} else {
allViolations.put(module, violations);
}
}
return allViolations;
} | @Test
void testTransitiveBundledDependencyMayNotBeOptionalIfParentHasProvidedScope() {
final Dependency dependencyA = createProvidedDependency("a");
final Dependency dependencyB = createMandatoryDependency("b");
final Set<Dependency> bundled = Collections.singleton(dependencyB);
final DependencyTree dependencyTree =
new DependencyTree()
.addDirectDependency(dependencyA)
.addTransitiveDependencyTo(dependencyB, dependencyA);
final Set<Dependency> violations =
ShadeOptionalChecker.checkOptionalFlags(MODULE, bundled, dependencyTree);
assertThat(violations).isEmpty();
} |
public Map<String, String> getTypes(final Set<String> streamIds,
final Set<String> fields) {
final Map<String, Set<String>> allFieldTypes = this.get(streamIds);
final Map<String, String> result = new HashMap<>(fields.size());
fields.forEach(field -> {
final Set<String> fieldTypes = allFieldTypes.get(field);
typeFromFieldType(fieldTypes).ifPresent(s -> result.put(field, s));
});
return result;
} | @Test
void getTypesBehavesCorrectlyIfMultipleScenariosAreMixed() {
final Pair<IndexFieldTypesService, StreamService> services = mockServices(
IndexFieldTypesDTO.create("indexSet1", "stream1", Set.of(
FieldTypeDTO.create("good_field", "long"),
FieldTypeDTO.create("bad_field", "ip")
)),
IndexFieldTypesDTO.create("indexSet2", "stream2", Set.of(
FieldTypeDTO.create("good_field", "long"),
FieldTypeDTO.create("bad_field", "text")
))
);
final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight());
assertThat(lookup.getTypes(Set.of("stream1", "stream2"), Set.of("good_field", "bad_field", "unknown_field")))
.satisfies(result -> assertThat(result).doesNotContainKey("bad_field")) //different type in different streams
.satisfies(result -> assertThat(result).doesNotContainKey("unknown_field")) //no type info
.satisfies(result -> assertThat(result).containsEntry("good_field", "long")); //proper type info
} |
@Override
public void release(String pathInZooKeeper) throws Exception {
final String path = normalizePath(pathInZooKeeper);
final String lockPath = getInstanceLockPath(path);
try {
deleteIfExists(lockPath);
} catch (Exception e) {
throw new Exception("Could not release the lock: " + lockPath + '.', e);
}
} | @Test
void testRelease() throws Exception {
final TestingLongStateHandleHelper longStateStorage = new TestingLongStateHandleHelper();
ZooKeeperStateHandleStore<TestingLongStateHandleHelper.LongStateHandle> zkStore =
new ZooKeeperStateHandleStore<>(getZooKeeperClient(), longStateStorage);
final String path = "/state";
zkStore.addAndLock(path, new TestingLongStateHandleHelper.LongStateHandle(42L));
final String lockPath = zkStore.getInstanceLockPath(path);
Stat stat = getZooKeeperClient().checkExists().forPath(lockPath);
assertThat(stat).as("Expected an existing lock").isNotNull();
zkStore.release(path);
stat =
getZooKeeperClient()
.checkExists()
.forPath(ZooKeeperStateHandleStore.getRootLockPath(path));
// release should have removed the lock child
assertThat(stat.getNumChildren()).as("Expected no lock nodes as children").isZero();
zkStore.releaseAndTryRemove(path);
stat = getZooKeeperClient().checkExists().forPath(path);
assertThat(stat).as("State node should have been removed.").isNull();
} |
static CSInitializer build(String targetType) {
CSInitializer officialCSInitializer = tryLoadCSInitializerByClassName(targetType);
if (officialCSInitializer != null) {
return officialCSInitializer;
}
log.info("[CSInitializerFactory] try load CSInitializerFactory by name failed, start to use Reflections!");
// JAVA SPI 机制太笨了,短期内继续保留 Reflections 官网下高版本兼容性
Reflections reflections = new Reflections(OmsConstant.PACKAGE);
Set<Class<? extends CSInitializer>> cSInitializerClzSet = reflections.getSubTypesOf(CSInitializer.class);
log.info("[CSInitializerFactory] scan subTypeOf CSInitializer: {}", cSInitializerClzSet);
for (Class<? extends CSInitializer> clz : cSInitializerClzSet) {
try {
CSInitializer csInitializer = clz.getDeclaredConstructor().newInstance();
String type = csInitializer.type();
log.info("[CSInitializerFactory] new instance for CSInitializer[{}] successfully, type={}, object: {}", clz, type, csInitializer);
if (targetType.equalsIgnoreCase(type)) {
return csInitializer;
}
} catch (Exception e) {
log.error("[CSInitializerFactory] new instance for CSInitializer[{}] failed, maybe you should provide a non-parameter constructor", clz);
ExceptionUtils.rethrow(e);
}
}
throw new PowerJobException(String.format("can't load CSInitializer[%s], ensure your package name start with 'tech.powerjob' and import the dependencies!", targetType));
} | @Test
void testBuildNormal() {
CSInitializerFactory.build("TEST");
} |
public final boolean checkIfExecuted(String input) {
return this.validator.isExecuted(Optional.of(ByteString.copyFromUtf8(input)));
} | @Test
public void checkIfExecuted_withString_executesValidator() {
TestValidatorIsCalledValidator testValidator = new TestValidatorIsCalledValidator();
Payload payload = new Payload("my-payload", testValidator, PAYLOAD_ATTRIBUTES, CONFIG);
payload.checkIfExecuted("my-input");
assertTrue(testValidator.wasCalled);
} |
public String getFilesDirectoryPath() {
return this.context != null
? absPath(this.context.getFilesDir())
: "";
} | @Test
public void getFilesDirectoryPathIsNotEmpty() {
assertThat(contextUtil.getFilesDirectoryPath(), endsWith("/files"));
} |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
@Category({ValidatesRunner.class, UsesTestStream.class})
public void testReshuffleWithTimestampsStreaming() {
TestStream<Long> stream =
TestStream.create(VarLongCoder.of())
.advanceWatermarkTo(new Instant(0L).plus(Duration.standardDays(48L)))
.addElements(
TimestampedValue.of(0L, new Instant(0L)),
TimestampedValue.of(1L, new Instant(0L).plus(Duration.standardDays(48L))),
TimestampedValue.of(
2L, BoundedWindow.TIMESTAMP_MAX_VALUE.minus(Duration.standardDays(48L))))
.advanceWatermarkToInfinity();
PCollection<KV<String, Long>> input =
pipeline
.apply(stream)
.apply(WithKeys.of(""))
.apply(Window.into(FixedWindows.of(Duration.standardMinutes(10L))));
PCollection<KV<String, Long>> reshuffled = input.apply(Reshuffle.of());
PAssert.that(reshuffled.apply(Values.create())).containsInAnyOrder(0L, 1L, 2L);
pipeline.run();
} |
@Override
public DeleteGroupsRequest.Builder buildBatchedRequest(
int coordinatorId,
Set<CoordinatorKey> keys
) {
List<String> groupIds = keys.stream().map(key -> key.idValue).collect(Collectors.toList());
DeleteGroupsRequestData data = new DeleteGroupsRequestData()
.setGroupsNames(groupIds);
return new DeleteGroupsRequest.Builder(data);
} | @Test
public void testBuildRequest() {
DeleteConsumerGroupsHandler handler = new DeleteConsumerGroupsHandler(logContext);
DeleteGroupsRequest request = handler.buildBatchedRequest(1, singleton(CoordinatorKey.byGroupId(groupId1))).build();
assertEquals(1, request.data().groupsNames().size());
assertEquals(groupId1, request.data().groupsNames().get(0));
} |
@Override
public FinderLocalAttributes attributes() {
return new FinderLocalAttributes(this);
} | @Test
public void testWriteUnixPermission() throws Exception {
Local l = new FinderLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
new DefaultLocalTouchFeature().touch(l);
final Permission permission = new Permission(644);
l.attributes().setPermission(permission);
assertEquals(permission, l.attributes().getPermission());
l.delete();
} |
@Override
public ModelLocalUriId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonNode node = p.getCodec().readTree(p);
String path = node.get("fullPath").asText();
return new ModelLocalUriId(LocalUri.parse(path));
} | @Test
void deserializeDecodedPath() throws IOException {
String json = "{\"model\":\"example\",\"basePath\":\"/some-id/instances/some-instance-id\"," +
"\"fullPath\":\"/example/some-id/instances/some-instance-id\"}";
ObjectMapper mapper = new ObjectMapper();
InputStream stream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
JsonParser parser = mapper.getFactory().createParser(stream);
DeserializationContext ctxt = mapper.getDeserializationContext();
ModelLocalUriId retrieved = new ModelLocalUriIdDeSerializer().deserialize(parser, ctxt);
String path = "/example/some-id/instances/some-instance-id";
LocalUri parsed = LocalUri.parse(path);
ModelLocalUriId expected = new ModelLocalUriId(parsed);
assertThat(retrieved).isEqualTo(expected);
} |
public File getExecutable() {
return new File(homeDirectory, "bin/elasticsearch");
} | @Test
public void getExecutable_resolve_executable_for_platform() throws IOException {
File sqHomeDir = temp.newFolder();
Props props = new Props(new Properties());
props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath());
props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath());
props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath());
props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath());
EsInstallation underTest = new EsInstallation(props);
assertThat(underTest.getExecutable()).isEqualTo(new File(sqHomeDir, "elasticsearch/bin/elasticsearch"));
} |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "logs/{executionId}")
@Operation(tags = {"Logs"}, summary = "Delete logs for a specific execution, taskrun or task")
public void delete(
@Parameter(description = "The execution id") @PathVariable String executionId,
@Parameter(description = "The min log level filter") @Nullable @QueryValue Level minLevel,
@Parameter(description = "The taskrun id") @Nullable @QueryValue String taskRunId,
@Parameter(description = "The task id") @Nullable @QueryValue String taskId,
@Parameter(description = "The attempt number") @Nullable @QueryValue Integer attempt
) {
logRepository.deleteByQuery(tenantService.resolveTenant(), executionId, taskId, taskRunId, minLevel, attempt);
} | @SuppressWarnings("unchecked")
@Test
void delete() {
LogEntry log1 = logEntry(Level.INFO);
LogEntry log2 = log1.toBuilder().message("another message").build();
LogEntry log3 = logEntry(Level.DEBUG);
logRepository.save(log1);
logRepository.save(log2);
logRepository.save(log3);
HttpResponse<?> delete = client.toBlocking().exchange(
HttpRequest.DELETE("/api/v1/logs/" + log1.getExecutionId())
);
assertThat(delete.getStatus(), is(HttpStatus.OK));
List<LogEntry> logs = client.toBlocking().retrieve(
HttpRequest.GET("/api/v1/logs/" + log1.getExecutionId()),
Argument.of(List.class, LogEntry.class)
);
assertThat(logs.size(), is(0));
} |
public static MetricsReporter combine(MetricsReporter first, MetricsReporter second) {
if (null == first) {
return second;
} else if (null == second || first == second) {
return first;
}
Set<MetricsReporter> reporters = Sets.newIdentityHashSet();
if (first instanceof CompositeMetricsReporter) {
reporters.addAll(((CompositeMetricsReporter) first).reporters());
} else {
reporters.add(first);
}
if (second instanceof CompositeMetricsReporter) {
reporters.addAll(((CompositeMetricsReporter) second).reporters());
} else {
reporters.add(second);
}
return new CompositeMetricsReporter(reporters);
} | @Test
public void combineSimpleReporters() {
MetricsReporter first = report -> {};
MetricsReporter second = report -> {};
MetricsReporter combined = MetricsReporters.combine(first, second);
assertThat(combined).isInstanceOf(MetricsReporters.CompositeMetricsReporter.class);
assertThat(((MetricsReporters.CompositeMetricsReporter) combined).reporters())
.hasSize(2)
.containsExactlyInAnyOrder(first, second);
} |
@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(pulsar.getWebServiceAddress(), pulsar.getWebServiceAddressTls(),
pulsar.getBrokerServiceUrl(), pulsar.getBrokerServiceUrlTls(), pulsar.getAdvertisedListeners());
lastData.setProtocols(protocolData);
// configure broker-topic mode
lastData.setPersistentTopicsEnabled(pulsar.getConfiguration().isEnablePersistentTopics());
lastData.setNonPersistentTopicsEnabled(pulsar.getConfiguration().isEnableNonPersistentTopics());
localData = new LocalBrokerData(pulsar.getWebServiceAddress(), pulsar.getWebServiceAddressTls(),
pulsar.getBrokerServiceUrl(), pulsar.getBrokerServiceUrlTls(), pulsar.getAdvertisedListeners());
localData.setProtocols(protocolData);
localData.setBrokerVersionString(pulsar.getBrokerVersion());
// configure broker-topic mode
localData.setPersistentTopicsEnabled(pulsar.getConfiguration().isEnablePersistentTopics());
localData.setNonPersistentTopicsEnabled(pulsar.getConfiguration().isEnableNonPersistentTopics());
localData.setLoadManagerClassName(conf.getLoadManagerClassName());
String brokerId = pulsar.getBrokerId();
brokerZnodePath = LoadManager.LOADBALANCE_BROKERS_ROOT + "/" + brokerId;
updateLocalBrokerData();
brokerDataLock = brokersData.acquireLock(brokerZnodePath, localData).join();
pulsarResources.getLoadBalanceResources()
.getBrokerTimeAverageDataResources()
.updateTimeAverageBrokerData(brokerId, new TimeAverageBrokerData())
.join();
updateAll();
} catch (Exception e) {
log.error("Unable to acquire lock for broker: [{}]", brokerZnodePath, e);
throw new PulsarServerException(e);
}
} | @Test
public void testBrokerAffinity() throws Exception {
// Start broker 3
pulsar3.start();
final String tenant = "test";
final String cluster = "test";
String namespace = tenant + "/" + cluster + "/" + "test";
String topic = "persistent://" + namespace + "/my-topic1";
admin1.clusters().createCluster(cluster, ClusterData.builder().serviceUrl(pulsar1.getWebServiceAddress()).build());
admin1.tenants().createTenant(tenant,
new TenantInfoImpl(Sets.newHashSet("appid1", "appid2"), Sets.newHashSet(cluster)));
admin1.namespaces().createNamespace(namespace, 16);
String topicLookup = admin1.lookups().lookupTopic(topic);
String bundleRange = admin1.lookups().getBundleRange(topic);
String brokerServiceUrl = pulsar1.getBrokerServiceUrl();
String brokerId = pulsar1.getBrokerId();
log.debug("initial broker service url - {}", topicLookup);
Random rand=new Random();
if (topicLookup.equals(brokerServiceUrl)) {
int x = rand.nextInt(2);
if (x == 0) {
brokerId = pulsar2.getBrokerId();
brokerServiceUrl = pulsar2.getBrokerServiceUrl();
}
else {
brokerId = pulsar3.getBrokerId();
brokerServiceUrl = pulsar3.getBrokerServiceUrl();
}
}
log.debug("destination broker service url - {}, broker url - {}", brokerServiceUrl, brokerId);
String leaderBrokerId = admin1.brokers().getLeaderBroker().getBrokerId();
log.debug("leader lookup address - {}, broker1 lookup address - {}", leaderBrokerId,
pulsar1.getBrokerId());
// Make a call to broker which is not a leader
if (!leaderBrokerId.equals(pulsar1.getBrokerId())) {
admin1.namespaces().unloadNamespaceBundle(namespace, bundleRange, brokerId);
}
else {
admin2.namespaces().unloadNamespaceBundle(namespace, bundleRange, brokerId);
}
sleep(2000);
String topicLookupAfterUnload = admin1.lookups().lookupTopic(topic);
log.debug("final broker service url - {}", topicLookupAfterUnload);
Assert.assertEquals(brokerServiceUrl, topicLookupAfterUnload);
} |
static void validateDependencies(Set<Artifact> dependencies, Set<String> allowedRules, boolean failOnUnmatched)
throws EnforcerRuleException {
SortedSet<Artifact> unmatchedArtifacts = new TreeSet<>();
Set<String> matchedRules = new HashSet<>();
for (Artifact dependency : dependencies) {
boolean matches = false;
for (String rule : allowedRules) {
if (matches(dependency, rule)){
matchedRules.add(rule);
matches = true;
break;
}
}
if (!matches) {
unmatchedArtifacts.add(dependency);
}
}
SortedSet<String> unmatchedRules = new TreeSet<>(allowedRules);
unmatchedRules.removeAll(matchedRules);
if (!unmatchedArtifacts.isEmpty() || (failOnUnmatched && !unmatchedRules.isEmpty())) {
StringBuilder errorMessage = new StringBuilder("Vespa dependency enforcer failed:\n");
if (!unmatchedArtifacts.isEmpty()) {
errorMessage.append("Dependencies not matching any rule:\n");
unmatchedArtifacts.forEach(a -> errorMessage.append(" - ").append(a.toString()).append('\n'));
}
if (failOnUnmatched && !unmatchedRules.isEmpty()) {
errorMessage.append("Rules not matching any dependency:\n");
unmatchedRules.forEach(p -> errorMessage.append(" - ").append(p).append('\n'));
}
throw new EnforcerRuleException(errorMessage.toString());
}
} | @Test
void matches_artifact_with_classifier() {
Set<Artifact> dependencies = Set.of(
artifact("com.google.inject", "guice", "4.2.3", "provided", "no_aop"));
assertDoesNotThrow(() -> EnforceDependencies.validateDependencies(
dependencies, Set.of("com.google.inject:guice:jar:no_aop:4.2.3:provided"), true));
EnforcerRuleException exception = assertThrows(
EnforcerRuleException.class,
() -> EnforceDependencies.validateDependencies(
dependencies, Set.of("com.google.inject:guice:4.2.3:provided"), true));
String expectedErrorMessage =
"""
Vespa dependency enforcer failed:
Dependencies not matching any rule:
- com.google.inject:guice:jar:no_aop:4.2.3:provided
Rules not matching any dependency:
- com.google.inject:guice:4.2.3:provided
""";
assertEquals(expectedErrorMessage, exception.getMessage());
} |
@Override
public void deleteDiyTemplate(Long id) {
// 校验存在
DiyTemplateDO diyTemplateDO = validateDiyTemplateExists(id);
// 校验使用中
if (BooleanUtil.isTrue(diyTemplateDO.getUsed())) {
throw exception(DIY_TEMPLATE_USED_CANNOT_DELETE);
}
// 删除
diyTemplateMapper.deleteById(id);
} | @Test
public void testDeleteDiyTemplate_success() {
// mock 数据
DiyTemplateDO dbDiyTemplate = randomPojo(DiyTemplateDO.class);
diyTemplateMapper.insert(dbDiyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbDiyTemplate.getId();
// 调用
diyTemplateService.deleteDiyTemplate(id);
// 校验数据不存在了
assertNull(diyTemplateMapper.selectById(id));
} |
public static List<String> findAll(String regex, CharSequence content, int group) {
return findAll(regex, content, group, new ArrayList<>());
} | @Test
public void findAllTest() {
// 查找所有匹配文本
final List<String> resultFindAll = ReUtil.findAll("\\w{2}", content, 0, new ArrayList<>());
final ArrayList<String> expected = CollectionUtil.newArrayList("ZZ", "Za", "aa", "bb", "bc", "cc", "12", "34");
assertEquals(expected, resultFindAll);
} |
public static List<String> parseLocationsFromConfig() throws InvalidConfException {
List<String> locations = new ArrayList<>();
URI uri;
switch (Config.cloud_native_storage_type.toLowerCase()) {
case "s3":
uri = normalizeConfigPath(Config.aws_s3_path, "s3", "Config.aws_s3_path", true);
locations.add(uri.toString());
break;
case "hdfs":
// no need to validate the scheme, it can be hdfs compatible filesystem with customer defined scheme such as: viewfs, webhdfs, ...
uri = normalizeConfigPath(Config.cloud_native_hdfs_url, "hdfs", "Config.cloud_native_hdfs_url", false);
locations.add(uri.toString());
break;
case "azblob":
uri = normalizeConfigPath(Config.azure_blob_path, "azblob", "Config.azure_blob_path", true);
locations.add(uri.toString());
break;
default:
return locations;
}
return locations;
} | @Test
public void testParseLocationsFromConfig() throws InvalidConfException {
Config.cloud_native_storage_type = "s3";
Config.aws_s3_path = "default-bucket/1";
{
List<String> locations = SharedDataStorageVolumeMgr.parseLocationsFromConfig();
Assert.assertEquals(1, locations.size());
Assert.assertEquals("s3://default-bucket/1", locations.get(0));
}
// with s3:// prefix
Config.aws_s3_path = "s3://default-bucket/1";
{
List<String> locations = SharedDataStorageVolumeMgr.parseLocationsFromConfig();
Assert.assertEquals(1, locations.size());
Assert.assertEquals("s3://default-bucket/1", locations.get(0));
}
Config.aws_s3_path = "s3://default-bucket";
{
List<String> locations = SharedDataStorageVolumeMgr.parseLocationsFromConfig();
Assert.assertEquals(1, locations.size());
Assert.assertEquals("s3://default-bucket", locations.get(0));
}
Config.aws_s3_path = "s3://default-bucket/";
{
List<String> locations = SharedDataStorageVolumeMgr.parseLocationsFromConfig();
Assert.assertEquals(1, locations.size());
Assert.assertEquals("s3://default-bucket/", locations.get(0));
}
// with invalid prefix
Config.aws_s3_path = "://default-bucket/1";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
// with wrong prefix
Config.aws_s3_path = "hdfs://default-bucket/1";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
Config.aws_s3_path = "s3://";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
Config.aws_s3_path = "bucketname:30/b";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
Config.aws_s3_path = "/";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
Config.aws_s3_path = "";
Assert.assertThrows(InvalidConfException.class, SharedDataStorageVolumeMgr::parseLocationsFromConfig);
Config.cloud_native_storage_type = "hdfs";
Config.cloud_native_hdfs_url = "hdfs://url";
{
List<String> locations = SharedDataStorageVolumeMgr.parseLocationsFromConfig();
Assert.assertEquals(1, locations.size());
Assert.assertEquals("hdfs://url", locations.get(0));
}
} |
@Override
public MergeAppend appendFile(DataFile file) {
add(file);
return this;
} | @TestTemplate
public void testFailure() {
// merge all manifests for this test
table.updateProperties().set("commit.manifest.min-count-to-merge", "1").commit();
assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0);
Snapshot snap = commit(table, table.newAppend().appendFile(FILE_A), branch);
TableMetadata base = readMetadata();
long baseId = snap.snapshotId();
V2Assert.assertEquals("Last sequence number should be 1", 1, base.lastSequenceNumber());
V1Assert.assertEquals(
"Table should end with last-sequence-number 0", 0, base.lastSequenceNumber());
ManifestFile initialManifest = snap.allManifests(table.io()).get(0);
validateManifest(
initialManifest,
dataSeqs(1L),
fileSeqs(1L),
ids(baseId),
files(FILE_A),
statuses(Status.ADDED));
table.ops().failCommits(5);
AppendFiles append = table.newAppend().appendFile(FILE_B);
Snapshot pending = apply(append, branch);
assertThat(pending.allManifests(table.io())).hasSize(1);
ManifestFile newManifest = pending.allManifests(table.io()).get(0);
assertThat(new File(newManifest.path())).exists();
validateManifest(
newManifest,
ids(pending.snapshotId(), baseId),
concat(files(FILE_B), files(initialManifest)));
assertThatThrownBy(() -> commit(table, append, branch))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Injected failure");
V2Assert.assertEquals(
"Last sequence number should be 1", 1, readMetadata().lastSequenceNumber());
V1Assert.assertEquals(
"Table should end with last-sequence-number 0", 0, readMetadata().lastSequenceNumber());
assertThat(latestSnapshot(table, branch).allManifests(table.io())).hasSize(1);
validateManifest(
latestSnapshot(table, branch).allManifests(table.io()).get(0),
dataSeqs(1L),
fileSeqs(1L),
ids(baseId),
files(initialManifest),
statuses(Status.ADDED));
assertThat(new File(newManifest.path())).doesNotExist();
} |
@Override
public ObjectNode encode(TrafficSelector selector, CodecContext context) {
checkNotNull(selector, "Traffic selector cannot be null");
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonCriteria = result.putArray(CRITERIA);
if (selector.criteria() != null) {
final JsonCodec<Criterion> criterionCodec =
context.codec(Criterion.class);
for (final Criterion criterion : selector.criteria()) {
jsonCriteria.add(criterionCodec.encode(criterion, context));
}
}
return result;
} | @Test
public void testTrafficSelectorEncode() {
Criterion inPort = Criteria.matchInPort(PortNumber.portNumber(0));
Criterion ethSrc = Criteria.matchEthSrc(MacAddress.valueOf("11:22:33:44:55:66"));
Criterion ethDst = Criteria.matchEthDst(MacAddress.valueOf("44:55:66:77:88:99"));
Criterion ethType = Criteria.matchEthType(Ethernet.TYPE_IPV4);
TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
TrafficSelector selector = sBuilder
.add(inPort)
.add(ethSrc)
.add(ethDst)
.add(ethType)
.build();
ObjectNode selectorJson = trafficSelectorCodec.encode(selector, context);
assertThat(selectorJson, TrafficSelectorJsonMatcher.matchesTrafficSelector(selector));
} |
@Override
public void putJobResourceRequirements(
JobID jobId, JobResourceRequirements jobResourceRequirements) throws Exception {
synchronized (lock) {
@Nullable final JobGraph jobGraph = recoverJobGraph(jobId);
if (jobGraph == null) {
throw new NoSuchElementException(
String.format(
"JobGraph for job [%s] was not found in JobGraphStore and is needed for attaching JobResourceRequirements.",
jobId));
}
JobResourceRequirements.writeToJobGraph(jobGraph, jobResourceRequirements);
putJobGraph(jobGraph);
}
} | @Test
public void testPutJobResourceRequirementsOfNonExistentJob() throws Exception {
final TestingStateHandleStore<JobGraph> stateHandleStore =
builder.setGetFunction(
ignore -> {
throw new StateHandleStore.NotExistException("Does not exist.");
})
.build();
final JobGraphStore jobGraphStore = createAndStartJobGraphStore(stateHandleStore);
assertThrows(
NoSuchElementException.class,
() ->
jobGraphStore.putJobResourceRequirements(
new JobID(), JobResourceRequirements.empty()));
} |
@Override
public DataSourceConfigDO getDataSourceConfig(Long id) {
// 如果 id 为 0,默认为 master 的数据源
if (Objects.equals(id, DataSourceConfigDO.ID_MASTER)) {
return buildMasterDataSourceConfig();
}
// 从 DB 中读取
return dataSourceConfigMapper.selectById(id);
} | @Test
public void testGetDataSourceConfig_master() {
// 准备参数
Long id = 0L;
// mock 方法
// 调用
DataSourceConfigDO dataSourceConfig = dataSourceConfigService.getDataSourceConfig(id);
// 断言
assertEquals(id, dataSourceConfig.getId());
assertEquals("primary", dataSourceConfig.getName());
assertEquals("http://localhost:3306", dataSourceConfig.getUrl());
assertEquals("yunai", dataSourceConfig.getUsername());
assertEquals("tudou", dataSourceConfig.getPassword());
} |
public static <T> T get(Class<T> clazz, Object... params) {
Assert.notNull(clazz, "Class must be not null !");
final String key = buildKey(clazz.getName(), params);
return get(key, () -> ReflectUtil.newInstance(clazz, params));
} | @Test
public void getTest(){
// 此测试中使用1000个线程获取单例对象,其间对象只被创建一次
ThreadUtil.concurrencyTest(1000, ()-> Singleton.get(TestBean.class));
} |
public static boolean isWebService(Optional<String> serviceName) {
return serviceName.isPresent()
&& IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey(
Ascii.toLowerCase(serviceName.get()));
} | @Test
public void isWebService_whenHttpService_returnsTrue() {
assertThat(
NetworkServiceUtils.isWebService(
NetworkService.newBuilder().setServiceName("http").build()))
.isTrue();
} |
public void execute() {
Profiler stepProfiler = Profiler.create(LOGGER).logTimeLast(true);
boolean allStepsExecuted = false;
try {
executeSteps(stepProfiler);
allStepsExecuted = true;
} finally {
if (listener != null) {
executeListener(allStepsExecuted);
}
}
} | @Test
public void execute_throws_IAE_if_step_adds_time_statistic() {
ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "time", "20");
try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) {
assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Statistic with key [time] is not accepted");
}
} |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchingFunctionException(arguments);
}
// if none were found (candidate isn't present) try again with implicit casting
candidate = findMatchingCandidate(arguments, true);
if (candidate.isPresent()) {
return candidate.get();
}
throw createNoMatchingFunctionException(arguments);
} | @Test
public void shouldFindNonVarargWithPartialNullValues() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING, STRING)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Arrays.asList(null, SqlArgument.of(SqlTypes.STRING)));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
} |
public String getCallbackUri(String secretString) {
String cbid = cbidGenerator.generate(secretString);
if (!isValidPortNumber(callbackPort)) {
throw new AssertionError("Invalid callbackPort number specified");
}
HostAndPort hostAndPort =
callbackPort == 80
? HostAndPort.fromHost(callbackAddress)
: HostAndPort.fromParts(callbackAddress, callbackPort);
// check if the specified address is raw IP or domain
if (InetAddresses.isInetAddress(callbackAddress)) {
return CbidProcessor.addCbidToUrl(cbid, hostAndPort);
} else if (InternetDomainName.isValid(callbackAddress)) {
return CbidProcessor.addCbidToSubdomain(cbid, hostAndPort);
}
// Should never reach here
throw new AssertionError("Unrecognized address format, should be Ip address or valid domain");
} | @Test
public void getCallbackUri_validIpv4Address_returnsUriWithCbidInPath() {
client = new TcsClient(VALID_IPV4_ADDRESS, VALID_PORT, VALID_URL, httpClient);
String url = client.getCallbackUri(SECRET);
String expectedUriString =
String.format("http://%s:%d/%s", VALID_IPV4_ADDRESS, VALID_PORT, CBID);
assertThat(url).isEqualTo(expectedUriString);
} |
public static MatchAll matchAll() {
return new AutoValue_FileIO_MatchAll.Builder()
.setConfiguration(MatchConfiguration.create(EmptyMatchTreatment.ALLOW_IF_WILDCARD))
.build();
} | @Test
@Category(NeedsRunner.class)
public void testMatchAllDisallowEmptyExplicit() throws IOException {
p.apply(Create.of(tmpFolder.getRoot().getAbsolutePath() + "/*"))
.apply(FileIO.matchAll().withEmptyMatchTreatment(EmptyMatchTreatment.DISALLOW));
thrown.expectCause(isA(FileNotFoundException.class));
p.run();
} |
@VisibleForTesting
void validateMenu(Long parentId, String name, Long id) {
MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name);
if (menu == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的菜单
if (id == null) {
throw exception(MENU_NAME_DUPLICATE);
}
if (!menu.getId().equals(id)) {
throw exception(MENU_NAME_DUPLICATE);
}
} | @Test
public void testValidateMenu_sonMenuNameDuplicate() {
// mock 父子菜单
MenuDO sonMenu = createParentAndSonMenu();
// 准备参数
Long parentId = sonMenu.getParentId();
Long otherSonMenuId = randomLongId();
String otherSonMenuName = sonMenu.getName(); //相同名称
// 调用,并断言异常
assertServiceException(() -> menuService.validateMenu(parentId, otherSonMenuName, otherSonMenuId),
MENU_NAME_DUPLICATE);
} |
public static Checksum newInstance(final String className)
{
Objects.requireNonNull(className, "className is required!");
if (Crc32.class.getName().equals(className))
{
return crc32();
}
else if (Crc32c.class.getName().equals(className))
{
return crc32c();
}
else
{
try
{
final Class<?> klass = Class.forName(className);
final Object instance = klass.getDeclaredConstructor().newInstance();
return (Checksum)instance;
}
catch (final ReflectiveOperationException ex)
{
throw new IllegalArgumentException("failed to create Checksum instance for class: " + className, ex);
}
}
} | @Test
void newInstanceThrowsNullPointerExceptionIfClassNameIsNull()
{
assertThrows(NullPointerException.class, () -> Checksums.newInstance(null));
} |
@Override
public final void checkout(File workDir, Revision revision) {
try {
if (workDir.exists()) {
FileUtils.deleteQuietly(workDir);
}
setupWorkspace(workDir);
LOGGER.debug("[TFS] Retrieving Files from Workspace {}, Working Folder {}, Revision {} ", workspace, workDir, revision);
retrieveFiles(workDir, revision);
} catch (Exception e) {
String exceptionMessage = String.format("Failed while checking out into Working Folder: %s, Project Path: %s, Workspace: %s, Username: %s, Domain: %s, Root Cause: %s", workDir, projectPath,
workspace,
userName,
domain, e.getMessage());
throw new RuntimeException(exceptionMessage, e);
} finally {
clearMapping(workDir);
}
} | @Test
public void testCheckout() throws Exception {
tfsCommand.checkout(workDir, revision);
verify(tfsCommand, times(1)).retrieveFiles(workDir, revision);
verifyMocks();
} |
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) {
final Map<Transformation<?>, Set<Transformation<?>>> outputMap =
buildOutputMap(transformations);
final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>();
final Set<Transformation<?>> alreadyTransformed = Sets.newIdentityHashSet();
final Queue<Transformation<?>> toTransformQueue = Queues.newArrayDeque(transformations);
while (!toTransformQueue.isEmpty()) {
final Transformation<?> transformation = toTransformQueue.poll();
if (!alreadyTransformed.contains(transformation)) {
alreadyTransformed.add(transformation);
final ChainInfo chainInfo = chainWithInputIfPossible(transformation, outputMap);
chainedTransformations.add(chainInfo.newTransformation);
chainedTransformations.removeAll(chainInfo.oldTransformations);
alreadyTransformed.addAll(chainInfo.oldTransformations);
// Add the chained transformation and its inputs to the to-optimize list
toTransformQueue.add(chainInfo.newTransformation);
toTransformQueue.addAll(chainInfo.newTransformation.getInputs());
}
}
return new ArrayList<>(chainedTransformations);
} | @Test
void testChainingUnorderedTransformations() {
ExternalPythonKeyedProcessOperator<?> keyedProcessOperator =
createKeyedProcessOperator(
"f1", new RowTypeInfo(Types.INT(), Types.INT()), Types.STRING());
ExternalPythonProcessOperator<?, ?> processOperator1 =
createProcessOperator("f2", Types.STRING(), Types.LONG());
ExternalPythonProcessOperator<?, ?> processOperator2 =
createProcessOperator("f3", Types.LONG(), Types.INT());
Transformation<?> sourceTransformation = mock(SourceTransformation.class);
OneInputTransformation<?, ?> keyedProcessTransformation =
new OneInputTransformation(
sourceTransformation,
"keyedProcess",
keyedProcessOperator,
keyedProcessOperator.getProducedType(),
2);
Transformation<?> processTransformation1 =
new OneInputTransformation(
keyedProcessTransformation,
"process",
processOperator1,
processOperator1.getProducedType(),
2);
Transformation<?> processTransformation2 =
new OneInputTransformation(
processTransformation1,
"process",
processOperator2,
processOperator2.getProducedType(),
2);
List<Transformation<?>> transformations = new ArrayList<>();
transformations.add(sourceTransformation);
transformations.add(processTransformation2);
transformations.add(processTransformation1);
transformations.add(keyedProcessTransformation);
List<Transformation<?>> optimized =
PythonOperatorChainingOptimizer.optimize(transformations);
assertThat(optimized).hasSize(2);
OneInputTransformation<?, ?> chainedTransformation =
(OneInputTransformation<?, ?>) optimized.get(1);
assertThat(sourceTransformation.getOutputType())
.isEqualTo(chainedTransformation.getInputType());
assertThat(processOperator2.getProducedType())
.isEqualTo(chainedTransformation.getOutputType());
OneInputStreamOperator<?, ?> chainedOperator = chainedTransformation.getOperator();
assertThat(chainedOperator).isInstanceOf(ExternalPythonKeyedProcessOperator.class);
validateChainedPythonFunctions(
((ExternalPythonKeyedProcessOperator<?>) chainedOperator).getPythonFunctionInfo(),
"f3",
"f2",
"f1");
} |
@Override
public void sendHeartbeatInvokeMessage(int currentId) {
var nextInstance = this.findNextInstance(currentId);
var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, "");
nextInstance.onMessage(heartbeatInvokeMessage);
} | @Test
void testSendHeartbeatInvokeMessage() {
try {
var instance1 = new BullyInstance(null, 1, 1);
var instance2 = new BullyInstance(null, 1, 2);
var instance3 = new BullyInstance(null, 1, 3);
Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3);
var messageManager = new BullyMessageManager(instanceMap);
messageManager.sendHeartbeatInvokeMessage(2);
var message = new Message(MessageType.HEARTBEAT_INVOKE, "");
var instanceClass = AbstractInstance.class;
var messageQueueField = instanceClass.getDeclaredField("messageQueue");
messageQueueField.setAccessible(true);
var messageSent = ((Queue<Message>) messageQueueField.get(instance3)).poll();
assertEquals(messageSent.getType(), message.getType());
assertEquals(messageSent.getContent(), message.getContent());
} catch (NoSuchFieldException | IllegalAccessException e) {
fail("Error to access private field.");
}
} |
public String convertInt(int i) {
return convert(i);
} | @Test
public void testSmoke() {
FileNamePattern pp = new FileNamePattern("t", context);
assertEquals("t", pp.convertInt(3));
pp = new FileNamePattern("foo", context);
assertEquals("foo", pp.convertInt(3));
pp = new FileNamePattern("%i foo", context);
assertEquals("3 foo", pp.convertInt(3));
pp = new FileNamePattern("foo%i.xixo", context);
assertEquals("foo3.xixo", pp.convertInt(3));
pp = new FileNamePattern("foo%i.log", context);
assertEquals("foo3.log", pp.convertInt(3));
pp = new FileNamePattern("foo.%i.log", context);
assertEquals("foo.3.log", pp.convertInt(3));
pp = new FileNamePattern("foo.%3i.log", context);
assertEquals("foo.003.log", pp.convertInt(3));
pp = new FileNamePattern("foo.%1i.log", context);
assertEquals("foo.43.log", pp.convertInt(43));
//pp = new FileNamePattern("%i.foo\\%", context);
//assertEquals("3.foo%", pp.convertInt(3));
//pp = new FileNamePattern("\\%foo", context);
//assertEquals("%foo", pp.convertInt(3));
} |
public void setCwe(List<String> cwe) {
this.cwe = cwe;
} | @Test
@SuppressWarnings("squid:S2699")
public void testSetCwe() {
//already tested, this is just left so the IDE doesn't recreate it.
} |
@Override
public CompletableFuture<ProxyRelayResult<ConsumeMessageDirectlyResult>> processConsumeMessageDirectly(
ProxyContext context, RemotingCommand command,
ConsumeMessageDirectlyResultRequestHeader header) {
CompletableFuture<ProxyRelayResult<ConsumeMessageDirectlyResult>> future = new CompletableFuture<>();
future.thenAccept(proxyOutResult -> {
RemotingServer remotingServer = this.brokerController.getRemotingServer();
if (remotingServer instanceof NettyRemotingAbstract) {
NettyRemotingAbstract nettyRemotingAbstract = (NettyRemotingAbstract) remotingServer;
RemotingCommand remotingCommand = RemotingCommand.createResponseCommand(null);
remotingCommand.setOpaque(command.getOpaque());
remotingCommand.setCode(proxyOutResult.getCode());
remotingCommand.setRemark(proxyOutResult.getRemark());
if (proxyOutResult.getCode() == ResponseCode.SUCCESS && proxyOutResult.getResult() != null) {
ConsumeMessageDirectlyResult consumeMessageDirectlyResult = proxyOutResult.getResult();
remotingCommand.setBody(consumeMessageDirectlyResult.encode());
}
SimpleChannel simpleChannel = new SimpleChannel(context.getRemoteAddress(), context.getLocalAddress());
nettyRemotingAbstract.processResponseCommand(simpleChannel.getChannelHandlerContext(), remotingCommand);
}
});
return future;
} | @Test
public void testProcessConsumeMessageDirectly() {
ConsumeMessageDirectlyResultRequestHeader requestHeader = new ConsumeMessageDirectlyResultRequestHeader();
String remark = "ok";
int opaque = 123;
RemotingCommand remotingCommand = RemotingCommand.createRequestCommand(RequestCode.CONSUME_MESSAGE_DIRECTLY, null);
remotingCommand.setOpaque(opaque);
ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
result.setConsumeResult(CMResult.CR_SUCCESS);
ArgumentCaptor<RemotingCommand> argumentCaptor = ArgumentCaptor.forClass(RemotingCommand.class);
CompletableFuture<ProxyRelayResult<ConsumeMessageDirectlyResult>> future =
localProxyRelayService.processConsumeMessageDirectly(ProxyContext.create(), remotingCommand, requestHeader);
future.complete(new ProxyRelayResult<>(ResponseCode.SUCCESS, remark, result));
Mockito.verify(nettyRemotingServerMock, Mockito.times(1))
.processResponseCommand(Mockito.any(SimpleChannelHandlerContext.class), argumentCaptor.capture());
RemotingCommand remotingCommand1 = argumentCaptor.getValue();
assertThat(remotingCommand1.getCode()).isEqualTo(ResponseCode.SUCCESS);
assertThat(remotingCommand1.getRemark()).isEqualTo(remark);
assertThat(remotingCommand1.getBody()).isEqualTo(result.encode());
} |
public abstract long queueDone(int queueIndex); | @Test
public void when_duplicateDoneCall_then_error() {
assertEquals(Long.MIN_VALUE, wc.queueDone(0));
assertThatThrownBy(() -> wc.queueDone(0))
.hasMessageContaining("Duplicate");
} |
public static Builder builder(final SqlStruct schema) {
return new Builder(schema);
} | @Test
public void shouldThrowOnSettingTooLargeAFieldIndex() {
// Given:
final int indexOverflow = SCHEMA.fields().size();
// When:
final DataException e = assertThrows(
DataException.class,
() -> KsqlStruct.builder(SCHEMA)
.set(indexOverflow, Optional.empty())
);
// Then:
assertThat(e.getMessage(), containsString("Invalid field index: " + indexOverflow));
} |
@CheckReturnValue
@NonNull public static Observable<Boolean> observePowerSavingState(
@NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) {
final RxSharedPrefs prefs = AnyApplication.prefs(context);
return Observable.combineLatest(
prefs
.getString(
R.string.settings_key_power_save_mode,
R.string.settings_default_power_save_mode_value)
.asObservable(),
enablePrefResId == 0
? Observable.just(true)
: prefs.getBoolean(enablePrefResId, defaultValueResId).asObservable(),
RxBroadcastReceivers.fromIntentFilter(
context.getApplicationContext(), getBatteryStateIntentFilter())
.startWith(new Intent(Intent.ACTION_BATTERY_OKAY)),
RxBroadcastReceivers.fromIntentFilter(
context.getApplicationContext(), getChargerStateIntentFilter())
.startWith(new Intent(Intent.ACTION_POWER_DISCONNECTED)),
getOsPowerSavingStateObservable(context),
(powerSavingPref, enabledPref, batteryIntent, chargerIntent, osPowerSavingState) -> {
if (!enabledPref) return false;
switch (powerSavingPref) {
case "never":
return false;
case "always":
return true;
default:
return osPowerSavingState
|| (Intent.ACTION_BATTERY_LOW.equals(batteryIntent.getAction())
&& Intent.ACTION_POWER_DISCONNECTED.equals(chargerIntent.getAction()));
}
})
.distinctUntilChanged();
} | @Test
public void testControlledByEnabledPref() {
AtomicReference<Boolean> state = new AtomicReference<>(null);
final Observable<Boolean> powerSavingState =
PowerSaving.observePowerSavingState(
getApplicationContext(), settings_key_power_save_mode_sound_control);
Assert.assertNull(state.get());
final Disposable disposable = powerSavingState.subscribe(state::set);
// starts as false
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(true);
Assert.assertEquals(Boolean.TRUE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
SharedPrefsHelper.setPrefsValue(R.string.settings_key_power_save_mode_sound_control, false);
// from this point it will always be FALSE (not low-battery)
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(true);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
disposable.dispose();
sendBatteryState(true);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
SharedPrefsHelper.setPrefsValue(R.string.settings_key_power_save_mode_sound_control, true);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(true);
Assert.assertEquals(Boolean.FALSE, state.get());
sendBatteryState(false);
Assert.assertEquals(Boolean.FALSE, state.get());
} |
public static AppNodesClusterHostsConsistency setInstance(HazelcastMember hzMember, AppSettings settings) {
return setInstance(hzMember, settings, LOG::warn);
} | @Test
public void setInstance_fails_with_ISE_when_called_twice_with_other_arguments() throws UnknownHostException {
TestHazelcastMember member1 = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(1, true));
TestHazelcastMember member2 = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(2, true));
AppNodesClusterHostsConsistency.setInstance(member1, new TestAppSettings());
assertThatThrownBy(() -> AppNodesClusterHostsConsistency.setInstance(member2, new TestAppSettings()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Instance is already set");
} |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDate(shardingValue.getValue())));
return ShardingAutoTableAlgorithmUtils.findMatchedTargetName(availableTargetNames, tableNameSuffix, shardingValue.getDataNodeInfo()).orElse(null);
} | @Test
void assertRangeDoShardingInValueWithMilliseconds() {
Properties props = PropertiesBuilder.build(
new Property("datetime-lower", "2020-01-01 00:00:00"), new Property("datetime-upper", "2020-01-01 00:00:30"), new Property("sharding-seconds", "1"));
AutoIntervalShardingAlgorithm shardingAlgorithm = (AutoIntervalShardingAlgorithm) TypedSPILoader.getService(ShardingAlgorithm.class, "AUTO_INTERVAL", props);
List<String> availableTargetNames = new LinkedList<>();
for (int i = 0; i < 32; i++) {
availableTargetNames.add("t_order_" + i);
}
Collection<String> actualWithoutMilliseconds = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("2020-01-01 00:00:11", "2020-01-01 00:00:21")));
assertThat(actualWithoutMilliseconds.size(), is(11));
Collection<String> actualWithOneMillisecond = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("2020-01-01 00:00:11.1", "2020-01-01 00:00:21.1")));
assertThat(actualWithOneMillisecond.size(), is(11));
Collection<String> actualWithTwoMilliseconds = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("2020-01-01 00:00:11.12", "2020-01-01 00:00:21.12")));
assertThat(actualWithTwoMilliseconds.size(), is(11));
Collection<String> actualWithThreeMilliseconds = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("2020-01-01 00:00:11.123", "2020-01-01 00:00:21.123")));
assertThat(actualWithThreeMilliseconds.size(), is(11));
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
try {
return serializer.serialize(topic, jsonValue);
} catch (SerializationException e) {
throw new DataException("Converting Kafka Connect data to byte[] failed due to serialization error: ", e);
}
} | @Test
public void arrayToJson() {
Schema int32Array = SchemaBuilder.array(Schema.INT32_SCHEMA).build();
JsonNode converted = parse(converter.fromConnectData(TOPIC, int32Array, Arrays.asList(1, 2, 3)));
validateEnvelope(converted);
assertEquals(parse("{ \"type\": \"array\", \"items\": { \"type\": \"int32\", \"optional\": false }, \"optional\": false }"),
converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME));
assertEquals(JsonNodeFactory.instance.arrayNode().add(1).add(2).add(3),
converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static Collection<ShardingSphereRule> buildRules(final Collection<RuleConfiguration> globalRuleConfigs,
final Map<String, ShardingSphereDatabase> databases, final ConfigurationProperties props) {
Collection<ShardingSphereRule> result = new LinkedList<>();
for (Entry<RuleConfiguration, GlobalRuleBuilder> entry : getRuleBuilderMap(globalRuleConfigs).entrySet()) {
result.add(entry.getValue().build(entry.getKey(), databases, props));
}
return result;
} | @Test
void assertBuildRules() {
Collection<ShardingSphereRule> shardingSphereRules = GlobalRulesBuilder
.buildRules(Collections.singletonList(new FixtureGlobalRuleConfiguration()), Collections.singletonMap("logic_db", buildDatabase()), mock(ConfigurationProperties.class));
assertThat(shardingSphereRules.size(), is(1));
} |
public FEELFnResult<Object> invoke(@ParameterName("list") List list) {
if ( list == null || list.isEmpty() ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty"));
} else {
try {
return FEELFnResult.ofResult(Collections.min(list, new InterceptNotComparableComparator()));
} catch (ClassCastException e) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "contains items that are not comparable"));
}
}
} | @Test
void invokeArrayWithHeterogenousTypes() {
FunctionTestUtil.assertResultError(minFunction.invoke(new Object[]{1, "test", BigDecimal.valueOf(10.2)}),
InvalidParametersEvent.class);
} |
public static Criterion matchPbbIsid(int pbbIsid) {
return new PbbIsidCriterion(pbbIsid);
} | @Test
public void testMatchPbbIsidMethod() {
Criterion matchPbbIsid = Criteria.matchPbbIsid(pbbIsid1);
PbbIsidCriterion pbbIsidCriterion =
checkAndConvert(matchPbbIsid,
Criterion.Type.PBB_ISID,
PbbIsidCriterion.class);
assertThat(pbbIsidCriterion.pbbIsid(), is(equalTo(pbbIsid1)));
} |
public static Schema schemaFromJavaBeanClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testPrimitiveArray() {
Schema schema =
JavaBeanUtils.schemaFromJavaBeanClass(
new TypeDescriptor<PrimitiveArrayBean>() {}, GetterTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(PRIMITIVE_ARRAY_BEAN_SCHEMA, schema);
} |
@ScalarOperator(LESS_THAN_OR_EQUAL)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThanOrEqual(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right)
{
return !left || right;
} | @Test
public void testLessThanOrEqual()
{
assertFunction("true <= true", BOOLEAN, true);
assertFunction("true <= false", BOOLEAN, false);
assertFunction("false <= true", BOOLEAN, true);
assertFunction("false <= false", BOOLEAN, true);
} |
@Around(CLIENT_INTERFACE_PUBLISH_CONFIG)
Object publishOrUpdateConfigAround(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String tenant, String content, String tag,
String appName, String srcUser, String configTags, String desc, String use, String effect, String type)
throws Throwable {
final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.PUBLISH_BY_HTTP;
final List<ConfigChangePluginService> pluginServices = getPluginServices(
configChangePointCutType);
// didn't enabled or add relative plugin
if (pluginServices.isEmpty()) {
return pjp.proceed();
}
ConfigChangeRequest configChangeRequest = new ConfigChangeRequest(configChangePointCutType);
configChangeRequest.setArg("dataId", dataId);
configChangeRequest.setArg("group", group);
configChangeRequest.setArg("tenant", tenant);
configChangeRequest.setArg("content", content);
configChangeRequest.setArg("tag", tag);
configChangeRequest.setArg("requestIpApp", appName);
configChangeRequest.setArg("srcIp", RequestUtil.getRemoteIp(request));
configChangeRequest.setArg("configTags", configTags);
configChangeRequest.setArg("desc", desc);
configChangeRequest.setArg("use", use);
configChangeRequest.setArg("effect", effect);
configChangeRequest.setArg("type", type);
return configChangeServiceHandle(pjp, pluginServices, configChangeRequest);
} | @Test
void testPublishOrUpdateConfigAround() throws Throwable {
Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_AFTER_TYPE);
ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
String srcUser = "user12324";
String dataId = "d1";
String group = "g1";
String tenant = "t1";
Mockito.when(proceedingJoinPoint.proceed(any())).thenReturn("mock success return");
Object o = configChangeAspect.publishOrUpdateConfigAround(proceedingJoinPoint, request, response, dataId, group, tenant, "c1", null,
null, srcUser, null, null, null, null, null);
Thread.sleep(20L);
// expect service executed.
Mockito.verify(configChangePluginService, Mockito.times(1))
.execute(any(ConfigChangeRequest.class), any(ConfigChangeResponse.class));
//expect join point processed success.
assertEquals("mock success return", o);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.