focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@JsonIgnore
public Map<String, StepTransition> getDag() {
return steps.stream().collect(MapHelper.toListMap(Step::getId, Step::getTransition));
} | @Test
public void testGetDag() throws Exception {
Workflow wf =
loadObject(
"fixtures/workflows/definition/sample-active-wf-with-props.json",
WorkflowDefinition.class)
.getWorkflow();
assertEquals(
threeItemMap(
"job.1", wf.getSteps().get... |
public Attributes readDataset() throws IOException {
return readDataset(o -> false);
} | @Test(expected = EOFException.class)
public void testNoOutOfMemoryErrorOnInvalidLength() throws IOException {
byte[] b = { 8, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 'e', 'v', 'i', 'l', 'l', 'e', 'n', 'g', 'h' };
try ( DicomInputStream in = new DicomInputStream(new ByteArrayInputStream(b))) {
i... |
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
Marshaller marshaller = getContext(clazz).createMarshaller();
setMarshallerProperties(marshaller);
if (marshallerEventHandler != null) {
marshaller.setEventHandler(marshallerEventHandler);
}
marshaller.setSchema(marshall... | @Test
void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder()
.withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd").build();
Marshaller marshaller = factory.createMarshaller(Object.class)... |
@Override
public void upgrade() {
if (configService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed.");
return;
}
var previousMigration = Optional.ofNullable(configService.get(V20191219090834_AddSourcesPage.MigrationCompleted.class));
... | @Test
void alreadyMigrated() {
thisMigrationHasRun();
this.migration.upgrade();
verify(clusterConfigService, never()).get(V20191219090834_AddSourcesPage.MigrationCompleted.class);
verify(clusterConfigService, never()).write(any());
} |
@Override
public void reportFailedCheckpoint(FailedCheckpointStats failed) {
statsReadWriteLock.lock();
try {
counts.incrementFailedCheckpoints();
history.replacePendingCheckpointById(failed);
dirty = true;
logCheckpointStatistics(failed);
... | @Test
void testCheckpointStatsListenerOnFailedCheckpoint() {
testCheckpointStatsListener(
(checkpointStatsTracker, pendingCheckpointStats) ->
checkpointStatsTracker.reportFailedCheckpoint(
pendingCheckpointStats.toFailedCheckpoint(
... |
@Override
public void deleteCategory(Long id) {
// 校验分类是否存在
validateProductCategoryExists(id);
// 校验是否还有子分类
if (productCategoryMapper.selectCountByParentId(id) > 0) {
throw exception(CATEGORY_EXISTS_CHILDREN);
}
// 校验分类是否绑定了 SPU
Long spuCount = pro... | @Test
public void testDeleteCategory_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> productCategoryService.deleteCategory(id), CATEGORY_NOT_EXISTS);
} |
public FEELFnResult<List<Object>> invoke(@ParameterName( "list" ) Object list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = new... | @Test
void invokeEmptyList() {
FunctionTestUtil.assertResultList(distinctValuesFunction.invoke(Collections.emptyList()),
Collections.emptyList());
} |
@Description("Returns the cardinality of the geometry collection")
@ScalarFunction("ST_NumGeometries")
@SqlType(INTEGER)
public static long stNumGeometries(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
Geometry geometry = deserialize(input);
if (geometry.isEmpty()) {
return 0;
... | @Test
public void testSTNumGeometries()
{
assertSTNumGeometries("POINT EMPTY", 0);
assertSTNumGeometries("LINESTRING EMPTY", 0);
assertSTNumGeometries("POLYGON EMPTY", 0);
assertSTNumGeometries("MULTIPOINT EMPTY", 0);
assertSTNumGeometries("MULTILINESTRING EMPTY", 0);
... |
@Override
public boolean supportsANSI92IntermediateSQL() {
return false;
} | @Test
void assertSupportsANSI92IntermediateSQL() {
assertFalse(metaData.supportsANSI92IntermediateSQL());
} |
@SafeVarargs
public static Optional<Predicate<Throwable>> createNegatedExceptionsPredicate(
Class<? extends Throwable>... ignoreExceptions) {
return exceptionPredicate(ignoreExceptions)
.map(Predicate::negate);
} | @Test
public void buildIgnoreExceptionsPredicate() {
Predicate<Throwable> predicate = PredicateCreator
.createNegatedExceptionsPredicate(RuntimeException.class, BusinessException.class)
.orElseThrow();
then(predicate.test(new RuntimeException())).isFalse();
then(pred... |
@Override
public SinkWriter<WindowedValue<IsmRecord<V>>> writer() throws IOException {
return new IsmSinkWriter(FileSystems.create(resourceId, MimeTypes.BINARY));
} | @Test
public void testWriteOutOfOrderKeysWithSameShardKeyIsError() throws Throwable {
IsmSink<byte[]> sink =
new IsmSink<>(
FileSystems.matchNewResource(tmpFolder.newFile().getPath(), false),
CODER,
BLOOM_FILTER_SIZE_LIMIT);
SinkWriter<WindowedValue<IsmRecord<byte[]... |
public static String fromBytes(byte[] bytes) throws IOException {
DataInputBuffer dbuf = new DataInputBuffer();
dbuf.reset(bytes, 0, bytes.length);
StringBuilder buf = new StringBuilder(bytes.length);
readChars(dbuf, buf, bytes.length);
return buf.toString();
} | @Test
public void test5ByteUtf8Sequence() throws Exception {
byte[] invalid = new byte[] {
0x01, 0x02, (byte)0xf8, (byte)0x88, (byte)0x80,
(byte)0x80, (byte)0x80, 0x04, 0x05 };
try {
UTF8.fromBytes(invalid);
fail("did not throw an exception");
} catch (UTFDataFormatException ut... |
public AlterSourceCommand create(final AlterSource statement) {
final DataSource dataSource = metaStore.getSource(statement.getName());
final String dataSourceType = statement.getDataSourceType().getKsqlType();
if (dataSource != null && dataSource.isSource()) {
throw new KsqlException(
Stri... | @Test
public void shouldCreateCommandForAlterTable() {
// Given:
final AlterSource alterSource = new AlterSource(TABLE_NAME, DataSourceType.KTABLE, NEW_COLUMNS);
// When:
final AlterSourceCommand result = alterSourceFactory.create(alterSource);
// Then:
assertEquals(result.getKsqlType(), Dat... |
public String toSnapshot(boolean hOption) {
return String.format(SNAPSHOT_FORMAT, formatSize(snapshotLength, hOption),
formatSize(snapshotFileCount, hOption),
formatSize(snapshotDirectoryCount, hOption),
formatSize(snapshotSpaceConsumed, hOption));
} | @Test
public void testToSnapshotNotHumanReadable() {
long snapshotLength = 1111;
long snapshotFileCount = 2222;
long snapshotDirectoryCount = 3333;
long snapshotSpaceConsumed = 4444;
ContentSummary contentSummary = new ContentSummary.Builder()
.snapshotLength(snapshotLength).snapshotFileC... |
@Override
public ProxyTopicRouteData getTopicRouteForProxy(ProxyContext ctx, List<Address> requestHostAndPortList,
String topicName) throws Exception {
TopicRouteData topicRouteData = getAllMessageQueueView(ctx, topicName).getTopicRouteData();
return new ProxyTopicRouteData(topicRouteData, r... | @Test
public void testGetTopicRouteForProxy() throws Throwable {
ProxyContext ctx = ProxyContext.create();
List<Address> addressList = Lists.newArrayList(new Address(Address.AddressScheme.IPv4, HostAndPort.fromParts("127.0.0.1", 8888)));
ProxyTopicRouteData proxyTopicRouteData = this.topicRo... |
@Override
public ByteBuf discardReadBytes() {
throw new ReadOnlyBufferException();
} | @Test
public void shouldRejectDiscardReadBytes() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
unmodifiableBuffer(EMPTY_BUFFER).discardReadBytes();
}
});
} |
CacheConfig<K, V> asCacheConfig() {
return this.copy(new CacheConfig<>(), false);
} | @Test
public void serializationSucceeds_whenKVTypes_setAsClassObjects() {
CacheConfig cacheConfig = newDefaultCacheConfig("test");
cacheConfig.setKeyType(Integer.class);
cacheConfig.setValueType(String.class);
PreJoinCacheConfig preJoinCacheConfig = new PreJoinCacheConfig(cacheConfig... |
public static String prettyJSON(String json) {
return prettyJSON(json, TAB_SEPARATOR);
} | @Test
public void testRenderResultSimpleStructure() throws Exception {
assertEquals("{\n" + TAB + "\"Hello\": \"World\",\n" + TAB + "\"more\": [\n"
+ TAB + TAB + "\"Something\",\n" + TAB
+ TAB + "\"else\"\n" + TAB + "]\n}", prettyJSON("{\"Hello\": \"World\", \"more\": [\"Some... |
public Set<String> getDataStorageTypes() {
return dataStorageMap.keySet();
} | @Test
void testGetDataStorageTypes() {
componentHolder.getDataStorageTypes();
} |
@VisibleForTesting
int getSignedEncodingLength(long n) {
return BITS_TO_LENGTH[log2Floor(n < 0 ? ~n : n) + 1];
} | @Test
public void testGetSignedEncodingLength() {
OrderedCode orderedCode = new OrderedCode();
assertEquals(10, orderedCode.getSignedEncodingLength(Long.MIN_VALUE));
assertEquals(10, orderedCode.getSignedEncodingLength(~(1L << 62)));
assertEquals(9, orderedCode.getSignedEncodingLength(~(1L << 62) + 1)... |
@Override
public boolean addAll(Collection<? extends E> c) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().addAll(c);
} | @Test
public void testDelegationOfUnsupportedFunctionAddAll() {
new PCollectionsHashSetWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.addAll(eq(Collections.emptyList())))
.defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.addAll(C... |
public double getLightHeight() {
return a;
} | @Test
public void examples() {
assertThat("neutral", example(0, 0), is(0));
assertThat("very much away from light", example(1000, -10000), is(-128));
assertThat("exactly pointing at light", example(1 / algo.getLightHeight(), 1 / algo.getLightHeight()), is(127));
} |
public ResourceMethodDescriptor process(final ServerResourceContext context)
{
String path = context.getRequestURI().getRawPath();
if (path.length() < 2)
{
throw new RoutingException(HttpStatus.S_404_NOT_FOUND.getCode());
}
if (path.charAt(0) == '/')
{
path = path.substring(1);
... | @Test
public void succeedsOnRootResourceGet() throws URISyntaxException
{
final TestSetup setup = new TestSetup();
setup.mockContextForRootResourceGetRequest(setup._rootPath + "/12345");
final RestLiRouter router = setup._router;
final ServerResourceContext context = setup._context;
final Resou... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testPreferredReadReplica() {
buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(),
Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis());
subscriptions.assignFromUser(singleton... |
public static String getPartitionColumn(TableConfig tableConfig) {
// check InstanceAssignmentConfigMap is null or empty,
if (!MapUtils.isEmpty(tableConfig.getInstanceAssignmentConfigMap())) {
for (InstanceAssignmentConfig instanceAssignmentConfig : tableConfig.getInstanceAssignmentConfigMap().values()) {... | @Test
public void testGetPartitionColumnWithoutAnyConfig() {
// without instanceAssignmentConfigMap
TableConfig tableConfig =
new TableConfigBuilder(TableType.REALTIME).setTableName(TABLE_NAME).build();
Assert.assertNull(TableConfigUtils.getPartitionColumn(tableConfig));
} |
public final StringSubject hasMessageThat() {
StandardSubjectBuilder check = check("getMessage()");
if (actual instanceof ErrorWithFacts && ((ErrorWithFacts) actual).facts().size() > 1) {
check =
check.withMessage(
"(Note from Truth: When possible, instead of asserting on the full ... | @Test
public void hasMessageThat_MessageHasNullMessage_failure() {
expectFailureWhenTestingThat(new NullPointerException("message")).hasMessageThat().isNull();
} |
public Order shipDate(OffsetDateTime shipDate) {
this.shipDate = shipDate;
return this;
} | @Test
public void shipDateTest() {
// TODO: test shipDate
} |
@Override
public Expression createExpression(Expression source, String expression, Object[] properties) {
return doCreateJsonPathExpression(source, expression, properties, false);
} | @Test
public void testExpressionPojo() {
Exchange exchange = new DefaultExchange(context);
Map pojo = new HashMap();
pojo.put("kind", "full");
pojo.put("type", "customer");
exchange.getIn().setBody(pojo);
Language lan = context.resolveLanguage("jsonpath");
Ex... |
public Blob build() throws IOException {
UniqueTarArchiveEntries uniqueTarArchiveEntries = new UniqueTarArchiveEntries();
// Adds all the layer entries as tar entries.
for (FileEntry layerEntry : layerEntries) {
// Adds the entries to uniqueTarArchiveEntries, which makes sure all entries are unique a... | @Test
public void testToBlob_reproducibility() throws IOException {
Path testRoot = temporaryFolder.getRoot().toPath();
Path root1 = Files.createDirectories(testRoot.resolve("files1"));
Path root2 = Files.createDirectories(testRoot.resolve("files2"));
// TODO: Currently this test only covers variatio... |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldDeserializedJsonArray() {
// Given:
final KsqlJsonDeserializer<List> deserializer = givenDeserializerForSchema(
SchemaBuilder
.array(Schema.OPTIONAL_INT64_SCHEMA)
.build(),
List.class
);
final byte[] bytes = serializeJson(ImmutableList.o... |
@Override
public void sendHeartbeatInvokeMessage(int currentId) {
var nextInstance = this.findNextInstance(currentId);
var heartbeatInvokeMessage = new Message(MessageType.HEARTBEAT_INVOKE, "");
nextInstance.onMessage(heartbeatInvokeMessage);
} | @Test
void testSendHeartbeatInvokeMessage() {
try {
var instance1 = new RingInstance(null, 1, 1);
var instance2 = new RingInstance(null, 1, 2);
var instance3 = new RingInstance(null, 1, 3);
Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3);
var mes... |
private long parseTimeoutMs() {
long timeout = options.has(timeoutMsOpt) ? options.valueOf(timeoutMsOpt) : -1;
return timeout >= 0 ? timeout : Long.MAX_VALUE;
} | @Test
public void testParseTimeoutMs() throws Exception {
String[] withoutTimeoutMs = new String[]{
"--bootstrap-server", "localhost:9092",
"--topic", "test",
"--partition", "0"
};
assertEquals(Long.MAX_VALUE, new ConsoleConsumerOptions(withoutTimeoutMs).t... |
@Override
public PageResult<MailAccountDO> getMailAccountPage(MailAccountPageReqVO pageReqVO) {
return mailAccountMapper.selectPage(pageReqVO);
} | @Test
public void testGetMailAccountPage() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class, o -> { // 等会查询到
o.setMail("768@qq.com");
o.setUsername("yunai");
});
mailAccountMapper.insert(dbMailAccount);
// 测试 mail 不匹配
m... |
private static FeedbackDelayGenerator resolveDelayGenerator(
final Context ctx,
final UdpChannel channel,
final boolean isMulticastSemantics)
{
if (isMulticastSemantics)
{
return ctx.multicastFeedbackDelayGenerator();
}
final Long nakDelayNs = cha... | @Test
void shouldInferFeedbackGeneratorBasedOnMulticastAddress()
{
final MediaDriver.Context context = new MediaDriver.Context()
.multicastFeedbackDelayGenerator(new OptimalMulticastDelayGenerator(10, 10))
.unicastFeedbackDelayGenerator(new StaticDelayGenerator(10));
fina... |
@Override
public String render(String text) {
if (StringUtils.isBlank(text)) {
return "";
}
if (regex.isEmpty() || link.isEmpty()) {
Comment comment = new Comment();
comment.escapeAndAdd(text);
return comment.render();
}
try {
... | @Test
public void shouldRenderStringWithSpecifiedRegexAndLink() throws Exception {
String link = "http://mingle05/projects/cce/cards/${ID}";
String regex = "(evo-\\d+)";
trackingTool = new DefaultCommentRenderer(link, regex);
String result = trackingTool.render("evo-111: checkin mes... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseMultipleTimestampStringAsTimestampInArray() throws Exception {
String tsStr1 = "2019-08-23T14:34:54.346Z";
String tsStr2 = "2019-01-23T15:12:34.567Z";
String tsStr3 = "2019-04-23T19:12:34.567Z";
String arrayStr = "[" + tsStr1 + "," + tsStr2 + ", " + tsS... |
@VisibleForTesting
static DeterminismEnvelope<ResourceID> getTaskManagerResourceID(
Configuration config, String rpcAddress, int rpcPort) {
final String metadata =
config.get(TaskManagerOptionsInternal.TASK_MANAGER_RESOURCE_ID_METADATA, "");
return config.getOptional(Tas... | @Test
void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception {
final Configuration configuration = createConfiguration();
final String rpcAddress = "flink";
final int rpcPort = 9090;
final ResourceID taskManagerResourceID =
TaskManagerRunner.get... |
public static HeightLock ofBlockHeight(int blockHeight) {
if (blockHeight < 0)
throw new IllegalArgumentException("illegal negative block height: " + blockHeight);
if (blockHeight >= THRESHOLD)
throw new IllegalArgumentException("block height too high: " + blockHeight);
r... | @Test
public void blockHeightSubtype() {
LockTime blockHeight = LockTime.ofBlockHeight(100);
assertTrue(blockHeight instanceof HeightLock);
assertTrue(((HeightLock) blockHeight).blockHeight() > 0);
} |
@Override
public boolean supports(String hashedPassword) {
return hashedPassword.startsWith(PREFIX) && hashedPassword.contains(SALT_PREFIX);
} | @Test
public void testSupports() throws Exception {
assertThat(bCryptPasswordAlgorithm.supports("foobar")).isFalse();
assertThat(bCryptPasswordAlgorithm.supports("{bcrypt}foobar")).isFalse();
assertThat(bCryptPasswordAlgorithm.supports("{bcrypt}foobar{salt}pepper")).isTrue();
assertT... |
public static String[] subtraction(String[] arr1, String[] arr2) {
if (arr1 == null || arr1.length == 0 || arr2 == null || arr2.length == 0) {
return arr1;
}
List<String> list = new ArrayList<>(Arrays.asList(arr1));
list.removeAll(Arrays.asList(arr2));
return list.toA... | @Test
void testArraySubtraction() {
assertNull(StringUtil.subtraction(null, arr("a", "test", "b", "a")));
assertArrayEquals(arr("a", "test", "b", "a"), StringUtil.subtraction(arr("a", "test", "b", "a"), null));
assertArrayEquals(arr("test"), StringUtil.subtraction(arr("a", "test", "b", "a"),... |
@Override
public Map<String, String> getAllVariables() {
Map<String, String> allVariables =
parentMetricGroup.getAllVariables(
this.settings.getReporterIndex(), this.settings.getExcludedVariables());
if (!this.settings.getAdditionalVariables().isEmpty()) {
... | @Test
void testGetAllVariablesWithAdditionalVariables() {
final FrontMetricGroup<?> frontMetricGroup =
new FrontMetricGroup<>(
new ReporterScopedSettings(
0,
'.',
MetricFil... |
public final void containsNoneIn(@Nullable Iterable<?> excluded) {
Collection<?> actual = iterableToCollection(checkNotNull(this.actual));
checkNotNull(excluded); // TODO(cpovirk): Produce a better exception message.
List<@Nullable Object> present = new ArrayList<>();
for (Object item : Sets.newLinkedHa... | @Test
public void iterableContainsNoneInArray() {
assertThat(asList(1, 2, 3)).containsNoneIn(new Integer[] {4, 5, 6});
expectFailureWhenTestingThat(asList(1, 2, 3)).containsNoneIn(new Integer[] {1, 2, 4});
} |
void validateLogLevelConfigs(Collection<AlterableConfig> ops) {
ops.forEach(op -> {
String loggerName = op.name();
switch (OpType.forId(op.configOperation())) {
case SET:
validateLoggerNameExists(loggerName);
String logLevel = op.va... | @Test
public void testValidateSetLogLevelConfig() {
MANAGER.validateLogLevelConfigs(Arrays.asList(new AlterableConfig().
setName(LOG.getName()).
setConfigOperation(OpType.SET.id()).
setValue("TRACE")));
} |
@Nonnull
@Override
public ScheduledFuture<?> schedule(@Nonnull Runnable command, long delay, @Nonnull TimeUnit unit) {
scheduledOnce.mark();
return delegate.schedule(new InstrumentedRunnable(command), delay, unit);
} | @Test
public void testScheduleCallable() throws Exception {
assertThat(submitted.getCount()).isZero();
assertThat(running.getCount()).isZero();
assertThat(completed.getCount()).isZero();
assertThat(duration.getCount()).isZero();
assertThat(scheduledOnce.getCount()).isZero()... |
public boolean containsInt(final int value)
{
return -1 != indexOf(value);
} | @Test
void shouldContainCorrectValues()
{
final int count = 20;
IntStream.range(0, count).forEachOrdered(list::addInt);
for (int i = 0; i < count; i++)
{
assertTrue(list.containsInt(i));
}
assertFalse(list.containsInt(-1));
assertFalse(list.c... |
private static void sqlConfig(XmlGenerator gen, Config config) {
SqlConfig sqlConfig = config.getSqlConfig();
JavaSerializationFilterConfig filterConfig = sqlConfig.getJavaReflectionFilterConfig();
gen.open("sql")
.node("statement-timeout-millis", sqlConfig.getStatementTimeoutMil... | @Test
public void testSqlConfig() {
Config config = new Config();
config.getSqlConfig().setStatementTimeoutMillis(30L);
config.getSqlConfig().setCatalogPersistenceEnabled(true);
JavaSerializationFilterConfig filterConfig = new JavaSerializationFilterConfig();
filterConfig.ge... |
@Override
protected boolean updateCacheIfNeed(final ConfigData<RuleData> result) {
return updateCacheIfNeed(result, ConfigGroupEnum.RULE);
} | @Test
public void testUpdateCacheIfNeed() {
final RuleDataRefresh ruleDataRefresh = mockRuleDataRefresh;
// update cache, then assert equals
ConfigData<RuleData> expect = new ConfigData<>();
expect.setLastModifyTime(System.currentTimeMillis());
ruleDataRefresh.updateCacheIfNe... |
private Object getKey(WindowedValue<InT> elem) {
KV<?, ?> kv = (KV<?, ?>) elem.getValue();
if (kv == null) {
return NULL_KEY;
} else {
Object key = kv.getKey();
return key == null ? NULL_KEY : key;
}
} | @Test
@Ignore("https://github.com/apache/beam/issues/23745")
public void testPipelineWithState() {
final List<KV<String, String>> input =
new ArrayList<>(
Arrays.asList(
KV.of("apple", "red"),
KV.of("banana", "yellow"),
KV.of("apple", "yellow")... |
public static HivePartitionStats fromCommonStats(long rowNums, long totalFileBytes) {
HiveCommonStats commonStats = new HiveCommonStats(rowNums, totalFileBytes);
return new HivePartitionStats(commonStats, ImmutableMap.of());
} | @Test
public void testFromCommonStats() {
long rowNums = 5;
long fileSize = 100;
HivePartitionStats hivePartitionStats = HivePartitionStats.fromCommonStats(rowNums, fileSize);
Assert.assertEquals(5, hivePartitionStats.getCommonStats().getRowNums());
Assert.assertEquals(100, h... |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.2");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportWhitelistedSites() throws IOException {
WhitelistedSite site1 = new WhitelistedSite();
site1.setId(1L);
site1.setClientId("foo");
WhitelistedSite site2 = new WhitelistedSite();
site2.setId(2L);
site2.setClientId("bar");
WhitelistedSite site3 = new WhitelistedSite();
site3.... |
public static boolean isVoid(@Nullable Type type) {
return type != null && type.getSort() == Type.VOID;
} | @Test
void testIsVoid() {
assertTrue(Types.isVoid(Type.getType("V")));
assertFalse(Types.isVoid(Type.getType("()V")));
assertFalse(Types.isVoid(Type.getType("[V")));
assertFalse(Types.isVoid(null));
} |
public static DataPermission remove() {
DataPermission dataPermission = DATA_PERMISSIONS.get().removeLast();
// 无元素时,清空 ThreadLocal
if (DATA_PERMISSIONS.get().isEmpty()) {
DATA_PERMISSIONS.remove();
}
return dataPermission;
} | @Test
public void testRemove() {
// mock 方法
DataPermission dataPermission01 = mock(DataPermission.class);
DataPermissionContextHolder.add(dataPermission01);
DataPermission dataPermission02 = mock(DataPermission.class);
DataPermissionContextHolder.add(dataPermission02);
... |
@Override
public void deleteTenant(Long id) {
// 校验存在
validateUpdateTenant(id);
// 删除
tenantMapper.deleteById(id);
} | @Test
public void testDeleteTenant_success() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class,
o -> o.setStatus(randomCommonStatus()));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbTenant.getId();
// 调用
tena... |
boolean createDatabase(@NotNull String name) throws TException {
return createDatabase(name, null, null, null);
} | @Test
public void createExistingDatabase() {
Throwable exception = Assertions.assertThrows(AlreadyExistsException.class,
() -> client.createDatabase(TEST_DATABASE));
} |
public String getDirectly(final String key) {
try {
byte[] ret = client.getData().forPath(key);
return Objects.isNull(ret) ? null : new String(ret, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new ShenyuException(e);
}
} | @Test
void getDirectly() throws Exception {
assertThrows(ShenyuException.class, () -> client.getDirectly("/test"));
GetDataBuilder getDataBuilder = mock(GetDataBuilder.class);
when(curatorFramework.getData()).thenReturn(getDataBuilder);
when(getDataBuilder.forPath(anyString())).thenR... |
public int getSaveFederationQueuePolicyFailedRetrieved() {
return numSaveFederationQueuePolicyFailedRetrieved.value();
} | @Test
public void testSaveFederationQueuePolicyFailedRetrieved() {
long totalBadBefore = metrics.getSaveFederationQueuePolicyFailedRetrieved();
badSubCluster.getSaveFederationQueuePolicyFailedRetrieved();
Assert.assertEquals(totalBadBefore + 1, metrics.getSaveFederationQueuePolicyFailedRetrieved());
} |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = MergeRollupTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
if (!validate(tableConfig, taskType)) {
continue;
... | @Test
public void testBufferTime() {
Map<String, Map<String, String>> taskConfigsMap = new HashMap<>();
Map<String, String> tableTaskConfigs = new HashMap<>();
tableTaskConfigs.put("daily.mergeType", "concat");
tableTaskConfigs.put("daily.bufferTimePeriod", "1d");
tableTaskConfigs.put("daily.bucke... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, Retry retry, String methodName)
throws Throwable {
RetryTransformer<?> retryTransformer = RetryTransformer.of(retry);
Object returnValue = proceedingJoinPoint.proceed();
return executeRxJava3Aspect(retryTransform... | @Test
public void testReactorTypes() throws Throwable {
Retry retry = Retry.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava3RetryAspectExt.handle(proceedingJoinPoint, retry, "testMethod"))
.isNotNull();
when(pro... |
public static String toAlias(String str) {
return toAlias(str, FitzpatrickAction.PARSE);
} | @Test
public void toAliasTest() {
String alias = EmojiUtil.toAlias("😄");
assertEquals(":smile:", alias);
} |
public ArtifactResolveRequest startArtifactResolveProcess(HttpServletRequest httpServletRequest) throws SamlParseException {
try {
final var artifactResolveRequest = validateRequest(httpServletRequest);
final var samlSession = updateArtifactResolveRequestWithSamlSession(artifactResolveRe... | @Test
void parseArtifactResolveInvalidVersion() throws SamlSessionException {
when(samlSessionServiceMock.loadSession(anyString())).thenReturn(samlSession);
SamlParseException exception = assertThrows(SamlParseException.class, () ->
artifactResolveService.startArtifactResolveProcess... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status,
final Delete.Callback deleteCallback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
session.getClient().move(file.getAbsolute(), renamed.getAbsolute... | @Test
public void testRename() throws BackgroundException {
final Touch touch = new MantaTouchFeature(session);
final Move move = new MantaMoveFeature(session);
final Delete delete = new MantaDeleteFeature(session);
final AttributesFinder attributesFinder = new MantaAttributesFinderF... |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void resolveScopeFromLifecycle_normal_notComparable() {
PublishSubject<IntHolder> lifecycle = PublishSubject.create();
TestObserver<?> o = testSource(resolveScopeFromLifecycle(lifecycle, new IntHolder(3)));
lifecycle.onNext(new IntHolder(0));
o.assertNoErrors().assertNotComplete();
... |
public RingbufferStoreConfig setStoreImplementation(@Nonnull RingbufferStore storeImplementation) {
this.storeImplementation = checkNotNull(storeImplementation, "Ringbuffer store cannot be null!");
this.className = null;
return this;
} | @Test
public void setStoreImplementation() {
SerializationService serializationService = new DefaultSerializationServiceBuilder().build();
RingbufferStore<Data> store = RingbufferStoreWrapper.create(
RingbufferService.getRingbufferNamespace("name"),
config, OBJECT, se... |
static JobManagerProcessSpec processSpecFromConfig(Configuration config) {
return createMemoryProcessSpec(PROCESS_MEMORY_UTILS.memoryProcessSpecFromConfig(config));
} | @Test
void testOffHeapMemoryDerivedFromJvmHeapAndTotalFlinkMemory() {
MemorySize jvmHeap = MemorySize.ofMebiBytes(150);
MemorySize defaultOffHeap = JobManagerOptions.OFF_HEAP_MEMORY.defaultValue();
MemorySize expectedOffHeap = MemorySize.ofMebiBytes(100).add(defaultOffHeap);
MemorySi... |
@Override
public void validateDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得科室信息
Map<Long, DeptDO> deptMap = getDeptMap(ids);
// 校验
ids.forEach(id -> {
DeptDO dept = deptMap.get(id);
if (dept == null) ... | @Test
public void testValidateDeptList_notEnable() {
// mock 数据
DeptDO deptDO = randomPojo(DeptDO.class).setStatus(CommonStatusEnum.DISABLE.getStatus());
deptMapper.insert(deptDO);
// 准备参数
List<Long> ids = singletonList(deptDO.getId());
// 调用, 并断言异常
assertSer... |
public static <K,V> Map<K,Pair<List<V>,List<V>>> cogroup(List<Pair<K,V>> left,List<Pair<K,V>> right) {
Map<K,Pair<List<V>,List<V>>> ret = new HashMap<>();
//group by key first to consolidate values
Map<K,List<V>> leftMap = groupByKey(left);
Map<K,List<V>> rightMap = groupByKey(right);
... | @Test
public void testCoGroup() {
List<Pair<String,String>> leftMap = new ArrayList<>();
List<Pair<String,String>> rightMap = new ArrayList<>();
leftMap.add(Pair.of("cat","adam"));
leftMap.add(Pair.of("dog","adam"));
rightMap.add(Pair.of("fish","alex"));
rightMap.ad... |
public static long sizeOf(Path path) throws IOException {
SizeVisitor visitor = new SizeVisitor();
Files.walkFileTree(path, visitor);
return visitor.size;
} | @Test
public void sizeOf_is_zero_on_empty_files() throws IOException {
File file = temporaryFolder.newFile();
assertThat(FileUtils2.sizeOf(file.toPath())).isZero();
} |
public static short translateBucketAcl(AccessControlList acl, String userId) {
short mode = (short) 0;
for (Grant grant : acl.getGrantsAsList()) {
Permission perm = grant.getPermission();
Grantee grantee = grant.getGrantee();
if (perm.equals(Permission.Read)) {
if (isUserIdInGrantee(gr... | @Test
public void translateEveryoneReadPermission() {
GroupGrantee allUsersGrantee = GroupGrantee.AllUsers;
mAcl.grantPermission(allUsersGrantee, Permission.Read);
Assert.assertEquals((short) 0500, S3AUtils.translateBucketAcl(mAcl, ID));
Assert.assertEquals((short) 0500, S3AUtils.translateBucketAcl(mA... |
void generate(MessageSpec message) throws Exception {
if (message.struct().versions().contains(Short.MAX_VALUE)) {
throw new RuntimeException("Message " + message.name() + " does " +
"not specify a maximum version.");
}
structRegistry.register(message);
schema... | @Test
public void testInvalidNullDefaultForPotentiallyNonNullableStruct() throws Exception {
MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList(
"{",
" \"type\": \"request\",",
" \"name\": \"FooBar\",",
" \"val... |
static <T> T getWildcardMappedObject(final Map<String, T> mapping, final String query) {
T value = mapping.get(query);
if (value == null) {
for (String key : mapping.keySet()) {
// Turn the search key into a regex, using all characters but the * as a literal.
... | @Test
public void testWildcardExtension() throws Exception
{
// Setup test fixture.
final Map<String, Object> haystack = Map.of("myplugin/*.jsp", new Object());
// Execute system under test.
final Object result = PluginServlet.getWildcardMappedObject(haystack, "myplugin/foo.jsp"... |
@Override
public String validateConfigurationRequestBody(Map<String, String> configuration) {
return NULLS_GSON.toJson(configuration);
} | @Test
public void validateConfigurationRequestBody_shouldSerializeConfigurationToJson() {
final ArtifactMessageConverterV2 converter = new ArtifactMessageConverterV2();
final String requestBody = converter.validateConfigurationRequestBody(Map.of("Foo", "Bar"));
assertThatJson("{\"Foo\":\"B... |
public MessageExt lookMessageByOffset(final long commitLogOffset) {
return this.store.lookMessageByOffset(commitLogOffset);
} | @Test
public void testLookMessageByOffset() {
when(messageStore.lookMessageByOffset(anyLong())).thenReturn(new MessageExt());
MessageExt messageExt = transactionBridge.lookMessageByOffset(123);
assertThat(messageExt).isNotNull();
} |
@Override
public KeyValueIterator<Windowed<K>, V> backwardFetch(final K key) {
Objects.requireNonNull(key, "key cannot be null");
return new MeteredWindowedKeyValueIterator<>(
wrapped().backwardFetch(keyBytes(key)),
fetchSensor,
iteratorDurationSensor,
... | @Test
public void shouldThrowNullPointerOnBackwardFetchIfFromIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> store.backwardFetch(null, "to"));
} |
private Object getKey(WindowedValue<InT> elem) {
KV<?, ?> kv = (KV<?, ?>) elem.getValue();
if (kv == null) {
return NULL_KEY;
} else {
Object key = kv.getKey();
return key == null ? NULL_KEY : key;
}
} | @Test
@Ignore("https://github.com/apache/beam/issues/23745")
public void testPipelineWithAggregation() {
final List<KV<String, Long>> input =
new ArrayList<>(
Arrays.asList(
KV.of("apple", 2L),
KV.of("banana", 5L),
KV.of("apple", 8L),
... |
@Transactional
public void updatePassword(String phone, String newPassword) {
User user = readUserOrThrow(phone);
user.updatePassword(passwordEncoderHelper.encodePassword(newPassword));
} | @DisplayName("존재하지 않는 사용자의 번호로 비밀번호 변경 요청이 올 경우 UserErrorException을 발생시킨다.")
@Test
void updatePasswordIfUserNotFound() {
// given
String phone = "010-1234-5678";
String newPassword = "newPassword123";
given(userService.readUserByPhone(phone)).willReturn(Optional.empty());
... |
public synchronized List<Page> getPages(
Long tableId,
int partNumber,
int totalParts,
List<Integer> columnIndexes,
long expectedRows)
{
if (!contains(tableId)) {
throw new PrestoException(MISSING_DATA, "Failed to find table on a worker... | @Test
public void testInsertPageWithoutCreate()
{
insertToTable(0L, 0L);
assertEquals(pagesStore.getPages(0L, 0, 1, ImmutableList.of(0), POSITIONS_PER_PAGE).size(), 1);
} |
@Override
public Prepare.PreparingTable getTable(List<String> names) {
Prepare.PreparingTable originRelOptTable = super.getTable(names);
if (originRelOptTable == null) {
return null;
} else {
// Wrap as FlinkPreparingTableBase to use in query optimization.
... | @Test
void testGetFlinkPreparingTableBase() {
// Mock CatalogSchemaTable.
final ObjectIdentifier objectIdentifier = ObjectIdentifier.of("a", "b", "c");
final ResolvedSchema schema =
new ResolvedSchema(Collections.emptyList(), Collections.emptyList(), null);
final Cata... |
@Udf(description = "Returns the base 10 logarithm of an INT value.")
public Double log(
@UdfParameter(
value = "value",
description = "the value get the base 10 logarithm of."
) final Integer value
) {
return log(value == null ? null : value.doubleValue())... | @Test
public void shouldHandleNegativeBase() {
assertThat(Double.isNaN(udf.log(-15, 13)), is(true));
assertThat(Double.isNaN(udf.log(-15L, 13L)), is(true));
assertThat(Double.isNaN(udf.log(-15.0, 13.0)), is(true));
} |
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException {
final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class);
... | @Test
void validateAssertionIsNotPresent() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException {
ArtifactResponse artifactResponse = artifactResponseService.buildArtifactResponse(getArtifactResolveRequest("failed", true, false, SAML_COMBICONNECT, Encr... |
public User getRequester() {
if (initiator.getType() == Initiator.Type.MANUAL) {
return ((ManualInitiator) initiator).getUser();
}
return null;
} | @Test
public void testGetRequester() {
RunRequest runRequest =
RunRequest.builder()
.currentPolicy(RunPolicy.START_FRESH_NEW_RUN)
.requester(User.create("tester"))
.build();
Assert.assertEquals("tester", runRequest.getRequester().getName());
runRequest =
... |
@Override
public String toString() {
return "com.alibaba.csp.sentinel.spi.SpiLoader[" + service.getName() + "]";
} | @Test
public void testToString() {
SpiLoader spiLoader = SpiLoader.of(ProcessorSlot.class);
assertEquals("com.alibaba.csp.sentinel.spi.SpiLoader[com.alibaba.csp.sentinel.slotchain.ProcessorSlot]"
, spiLoader.toString());
} |
@Override
protected double maintain() {
// Reboot candidates: Nodes in long-term states, where we know we can safely orchestrate a reboot
List<Node> nodesToReboot = nodeRepository().nodes().list(Node.State.active, Node.State.ready).stream()
.filter(node -> node.type().isHost())
... | @Test(timeout = 30_000) // Avoid looping forever if assertions don't hold
public void testRebootScheduledEvenWithSmallProbability() {
Duration rebootInterval = Duration.ofDays(30);
InMemoryFlagSource flagSource = new InMemoryFlagSource();
ProvisioningTester tester = createTester(rebootInterv... |
public static Boolean isMultiInstance() {
return isMultiInstance;
} | @Test
void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException {
initMethod.invoke(JvmUtil.class);
Boolean multiInstance = JvmUtil.isMultiInstance();
assertFalse(multiInstance);
} |
@Override
public void patchInstance(String namespaceId, String serviceName, InstancePatchObject patchObject)
throws NacosException {
Service service = getService(namespaceId, serviceName, true);
Instance instance = getInstance(namespaceId, serviceName, patchObject.getCluster(), patchObje... | @Test
void testPatchInstance() throws NacosException {
Instance instance = new Instance();
instance.setIp("1.1.1.1");
instance.setPort(8848);
instance.setClusterName("C");
List<Instance> instances = Collections.singletonList(instance);
ServiceInfo serviceInfo... |
@Override
public boolean wasNull() throws SQLException {
return mergedResult.wasNull();
} | @Test
void assertWasNull() throws SQLException {
assertFalse(createDecoratedEncryptShowCreateTableMergedResult(mergedResult, mock(EncryptRule.class)).wasNull());
} |
public ParamType getForeachParamType(
String foreachInlineWorkflowId, String stepId, String paramName) {
String ret =
withMetricLogError(
() ->
withRetryableQuery(
GET_PARAM_TYPE_FROM_FOREACH_TEMPLATE,
stmt -> {
... | @Test
public void testGetForeachParamType() throws Exception {
si = loadObject("fixtures/instances/sample-step-instance-succeeded.json", StepInstance.class);
si.setStepAttemptId(10);
stepDao.insertOrUpsertStepInstance(si, false);
assertEquals(
ParamType.LONG, stepDao.getForeachParamType("sampl... |
private String getEnv(String envName, InterpreterLaunchContext context) {
String env = context.getProperties().getProperty(envName);
if (StringUtils.isBlank(env)) {
env = System.getenv(envName);
}
if (StringUtils.isBlank(env)) {
LOGGER.warn("environment variable: {} is empty", envName);
... | @Test
void testLocalMode() throws IOException {
SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null);
Properties properties = new Properties();
properties.setProperty("SPARK_HOME", sparkHome);
properties.setProperty("ENV_1", "");
properties.setProperty("property_1", "value... |
int doWork(final long nowNs)
{
int workCount = 0;
switch (state)
{
case INIT:
workCount += init(nowNs);
break;
case CANVASS:
workCount += canvass(nowNs);
break;
case NOMINATE:
... | @Test
void shouldElectSingleNodeClusterLeader()
{
final long leadershipTermId = NULL_VALUE;
final long logPosition = 0;
final ClusterMember[] clusterMembers = ClusterMember.parse(
"0,ingressEndpoint,consensusEndpoint,logEndpoint,catchupEndpoint,archiveEndpoint");
fin... |
public static Set<Class<?>> getInterfaces(Class<?> clazz) {
if (clazz.isInterface()) {
return Collections.singleton(clazz);
}
Set<Class<?>> interfaces = new LinkedHashSet<>();
while (clazz != null) {
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<... | @Test
public void testGetInterfaces() {
Assertions.assertArrayEquals(new Object[]{Serializable.class},
ReflectionUtil.getInterfaces(Serializable.class).toArray());
Assertions.assertArrayEquals(new Object[]{
Map.class, Cloneable.class, Serializable.class},
... |
@PrivateApi
public static void waitWithDeadline(Collection<? extends Future> futures, long timeout, TimeUnit timeUnit) {
waitWithDeadline(futures, timeout, timeUnit, IGNORE_ALL_EXCEPT_LOG_MEMBER_LEFT);
} | @Test
public void test_waitWithDeadline_failing_second() {
AtomicBoolean waitLock = new AtomicBoolean(true);
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
futures.add(executorService.submit(new FailingCallable(waitLock)));
}
ExceptionCo... |
@Description("ChiSquared cdf given the df parameter and value")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double chiSquaredCdf(
@SqlType(StandardTypes.DOUBLE) double df,
@SqlType(StandardTypes.DOUBLE) double value)
{
checkCondition(value >= 0, INVALID_F... | @Test
public void testChiSquaredCdf()
{
assertFunction("chi_squared_cdf(3, 0.0)", DOUBLE, 0.0);
assertFunction("round(chi_squared_cdf(3, 1.0), 4)", DOUBLE, 0.1987);
assertFunction("round(chi_squared_cdf(3, 2.5), 2)", DOUBLE, 0.52);
assertFunction("round(chi_squared_cdf(3, 4), 2)"... |
@Override
public Iterator<E> iterator() {
return new ElementIterator();
} | @Test
public void testIterator() {
final int elementCount = 10;
final BitSet foundElements = new BitSet(elementCount);
final OAHashSet<Integer> set = new OAHashSet<>(8);
populateSet(set, elementCount);
for (int stored : set) {
foundElements.set(stored);
}... |
public static String parsePath(String uri, Map<String, String> patterns) {
if (uri == null) {
return null;
} else if (StringUtils.isBlank(uri)) {
return String.valueOf(SLASH);
}
CharacterIterator ci = new StringCharacterIterator(uri);
StringBuilder pathBuf... | @Test(description = "parse path with two params in one part")
public void parsePathWithTwoParamsInOnePart() {
final Map<String, String> regexMap = new HashMap<String, String>();
final String path = PathUtils.parsePath("/{a:\\w+}-{b:\\w+}/c", regexMap);
assertEquals(path, "/{a}-{b}/c");
... |
@Override
public ListenableFuture<?> execute(CreateMaterializedView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, Session session, List<Expression> parameters, WarningCollector warningCollector)
{
QualifiedObjectName viewName = createQualifiedObjectNam... | @Test
public void testCreateMaterializedViewExistsFalse()
{
SqlParser parser = new SqlParser();
String sql = String.format("CREATE MATERIALIZED VIEW %s AS SELECT 2021 AS col_0 FROM %s", MATERIALIZED_VIEW_B, TABLE_A);
CreateMaterializedView statement = (CreateMaterializedView) parser.crea... |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeHttpEndpoint() throws Exception {
String out1 = URISupport.normalizeUri("http://www.google.com?q=Camel");
String out2 = URISupport.normalizeUri("http:www.google.com?q=Camel");
assertEquals(out1, out2);
assertTrue(out1.startsWith("http://"), "Should have... |
@Override
protected void runTask() {
if (backgroundJobServer.isRunning() && reentrantLock.tryLock()) {
try {
LOGGER.trace("Looking for enqueued jobs... ");
final AmountRequest workPageRequest = workDistributionStrategy.getWorkPageRequest();
if (wor... | @Test
void testTaskCanHappenAgainAfterException() {
Job enqueuedJob1 = anEnqueuedJob().build();
Job enqueuedJob2 = anEnqueuedJob().build();
when(storageProvider.getJobsToProcess(eq(backgroundJobServer), any()))
.thenThrow(new StorageException("Some error occurred"))
... |
@SuppressWarnings("fallthrough")
@Override
public void authenticate() throws IOException {
if (saslState != SaslState.REAUTH_PROCESS_HANDSHAKE) {
if (netOutBuffer != null && !flushNetOutBufferAndUpdateInterestOps())
return;
if (saslServer != null && saslServer.is... | @Test
public void testUnexpectedRequestType() throws IOException {
TransportLayer transportLayer = mock(TransportLayer.class);
Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG,
Collections.singletonList(SCRAM_SHA_256.mechanismName... |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void givenTableNameProperty_whenCreateMapLoader_thenUseTableNameWithCustomSchema() {
assumeTrue(objectProvider instanceof JdbcDatabaseProvider);
var jdbcDatabaseProvider = (JdbcObjectProvider) objectProvider;
String schemaName = "custom_schema";
jdbcDatabaseProvider.crea... |
public static String camelToSplitName(String camelName, String split) {
if (isEmpty(camelName)) {
return camelName;
}
if (!isWord(camelName)) {
// convert Ab-Cd-Ef to ab-cd-ef
if (isSplitCase(camelName, split.charAt(0))) {
return camelName.toLo... | @Test
void testCamelToSplitName() throws Exception {
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("abCdEf", "-"));
assertEquals("ab-cd-ef", StringUtils.camelToSplitName("AbCdEf", "-"));
assertEquals("abcdef", StringUtils.camelToSplitName("abcdef", "-"));
// assertEquals("nam... |
public void run(OutputReceiver<PartitionRecord> receiver) throws InvalidProtocolBufferException {
// Erase any existing missing partitions.
metadataTableDao.writeDetectNewPartitionMissingPartitions(new HashMap<>());
List<PartitionRecord> partitions = metadataTableDao.readAllStreamPartitions();
for (Pa... | @Test
public void testResetMissingPartitions() throws InvalidProtocolBufferException {
HashMap<ByteStringRange, Instant> missingPartitionsDuration = new HashMap<>();
missingPartitionsDuration.put(ByteStringRange.create("A", "B"), Instant.now());
metadataTableDao.writeDetectNewPartitionMissingPartitions(mi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.