focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public UserDefinedFunctionDescriptor(String name, String classpath) {
this.name = name;
this.classpath = classpath;
this.className = classpath.substring(classpath.lastIndexOf('.') + 1);
try {
Class<?> clazz = Class.forName(classpath);
isCdcPipelineUdf = isCdcPipelineUdf(clazz);
if (isCdcPipelineUdf) {
// We use reflection to invoke UDF methods since we may add more methods
// into UserDefinedFunction interface, thus the provided UDF classes
// might not be compatible with the interface definition in CDC common.
returnTypeHint =
(DataType) clazz.getMethod("getReturnType").invoke(clazz.newInstance());
} else {
returnTypeHint = null;
}
} catch (ClassNotFoundException
| InvocationTargetException
| IllegalAccessException
| NoSuchMethodException
| InstantiationException e) {
throw new IllegalArgumentException(
"Failed to instantiate UDF " + name + "@" + classpath, e);
}
} | @Test
void testUserDefinedFunctionDescriptor() {
assertThat(new UserDefinedFunctionDescriptor("cdc_udf", CdcUdf.class.getName()))
.extracting("name", "className", "classpath", "returnTypeHint", "isCdcPipelineUdf")
.containsExactly(
"cdc_udf",
"UserDefinedFunctionDescriptorTest$CdcUdf",
"org.apache.flink.cdc.runtime.operators.transform.UserDefinedFunctionDescriptorTest$CdcUdf",
null,
true);
assertThat(
new UserDefinedFunctionDescriptor(
"cdc_udf_with_type_hint", CdcUdfWithTypeHint.class.getName()))
.extracting("name", "className", "classpath", "returnTypeHint", "isCdcPipelineUdf")
.containsExactly(
"cdc_udf_with_type_hint",
"UserDefinedFunctionDescriptorTest$CdcUdfWithTypeHint",
"org.apache.flink.cdc.runtime.operators.transform.UserDefinedFunctionDescriptorTest$CdcUdfWithTypeHint",
DataTypes.TIMESTAMP_LTZ(9),
true);
assertThat(new UserDefinedFunctionDescriptor("flink_udf", FlinkUdf.class.getName()))
.extracting("name", "className", "classpath", "returnTypeHint", "isCdcPipelineUdf")
.containsExactly(
"flink_udf",
"UserDefinedFunctionDescriptorTest$FlinkUdf",
"org.apache.flink.cdc.runtime.operators.transform.UserDefinedFunctionDescriptorTest$FlinkUdf",
null,
false);
assertThatThrownBy(
() -> new UserDefinedFunctionDescriptor("not_udf", NotUDF.class.getName()))
.isExactlyInstanceOf(IllegalArgumentException.class)
.hasMessage(
"Failed to detect UDF class class org.apache.flink.cdc.runtime.operators.transform.UserDefinedFunctionDescriptorTest$NotUDF "
+ "since it never implements interface org.apache.flink.cdc.common.udf.UserDefinedFunction or "
+ "extends Flink class org.apache.flink.table.functions.ScalarFunction.");
assertThatThrownBy(
() ->
new UserDefinedFunctionDescriptor(
"not_even_exist", "not.a.valid.class.path"))
.isExactlyInstanceOf(IllegalArgumentException.class)
.hasMessage("Failed to instantiate UDF [email protected]");
} |
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
configureSamplingInterval(configs);
configurePrometheusAdapter(configs);
configureQueryMap(configs);
} | @Test(expected = ConfigException.class)
public void testGetSamplesWithCustomNegativeSamplingInterval() throws Exception {
Map<String, Object> config = new HashMap<>();
config.put(PROMETHEUS_SERVER_ENDPOINT_CONFIG, "http://kafka-cluster-1.org:9090");
config.put(PROMETHEUS_QUERY_RESOLUTION_STEP_MS_CONFIG, "-2000");
addCapacityConfig(config);
_prometheusMetricSampler.configure(config);
} |
@Field
public void setExtractInlineImageMetadataOnly(boolean extractInlineImageMetadataOnly) {
defaultConfig.setExtractInlineImageMetadataOnly(extractInlineImageMetadataOnly);
} | @Test
public void testExtractInlineImageMetadata() throws Exception {
ParseContext context = new ParseContext();
PDFParserConfig config = new PDFParserConfig();
config.setExtractInlineImageMetadataOnly(true);
context.set(PDFParserConfig.class, config);
List<Metadata> metadataList = getRecursiveMetadata("testOCR.pdf", context);
assertNull(context.get(ZeroByteFileException.IgnoreZeroByteFileException.class));
assertEquals(2, metadataList.size());
assertEquals("image/png", metadataList.get(1).get(Metadata.CONTENT_TYPE));
assertEquals("/image0.png",
metadataList.get(1).get(TikaCoreProperties.EMBEDDED_RESOURCE_PATH));
assertEquals(261, (int) metadataList.get(1).getInt(Metadata.IMAGE_LENGTH));
assertEquals(934, (int) metadataList.get(1).getInt(Metadata.IMAGE_WIDTH));
assertEquals("image0.png", metadataList.get(1).get(TikaCoreProperties.RESOURCE_NAME_KEY));
} |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not found.", groupId));
}
if (group == null) {
ClassicGroup classicGroup = new ClassicGroup(logContext, groupId, ClassicGroupState.EMPTY, time, metrics);
groups.put(groupId, classicGroup);
metrics.onClassicGroupStateTransition(null, classicGroup.currentState());
return classicGroup;
} else {
if (group.type() == CLASSIC) {
return (ClassicGroup) group;
} else {
// We don't support upgrading/downgrading between protocols at the moment so
// we throw an exception if a group exists with the wrong type.
throw new GroupIdNotFoundException(String.format("Group %s is not a classic group.",
groupId));
}
}
} | @Test
public void testGroupStuckInRebalanceTimeoutDueToNonjoinedStaticMember() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
int longSessionTimeoutMs = 10000;
int rebalanceTimeoutMs = 5000;
GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinAndRebalance(
"group-id",
"leader-instance-id",
"follower-instance-id",
rebalanceTimeoutMs,
longSessionTimeoutMs
);
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup("group-id", false);
// New member joins
GroupMetadataManagerTestContext.JoinResult joinResult = context.sendClassicGroupJoin(
new GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
.withGroupId("group-id")
.withMemberId(UNKNOWN_MEMBER_ID)
.withProtocolSuperset()
.withSessionTimeoutMs(longSessionTimeoutMs)
.build()
);
// The new dynamic member has been elected as leader
GroupMetadataManagerTestContext.assertNoOrEmptyResult(context.sleep(rebalanceTimeoutMs));
assertTrue(joinResult.joinFuture.isDone());
assertEquals(Errors.NONE.code(), joinResult.joinFuture.get().errorCode());
assertEquals(joinResult.joinFuture.get().leader(), joinResult.joinFuture.get().memberId());
assertEquals(3, joinResult.joinFuture.get().members().size());
assertEquals(2, joinResult.joinFuture.get().generationId());
assertTrue(group.isInState(COMPLETING_REBALANCE));
assertEquals(
mkSet(rebalanceResult.leaderId, rebalanceResult.followerId, joinResult.joinFuture.get().memberId()),
group.allMemberIds()
);
assertEquals(
mkSet(rebalanceResult.leaderId, rebalanceResult.followerId),
group.allStaticMemberIds()
);
assertEquals(
mkSet(joinResult.joinFuture.get().memberId()),
group.allDynamicMemberIds()
);
// Send a special leave group request from static follower, moving group towards PreparingRebalance
CoordinatorResult<LeaveGroupResponseData, CoordinatorRecord> leaveResult = context.sendClassicGroupLeave(
new LeaveGroupRequestData()
.setGroupId("group-id")
.setMembers(Collections.singletonList(
new MemberIdentity()
.setMemberId(rebalanceResult.followerId)
.setGroupInstanceId("follower-instance-id")
))
);
LeaveGroupResponseData expectedResponse = new LeaveGroupResponseData()
.setMembers(Collections.singletonList(
new LeaveGroupResponseData.MemberResponse()
.setMemberId(rebalanceResult.followerId)
.setGroupInstanceId("follower-instance-id")));
assertEquals(expectedResponse, leaveResult.response());
assertTrue(group.isInState(PREPARING_REBALANCE));
context.sleep(rebalanceTimeoutMs);
// Only static leader is maintained, and group is stuck at PreparingRebalance stage
assertTrue(group.allDynamicMemberIds().isEmpty());
assertEquals(Collections.singleton(rebalanceResult.leaderId), group.allMemberIds());
assertTrue(group.allDynamicMemberIds().isEmpty());
assertEquals(2, group.generationId());
assertTrue(group.isInState(PREPARING_REBALANCE));
} |
public static Calendar getCalendar(Object date, Calendar defaultValue) {
Calendar cal = new GregorianCalendar();
if (date instanceof java.util.Date) {
cal.setTime((java.util.Date) date);
return cal;
} else if (date != null) {
Optional<Date> d = tryToParseDate(date);
if (!d.isPresent()) {
return defaultValue;
}
cal.setTime(d.get());
} else {
cal = defaultValue;
}
return cal;
} | @Test
public void testGetCalendarObjectCalendarWithInvalidStringAndNullDefault() {
assertNull(Converter.getCalendar("invalid date", null));
} |
@Override
public void setAll(Properties properties) {
@SuppressWarnings("unchecked") Enumeration<String> names =
(Enumeration<String>) properties.propertyNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
Property property = Property.get(name);
if (property == null) {
throw new PropertyTypeException("Unknown property: " + name);
}
String value = properties.getProperty(name);
if (property.isMultiValuePermitted()) {
this.set(property, new String[]{value});
} else {
this.set(property, value);
}
}
} | @Test
public void testSetAll() {
Properties props = new Properties();
props.put(TikaCoreProperties.FORMAT.getName(), "format");
props.put(TikaCoreProperties.SUBJECT.getName(), "keyword");
xmpMeta.setAll(props);
assertEquals("format", xmpMeta.get(TikaCoreProperties.FORMAT));
String[] values = xmpMeta.getValues(TikaCoreProperties.SUBJECT);
assertEquals(1, values.length);
assertEquals("keyword", values[0]);
} |
@Override
public boolean advanceBy(long amount, TimeUnit unit) {
return advanceTo(SystemClock.uptimeMillis() + unit.toMillis(amount));
} | @Test
public void advanceBy() {
Runnable runnable = mock(Runnable.class);
new Handler(getMainLooper()).postDelayed(runnable, 100);
verify(runnable, times(0)).run();
assertThat(scheduler.advanceBy(100, TimeUnit.MILLISECONDS)).isTrue();
verify(runnable, times(1)).run();
} |
@SuppressWarnings("unchecked")
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE);
Serde<T> windowInnerClassSerde = null;
if (windowedInnerClassSerdeConfig != null) {
try {
windowInnerClassSerde = Utils.newInstance(windowedInnerClassSerdeConfig, Serde.class);
} catch (final ClassNotFoundException e) {
throw new ConfigException(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, windowedInnerClassSerdeConfig,
"Serde class " + windowedInnerClassSerdeConfig + " could not be found.");
}
}
if (inner != null && windowedInnerClassSerdeConfig != null) {
if (!inner.getClass().getName().equals(windowInnerClassSerde.serializer().getClass().getName())) {
throw new IllegalArgumentException("Inner class serializer set using constructor "
+ "(" + inner.getClass().getName() + ")" +
" is different from the one set in windowed.inner.class.serde config " +
"(" + windowInnerClassSerde.serializer().getClass().getName() + ").");
}
} else if (inner == null && windowedInnerClassSerdeConfig == null) {
throw new IllegalArgumentException("Inner class serializer should be set either via constructor " +
"or via the windowed.inner.class.serde config");
} else if (inner == null)
inner = windowInnerClassSerde.serializer();
} | @Test
public void shouldThrowConfigExceptionWhenInvalidWindowInnerClassSerialiserSupplied() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
assertThrows(ConfigException.class, () -> sessionWindowedSerializer.configure(props, false));
} |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
// Based on HTTP component documentation:
return getHttpMethod(exchange, endpoint);
} | @Test
public void testGetOperationName() {
Exchange exchange = Mockito.mock(Exchange.class);
Message message = Mockito.mock(Message.class);
Mockito.when(exchange.getIn()).thenReturn(message);
Mockito.when(message.getHeader(Exchange.HTTP_METHOD)).thenReturn("PUT");
SpanDecorator decorator = new AbstractHttpSpanDecorator() {
@Override
public String getComponent() {
return null;
}
@Override
public String getComponentClassName() {
return null;
}
};
assertEquals("PUT", decorator.getOperationName(exchange, null));
} |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfByteArrayNegativePrefixLengthIPv6() {
IpPrefix ipPrefix;
byte[] value;
value = new byte[] {0x11, 0x11, 0x22, 0x22,
0x33, 0x33, 0x44, 0x44,
0x55, 0x55, 0x66, 0x66,
0x77, 0x77, (byte) 0x88, (byte) 0x88};
ipPrefix = IpPrefix.valueOf(IpAddress.Version.INET6, value, -1);
} |
@VisibleForTesting
static void instantiateMetaspaceMemoryMetrics(final MetricGroup parentMetricGroup) {
final List<MemoryPoolMXBean> memoryPoolMXBeans =
ManagementFactory.getMemoryPoolMXBeans().stream()
.filter(bean -> "Metaspace".equals(bean.getName()))
.collect(Collectors.toList());
if (memoryPoolMXBeans.isEmpty()) {
LOG.info(
"The '{}' metrics will not be exposed because no pool named 'Metaspace' could be found. This might be caused by the used JVM.",
METRIC_GROUP_METASPACE_NAME);
return;
}
final MetricGroup metricGroup = parentMetricGroup.addGroup(METRIC_GROUP_METASPACE_NAME);
final Iterator<MemoryPoolMXBean> beanIterator = memoryPoolMXBeans.iterator();
final MemoryPoolMXBean firstPool = beanIterator.next();
instantiateMemoryUsageMetrics(metricGroup, firstPool::getUsage);
if (beanIterator.hasNext()) {
LOG.debug(
"More than one memory pool named 'Metaspace' is present. Only the first pool was used for instantiating the '{}' metrics.",
METRIC_GROUP_METASPACE_NAME);
}
} | @Test
void testMetaspaceMetricUsageNotStatic() throws Exception {
assertThat(hasMetaspaceMemoryPool())
.withFailMessage("Requires JVM with Metaspace memory pool")
.isTrue();
final InterceptingOperatorMetricGroup metaspaceMetrics =
new InterceptingOperatorMetricGroup() {
@Override
public MetricGroup addGroup(String name) {
return this;
}
};
MetricUtils.instantiateMetaspaceMemoryMetrics(metaspaceMetrics);
@SuppressWarnings("unchecked")
final Gauge<Long> used = (Gauge<Long>) metaspaceMetrics.get(MetricNames.MEMORY_USED);
runUntilMetricChanged("Metaspace", 10, MetricUtilsTest::redefineDummyClass, used);
} |
@Operation(summary = "queryAccessTokenList", description = "QUERY_ACCESS_TOKEN_LIST_NOTES")
@Parameters({
@Parameter(name = "searchVal", description = "SEARCH_VAL", schema = @Schema(implementation = String.class)),
@Parameter(name = "pageNo", description = "PAGE_NO", required = true, schema = @Schema(implementation = int.class), example = "1"),
@Parameter(name = "pageSize", description = "PAGE_SIZE", required = true, schema = @Schema(implementation = int.class), example = "20")
})
@GetMapping()
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_ACCESSTOKEN_LIST_PAGING_ERROR)
public Result<PageInfo<AccessToken>> queryAccessTokenList(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@RequestParam("pageNo") Integer pageNo,
@RequestParam(value = "searchVal", required = false) String searchVal,
@RequestParam("pageSize") Integer pageSize) {
checkPageParams(pageNo, pageSize);
searchVal = ParameterUtils.handleEscapes(searchVal);
PageInfo<AccessToken> accessTokenPageInfo =
accessTokenService.queryAccessTokenList(loginUser, searchVal, pageNo, pageSize);
return Result.success(accessTokenPageInfo);
} | @Test
public void testQueryAccessTokenList() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("pageNo", "1");
paramsMap.add("pageSize", "20");
paramsMap.add("searchVal", "");
MvcResult mvcResult = mockMvc.perform(get("/access-tokens")
.header("sessionId", sessionId)
.params(paramsMap))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class);
Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());
logger.info(mvcResult.getResponse().getContentAsString());
} |
@Override
public void startIt() {
if (semaphore.tryAcquire()) {
try {
executorService.execute(this::doDatabaseMigration);
} catch (RuntimeException e) {
semaphore.release();
throw e;
}
} else {
LOGGER.trace("{}: lock is already taken or process is already running", Thread.currentThread().getName());
}
} | @Test
public void status_is_FAILED_and_failure_stores_the_exception_when_trigger_throws_an_exception() {
mockMigrationThrowsError();
underTest.startIt();
assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.FAILED);
assertThat(migrationState.getError()).get().isSameAs(AN_ERROR);
assertThat(migrationState.getStartedAt()).isNotNull();
} |
public boolean isCombo()
{
return getCOSObject().getFlag(COSName.FF, FLAG_COMBO);
} | @Test
void createListBox()
{
PDChoice choiceField = new PDListBox(acroForm);
assertEquals(choiceField.getFieldType(), choiceField.getCOSObject().getNameAsString(COSName.FT));
assertEquals("Ch", choiceField.getFieldType());
assertFalse(choiceField.isCombo());
} |
@Override
public String buildContext() {
final PluginDO after = (PluginDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the plugin [%s] is %s", after.getName(), StringUtils.lowerCase(getType().getType().toString()));
}
return String.format("the plugin [%s] is %s : %s", after.getName(), StringUtils.lowerCase(getType().getType().toString()), contrast());
} | @Test
public void updatePluginBuildContextTest() {
String eventTypeStr = StringUtils.lowerCase(EventTypeEnum.PLUGIN_UPDATE.getType().toString());
PluginChangedEvent pluginUpdateEventWithoutChange = new PluginChangedEvent(pluginDO, pluginDO, EventTypeEnum.PLUGIN_UPDATE, "test-operator");
String withoutChangeContrast = "it no change";
String context =
String.format("the plugin [%s] is %s : %s", pluginDO.getName(), eventTypeStr, withoutChangeContrast);
assertEquals(context, pluginUpdateEventWithoutChange.buildContext());
PluginChangedEvent pluginUpdateEventNotSameDO = new PluginChangedEvent(withoutChangePluginDO, pluginDO, EventTypeEnum.PLUGIN_UPDATE, "test-operator");
assertEquals(context, pluginUpdateEventNotSameDO.buildContext());
final StringBuilder contrast = new StringBuilder();
contrast.append(String.format("name[%s => %s] ", pluginDO.getName(), changePluginDO.getName()));
contrast.append(String.format("config[%s => %s] ", pluginDO.getConfig(), changePluginDO.getConfig()));
contrast.append(String.format("role[%s => %s] ", pluginDO.getRole(), changePluginDO.getRole()));
contrast.append(String.format("enable[%s => %s] ", pluginDO.getEnabled(), changePluginDO.getEnabled()));
contrast.append(String.format("sort[%s => %s] ", pluginDO.getSort(), changePluginDO.getSort()));
String changeContext = String.format("the plugin [%s] is %s : %s", changePluginDO.getName(), eventTypeStr, contrast);
PluginChangedEvent pluginUpdateEventChange = new PluginChangedEvent(changePluginDO, pluginDO, EventTypeEnum.PLUGIN_UPDATE, "test-operator");
assertEquals(changeContext, pluginUpdateEventChange.buildContext());
} |
@Override
public Expression createExpression(Expression source, String expression, Object[] properties) {
return doCreateJsonPathExpression(source, expression, properties, false);
} | @Test
public void testUnpackJsonArray() {
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody(new File("src/test/resources/expensive.json"));
JsonPathLanguage language = (JsonPathLanguage) context.resolveLanguage("jsonpath");
Expression expression = language.createExpression("$.store.book",
new Object[] { null, null, null, null, null, null, true, true });
String json = expression.evaluate(exchange, String.class);
// check that a single json object is returned, not an array
assertTrue(json.startsWith("{") && json.endsWith("}"));
} |
@Override
public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds,
final DescribeConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future =
DescribeConsumerGroupsHandler.newFuture(groupIds);
DescribeConsumerGroupsHandler handler = new DescribeConsumerGroupsHandler(options.includeAuthorizedOperations(), logContext);
invokeDriver(handler, future, options.timeoutMs);
return new DescribeConsumerGroupsResult(future.all().entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().idValue, Map.Entry::getValue)));
} | @Test
public void testDescribeOldAndNewConsumerGroups() throws Exception {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.kafkaClient().prepareResponse(new FindCoordinatorResponse(
new FindCoordinatorResponseData()
.setCoordinators(asList(
FindCoordinatorResponse.prepareCoordinatorResponse(Errors.NONE, "grp1", env.cluster().controller()),
FindCoordinatorResponse.prepareCoordinatorResponse(Errors.NONE, "grp2", env.cluster().controller())
))
));
env.kafkaClient().prepareResponse(new ConsumerGroupDescribeResponse(
new ConsumerGroupDescribeResponseData()
.setGroups(asList(
new ConsumerGroupDescribeResponseData.DescribedGroup()
.setGroupId("grp1")
.setGroupState("Stable")
.setGroupEpoch(10)
.setAssignmentEpoch(10)
.setAssignorName("range")
.setAuthorizedOperations(Utils.to32BitField(emptySet()))
.setMembers(singletonList(
new ConsumerGroupDescribeResponseData.Member()
.setMemberId("memberId")
.setInstanceId("instanceId")
.setClientHost("host")
.setClientId("clientId")
.setMemberEpoch(10)
.setRackId("rackid")
.setSubscribedTopicNames(singletonList("foo"))
.setSubscribedTopicRegex("regex")
.setAssignment(new ConsumerGroupDescribeResponseData.Assignment()
.setTopicPartitions(singletonList(
new ConsumerGroupDescribeResponseData.TopicPartitions()
.setTopicId(Uuid.randomUuid())
.setTopicName("foo")
.setPartitions(singletonList(0))
)))
.setTargetAssignment(new ConsumerGroupDescribeResponseData.Assignment()
.setTopicPartitions(singletonList(
new ConsumerGroupDescribeResponseData.TopicPartitions()
.setTopicId(Uuid.randomUuid())
.setTopicName("foo")
.setPartitions(singletonList(1))
)))
)),
new ConsumerGroupDescribeResponseData.DescribedGroup()
.setGroupId("grp2")
.setErrorCode(Errors.GROUP_ID_NOT_FOUND.code())
))
));
env.kafkaClient().prepareResponse(new DescribeGroupsResponse(
new DescribeGroupsResponseData()
.setGroups(Collections.singletonList(
DescribeGroupsResponse.groupMetadata(
"grp2",
Errors.NONE,
"Stable",
ConsumerProtocol.PROTOCOL_TYPE,
"range",
singletonList(
DescribeGroupsResponse.groupMember(
"0",
null,
"clientId0",
"clientHost",
ConsumerProtocol.serializeAssignment(
new ConsumerPartitionAssignor.Assignment(
Collections.singletonList(new TopicPartition("bar", 0))
)
).array(),
null
)
),
Collections.emptySet()
)
))
));
DescribeConsumerGroupsResult result = env.adminClient()
.describeConsumerGroups(asList("grp1", "grp2"));
Map<String, ConsumerGroupDescription> expectedResult = new HashMap<>();
expectedResult.put("grp1", new ConsumerGroupDescription(
"grp1",
false,
Collections.singletonList(
new MemberDescription(
"memberId",
Optional.of("instanceId"),
"clientId",
"host",
new MemberAssignment(
Collections.singleton(new TopicPartition("foo", 0))
),
Optional.of(new MemberAssignment(
Collections.singleton(new TopicPartition("foo", 1))
))
)
),
"range",
GroupType.CONSUMER,
ConsumerGroupState.STABLE,
env.cluster().controller(),
Collections.emptySet()
));
expectedResult.put("grp2", new ConsumerGroupDescription(
"grp2",
false,
Collections.singletonList(
new MemberDescription(
"0",
Optional.empty(),
"clientId0",
"clientHost",
new MemberAssignment(
Collections.singleton(new TopicPartition("bar", 0))
)
)
),
"range",
GroupType.CLASSIC,
ConsumerGroupState.STABLE,
env.cluster().controller(),
Collections.emptySet()
));
assertEquals(expectedResult, result.all().get());
}
} |
public boolean hasAnyMethodHandlerAnnotation() {
return !operationsWithHandlerAnnotation.isEmpty();
} | @Test
public void testHandlerOnDerived() {
BeanInfo info = new BeanInfo(context, MyDerivedClass.class);
assertFalse(info.hasAnyMethodHandlerAnnotation());
} |
public static void unmap(String resourceDescription, ByteBuffer buffer) throws IOException {
if (!buffer.isDirect())
throw new IllegalArgumentException("Unmapping only works with direct buffers");
if (UNMAP == null)
throw UNMAP_NOT_SUPPORTED_EXCEPTION;
try {
UNMAP.invokeExact(buffer);
} catch (Throwable throwable) {
throw new IOException("Unable to unmap the mapped buffer: " + resourceDescription, throwable);
}
} | @Test
public void testUnmap() throws Exception {
File file = TestUtils.tempFile();
try (FileChannel channel = FileChannel.open(file.toPath())) {
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, 0);
ByteBufferUnmapper.unmap(file.getAbsolutePath(), map);
}
} |
public static <K> KTableHolder<K> build(
final KTableHolder<K> table,
final TableFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(table, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldBuildSqlPredicateCorrectly() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(predicateFactory).create(
filterExpression,
schema,
ksqlConfig,
functionRegistry
);
} |
@Override
public void recordStateMachineFinished(StateMachineInstance machineInstance, ProcessContext context) {
if (machineInstance != null) {
try {
// save to db
Map<String, Object> endParams = machineInstance.getEndParams();
if (endParams != null) {
endParams.remove(DomainConstants.VAR_NAME_GLOBAL_TX);
}
// if success, clear exception
if (ExecutionStatus.SU.equals(machineInstance.getStatus()) && machineInstance.getException() != null) {
machineInstance.setException(null);
}
machineInstance.setSerializedEndParams(paramsSerializer.serialize(machineInstance.getEndParams()));
machineInstance.setSerializedException(exceptionSerializer.serialize(machineInstance.getException()));
int effect = executeUpdate(stateLogStoreSqls.getRecordStateMachineFinishedSql(dbType),
STATE_MACHINE_INSTANCE_TO_STATEMENT_FOR_UPDATE, machineInstance);
if (effect < 1) {
LOGGER.warn("StateMachineInstance[{}] is recovery by server, skip recordStateMachineFinished.", machineInstance.getId());
} else {
StateMachineConfig stateMachineConfig = (StateMachineConfig) context.getVariable(
DomainConstants.VAR_NAME_STATEMACHINE_CONFIG);
if (EngineUtils.isTimeout(machineInstance.getGmtUpdated(), stateMachineConfig.getTransOperationTimeout())) {
LOGGER.warn("StateMachineInstance[{}] is execution timeout, skip report transaction finished to server.", machineInstance.getId());
} else if (StringUtils.isEmpty(machineInstance.getParentId())) {
//if parentId is not null, machineInstance is a SubStateMachine, do not report global transaction.
reportTransactionFinished(machineInstance, context);
}
}
} finally {
RootContext.unbind();
RootContext.unbindBranchType();
}
}
} | @Test
public void testRecordStateMachineFinished() {
DbAndReportTcStateLogStore dbAndReportTcStateLogStore = new DbAndReportTcStateLogStore();
StateMachineInstanceImpl stateMachineInstance = new StateMachineInstanceImpl();
ProcessContextImpl context = new ProcessContextImpl();
context.setVariable(DomainConstants.VAR_NAME_STATEMACHINE_CONFIG, new DbStateMachineConfig());
Assertions.assertThrows(NullPointerException.class,
() -> dbAndReportTcStateLogStore.recordStateMachineFinished(stateMachineInstance, context));
} |
@Override
public void setIndex(int readerIndex, int writerIndex) {
if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) {
throw new IndexOutOfBoundsException();
}
this.readerIndex = readerIndex;
this.writerIndex = writerIndex;
} | @Test
void setIndexBoundaryCheck2() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(CAPACITY / 2, CAPACITY / 4));
} |
@SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:FinalParameters"})
protected static int send(
final String customerId, final byte[] bytes, final HttpPost httpPost, final HttpHost proxy,
CloseableHttpClient httpClient, final ResponseHandler responseHandler
) {
int statusCode = DEFAULT_STATUS_CODE;
if (bytes != null && bytes.length > 0 && httpPost != null && customerId != null) {
// add the body to the request
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.LEGACY);
builder.addTextBody("cid", customerId);
builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, "filename");
httpPost.setEntity(builder.build());
httpPost.addHeader("api-version", "phone-home-v1");
// set the HTTP config
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS))
.setConnectionRequestTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS))
.setResponseTimeout(Timeout.ofMilliseconds(REQUEST_TIMEOUT_MS))
.build();
CloseableHttpResponse response = null;
try {
if (proxy != null) {
log.debug("setting proxy to {}", proxy);
config = RequestConfig.copy(config).setProxy(proxy).build();
httpPost.setConfig(config);
final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
if (httpClient == null) {
httpClient = HttpClientBuilder
.create()
.setRoutePlanner(routePlanner)
.setDefaultRequestConfig(config)
.build();
}
} else {
if (httpClient == null) {
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
}
response = httpClient.execute(httpPost);
if (responseHandler != null) {
responseHandler.handle(response);
}
// send request
log.debug("POST request returned {}", new StatusLine(response).toString());
statusCode = response.getCode();
} catch (IOException e) {
log.error("Could not submit metrics to Confluent: {}", e.getMessage());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
log.warn("could not close http client", e);
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.warn("could not close http response", e);
}
}
}
} else {
statusCode = HttpStatus.SC_BAD_REQUEST;
}
return statusCode;
} | @Test
public void testSubmitIgnoresEmptyInput() {
// Given
HttpPost p = mock(HttpPost.class);
byte[] emptyData = new byte[0];
// When
WebClient.send(customerId, emptyData, p, null);
// Then
verifyNoMoreInteractions(p);
} |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREFIX);
ArrayList<String> dest = new ArrayList<>(destDir);
if (containsBasePath(children)) {
// there's a base marker in the path
List<String> baseChildren = basePathChildren(children);
checkArgument(!baseChildren.isEmpty(),
"No path found under " + BASE);
dest.addAll(baseChildren);
} else {
dest.add(filename(children));
}
return dest;
} else {
return elements;
}
} | @Test
public void testFinalDestinationRootMagic2() {
assertEquals(l("3.txt"),
finalDestination(l(MAGIC_PATH_PREFIX, "2", "3.txt")));
} |
@Override
public void onElement(OnElementContext c) throws Exception {
getRepeated(c).invokeOnElement(c);
} | @Test
public void testOnElement() throws Exception {
setUp(FixedWindows.of(Duration.millis(10)));
tester.injectElements(37);
verify(mockTrigger).onElement(Mockito.any());
} |
public ShardingSphereSchema getSchema(final String schemaName) {
return schemas.get(schemaName);
} | @Test
void assertGetSchema() {
DatabaseType databaseType = mock(DatabaseType.class);
RuleMetaData ruleMetaData = mock(RuleMetaData.class);
ShardingSphereSchema schema = mock(ShardingSphereSchema.class);
ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", databaseType, mock(ResourceMetaData.class), ruleMetaData, Collections.singletonMap("schema1", schema));
assertThat(database.getSchema("schema1"), is(schema));
assertNull(database.getSchema("non_existent_schema"));
} |
@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 shouldThrowIfCsasKeyFormatDoesnotSupportInference() {
// Given:
givenFormatsAndProps("kafka", null,
ImmutableMap.of("KEY_SCHEMA_ID", new IntegerLiteral(42)));
givenDDLSchemaAndFormats(LOGICAL_SCHEMA, "kafka", "avro",
SerdeFeature.WRAP_SINGLES, SerdeFeature.UNWRAP_SINGLES);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> injector.inject(csasStatement)
);
// Then:
assertThat(e.getMessage(),
containsString("KEY_FORMAT should support schema inference when "
+ "KEY_SCHEMA_ID is provided. Current format is KAFKA."));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void unpinChatMessage() {
BaseResponse response = bot.execute(new UnpinChatMessage(groupId).messageId(3600));
assertTrue(response.isOk());
} |
public static String getGroupKey(ThreadPoolParameter parameter) {
return StringUtil.createBuilder()
.append(parameter.getTpId())
.append(Constants.GROUP_KEY_DELIMITER)
.append(parameter.getItemId())
.append(Constants.GROUP_KEY_DELIMITER)
.append(parameter.getTenantId())
.toString();
} | @Test
public void assertGetGroupKey() {
String testText = "message-consume+dynamic-threadpool-example+prescription";
ThreadPoolParameterInfo parameter = ThreadPoolParameterInfo.builder()
.tenantId("prescription").itemId("dynamic-threadpool-example").tpId("message-consume").build();
Assert.isTrue(testText.equals(ContentUtil.getGroupKey(parameter)));
} |
public static Level toLevel(String sArg) {
return toLevel(sArg, Level.DEBUG);
} | @Test
public void smoke() {
assertEquals(Level.TRACE, Level.toLevel("TRACE"));
assertEquals(Level.DEBUG, Level.toLevel("DEBUG"));
assertEquals(Level.INFO, Level.toLevel("INFO"));
assertEquals(Level.WARN, Level.toLevel("WARN"));
assertEquals(Level.ERROR, Level.toLevel("ERROR"));
} |
public ServiceBuilder<U> addMethods(List<? extends MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
} | @Test
void addMethods() {
MethodConfig method = new MethodConfig();
ServiceBuilder builder = new ServiceBuilder();
builder.addMethods(Collections.singletonList(method));
Assertions.assertTrue(builder.build().getMethods().contains(method));
Assertions.assertEquals(1, builder.build().getMethods().size());
} |
@Description("Get the plan ids of given plan node")
@ScalarFunction("json_presto_query_plan_ids")
@SqlType("ARRAY<VARCHAR>")
@SqlNullable
public static Block jsonPlanIds(@TypeParameter("ARRAY<VARCHAR>") ArrayType arrayType,
@SqlType(StandardTypes.JSON) Slice jsonPlan)
{
List<JsonRenderedNode> planFragments = parseJsonPlanFragmentsAsList(jsonPlan);
if (planFragments == null) {
return null;
}
Map<String, List<String>> planMap = extractPlanIds(planFragments);
return constructSqlArray(arrayType, planMap.keySet().stream().collect(Collectors.toList()));
} | @Test
public void testJsonPlanIds()
{
assertFunction("json_presto_query_plan_ids(null)", new ArrayType(VARCHAR), null);
assertFunction("json_presto_query_plan_ids(json '" +
TestJsonPrestoQueryPlanFunctionUtils.joinPlan.replaceAll("'", "''") + "')",
new ArrayType(VARCHAR), ImmutableList.of("253", "313", "314", "8", "251", "284", "230", "252"));
} |
public static Object remove(Object root, DataIterator it)
{
DataElement element;
// construct the list of Data objects to remove
// don't remove in place because iterator behavior with removals while iterating is undefined
ArrayList<ToRemove> removeList = new ArrayList<>();
while ((element = it.next()) != null)
{
ToRemove toRemove = new ToRemove(element);
removeList.add(toRemove);
}
// perform actual removal in reverse order to make sure deleting array elements starts with higher indices
for (int i = removeList.size() - 1; i >= 0; i--)
{
ToRemove toRemove = removeList.get(i);
if (toRemove.isRoot())
{
root = null;
}
else
{
toRemove.remove();
}
}
return root;
} | @Test
public void testRemoveByPredicateWithPostOrder() throws Exception
{
SimpleTestData data = IteratorTestData.createSimpleTestData();
SimpleDataElement el = data.getDataElement();
Builder.create(el.getValue(), el.getSchema(), IterationOrder.POST_ORDER)
.filterBy(Predicates.pathMatchesPathSpec(IteratorTestData.PATH_TO_ID))
.remove();
assertTrue(data.getValue().getDataList("foo").getDataMap(0).getInteger("id") == null);
assertTrue(data.getValue().getDataList("foo").getDataMap(1).getInteger("id") == null);
assertTrue(data.getValue().getDataList("foo").getDataMap(2).getInteger("id") == null);
} |
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) {
if (msgs instanceof CodecOutputList) {
fireChannelRead(ctx, (CodecOutputList) msgs, numElements);
} else {
for (int i = 0; i < numElements; i++) {
ctx.fireChannelRead(msgs.get(i));
}
}
} | @Test
public void testDoesNotOverReadOnChannelReadComplete() {
ReadInterceptingHandler interceptor = new ReadInterceptingHandler();
EmbeddedChannel channel = new EmbeddedChannel(interceptor, new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
// NOOP
}
});
channel.config().setAutoRead(false);
assertEquals(1, interceptor.readsTriggered);
channel.pipeline().fireChannelReadComplete();
assertEquals(1, interceptor.readsTriggered);
channel.pipeline().fireChannelRead(Unpooled.buffer().writeZero(8));
assertEquals(1, interceptor.readsTriggered);
// This should trigger a read() as we did not forward any message.
channel.pipeline().fireChannelReadComplete();
assertEquals(2, interceptor.readsTriggered);
// Explicit calling fireChannelReadComplete() again without calling fireChannelRead(...) before should
// not trigger another read()
channel.pipeline().fireChannelReadComplete();
assertEquals(2, interceptor.readsTriggered);
channel.pipeline().fireChannelRead(Unpooled.buffer().writeZero(8));
assertEquals(2, interceptor.readsTriggered);
// This should trigger a read() as we did not forward any message.
channel.pipeline().fireChannelReadComplete();
assertEquals(3, interceptor.readsTriggered);
channel.finishAndReleaseAll();
} |
@Override
public void abortDm(MdId mdName, MaIdShort maName, MepId mepId)
throws CfmConfigException {
throw new UnsupportedOperationException("Not yet implemented");
} | @Test
public void testAbortOneDm() throws CfmConfigException {
//TODO: Implement underlying method
try {
soamManager.abortDm(MDNAME1, MANAME1, MEPID1, DMID101);
fail("Expecting UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
} |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/or a JWE with JSON claims as the payload.
// In this example it is a JWS nested inside a JWE
// So we first create a JsonWebSignature object.
JsonWebSignature jws = new JsonWebSignature();
// The payload of the JWS is JSON content of the JWT Claims
jws.setPayload(claims.toJson());
// The JWT is signed using the sender's private key
jws.setKey(privateKey);
// Get provider from security config file, it should be two digit
// And the provider id will set as prefix for keyid in the token header, for example: 05100
// if there is no provider id, we use "00" for the default value
String provider_id = "";
if (jwtConfig.getProviderId() != null) {
provider_id = jwtConfig.getProviderId();
if (provider_id.length() == 1) {
provider_id = "0" + provider_id;
} else if (provider_id.length() > 2) {
logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
provider_id = provider_id.substring(0, 2);
}
}
jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());
// Set the signature algorithm on the JWT/JWS that will integrity protect the claims
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
// Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
// representation, which is a string consisting of three dot ('.') separated
// base64url-encoded parts in the form Header.Payload.Signature
jwt = jws.getCompactSerialization();
return jwt;
} | @Test
public void AcGroupAccessControlRight() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaimsGroup("stevehu", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("account.r", "account.w"), "admin frontOffice");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePrivateKey(long_key, KeyUtil.RSA));
System.out.println("***Long lived token Authorization code customer with roles***: " + jwt);
} |
@Override
public boolean isInstalled(final Application application) {
synchronized(NSWorkspace.class) {
if(Application.notfound.equals(application)) {
return false;
}
return workspace.absolutePathForAppBundleWithIdentifier(
application.getIdentifier()) != null;
}
} | @Test
public void testInstalled() {
ApplicationFinder f = new LaunchServicesApplicationFinder();
assertTrue(f.isInstalled(new Application("com.apple.Preview", "Preview")));
assertFalse(f.isInstalled(new Application("com.apple.Preview_", "Preview")));
assertFalse(f.isInstalled(Application.notfound));
} |
@Override
public void onRollbackFailure(GlobalTransaction tx, Throwable originalException) {
LOGGER.warn("Failed to rollback transaction[" + tx.getXid() + "]", originalException);
TIMER.newTimeout(new DefaultFailureHandlerImpl.CheckTimerTask(tx, GlobalStatus.Rollbacked),
SCHEDULE_INTERVAL_SECONDS, TimeUnit.SECONDS);
} | @Test
void onRollbackFailure() throws Exception {
RootContext.bind(DEFAULT_XID);
DefaultGlobalTransaction tx = (DefaultGlobalTransaction)GlobalTransactionContext.getCurrentOrCreate();
FailureHandler failureHandler = new DefaultFailureHandlerImpl();
failureHandler.onRollbackFailure(tx, new MyRuntimeException("").getCause());
// get timer
Class<?> c = Class.forName("io.seata.tm.api.DefaultFailureHandlerImpl");
Field field = c.getDeclaredField("TIMER");
field.setAccessible(true);
HashedWheelTimer timer = (HashedWheelTimer) field.get(failureHandler);
// assert timer pendingCount: first time is 1
Long pendingTimeout = timer.pendingTimeouts();
Assertions.assertEquals(pendingTimeout,1L);
//set globalStatus
globalStatus= GlobalStatus.Rollbacked;
Thread.sleep(25*1000L);
pendingTimeout = timer.pendingTimeouts();
LOGGER.info("pendingTimeout {}" ,pendingTimeout);
//all timer is done
Assertions.assertEquals(pendingTimeout,0L);
} |
public static String format(LocalDateTime localDateTime, String format) {
return LocalDateTimeUtil.format(localDateTime, format);
} | @Test
public void formatSpeedTest(){
Date value = new Date();
//long t0 = System.currentTimeMillis();
//此处先加载FastDateFormat对象,保存到FastDateFormat.CACHE中
//解决后面两个for循环中保存到FastDateFormat对象创建未时差异的问题。
FastDateFormat.getInstance("YYYY-MM-dd HH:mm:ss.SSS");
long t1 = System.currentTimeMillis();
String strTime = null;
for(int i=0; i<50000; i++){
strTime = DateUtil.format(value, "YYYY-MM-dd HH:mm:ss.SSS");
}
assertNotNull(strTime);
long t2 = System.currentTimeMillis();
for(int i=0; i<50000; i++){
strTime = FastDateFormat.getInstance("YYYY-MM-dd HH:mm:ss.SSS").format(value);
}
assertNotNull(strTime);
long t3 = System.currentTimeMillis();
//long initTime = t1 - t0;
long formtTime1 = t2 - t1;
long formatTime2 = t3 - t2;
//此处仍然不明白,两个for循环实际执行format方法都一样,为什么第1个for时间大致是第2个for的3倍。
assertTrue(formtTime1 > formatTime2);
/*
* System.out.println("t1-t0="+(t1-t0));
* System.out.println("t2-t1="+(t2-t1));
* System.out.println("t3-t2="+(t3-t2));
*
* 由日志可以看出,第1个for时间大致是第2个for的3倍
*
* t1-t0=46
* t2-t1=65
* t3-t2=25
*/
} |
private void extractLinks(Page page, Selector urlRegionSelector, List<Pattern> urlPatterns) {
List<String> links;
if (urlRegionSelector == null) {
links = page.getHtml().links().all();
} else {
links = page.getHtml().selectList(urlRegionSelector).links().all();
}
for (String link : links) {
for (Pattern targetUrlPattern : urlPatterns) {
Matcher matcher = targetUrlPattern.matcher(link);
if (matcher.find()) {
page.addTargetRequest(new Request(matcher.group(0)));
}
}
}
} | @Test
public void testExtractLinks() throws Exception {
ModelPageProcessor modelPageProcessor = ModelPageProcessor.create(null, MockModel.class);
Page page = pageMocker.getMockPage();
modelPageProcessor.process(page);
assertThat(page.getTargetRequests()).containsExactly(new Request("http://webmagic.io/bar/3"), new Request("http://webmagic.io/bar/4"), new Request("http://webmagic.io/foo/3"), new Request("http://webmagic.io/foo/4"));
} |
public String getUuid() {
return toString();
} | @Test
public void generatesValidType4UUID() {
// Given
Uuid uuid = new Uuid();
// When
String generatedUUID = uuid.getUuid();
// Then
assertTrue(generatedUUID.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"));
} |
@Override
public void onServerStart(Server server) {
List<CoreExtensionBridge> bridges = componentContainer.getComponentsByType(CoreExtensionBridge.class);
for (CoreExtensionBridge bridge : bridges) {
Profiler profiler = Profiler.create(LOGGER).startInfo(format("Bootstrapping %s", bridge.getPluginName()));
bridge.startPlugin(componentContainer);
profiler.stopInfo();
}
} | @Test
public void onServerStart_calls_startPlugin_if_Bridge_exists_in_container() {
componentContainer.add(bridge);
componentContainer.startComponents();
underTest.onServerStart(mock(Server.class));
verify(bridge).getPluginName();
verify(bridge).startPlugin(componentContainer);
verifyNoMoreInteractions(bridge);
} |
public static Level toLevel(String sArg) {
return toLevel(sArg, Level.DEBUG);
} | @Test
public void smoke( ) {
assertEquals(Level.TRACE, Level.toLevel("TRACE"));
assertEquals(Level.DEBUG, Level.toLevel("DEBUG"));
assertEquals(Level.INFO, Level.toLevel("INFO"));
assertEquals(Level.WARN, Level.toLevel("WARN"));
assertEquals(Level.ERROR, Level.toLevel("ERROR"));
} |
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
return new JmsConsumer( stepMeta, stepDataInterface, copyNr, transMeta, trans );
} | @Test
public void withVariablesGetsNewObjectFromRegistry() throws KettleXMLException, KettleMissingPluginsException {
String path = getClass().getResource( "/jms-consumer.ktr" ).getPath();
TransMeta transMeta = new TransMeta( path, new Variables() );
StepMeta step = transMeta.getStep( 0 );
JmsConsumerMeta jmsMeta = (JmsConsumerMeta) step.getStepMetaInterface();
assertEquals( "${testOne}", jmsMeta.jmsDelegate.amqUrl );
Variables variables = new Variables();
variables.setVariable( "testOne", "changedValue" );
JmsConsumerMeta jmsMetaWithVars = (JmsConsumerMeta) jmsMeta.withVariables( variables );
assertEquals( "changedValue", jmsMetaWithVars.jmsDelegate.amqUrl );
} |
@Async
public void sendAfnemersBerichtAanDGL(AfnemersberichtAanDGL afnemersberichtAanDGL, Afnemersbericht afnemersbericht){
boolean success = digileveringClient.sendRequest(afnemersberichtAanDGL);
afnemersbericht.setStatus(success ? Afnemersbericht.Status.PENDING : Afnemersbericht.Status.SEND_FAILED);
afnemersberichtRepository.save(afnemersbericht);
} | @Test
public void testSendAfnemersBerichtAanDGL(){
AfnemersberichtAanDGL afnemersberichtAanDGL = new AfnemersberichtAanDGL();
Afnemersbericht afnemersbericht = new Afnemersbericht();
classUnderTest.sendAfnemersBerichtAanDGL(afnemersberichtAanDGL, afnemersbericht);
verify(digileveringClient, times(1)).sendRequest(afnemersberichtAanDGL);
verify(afnemersberichtRepository, times(1)).save(afnemersbericht);
} |
@SuppressWarnings("unchecked")
public <V> V run(String callableName, RetryOperation<V> operation)
{
int attempt = 1;
while (true) {
try {
return operation.run();
}
catch (Exception e) {
if (attempt >= maxAttempts || !retryPredicate.test(e)) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
QueryException qe = (QueryException) e;
attempt++;
int delayMillis = (int) min(minBackoffDelay.toMillis() * pow(scaleFactor, attempt - 1), maxBackoffDelay.toMillis());
int jitterMillis = ThreadLocalRandom.current().nextInt(max(1, (int) (delayMillis * 0.1)));
log.debug(
"Failed on executing %s with attempt %d. Retry after %sms. Cause: %s",
callableName,
attempt - 1,
delayMillis,
qe.getMessage());
try {
MILLISECONDS.sleep(delayMillis + jitterMillis);
}
catch (InterruptedException ie) {
currentThread().interrupt();
throw new RuntimeException(ie);
}
}
}
} | @Test(timeOut = 5000)
public void testBackoffTimeCapped()
{
RetryDriver retryDriver = new RetryDriver(
new RetryConfig()
.setMaxAttempts(5)
.setMinBackoffDelay(new Duration(10, MILLISECONDS))
.setMaxBackoffDelay(new Duration(100, MILLISECONDS))
.setScaleFactor(1000),
exception -> (exception instanceof QueryException) ? (((QueryException) exception).getType() == CLUSTER_CONNECTION) : FALSE);
retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION));
} |
static int maskChecksum(long checksum) {
return (int) ((checksum >> 15 | checksum << 17) + 0xa282ead8);
} | @Test
public void testMaskChecksum() {
ByteBuf input = Unpooled.wrappedBuffer(new byte[] {
0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00,
0x5f, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65,
0x61, 0x74, 0x5f,
});
assertEquals(0x44a4301f, calculateChecksum(input));
input.release();
} |
@Override
public boolean isContainer(final Path file) {
if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(host))) {
return super.isContainer(file);
}
return false;
} | @Test
public void testContainer() {
assertTrue("/", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).isContainer(new Path("/b", EnumSet.of(Path.Type.directory))));
assertEquals("b", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).getContainer(new Path("/b/f", EnumSet.of(Path.Type.file))).getName());
assertFalse("/", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).isContainer(new Path("/b/f", EnumSet.of(Path.Type.file))));
assertEquals("b", new S3PathContainerService(new Host(new S3Protocol(), "s3.amazonaws.com")).getContainer(new Path("/b/f", EnumSet.of(Path.Type.file))).getName());
} |
public static SegmentGenerationJobSpec getSegmentGenerationJobSpec(String jobSpecFilePath, String propertyFilePath,
Map<String, Object> context, Map<String, String> environmentValues) {
Properties properties = new Properties();
if (propertyFilePath != null) {
try {
properties.load(FileUtils.openInputStream(new File(propertyFilePath)));
} catch (IOException e) {
throw new RuntimeException(
String.format("Unable to read property file [%s] into properties.", propertyFilePath), e);
}
}
Map<String, Object> propertiesMap = (Map) properties;
if (environmentValues != null) {
for (String propertyName: propertiesMap.keySet()) {
if (environmentValues.get(propertyName) != null) {
propertiesMap.put(propertyName, environmentValues.get(propertyName));
}
}
}
if (context != null) {
propertiesMap.putAll(context);
}
String jobSpecTemplate;
try {
jobSpecTemplate = IOUtils.toString(new BufferedReader(new FileReader(jobSpecFilePath)));
} catch (IOException e) {
throw new RuntimeException(String.format("Unable to read ingestion job spec file [%s].", jobSpecFilePath), e);
}
String jobSpecStr;
try {
jobSpecStr = GroovyTemplateUtils.renderTemplate(jobSpecTemplate, propertiesMap);
} catch (Exception e) {
throw new RuntimeException(String
.format("Unable to render templates on ingestion job spec template file - [%s] with propertiesMap - [%s].",
jobSpecFilePath, Arrays.toString(propertiesMap.entrySet().toArray())), e);
}
String jobSpecFormat = (String) propertiesMap.getOrDefault(JOB_SPEC_FORMAT, YAML);
if (jobSpecFormat.equals(JSON)) {
try {
return JsonUtils.stringToObject(jobSpecStr, SegmentGenerationJobSpec.class);
} catch (IOException e) {
throw new RuntimeException(String
.format("Unable to parse job spec - [%s] to JSON with propertiesMap - [%s]", jobSpecFilePath,
Arrays.toString(propertiesMap.entrySet().toArray())), e);
}
}
return new Yaml().loadAs(jobSpecStr, SegmentGenerationJobSpec.class);
} | @Test
public void testIngestionJobLauncherWithTemplate() {
Map<String, Object> context =
GroovyTemplateUtils.getTemplateContext(Arrays.asList("year=2020", "month=05", "day=06"));
SegmentGenerationJobSpec spec = IngestionJobLauncher.getSegmentGenerationJobSpec(
GroovyTemplateUtils.class.getClassLoader().getResource("ingestion_job_spec_template.yaml").getFile(),
null, context, _defaultEnvironmentValues);
Assert.assertEquals(spec.getInputDirURI(), "file:///path/to/input/2020/05/06");
Assert.assertEquals(spec.getOutputDirURI(), "file:///path/to/output/2020/05/06");
// searchRecursively is set to false in the yaml file.
Assert.assertFalse(spec.isSearchRecursively());
} |
@Override
public boolean next() throws SQLException {
if (skipAll) {
return false;
}
if (!paginationContext.getActualRowCount().isPresent()) {
return getMergedResult().next();
}
return rowNumber++ <= paginationContext.getActualRowCount().get() && getMergedResult().next();
} | @Test
void assertNextForSkipAll() throws SQLException {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(schema);
SQLServerSelectStatement sqlStatement = new SQLServerSelectStatement();
sqlStatement.setProjections(new ProjectionsSegment(0, 0));
sqlStatement.setLimit(new LimitSegment(0, 0, new NumberLiteralRowNumberValueSegment(0, 0, Long.MAX_VALUE, true), null));
SelectStatementContext selectStatementContext =
new SelectStatementContext(createShardingSphereMetaData(database), Collections.emptyList(), sqlStatement, DefaultDatabase.LOGIC_NAME, Collections.emptyList());
ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "SQLServer"));
MergedResult actual = resultMerger.merge(Arrays.asList(mockQueryResult(), mockQueryResult(),
mockQueryResult(), mockQueryResult()), selectStatementContext, mockShardingSphereDatabase(), mock(ConnectionContext.class));
assertFalse(actual.next());
} |
public State currentState() {
return lastState.get().state;
} | @Test
public void currentStateIsNullWhenNotInitialized() {
assertNull(tracker.currentState());
} |
static void setHaConf(String nsId, Configuration conf) {
conf.set(DFSConfigKeys.DFS_NAMESERVICES, nsId);
final String haNNKey = DFS_HA_NAMENODES_KEY_PREFIX + "." + nsId;
conf.set(haNNKey, "nn0,nn1");
final String rpcKey = DFS_NAMENODE_RPC_ADDRESS_KEY + "." + nsId + ".";
conf.set(rpcKey + "nn0", "127.0.0.1:8080");
conf.set(rpcKey + "nn1", "127.0.0.1:8080");
} | @Test
public void testHaConf() {
final Configuration conf = new Configuration();
final String nsId = "cluster0";
FsImageValidation.setHaConf(nsId, conf);
Assert.assertTrue(HAUtil.isHAEnabled(conf, nsId));
} |
static void chDir(String workingDir) throws Exception {
CLibrary.chdir(workingDir);
System.setProperty("user.dir", workingDir);
// change current dir for the java.io.File class
Class<?> fileClass = Class.forName("java.io.File");
if (JavaVersion.getJavaSpec() >= 11.0) {
Field fsField = fileClass.getDeclaredField(JavaVersion.getJavaSpec() >= 21.0 ? "FS" : "fs");
fsField.setAccessible(true);
Object fs = fsField.get(null);
Field userDirField = fs.getClass().getDeclaredField("userDir");
userDirField.setAccessible(true);
userDirField.set(fs, workingDir);
}
// change current dir for the java.nio.Path class
Object fs = FileSystems.getDefault();
Class<?> fsClass = fs.getClass();
while (fsClass != Object.class) {
if ("sun.nio.fs.UnixFileSystem".equals(fsClass.getName())) {
Field defaultDirectoryField = fsClass.getDeclaredField("defaultDirectory");
defaultDirectoryField.setAccessible(true);
String encoding = System.getProperty("sun.jnu.encoding");
Charset charset = encoding != null ? Charset.forName(encoding) : Charset.defaultCharset();
defaultDirectoryField.set(fs, workingDir.getBytes(charset));
} else if ("sun.nio.fs.WindowsFileSystem".equals(fsClass.getName())) {
Field defaultDirectoryField = fsClass.getDeclaredField("defaultDirectory");
Field defaultRootField = fsClass.getDeclaredField("defaultRoot");
defaultDirectoryField.setAccessible(true);
defaultRootField.setAccessible(true);
Path wdir = Paths.get(workingDir);
Path root = wdir.getRoot();
defaultDirectoryField.set(fs, wdir.toString());
defaultRootField.set(fs, root.toString());
}
fsClass = fsClass.getSuperclass();
}
} | @Test
void testChdir() throws Exception {
File d = new File("target/tstDir").getAbsoluteFile();
d.mkdirs();
EnvHelper.chDir(d.toString());
assertEquals(new File(d, "test").getAbsolutePath(), new File("test").getAbsolutePath());
assertEquals(
d.toPath().resolve("test").toAbsolutePath().toString(),
Paths.get("test").toAbsolutePath().toString());
} |
public static ColumnName generateSyntheticJoinKey(final Stream<LogicalSchema> schemas) {
final AliasGenerator generator = buildAliasGenerators(schemas)
.getOrDefault(
SYNTHETIC_JOIN_KEY_COLUMN_PRIFIX,
new AliasGenerator(0, SYNTHETIC_JOIN_KEY_COLUMN_PRIFIX, ImmutableSet.of())
);
return generator.next();
} | @Test
public void shouldDefaultToRowKeySyntheticJoinColumn() {
// When:
final ColumnName columnName = ColumnNames.generateSyntheticJoinKey(Stream.of());
// Then:
assertThat(columnName, is(ColumnName.of("ROWKEY")));
} |
public String getStatisticsForChannel(String subscribeChannel) {
return filterService.getFiltersForChannel(subscribeChannel).stream()
.map(PrioritizedFilter::statistics)
.map(PrioritizedFilterStatistics::toString)
.collect(Collectors.joining(",\n", "[", "]"));
} | @Test
void testGetStatisticsForChannel() {
String channel = "test";
service.getStatisticsForChannel(channel);
Mockito.verify(filterService, Mockito.times(1)).getFiltersForChannel(channel);
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testNullFieldShouldNotMatch() {
final String fieldName = "nullfield";
final StreamRule rule = getSampleRule();
rule.setField(fieldName);
final Message msg = getSampleMessage();
msg.addField(fieldName, null);
final StreamRuleMatcher matcher = getMatcher(rule);
assertFalse(matcher.match(msg, rule));
} |
public Iterator<V> values() {
return new LongObjectCacheValuesIterator<>(this);
} | @Test
public void cacheIterator() {
LongObjectCache<String> cache = new LongObjectCache<>(4);
cache.put(0, "An IDE");
cache.put(1, "good IDEA");
cache.put(2, "better IDEA");
cache.put(3, "perfect IDEA");
cache.put(4, "IDEAL");
HashSet<String> values = new HashSet<>();
final Iterator<String> it = cache.values();
while (it.hasNext()) {
values.add(it.next());
}
Assert.assertNull(cache.get(0));
Assert.assertFalse(values.contains("An IDE"));
Assert.assertTrue(values.contains("good IDEA"));
Assert.assertTrue(values.contains("better IDEA"));
Assert.assertTrue(values.contains("perfect IDEA"));
Assert.assertTrue(values.contains("IDEAL"));
} |
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 group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
.reportStorageNodeState(4, State.DOWN);
final ClusterStateGenerator.Params params = fixture.generatorParams().minNodeRatioPerGroup(0.65);
final AnnotatedClusterState state = ClusterStateGenerator.generatedStateFrom(params);
assertThat(state.toString(), equalTo("distributor:9 storage:9 .4.s:d")); // No other nodes down implicitly
} |
public void setNewConfiguration(@NonNull Configuration newConfiguration) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mAskAppContext = mAskAppContext.createConfigurationContext(newConfiguration);
}
mPackageContext.clear();
} | @Test
public void testSetNewConfiguration() {
var withLocal = new TestableAddOn("id1", "name111", 8);
Assert.assertSame(getApplicationContext(), withLocal.getPackageContext());
Assert.assertEquals(
1, withLocal.getPackageContext().getResources().getConfiguration().orientation);
var newConfig = getApplicationContext().getResources().getConfiguration();
newConfig.orientation = 2;
withLocal.setNewConfiguration(newConfig);
Assert.assertNotSame(getApplicationContext(), withLocal.getPackageContext());
Assert.assertEquals(
getApplicationContext().getPackageName(), withLocal.getPackageContext().getPackageName());
Assert.assertEquals(
2, withLocal.getPackageContext().getResources().getConfiguration().orientation);
} |
@UdafFactory(description = "sum double values in a list into a single double")
public static TableUdaf<List<Double>, Double, Double> sumDoubleList() {
return new TableUdaf<List<Double>, Double, Double>() {
@Override
public Double initialize() {
return 0.0;
}
@Override
public Double aggregate(final List<Double> valueToAdd, final Double aggregateValue) {
if (valueToAdd == null) {
return aggregateValue;
}
return aggregateValue + sumList(valueToAdd);
}
@Override
public Double merge(final Double aggOne, final Double aggTwo) {
return aggOne + aggTwo;
}
@Override
public Double map(final Double agg) {
return agg;
}
@Override
public Double undo(final List<Double> valueToUndo, final Double aggregateValue) {
if (valueToUndo == null) {
return aggregateValue;
}
return aggregateValue - sumList(valueToUndo);
}
private double sumList(final List<Double> list) {
return sum(list, initialize(), Double::sum);
}
};
} | @Test
public void shouldSumDoubleList() {
final TableUdaf<List<Double>, Double, Double> udaf = ListSumUdaf.sumDoubleList();
final Double[] values = new Double[] {1.0, 1.0, 1.0, 1.0, 1.0};
final List<Double> list = Arrays.asList(values);
final Double sum = udaf.aggregate(list, 0.0);
assertThat(5.0, equalTo(sum));
} |
public void setIncludedCipherSuites(String cipherSuites) {
this.includedCipherSuites = cipherSuites;
} | @Test
public void testSetIncludedCipherSuites() throws Exception {
configurable.setSupportedCipherSuites(new String[] { "A", "B", "C", "D" });
configuration.setIncludedCipherSuites("A,B ,C, D");
configuration.configure(configurable);
assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" },
configurable.getEnabledCipherSuites()));
} |
public void check(List<String> words) throws MnemonicException {
toEntropy(words);
} | @Test(expected = MnemonicException.MnemonicLengthException.class)
public void testEmptyMnemonic() throws Exception {
List<String> words = new ArrayList<>();
mc.check(words);
} |
@Override
public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) {
refreshClassLoader(classLoader);
} | @Test
void testConfig1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
System.setProperty(CLASS_DESERIALIZE_ALLOWED_LIST, "test.package1, test.package2, ,");
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel);
serializeSecurityConfigurator.onAddClassLoader(
moduleModel, Thread.currentThread().getContextClassLoader());
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1"));
Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2"));
System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST);
frameworkModel.destroy();
} |
@Override
public void finish() throws IOException {
if (expression != null) {
expression.finish();
}
} | @Test
public void finish() throws IOException {
test.finish();
verify(expr).finish();
verifyNoMoreInteractions(expr);
} |
static void createCompactedTopic(String topicName, short partitions, short replicationFactor, Admin admin) {
NewTopic topicDescription = TopicAdmin.defineTopic(topicName).
compacted().
partitions(partitions).
replicationFactor(replicationFactor).
build();
CreateTopicsOptions args = new CreateTopicsOptions().validateOnly(false);
try {
admin.createTopics(singleton(topicDescription), args).values().get(topicName).get();
log.info("Created topic '{}'", topicName);
} catch (InterruptedException e) {
Thread.interrupted();
throw new ConnectException("Interrupted while attempting to create/find topic '" + topicName + "'", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof TopicExistsException) {
log.debug("Unable to create topic '{}' since it already exists.", topicName);
return;
}
if (cause instanceof UnsupportedVersionException) {
log.debug("Unable to create topic '{}' since the brokers do not support the CreateTopics API." +
" Falling back to assume topic exists or will be auto-created by the broker.",
topicName);
return;
}
if (cause instanceof TopicAuthorizationException) {
log.debug("Not authorized to create topic(s) '{}' upon the brokers." +
" Falling back to assume topic(s) exist or will be auto-created by the broker.",
topicName);
return;
}
if (cause instanceof ClusterAuthorizationException) {
log.debug("Not authorized to create topic '{}'." +
" Falling back to assume topic exists or will be auto-created by the broker.",
topicName);
return;
}
if (cause instanceof InvalidConfigurationException) {
throw new ConnectException("Unable to create topic '" + topicName + "': " + cause.getMessage(),
cause);
}
if (cause instanceof TimeoutException) {
// Timed out waiting for the operation to complete
throw new ConnectException("Timed out while checking for or creating topic '" + topicName + "'." +
" This could indicate a connectivity issue, unavailable topic partitions, or if" +
" this is your first use of the topic it may have taken too long to create.", cause);
}
throw new ConnectException("Error while attempting to create/find topic '" + topicName + "'", e);
}
} | @Test
public void testCreateCompactedTopicAssumeTopicAlreadyExistsWithUnsupportedVersionException() throws Exception {
Map<String, KafkaFuture<Void>> values = Collections.singletonMap(TOPIC, future);
when(future.get()).thenThrow(new ExecutionException(new UnsupportedVersionException("unsupported")));
when(ctr.values()).thenReturn(values);
when(admin.createTopics(any(), any())).thenReturn(ctr);
MirrorUtils.createCompactedTopic(TOPIC, (short) 1, (short) 1, admin);
verify(future).get();
verify(ctr).values();
verify(admin).createTopics(any(), any());
} |
public void removeSubscription(Topic topic) {
subscriptions.remove(new Subscription(data.clientId(), topic, MqttSubscriptionOption.onlyFromQos(MqttQoS.EXACTLY_ONCE)));
} | @Test
public void testRemoveSubscription() {
client.addSubscriptions(Arrays.asList(new Subscription(CLIENT_ID, new Topic("topic/one"), MqttSubscriptionOption.onlyFromQos(MqttQoS.AT_MOST_ONCE))));
Assertions.assertThat(client.getSubscriptions()).hasSize(1);
client.addSubscriptions(Arrays.asList(new Subscription(CLIENT_ID, new Topic("topic/one"), MqttSubscriptionOption.onlyFromQos(MqttQoS.EXACTLY_ONCE))));
Assertions.assertThat(client.getSubscriptions()).hasSize(1);
client.removeSubscription(new Topic("topic/one"));
Assertions.assertThat(client.getSubscriptions()).isEmpty();
} |
@Override
public int getUnstableBars() {
return 0;
} | @Test
public void testUnstableBars() {
KalmanFilterIndicator kalmanIndicator = new KalmanFilterIndicator(closePrice);
Assert.assertEquals(0, kalmanIndicator.getUnstableBars());
} |
public static MetadataUpdate fromJson(String json) {
return JsonUtil.parse(json, MetadataUpdateParser::fromJson);
} | @Test
public void testMetadataUpdateWithoutActionCannotDeserialize() {
List<String> invalidJson =
ImmutableList.of("{\"action\":null,\"format-version\":2}", "{\"format-version\":2}");
for (String json : invalidJson) {
assertThatThrownBy(() -> MetadataUpdateParser.fromJson(json))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse metadata update. Missing field: action");
}
} |
@Override
public CompletableFuture<List<MessageExt>> queryMessage(String address, boolean uniqueKeyFlag, boolean decompressBody,
QueryMessageRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<List<MessageExt>> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_MESSAGE, requestHeader);
request.addExtField(MixAll.UNIQUE_MSG_QUERY_FLAG, String.valueOf(uniqueKeyFlag));
remotingClient.invoke(address, request, timeoutMillis).thenAccept(response -> {
if (response.getCode() == ResponseCode.SUCCESS) {
List<MessageExt> wrappers = MessageDecoder.decodesBatch(ByteBuffer.wrap(response.getBody()), true, decompressBody, true);
future.complete(filterMessages(wrappers, requestHeader.getTopic(), requestHeader.getKey(), uniqueKeyFlag));
} else if (response.getCode() == ResponseCode.QUERY_NOT_FOUND) {
List<MessageExt> wrappers = new ArrayList<>();
future.complete(wrappers);
} else {
log.warn("queryMessage getResponseCommand failed, {} {}, header={}", response.getCode(), response.getRemark(), requestHeader);
future.completeExceptionally(new MQClientException(response.getCode(), response.getRemark()));
}
});
return future;
} | @Test
public void assertQueryMessageWithNotFound() throws Exception {
when(response.getCode()).thenReturn(ResponseCode.QUERY_NOT_FOUND);
QueryMessageRequestHeader requestHeader = mock(QueryMessageRequestHeader.class);
CompletableFuture<List<MessageExt>> actual = mqClientAdminImpl.queryMessage(defaultBrokerAddr, false, false, requestHeader, defaultTimeout);
List<MessageExt> messageExtList = actual.get();
assertNotNull(messageExtList);
assertEquals(0, messageExtList.size());
} |
public static CsvReader getReader(CsvReadConfig config) {
return new CsvReader(config);
} | @Test
public void readTest() {
CsvReader reader = CsvUtil.getReader();
//从文件中读取CSV数据
CsvData data = reader.read(FileUtil.file("test.csv"));
List<CsvRow> rows = data.getRows();
final CsvRow row0 = rows.get(0);
assertEquals("sss,sss", row0.get(0));
assertEquals("姓名", row0.get(1));
assertEquals("性别", row0.get(2));
assertEquals("关注\"对象\"", row0.get(3));
assertEquals("年龄", row0.get(4));
assertEquals("", row0.get(5));
assertEquals("\"", row0.get(6));
} |
private MergeSortedPages() {} | @Test
public void testSortingYields()
throws Exception
{
DriverYieldSignal yieldSignal = new DriverYieldSignal();
yieldSignal.forceYieldForTesting();
List<Type> types = ImmutableList.of(INTEGER);
WorkProcessor<Page> mergedPages = MergeSortedPages.mergeSortedPages(
ImmutableList.of(WorkProcessor.fromIterable(rowPagesBuilder(types)
.row(1)
.build())),
new SimplePageWithPositionComparator(types, ImmutableList.of(0), ImmutableList.of(DESC_NULLS_LAST)),
ImmutableList.of(0),
types,
(pageBuilder, pageWithPosition) -> pageBuilder.isFull(),
false,
newSimpleAggregatedMemoryContext().newAggregatedMemoryContext(),
yieldSignal);
// yield signal is on
assertFalse(mergedPages.process());
yieldSignal.resetYieldForTesting();
// page is produced
assertTrue(mergedPages.process());
assertFalse(mergedPages.isFinished());
Page page = mergedPages.getResult();
MaterializedResult expected = resultBuilder(TEST_SESSION, types)
.row(1)
.build();
assertEquals(toMaterializedResult(TEST_SESSION, types, ImmutableList.of(page)), expected);
// merge source finished
assertTrue(mergedPages.process());
assertTrue(mergedPages.isFinished());
} |
@Override
public TimestampedKeyValueStore<K, V> build() {
KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof TimestampedBytesStore)) {
if (store.persistent()) {
store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store);
} else {
store = new InMemoryTimestampedKeyValueStoreMarker(store);
}
}
return new MeteredTimestampedKeyValueStore<>(
maybeWrapCaching(maybeWrapLogging(store)),
storeSupplier.metricsScope(),
time,
keySerde,
valueSerde);
} | @Test
public void shouldHaveCachingAndChangeLoggingWhenBothEnabled() {
setUp();
final TimestampedKeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.withCachingEnabled()
.build();
final WrappedStateStore caching = (WrappedStateStore) ((WrappedStateStore) store).wrapped();
final WrappedStateStore changeLogging = (WrappedStateStore) caching.wrapped();
assertThat(store, instanceOf(MeteredTimestampedKeyValueStore.class));
assertThat(caching, instanceOf(CachingKeyValueStore.class));
assertThat(changeLogging, instanceOf(ChangeLoggingTimestampedKeyValueBytesStore.class));
assertThat(changeLogging.wrapped(), CoreMatchers.equalTo(inner));
} |
public UserGroupDto addMembership(String groupUuid, String userUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
UserDto userDto = findUserOrThrow(userUuid, dbSession);
GroupDto groupDto = findNonDefaultGroupOrThrow(groupUuid, dbSession);
UserGroupDto userGroupDto = new UserGroupDto().setGroupUuid(groupUuid).setUserUuid(userUuid);
checkArgument(isNotInGroup(dbSession, groupUuid, userUuid), "User '%s' is already a member of group '%s'", userDto.getLogin(), groupDto.getName());
userGroupDao.insert(dbSession, userGroupDto, groupDto.getName(), userDto.getLogin());
dbSession.commit();
return userGroupDto;
}
} | @Test
public void addMembership_ifGroupNotFound_shouldThrow() {
mockUserDto();
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> groupMembershipService.addMembership(GROUP_A, USER_1))
.withMessage("Group 'group_a' not found");
} |
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception { // NOPMD
// cette méthode est appelée par le conteneur ejb grâce à l'annotation AroundInvoke
if (DISABLED || !EJB_COUNTER.isDisplayed()) {
return context.proceed();
}
// nom identifiant la requête
final String requestName = getRequestName(context);
boolean systemError = false;
try {
EJB_COUNTER.bindContextIncludingCpu(requestName);
return context.proceed();
} catch (final Error e) {
// on catche Error pour avoir les erreurs systèmes
// mais pas Exception qui sont fonctionnelles en général
systemError = true;
throw e;
} finally {
// on enregistre la requête dans les statistiques
EJB_COUNTER.addRequestForCurrentContext(systemError);
}
} | @Test
public void testMonitoringCdi() throws Exception {
final Counter ejbCounter = MonitoringProxy.getEjbCounter();
ejbCounter.clear();
final MonitoringCdiInterceptor interceptor = new MonitoringCdiInterceptor();
ejbCounter.setDisplayed(true);
interceptor.intercept(new InvokeContext(false));
assertSame("requestsCount", 1, ejbCounter.getRequestsCount());
} |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 0. 初始化积分
MemberUserRespDTO user = memberUserApi.getUser(param.getUserId());
result.setTotalPoint(user.getPoint()).setUsePoint(0);
// 1.1 校验是否使用积分
if (!BooleanUtil.isTrue(param.getPointStatus())) {
return;
}
// 1.2 校验积分抵扣是否开启
MemberConfigRespDTO config = memberConfigApi.getConfig();
if (!isDeductPointEnable(config)) {
return;
}
// 1.3 校验用户积分余额
if (user.getPoint() == null || user.getPoint() <= 0) {
return;
}
// 2.1 计算积分优惠金额
int pointPrice = calculatePointPrice(config, user.getPoint(), result);
// 2.2 计算分摊的积分、抵扣金额
List<TradePriceCalculateRespBO.OrderItem> orderItems = filterList(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSelected);
List<Integer> dividePointPrices = TradePriceCalculatorHelper.dividePrice(orderItems, pointPrice);
List<Integer> divideUsePoints = TradePriceCalculatorHelper.dividePrice(orderItems, result.getUsePoint());
// 3.1 记录优惠明细
TradePriceCalculatorHelper.addPromotion(result, orderItems,
param.getUserId(), "积分抵扣", PromotionTypeEnum.POINT.getType(),
StrUtil.format("积分抵扣:省 {} 元", TradePriceCalculatorHelper.formatPrice(pointPrice)),
dividePointPrices);
// 3.2 更新 SKU 优惠金额
for (int i = 0; i < orderItems.size(); i++) {
TradePriceCalculateRespBO.OrderItem orderItem = orderItems.get(i);
orderItem.setPointPrice(dividePointPrices.get(i));
orderItem.setUsePoint(divideUsePoints.get(i));
TradePriceCalculatorHelper.recountPayPrice(orderItem);
}
TradePriceCalculatorHelper.recountAllPrice(result);
} | @Test
public void testCalculate_PointStatusFalse() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(233L).setPointStatus(false) // 是否使用积分
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2).setSelected(true), // 使用积分
new TradePriceCalculateReqBO.Item().setSkuId(20L).setCount(3).setSelected(true), // 使用积分
new TradePriceCalculateReqBO.Item().setSkuId(30L).setCount(5).setSelected(false) // 未选中,不使用积分
));
TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
.setType(TradeOrderTypeEnum.NORMAL.getType())
.setPrice(new TradePriceCalculateRespBO.Price())
.setPromotions(new ArrayList<>())
.setItems(asList(
new TradePriceCalculateRespBO.OrderItem().setSkuId(10L).setCount(2).setSelected(true)
.setPrice(100).setSpuId(1L),
new TradePriceCalculateRespBO.OrderItem().setSkuId(20L).setCount(3).setSelected(true)
.setPrice(50).setSpuId(2L),
new TradePriceCalculateRespBO.OrderItem().setSkuId(30L).setCount(5).setSelected(false)
.setPrice(30).setSpuId(3L)
));
// 保证价格被初始化上
TradePriceCalculatorHelper.recountPayPrice(result.getItems());
TradePriceCalculatorHelper.recountAllPrice(result);
// 调用
tradePointUsePriceCalculator.calculate(param, result);
// 断言:没有使用积分
assertNotUsePoint(result);
} |
public static String expandVars(String env) {
OrderedProperties ops = new OrderedProperties();
ops.addStringPairs(env);
Map<String, String> map = ops.asMap();
StringBuilder resultBuilder = new StringBuilder();
for (Map.Entry<String, String> entry: map.entrySet()) {
resultBuilder.append(entry.getKey() + "=" + expandVar(entry.getValue(), ops.asMap()) + "\n");
}
return resultBuilder.toString();
} | @Test
public void testVarExpansion() {
String input = "log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\n" +
"log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\n" +
"log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %p %m (%c) [%t]%n\n" +
"mirrormaker.root.logger=INFO\n" +
"log4j.rootLogger=${mirrormaker.root.logger}, CONSOLE";
String expectedOutput = "log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\n" +
"log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\n" +
"log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %p %m (%c) [%t]%n\n" +
"mirrormaker.root.logger=INFO\n" +
"log4j.rootLogger=INFO, CONSOLE\n";
String result = Util.expandVars(input);
assertThat(result, is(expectedOutput));
} |
protected static boolean assertFalse(String string) {
return string == null
|| StringUtils.EMPTY.equals(string)
|| StringUtils.FALSE.equalsIgnoreCase(string)
|| StringUtils.NULL.equals(string);
} | @Test
public void assertFalse() {
Assert.assertTrue(ConfigValueHelper.assertFalse(null));
Assert.assertTrue(ConfigValueHelper.assertFalse(""));
Assert.assertTrue(ConfigValueHelper.assertFalse("fALse"));
Assert.assertTrue(ConfigValueHelper.assertFalse("null"));
Assert.assertFalse(ConfigValueHelper.assertFalse("xasda"));
} |
public void fetchStringValues(String column, int[] inDocIds, int length, String[] outValues) {
_columnValueReaderMap.get(column).readStringValues(inDocIds, length, outValues);
} | @Test
public void testFetchStringValues() {
testFetchStringValues(INT_COLUMN);
testFetchStringValues(LONG_COLUMN);
testFetchStringValues(FLOAT_COLUMN);
testFetchStringValues(DOUBLE_COLUMN);
testFetchStringValues(BIG_DECIMAL_COLUMN);
testFetchStringValues(STRING_COLUMN);
testFetchStringValues(NO_DICT_INT_COLUMN);
testFetchStringValues(NO_DICT_LONG_COLUMN);
testFetchStringValues(NO_DICT_FLOAT_COLUMN);
testFetchStringValues(NO_DICT_DOUBLE_COLUMN);
testFetchStringValues(NO_DICT_BIG_DECIMAL_COLUMN);
testFetchStringValues(NO_DICT_STRING_COLUMN);
} |
@Override
public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() {
return new UnbindChangeProcessor();
} | @Test
public void leftJoinShouldPropagateDeletionOfAPrimaryKey() {
final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>();
leftJoinProcessor.init(context);
context.setRecordMetadata("topic", 0, 0);
leftJoinProcessor.process(new Record<>(pk, new Change<>(null, new LeftValue(fk1)), 0));
assertThat(context.forwarded().size(), greaterThan(0));
assertThat(
context.forwarded().get(0).record(),
is(new Record<>(fk1, new SubscriptionWrapper<>(null, DELETE_KEY_AND_PROPAGATE, pk, 0), 0))
);
} |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw Status.UNAUTHENTICATED.asRuntimeException();
}
final Mono<Account> account = switch (request.getAuthenticationCase()) {
case GROUP_SEND_TOKEN ->
groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), List.of(targetIdentifier))
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier)))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()));
case UNIDENTIFIED_ACCESS_KEY ->
getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
default -> Mono.error(Status.INVALID_ARGUMENT.asException());
};
return account.map(targetAccount -> ProfileGrpcHelper.buildUnversionedProfileResponse(targetIdentifier,
null,
targetAccount,
profileBadgeConverter));
} | @Test
void getUnversionedProfileNoAuth() {
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
} |
@SuppressWarnings("unchecked")
@Override
protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
// simple types
if (initialInstance.isValid() && !(initialInstance.getValue() instanceof Map)) {
return initialInstance.getValue();
}
Map<String, Object> toReturn = (Map<String, Object>) initialInstance.orElseGet(HashMap::new);
for (Map.Entry<List<String>, Object> listObjectEntry : params.entrySet()) {
// direct mapping already considered
if (listObjectEntry.getKey().isEmpty()) {
continue;
}
List<String> allSteps = listObjectEntry.getKey();
List<String> steps = allSteps.subList(0, allSteps.size() - 1);
String lastStep = allSteps.get(allSteps.size() - 1);
Map<String, Object> targetMap = toReturn;
for (String step : steps) {
targetMap = (Map<String, Object>) targetMap.computeIfAbsent(step, k -> new HashMap<>());
}
targetMap.put(lastStep, listObjectEntry.getValue());
}
return toReturn;
} | @Test
public void createObject_directMappingSimpleType() {
Map<List<String>, Object> params = new HashMap<>();
String directMappingSimpleTypeValue = "TestName";
params.put(List.of(), directMappingSimpleTypeValue);
ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params);
Object objectRaw = runnerHelper.createObject(initialInstance, String.class.getCanonicalName(), params, getClass().getClassLoader());
assertThat(objectRaw).isInstanceOf(String.class).isEqualTo(directMappingSimpleTypeValue);
} |
@Override
public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp,
final String srcUser) {
ConfigInfoStateWrapper configInfo4BetaState = this.findConfigInfo4BetaState(configInfo.getDataId(),
configInfo.getGroup(), configInfo.getTenant());
if (configInfo4BetaState == null) {
return addConfigInfo4Beta(configInfo, betaIps, srcIp, srcUser);
} else {
return updateConfigInfo4Beta(configInfo, betaIps, srcIp, srcUser);
}
} | @Test
void testInsertOrUpdateBetaOfException() {
String dataId = "betaDataId113";
String group = "group113";
String tenant = "tenant113";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper.setDataId(dataId);
mockedConfigInfoStateWrapper.setGroup(group);
mockedConfigInfoStateWrapper.setTenant(tenant);
mockedConfigInfoStateWrapper.setId(123456L);
mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis());
when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(mockedConfigInfoStateWrapper);
String betaIps = "betaips...";
String srcIp = "srcUp...";
String srcUser = "srcUser...";
String appName = "appname";
String content = "content111";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
configInfo.setEncryptedDataKey("key34567");
// mock update throw CannotGetJdbcConnectionException
when(jdbcTemplate.update(anyString(), eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser),
eq(configInfo.getAppName()), eq(configInfo.getEncryptedDataKey()), eq(dataId), eq(group),
eq(tenant))).thenThrow(new CannotGetJdbcConnectionException("mock fail"));
//execute of update& expect.
try {
externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser);
assertTrue(false);
} catch (Exception exception) {
assertEquals("mock fail", exception.getMessage());
}
//mock query return null
when(jdbcTemplate.queryForObject(anyString(), eq(new Object[]{dataId, group, tenant}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null);
//mock add throw CannotGetJdbcConnectionException
when(jdbcTemplate.update(anyString(), eq(dataId), eq(group), eq(tenant), eq(configInfo.getAppName()),
eq(configInfo.getContent()), eq(configInfo.getMd5()), eq(betaIps), eq(srcIp), eq(srcUser),
eq(configInfo.getEncryptedDataKey()))).thenThrow(new CannotGetJdbcConnectionException("mock fail add"));
//execute of add& expect.
try {
externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser);
assertTrue(false);
} catch (Exception exception) {
assertEquals("mock fail add", exception.getMessage());
}
//mock query throw CannotGetJdbcConnectionException
when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {dataId, group, tenant}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenThrow(new CannotGetJdbcConnectionException("get c fail"));
//execute of add& expect.
try {
externalConfigInfoBetaPersistService.insertOrUpdateBeta(configInfo, betaIps, srcIp, srcUser);
assertTrue(false);
} catch (Exception exception) {
assertEquals("get c fail", exception.getMessage());
}
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testImplicitCrossJoin()
{
// TODO: validate output
analyze("SELECT * FROM t1, t2");
} |
public static void cleanBuffer(final ByteBuffer buffer) {
if (null == buffer) {
return;
}
if (!buffer.isDirect()) {
return;
}
PlatformDependent.freeDirectBuffer(buffer);
} | @Test
public void testCleanBuffer() {
UtilAll.cleanBuffer(null);
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(10));
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(0));
UtilAll.cleanBuffer(ByteBuffer.allocate(10));
} |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void lifecycleCheckEndDisabled_shouldRouteThroughOnError() {
TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED);
testSource(resolveScopeFromLifecycle(lifecycle, false))
.assertError(LifecycleEndedException.class);
} |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), windows);
} | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullOtherStreamOnJoinWithStreamJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(
null,
MockValueJoiner.TOSTRING_JOINER,
JoinWindows.of(ofMillis(10)),
StreamJoined.as("name")));
assertThat(exception.getMessage(), equalTo("otherStream can't be null"));
} |
public static MonthsWindows months(int number) {
return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC);
} | @Test
public void testMonths() throws Exception {
Map<IntervalWindow, Set<String>> expected = new HashMap<>();
final List<Long> timestamps =
Arrays.asList(
makeTimestamp(2014, 1, 1, 0, 0).getMillis(),
makeTimestamp(2014, 1, 31, 5, 5).getMillis(),
makeTimestamp(2014, 2, 1, 0, 0).getMillis(),
makeTimestamp(2014, 2, 15, 5, 5).getMillis(),
makeTimestamp(2015, 1, 1, 0, 0).getMillis(),
makeTimestamp(2015, 1, 31, 5, 5).getMillis());
expected.put(
new IntervalWindow(makeTimestamp(2014, 1, 1, 0, 0), makeTimestamp(2014, 2, 1, 0, 0)),
set(timestamps.get(0), timestamps.get(1)));
expected.put(
new IntervalWindow(makeTimestamp(2014, 2, 1, 0, 0), makeTimestamp(2014, 3, 1, 0, 0)),
set(timestamps.get(2), timestamps.get(3)));
expected.put(
new IntervalWindow(makeTimestamp(2015, 1, 1, 0, 0), makeTimestamp(2015, 2, 1, 0, 0)),
set(timestamps.get(4), timestamps.get(5)));
assertEquals(expected, runWindowFn(CalendarWindows.months(1), timestamps));
} |
public Map<String, String> confirm(RdaConfirmRequest params) {
AppSession appSession = appSessionService.getSession(params.getAppSessionId());
AppAuthenticator appAuthenticator = appAuthenticatorService.findByUserAppId(appSession.getUserAppId());
if(!checkSecret(params, appSession) || !checkAccount(params, appSession)){
appSession.setRdaSessionStatus("ABORTED");
appSessionService.save(appSession);
return Map.of("arrivalStatus", "NOK");
}
if(checkAndProcessError(params, appSession)){
appSessionService.save(appSession);
return Map.of("arrivalStatus", "OK");
}
if (!switchService.digidAppSwitchEnabled()) {
digidClient.remoteLog("853",
Map.of(lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId(), lowerUnderscore(HIDDEN), true));
appSession.setRdaSessionStatus("REFUTED");
} else if (!switchService.digidRdaSwitchEnabled()){
digidClient.remoteLog("579",
Map.of(lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId(), lowerUnderscore(HIDDEN), true));
appSession.setRdaSessionStatus("REFUTED");
} else if (params.isVerified() && (SCANNING.equals(appSession.getRdaSessionStatus()) ||
SCANNING_FOREIGN.equals(appSession.getRdaSessionStatus()))) {
appSession.setRdaSessionStatus("VERIFIED");
appAuthenticator.setSubstantieelActivatedAt(ZonedDateTime.now());
appAuthenticator.setSubstantieelDocumentType(params.getDocumentType().toLowerCase());
if (appAuthenticator.getWidActivatedAt() == null) {
appAuthenticator.setIssuerType("rda");
}
storeIdCheckDocument(params.getDocumentNumber(), params.getDocumentType(), appSession.getAccountId(), appAuthenticator.getUserAppId());
if (ID_CHECK_ACTION.equals(appSession.getRdaAction())) {
digidClient.remoteLog("1321",
Map.of("document_type", params.getDocumentType().toLowerCase(), lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId()));
} else {
digidClient.remoteLog("848",
Map.of("document_type", params.getDocumentType().toLowerCase(),
lowerUnderscore(ACCOUNT_ID), appAuthenticator.getAccountId(),
lowerUnderscore(APP_CODE), appAuthenticator.getAppCode(),
lowerUnderscore(DEVICE_NAME), appAuthenticator.getDeviceName()));
}
appAuthenticatorService.save(appAuthenticator);
if(appSession.getFlow().equals(UpgradeLoginLevel.NAME)) {
digidClient.sendNotificationMessage(appSession.getAccountId(), "ED024", "SMS20");
logger.debug("Sending notify email ED024 / SMS20 for device {}", appAuthenticator.getDeviceName());
}
}
appSession.setAppAuthenticationLevel(appAuthenticator.getAuthenticationLevel());
appSessionService.save(appSession);
return Map.of("arrivalStatus", "OK");
} | @Test
void checkForeignBsnError(){
appSession.setRdaSessionStatus("SCANNING_FOREIGN");
when(appSessionService.getSession(any())).thenReturn(appSession);
when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator);
when(digidClient.checkBsn(any(),any())).thenReturn(Map.of(STATUS, "NOK"));
Map<String, String> result = rdaService.confirm(rdaConfirmRequest);
assertEquals("BSN_NOT_MATCHING", appSession.getRdaSessionStatus());
assertEquals("OK", result.get("arrivalStatus"));
} |
@Override
protected Source.Reader<T> createReader(@Nonnull FlinkSourceSplit<T> sourceSplit)
throws IOException {
Source<T> beamSource = sourceSplit.getBeamSplitSource();
return createUnboundedSourceReader(beamSource, sourceSplit.getSplitState());
} | @Test
public void testSnapshotStateAndRestore() throws Exception {
final int numSplits = 2;
final int numRecordsPerSplit = 10;
List<FlinkSourceSplit<KV<Integer, Integer>>> splits =
createSplits(numSplits, numRecordsPerSplit, 0);
RecordsValidatingOutput validatingOutput = new RecordsValidatingOutput(splits);
List<FlinkSourceSplit<KV<Integer, Integer>>> snapshot;
// Create a reader, take a snapshot.
try (SourceReader<
WindowedValue<ValueWithRecordId<KV<Integer, Integer>>>,
FlinkSourceSplit<KV<Integer, Integer>>>
reader = createReader()) {
pollAndValidate(reader, splits, validatingOutput, numSplits * numRecordsPerSplit / 2);
snapshot = reader.snapshotState(0L);
}
// Create another reader, add the snapshot splits back.
try (SourceReader<
WindowedValue<ValueWithRecordId<KV<Integer, Integer>>>,
FlinkSourceSplit<KV<Integer, Integer>>>
reader = createReader()) {
pollAndValidate(reader, snapshot, validatingOutput, Integer.MAX_VALUE);
}
} |
@Override
public PageData<User> findTenantAdmins(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(
userRepository
.findUsersByAuthority(
tenantId,
NULL_UUID,
pageLink.getTextSearch(),
Authority.TENANT_ADMIN,
DaoUtil.toPageable(pageLink)));
} | @Test
public void testFindTenantAdmins() {
PageLink pageLink = new PageLink(20);
PageData<User> tenantAdmins1 = userDao.findTenantAdmins(tenantId, pageLink);
assertEquals(20, tenantAdmins1.getData().size());
pageLink = pageLink.nextPageLink();
PageData<User> tenantAdmins2 = userDao.findTenantAdmins(tenantId,
pageLink);
assertEquals(10, tenantAdmins2.getData().size());
pageLink = pageLink.nextPageLink();
PageData<User> tenantAdmins3 = userDao.findTenantAdmins(tenantId,
pageLink);
assertEquals(0, tenantAdmins3.getData().size());
} |
public static JavaToSqlTypeConverter javaToSqlConverter() {
return JAVA_TO_SQL_CONVERTER;
} | @Test
public void shouldConvertJavaLongToSqlBigInt() {
assertThat(javaToSqlConverter().toSqlType(Long.class), is(SqlBaseType.BIGINT));
} |
public TolerantFloatComparison isNotWithin(float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected);
checkTolerance(tolerance);
if (!notEqualWithinTolerance(actual, expected, tolerance)) {
failWithoutActual(
fact("expected not to be", floatToString(expected)),
butWas(),
fact("within tolerance", floatToString(tolerance)));
}
}
};
} | @Test
public void isNotWithinOf() {
assertThatIsNotWithinFails(2.0f, 0.0f, 2.0f);
assertThatIsNotWithinFails(2.0f, 0.00001f, 2.0f);
assertThatIsNotWithinFails(2.0f, 1000.0f, 2.0f);
assertThatIsNotWithinFails(2.0f, 1.00001f, 3.0f);
assertThat(2.0f).isNotWithin(0.99999f).of(3.0f);
assertThat(2.0f).isNotWithin(1000.0f).of(1003.0f);
assertThatIsNotWithinFails(2.0f, 0.0f, Float.POSITIVE_INFINITY);
assertThatIsNotWithinFails(2.0f, 0.0f, Float.NaN);
assertThatIsNotWithinFails(Float.NEGATIVE_INFINITY, 1000.0f, 2.0f);
assertThatIsNotWithinFails(Float.NaN, 1000.0f, 2.0f);
} |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupCommands);
} | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldThrowIfCannotDeleteTopic() {
// Given:
when(topicClient.isTopicExists(COMMAND_TOPIC_NAME)).thenReturn(true).thenReturn(true);
doThrow(new RuntimeException("denied")).when(topicClient)
.deleteTopics(Collections.singletonList(COMMAND_TOPIC_NAME));
// When:
final Exception e = assertThrows(
RuntimeException.class,
() -> restoreCommandTopic.restore(Collections.singletonList(BACKUP_COMMANDS.get(0))));
// Then:
assertThat(e.getMessage(), containsString("denied"));
verify(topicClient).isTopicExists(COMMAND_TOPIC_NAME);
verify(topicClient).deleteTopics(Collections.singletonList(COMMAND_TOPIC_NAME));
verifyNoMoreInteractions(topicClient);
verifyNoMoreInteractions(kafkaProducer);
} |
@Override
public void getChildren(final String path, final boolean watch, final AsyncCallback.ChildrenCallback cb, final Object ctx)
{
if (!SymlinkUtil.containsSymlink(path))
{
_zk.getChildren(path, watch, cb, ctx);
}
else
{
SymlinkChildrenCallback compositeCallback = new SymlinkChildrenCallback(path, _defaultWatcher, cb);
getChildren0(path, watch ? compositeCallback : null, compositeCallback, ctx);
}
} | @Test
public void testSymlinkWithChildrenWatcher2() throws ExecutionException, InterruptedException
{
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AsyncCallback.ChildrenCallback callback2 = new AsyncCallback.ChildrenCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, List<String> children)
{
Assert.assertEquals(path, "/foo/$link");
Assert.assertEquals(children.size(), 5);
latch2.countDown();
}
};
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
Assert.assertEquals(event.getType(), Event.EventType.NodeChildrenChanged);
_zkClient.getZooKeeper().getChildren(event.getPath(), null, callback2, null);
}
};
AsyncCallback.ChildrenCallback callback = new AsyncCallback.ChildrenCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, List<String> children)
{
latch1.countDown();
}
};
// set watcher to /foo/$link
_zkClient.getZooKeeper().getChildren("/foo/$link", watcher, callback, null);
latch1.await(30, TimeUnit.SECONDS);
// update symlink
_zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback<>());
latch2.await(30, TimeUnit.SECONDS);
FutureCallback<None> fcb = new FutureCallback<>();
// restore symlink
_zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb);
fcb.get();
} |
public static Optional<OP_TYPE> getOpTypeFromTargets(Targets targets, String fieldName) {
if (targets != null && targets.getTargets() != null) {
return targets.getTargets().stream()
.filter(target -> Objects.equals(fieldName,target.getField()) && target.getOpType() != null)
.findFirst()
.map(dataField -> OP_TYPE.byName(dataField.getOpType().value()));
} else {
return Optional.empty();
}
} | @Test
void getOpTypeFromTargets() {
Optional<OP_TYPE> opType = org.kie.pmml.compiler.api.utils.ModelUtils.getOpTypeFromTargets(null, "vsd");
assertThat(opType).isNotNull();
assertThat(opType.isPresent()).isFalse();
final Targets targets = new Targets();
opType = org.kie.pmml.compiler.api.utils.ModelUtils.getOpTypeFromTargets(targets, "vsd");
assertThat(opType).isNotNull();
assertThat(opType.isPresent()).isFalse();
IntStream.range(0, 3).forEach(i -> {
final Target target = getRandomTarget();
targets.addTargets(target);
});
targets.getTargets().forEach(target -> {
Optional<OP_TYPE> retrieved = org.kie.pmml.compiler.api.utils.ModelUtils.getOpTypeFromTargets(targets,target.getField());
assertThat(retrieved).isNotNull();
assertThat(retrieved).isPresent();
OP_TYPE expected = OP_TYPE.byName(target.getOpType().value());
assertThat(retrieved.get()).isEqualTo(expected);
});
} |
public static String sanitizePath(String path) {
String sanitized = path;
if (path != null) {
sanitized = PATH_USERINFO_PASSWORD.matcher(sanitized).replaceFirst("$1xxxxxx$3");
}
return sanitized;
} | @Test
public void testSanitizePathWithUserInfoAndColonPassword() {
String path = "USERNAME:HARRISON:[email protected]";
String expected = "USERNAME:[email protected]";
assertEquals(expected, URISupport.sanitizePath(path));
} |
@Override
public int hashCode() {
return Arrays.hashCode(components);
} | @Test
public void testEqualsAndHashCode() {
CompositeValue a = value("a", 'a');
assertThat(a).isNotNull();
assertThat(a).isEqualTo(a);
assertThat(value("a", 'a')).isEqualTo(value("a", 'a'));
assertThat(value("a", 'a').hashCode()).isEqualTo(value("a", 'a').hashCode());
assertThat(value("a", 'a')).isNotEqualTo(value('a', "a"));
assertThat(value("a", 'a')).isNotEqualTo(value("b", 'b'));
assertThat(value("a", 'a')).isNotEqualTo(value('b', "b"));
assertThat(value("a", 'a')).isNotEqualTo(value(null, 'a'));
assertThat(value("a", 'a')).isNotEqualTo(value("a", NULL));
assertThat(value("a", 'a')).isNotEqualTo(value("a", NEGATIVE_INFINITY));
assertThat(value("a", 'a')).isNotEqualTo(value("a", POSITIVE_INFINITY));
} |
@Override
public boolean register(String name, ProcNodeInterface node) {
return false;
} | @Test
public void testRegister() {
Assert.assertFalse(optimizeProcDir.register(null, null));
} |
@Override
public List<OAuth2ApproveDO> getApproveList(Long userId, Integer userType, String clientId) {
List<OAuth2ApproveDO> approveDOs = oauth2ApproveMapper.selectListByUserIdAndUserTypeAndClientId(
userId, userType, clientId);
approveDOs.removeIf(o -> DateUtils.isExpired(o.getExpiresTime()));
return approveDOs;
} | @Test
public void testGetApproveList() {
// 准备参数
Long userId = 10L;
Integer userType = UserTypeEnum.ADMIN.getValue();
String clientId = randomString();
// mock 数据
OAuth2ApproveDO approve = randomPojo(OAuth2ApproveDO.class).setUserId(userId)
.setUserType(userType).setClientId(clientId).setExpiresTime(LocalDateTimeUtil.offset(LocalDateTime.now(), 1L, ChronoUnit.DAYS));
oauth2ApproveMapper.insert(approve); // 未过期
oauth2ApproveMapper.insert(ObjectUtil.clone(approve).setId(null)
.setExpiresTime(LocalDateTimeUtil.offset(LocalDateTime.now(), -1L, ChronoUnit.DAYS))); // 已过期
// 调用
List<OAuth2ApproveDO> result = oauth2ApproveService.getApproveList(userId, userType, clientId);
// 断言
assertEquals(1, result.size());
assertPojoEquals(approve, result.get(0));
} |
public static void write(ServiceInfo dom, String dir) {
try {
makeSureCacheDirExists(dir);
File file = new File(dir, dom.getKeyEncoded());
createFileIfAbsent(file, false);
StringBuilder keyContentBuffer = new StringBuilder();
String json = dom.getJsonFromServer();
if (StringUtils.isEmpty(json)) {
json = JacksonUtils.toJson(dom);
}
keyContentBuffer.append(json);
//Use the concurrent API to ensure the consistency.
ConcurrentDiskUtil.writeFileContent(file, keyContentBuffer.toString(), Charset.defaultCharset().toString());
} catch (Throwable e) {
NAMING_LOGGER.error("[NA] failed to write cache for dom:" + dom.getName(), e);
}
} | @Test
void testWriteCacheWithErrorPath() {
File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded());
try {
file.mkdirs();
DiskCache.write(serviceInfo, CACHE_DIR);
assertTrue(file.isDirectory());
} finally {
file.delete();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.