focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void release() {
try {
releasedStateLock.writeLock().lock();
isReleased = true;
} finally {
releasedStateLock.writeLock().unlock();
}
if (executor != null) {
executor.shutdown();
try {
if (!e... | @Test
void testRelease() throws IOException {
int numBuffers = 5;
BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers);
TieredStorageMemoryManagerImpl storageMemoryManager =
createStorageMemoryManager(
bufferPool,
... |
@VisibleForTesting
static IndexRange computeConsumedSubpartitionRange(
int consumerSubtaskIndex,
int numConsumers,
Supplier<Integer> numOfSubpartitionsSupplier,
boolean isDynamicGraph,
boolean isBroadcast) {
int consumerIndex = consumerSubtaskIndex... | @Test
void testComputeConsumedSubpartitionRange3to2() {
final IndexRange range1 = computeConsumedSubpartitionRange(0, 2, 3);
assertThat(range1).isEqualTo(new IndexRange(0, 0));
final IndexRange range2 = computeConsumedSubpartitionRange(1, 2, 3);
assertThat(range2).isEqualTo(new Inde... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowStatement) {
return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s... | @Test
void assertCreateWithShowSQLStatement() {
Optional<DatabaseAdminExecutor> actual = new PostgreSQLAdminExecutorCreator().create(new UnknownSQLStatementContext(new PostgreSQLShowStatement("client_encoding")));
assertTrue(actual.isPresent());
assertThat(actual.get(), instanceOf(PostgreSQL... |
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 invokeList() {
final List testValues = Arrays.asList(1, BigDecimal.valueOf(10.1), "test", 1, "test", BigDecimal.valueOf(10.1));
FunctionTestUtil.assertResultList(
distinctValuesFunction.invoke(testValues),
Arrays.asList(1, BigDecimal.valueOf(10.1), "test"))... |
public static Builder builder() {
return new Builder();
} | @Test
public void testEqualsAndHashCode() {
SpringCloudSelectorHandle selectorHandle1 = SpringCloudSelectorHandle.builder().serviceId("serviceId").build();
SpringCloudSelectorHandle selectorHandle2 = SpringCloudSelectorHandle.builder().serviceId("serviceId").build();
assertThat(Immu... |
public static Object getValueOrCachedValue(Record record, SerializationService serializationService) {
Object cachedValue = record.getCachedValueUnsafe();
if (cachedValue == NOT_CACHED) {
//record does not support caching at all
return record.getValue();
}
for (; ... | @Test
public void givenCachedDataRecord_whenThreadIsInside_thenGetValueOrCachedValueReturnsTheThread() {
// given
Record record = new CachedDataRecordWithStats();
// when
SerializableThread objectPayload = new SerializableThread();
Data dataPayload = serializationService.toD... |
@Override
public void changeLogLevel(LoggerLevel level) {
requireNonNull(level, "level can't be null");
call(new ChangeLogLevelActionClient(level));
} | @Test
public void changeLogLevel_does_not_fail_when_http_code_is_200() {
server.enqueue(new MockResponse().setResponseCode(200));
setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE);
underTest.changeLogLevel(LoggerLevel.TRACE);
} |
@VisibleForTesting
static AbsoluteUnixPath getAppRootChecked(
RawConfiguration rawConfiguration, ProjectProperties projectProperties)
throws InvalidAppRootException {
String appRoot = rawConfiguration.getAppRoot();
if (appRoot.isEmpty()) {
appRoot =
projectProperties.isWarProject()... | @Test
public void testGetAppRootChecked_defaultWarProject() throws InvalidAppRootException {
when(rawConfiguration.getAppRoot()).thenReturn("");
when(projectProperties.isWarProject()).thenReturn(true);
assertThat(PluginConfigurationProcessor.getAppRootChecked(rawConfiguration, projectProperties))
... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testRecordWithFutureTimestampIsRejected() {
long timestampBeforeMaxConfig = Duration.ofHours(24).toMillis(); // 24 hrs
long timestampAfterMaxConfig = Duration.ofHours(1).toMillis(); // 1 hr
long now = System.currentTimeMillis();
long fiveMinutesAfterThreshold = now ... |
@Override
public JCParens inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Parens(getExpression().inline(inliner));
} | @Test
public void inline() {
assertInlines("(5L)", UParens.create(ULiteral.longLit(5L)));
} |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCorrectCodeForDate() {
// Given:
final DateLiteral time = new DateLiteral(new Date(864000000));
// When:
final String java = sqlToJavaVisitor.process(time);
// Then:
assertThat(java, is("1970-01-11"));
} |
public static boolean isWebService(Optional<String> serviceName) {
return serviceName.isPresent()
&& IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey(
Ascii.toLowerCase(serviceName.get()));
} | @Test
public void isWebService_whenSslHttpService_returnsTrue() {
assertThat(
NetworkServiceUtils.isWebService(
NetworkService.newBuilder().setServiceName("ssl/http").build()))
.isTrue();
} |
public static InetSocketAddress parseHostPortAddress(String hostPort) {
URL url = validateHostPortString(hostPort);
return new InetSocketAddress(url.getHost(), url.getPort());
} | @Test
void testParseHostPortAddress() {
final InetSocketAddress socketAddress = new InetSocketAddress("foo.com", 8080);
assertThat(NetUtils.parseHostPortAddress("foo.com:8080")).isEqualTo(socketAddress);
} |
JavaClasses getClassesToAnalyzeFor(Class<?> testClass, ClassAnalysisRequest classAnalysisRequest) {
checkNotNull(testClass);
checkNotNull(classAnalysisRequest);
if (cachedByTest.containsKey(testClass)) {
return cachedByTest.get(testClass);
}
LocationsKey locations =... | @Test
public void gets_all_classes_relative_to_class() {
JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, analyzePackagesOf(getClass()));
assertThat(classes).isNotEmpty();
assertThat(classes.contain(getClass())).as("root class is contained itself").isTrue();
} |
@Override
public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Er... | @Test
public void testRebalanceMetricsOnFailedRebalance() {
ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup();
ConsumerGroupHeartbeatResponse heartbeatResponse = createConsumerGroupHeartbeatResponse(new Assignment());
membershipManager.onHeartbeatSuccess(hea... |
public void removeMap(String mapId) {
IndexInformation info = cache.get(mapId);
if (info == null || isUnderConstruction(info)) {
return;
}
info = cache.remove(mapId);
if (info != null) {
totalMemoryUsed.addAndGet(-info.getSize());
if (!queue.remove(mapId)) {
LOG.warn("Map I... | @Test
public void testRemoveMap() throws Exception {
// This test case use two thread to call getIndexInformation and
// removeMap concurrently, in order to construct race condition.
// This test case may not repeatable. But on my macbook this test
// fails with probability of 100% on code before MA... |
@Deprecated
protected DBSort.SortBuilder getSortBuilder(String order, String field) {
DBSort.SortBuilder sortBuilder;
if ("desc".equalsIgnoreCase(order)) {
sortBuilder = DBSort.desc(field);
} else {
sortBuilder = DBSort.asc(field);
}
return sortBuilder... | @Test
public void sortBuilder() {
assertThat(dbService.getSortBuilder("asc", "f")).isEqualTo(DBSort.asc("f"));
assertThat(dbService.getSortBuilder("aSc", "f")).isEqualTo(DBSort.asc("f"));
assertThat(dbService.getSortBuilder("desc", "f")).isEqualTo(DBSort.desc("f"));
assertThat(dbServ... |
public <T> void compareSupplierResult(final T expected, final Supplier<T> experimentSupplier) {
final Timer.Sample sample = Timer.start();
try {
final T result = experimentSupplier.get();
recordResult(expected, result, sample);
} catch (final Exception e) {
recordError(e, sample);
}
... | @Test
void compareSupplierResultError() {
experiment.compareSupplierResult(12, () -> {
throw new RuntimeException("OH NO");
});
verify(errorTimer).record(anyLong(), eq(TimeUnit.NANOSECONDS));
} |
public static String convertToString(Object parsedValue, Type type) {
if (parsedValue == null) {
return null;
}
if (type == null) {
return parsedValue.toString();
}
switch (type) {
case BOOLEAN:
case SHORT:
case INT:
... | @Test
public void testConvertValueToStringPassword() {
assertEquals(Password.HIDDEN, ConfigDef.convertToString(new Password("foobar"), Type.PASSWORD));
assertEquals("foobar", ConfigDef.convertToString("foobar", Type.PASSWORD));
assertNull(ConfigDef.convertToString(null, Type.PASSWORD));
... |
public static Traits parseTraits(String[] traits) {
if (traits == null || traits.length == 0) {
return new Traits();
}
Map<String, Map<String, Object>> traitConfigMap = new HashMap<>();
for (String traitExpression : traits) {
//traitName.key=value
fi... | @Test
public void parseTraitsTest() {
String[] traits = new String[] {
"custom.property=custom",
"container.port=8080",
"container.port-name=custom" };
Traits traitsSpec = TraitHelper.parseTraits(traits);
Assertions.assertNotNull(traitsSpec);
... |
@Override
public int countWords(Note note) {
int count = 0;
String[] fields = {note.getTitle(), note.getContent()};
for (String field : fields) {
field = sanitizeTextForWordsAndCharsCount(note, field);
boolean word = false;
int endOfLine = field.length() - 1;
for (int i = 0; i < fi... | @Test
public void getWords() {
Note note = getNote(1L, "one two", "three\n four five");
assertEquals(5, new DefaultWordCounter().countWords(note));
note.setTitle("singleword");
assertEquals(4, new DefaultWordCounter().countWords(note));
} |
static byte[] adaptArray(byte[] ftdiData)
{
int length = ftdiData.length;
if(length > 64)
{
int n = 1;
int p = 64;
// Precalculate length without FTDI headers
while(p < length)
{
n++;
p = n*64;
... | @Test
public void testMultipleFull() {
byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,... |
@Nullable
public PlanCoordinator getCoordinator(long jobId) {
return mCoordinators.get(jobId);
} | @Test
public void testGetCoordinator() throws Exception {
long jobId = addJob(100);
assertNull("job id should not exist", mTracker.getCoordinator(-1));
assertNotNull("job should exist", mTracker.getCoordinator(jobId));
assertFalse("job should not be finished", mTracker.getCoordinator(jobId).isJobFinis... |
@Override
public void close() {
getListener().onClose(this);
} | @Test
public void shouldNotCloseKafkaStreamsOnClose() {
// When:
sandbox.close();
// Then:
verifyNoMoreInteractions(kafkaStreams);
} |
@SneakyThrows(GeneralSecurityException.class)
@Override
public String encrypt(final Object plainValue) {
if (null == plainValue) {
return null;
}
byte[] result = getCipher(Cipher.ENCRYPT_MODE).doFinal(String.valueOf(plainValue).getBytes(StandardCharsets.UTF_8));
retur... | @Test
void assertEncryptNullValue() {
assertNull(cryptographicAlgorithm.encrypt(null));
} |
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
getDeclaredFields(type, FieldUtils::isEnumMemberField).stream()
.ma... | @Test
void testBuild() {
TypeElement typeElement = getType(Color.class);
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache);
assertEquals(Color.class.getName(), typeDefinition.get... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds);
intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub);
for (String feature : FEATURES_IN_ORDER)
{
... | @Disabled
@Test
void testApplyTransforms_cjct()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(638,688,636,640,639);
// when
List<Integer> result = gsubWorkerForDevanagari.applyTransforms(getGlyphIds("द्मद्ध्र्यब्दद्वद्य"));
// then
assertEquals(gl... |
public static <UserT, DestinationT, OutputT> WriteFiles<UserT, DestinationT, OutputT> to(
FileBasedSink<UserT, DestinationT, OutputT> sink) {
checkArgument(sink != null, "sink can not be null");
return new AutoValue_WriteFiles.Builder<UserT, DestinationT, OutputT>()
.setSink(sink)
.setComp... | @Test
@Category(NeedsRunner.class)
public void testWrite() throws IOException {
List<String> inputs =
Arrays.asList(
"Critical canary",
"Apprehensive eagle",
"Intimidating pigeon",
"Pedantic gull",
"Frisky finch");
runWrite(inputs, IDENTITY... |
public static String get(@NonNull SymbolRequest request) {
String name = request.getName();
String title = request.getTitle();
String tooltip = request.getTooltip();
String htmlTooltip = request.getHtmlTooltip();
String classes = request.getClasses();
String pluginName = ... | @Test
@DisplayName("When resolving a missing symbol, a placeholder is generated instead")
void missingSymbolDefaultsToPlaceholder() {
String symbol = Symbol.get(new SymbolRequest.Builder()
.withName("missing-icon")
.bu... |
void readOperatingSystemList(String initialOperatingSystemJson) throws IOException {
JSONArray systems = JSONArray.fromObject(initialOperatingSystemJson);
if (systems.isEmpty()) {
throw new IOException("Empty data set");
}
for (Object systemObj : systems) {
if (!(... | @Test
public void testReadOperatingSystemListNoPattern() {
IOException e = assertThrows(IOException.class, () -> monitor.readOperatingSystemList("[{\"endOfLife\": \"2029-03-31\"}]"));
assertThat(e.getMessage(), is("Missing pattern in definition file"));
} |
@Override
public int getMaxRowSize() {
return 0;
} | @Test
void assertGetMaxRowSize() {
assertThat(metaData.getMaxRowSize(), is(0));
} |
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final SelectionParameters other = (SelectionParamet... | @Test
public void testEqualsWitNull() {
List<String> qualifyingNames = Arrays.asList( "language", "german" );
TypeMirror resultType = new TestTypeMirror( "resultType" );
List<TypeMirror> qualifiers = new ArrayList<>();
qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeType"... |
@InvokeOnHeader(CONTROL_ACTION_UNSUBSCRIBE)
public void performUnsubscribe(final Message message, AsyncCallback callback) {
Map<String, Object> headers = message.getHeaders();
String subscriptionId = (String) headers.getOrDefault(CONTROL_SUBSCRIPTION_ID, configuration.getSubscriptionId());
S... | @Test
void performUnsubscribeAction() {
String subscriptionId = "testId";
String subscribeChannel = "testChannel";
Map<String, Object> headers = Map.of(
CONTROL_ACTION_HEADER, CONTROL_ACTION_UNSUBSCRIBE,
CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel,
... |
@ShellMethod(key = {"temp_query", "temp query"}, value = "query against created temp view")
public String query(
@ShellOption(value = {"--sql"}, help = "select query to run against view") final String sql) {
try {
HoodieCLI.getTempViewProvider().runQuery(sql);
return QUERY_SUCCESS;
} catch ... | @Test
public void testQuery() {
Object result = shell.evaluate((MockCommandLineInput) () ->
String.format("temp query --sql 'select * from %s'", tableName));
assertEquals(TempViewCommand.QUERY_SUCCESS, result.toString());
} |
@Override
protected ReadableByteChannel open(LocalResourceId resourceId) throws IOException {
LOG.debug("opening file {}", resourceId);
@SuppressWarnings("resource") // The caller is responsible for closing the channel.
FileInputStream inputStream = new FileInputStream(resourceId.getPath().toFile());
... | @Test
public void testReadNonExistentFile() throws Exception {
thrown.expect(FileNotFoundException.class);
localFileSystem
.open(
LocalResourceId.fromPath(
temporaryFolder.getRoot().toPath().resolve("non-existent-file.txt"),
false /* isDirectory */))
... |
public Set<String> getSearchableTags() {
return searchableTags.get();
} | @Test
public void testGetDefaultSearchableTags() {
Assertions.assertEquals(searchableTracesTagsWatcher.getSearchableTags(),
Arrays.stream(moduleConfig.getSearchableTracesTags().split(",")).collect(Collectors.toSet()));
} |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa... | @Test
public void testValidateClientAcknowledgement_rollover_edgecase3() throws Exception
{
// Setup test fixture.
final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1;
final long h = 0;
final long oldH = MAX-2;
final Long lastUnackedX = 0L;
// Execut... |
@SuppressWarnings("unchecked")
public static String encode(Type parameter) {
if (parameter instanceof NumericType) {
return encodeNumeric(((NumericType) parameter));
} else if (parameter instanceof Address) {
return encodeAddress((Address) parameter);
} else if (param... | @Test
public void testPrimitiveChar() {
assertEquals(
encode(new Char('a')),
("0000000000000000000000000000000000000000000000000000000000000001"
+ "6100000000000000000000000000000000000000000000000000000000000000"));
assertEquals(
... |
public static String getPackageName(Class<?> clazz) {
return getPackageName(clazz.getName());
} | @Test
public void testGetPackageNameForSimpleName() {
String packageName = ClassUtils.getPackageName(AbstractMap.class.getSimpleName());
assertEquals("", packageName);
} |
public static List<String> extractLinks(String content) {
if (content == null || content.length() == 0) {
return Collections.emptyList();
}
List<String> extractions = new ArrayList<>();
final Matcher matcher = LINKS_PATTERN.matcher(content);
while (matcher.find()) {
... | @Test
public void testExtractLinksHttp() {
List<String> links = RegexUtils.extractLinks(
"Test with http://www.nutch.org/index.html is it found? " +
"What about www.google.com at http://www.google.de " +
"A longer URL could be http://www.sybit.... |
public static PTransform<PCollection<String>, PCollection<Row>> withSchemaAndNullBehavior(
Schema rowSchema, NullBehavior nullBehavior) {
RowJson.verifySchemaSupported(rowSchema);
return new JsonToRowFn(rowSchema, nullBehavior);
} | @Test
@Category(NeedsRunner.class)
public void testParsesRowsMissing() throws Exception {
PCollection<String> jsonPersons =
pipeline.apply("jsonPersons", Create.of(JSON_PERSON_WITH_IMPLICIT_NULLS));
PCollection<Row> personRows =
jsonPersons
.apply(
((JsonToRowFn... |
public boolean watch(String vGroup) {
String namingAddr = getNamingAddr();
String clientAddr = NetUtil.getLocalHost();
StringBuilder watchAddrBuilder = new StringBuilder(HTTP_PREFIX)
.append(namingAddr)
.append("/naming/v1/watch?")
.append(VGROUP_K... | @Test
public void testWatch() throws Exception {
NamingserverRegistryServiceImpl registryService = (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide();
//1.注册cluster1下的一个节点
InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
re... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof OutboundPacket) {
final DefaultOutboundPacket other = (DefaultOutboundPacket) obj;
return Objects.equals(this.sendThrough, other.sendThrough) &&
... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(packet1, sameAsPacket1)
.addEqualityGroup(packet2)
.addEqualityGroup(packet1WithInPort)
.testEquals();
} |
@Override
public int size() {
return unmodifiableList.size();
} | @Test
public void testPrimaryConstructor() {
HDPath path = new HDPath(true, Collections.emptyList());
assertTrue("Has private key returns false incorrectly", path.hasPrivateKey);
assertEquals("Path not empty", path.size(), 0);
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testGenericsNotInSuperclassWithNonGenericClassAtEnd() {
// use TypeExtractor
RichMapFunction<?, ?> function =
new RichMapFunction<ChainedFour, ChainedFour>() {
private static final long serialVersionUID =... |
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException {
return buildFunction(functionDefinition, true);
} | @Test
public void testBuildFunctionStructArrayParameterAndReturn() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
true,
Arrays.asList(
new NamedType(
... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testChemistryCheck()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_AMULET_OF_CHEMISTRY, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_AMULET_OF_CHEMIST... |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null)
return rule.getInverted();
try {
final Pattern pattern = patternCache.get(rule.getValue());
final CharSequence charSequence = new InterruptibleCharSequence(m... | @Test
public void testSuccessfulMatch() {
StreamRule rule = getSampleRule();
rule.setValue("^foo");
Message msg = getSampleMessage();
msg.addField("something", "foobar");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
public static ProducingResult createProducingResult(
ResolvedSchema inputSchema, @Nullable Schema declaredSchema) {
// no schema has been declared by the user,
// the schema will be entirely derived from the input
if (declaredSchema == null) {
// go through data type to ... | @Test
void testOutputToRowDataType() {
final ResolvedSchema inputSchema =
ResolvedSchema.of(
Column.physical("c", INT()),
Column.physical("a", BOOLEAN()),
Column.physical("B", DOUBLE())); // case-insensitive mapping
... |
public HttpHost[] getHttpHosts() {
return httpHosts;
} | @Test
public void usesElasticsearchDefaults() {
EsConfig esConfig = new EsConfig();
HttpHost[] httpHosts = esConfig.getHttpHosts();
assertEquals(1, httpHosts.length);
assertEquals("http", httpHosts[0].getSchemeName());
assertEquals(9200, httpHosts[0].getPort());
asser... |
@Override
public void registerProvider(TableProvider provider) {
if (providers.containsKey(provider.getTableType())) {
throw new IllegalArgumentException(
"Provider is already registered for table type: " + provider.getTableType());
}
initTablesFromProvider(provider);
this.providers.p... | @Test(expected = IllegalArgumentException.class)
public void testRegisterProvider_duplicatedTableType() throws Exception {
store.registerProvider(new MockTableProvider("mock"));
store.registerProvider(new MockTableProvider("mock"));
} |
@Override
public String apply(Object lambda) {
if (lambda.toString().equals("INSTANCE")) { // Materialized lambda
return getExpressionHash(lambda);
}
if (lambda instanceof Supplier) {
lambda = (( Supplier ) lambda).get();
}
SerializedLambda extracted ... | @Test
public void testMaterializedLambdaFingerprint() {
LambdaIntrospector lambdaIntrospector = new LambdaIntrospector();
String fingerprint = lambdaIntrospector.apply(LambdaPredicate21D56248F6A2E8DA3990031D77D229DD.INSTANCE);
assertThat(fingerprint).isEqualTo("4DEB93975D9859892B1A5FD4B38E2... |
@Override
public boolean put(K key, V value) {
return get(putAsync(key, value));
} | @Test
public void testValues() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("test1");
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("0"), new SimpleValue("3"));
map.put(new... |
@Override
public YamlMaskTableRuleConfiguration swapToYamlConfiguration(final MaskTableRuleConfiguration data) {
YamlMaskTableRuleConfiguration result = new YamlMaskTableRuleConfiguration();
for (MaskColumnRuleConfiguration each : data.getColumns()) {
result.getColumns().put(each.getLogi... | @Test
void assertSwapToYamlConfiguration() {
Collection<MaskColumnRuleConfiguration> encryptColumnRuleConfigs = Arrays.asList(
new MaskColumnRuleConfiguration("mask_column_1", "md5_mask"),
new MaskColumnRuleConfiguration("mask_column_2", "keep_from_x_to_y"),
n... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldExecutePrintTopic() throws Exception {
// Given:
int numRows = 10;
List<String> expectedResponse = setupPrintTopicResponse(numRows);
String command = "print topic whatever";
// When:
KsqlTarget target = ksqlClient.target(serverUri);
RestResponse<StreamPublisher<St... |
@Override
public Set<KubevirtPort> ports(String networkId) {
checkArgument(!Strings.isNullOrEmpty(networkId), ERR_NULL_PORT_NET_ID);
return ImmutableSet.copyOf(kubevirtPortStore.ports().stream()
.filter(p -> p.networkId().equals(networkId))
.collect(Collectors.toSet()... | @Test
public void testGetPorts() {
createBasicPorts();
assertEquals("Number of port did not match", 1, target.ports().size());
} |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
try {
final SoftwareVersionData version = session.softwareVersion();
final Matcher matcher = Pattern.compile(SDSSession.VERSION_REGEX).matcher(version.getRestApiVersion());
... | @Test
public void testWriteTimestampFolder() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, ... |
public static HttpRequestMessage getRequestFromChannel(Channel ch) {
return ch.attr(ATTR_ZUUL_REQ).get();
} | @Test
void maxHeaderSizeExceeded_setBadRequestStatus() {
int maxInitialLineLength = BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get();
int maxHeaderSize = 10;
int maxChunkSize = BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get();
ClientRequestReceiver receiver = new ClientReques... |
void finishReport() {
List<StepDefContainer> stepDefContainers = new ArrayList<>();
for (Map.Entry<String, List<StepContainer>> usageEntry : usageMap.entrySet()) {
StepDefContainer stepDefContainer = new StepDefContainer(
usageEntry.getKey(),
createStepContain... | @Test
@Disabled("TODO")
void doneWithUsageStatisticStrategies() throws JSONException {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
UsageFormatter.StepContainer stepContainer = new UsageFormatter.StepContainer("a step");
... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void ensure_order_type_random_with_seed_is_used() {
RuntimeOptions options = parser
.parse("--order", "random:5000")
.build();
Pickle a = createPickle("file:path/file1.feature", "a");
Pickle b = createPickle("file:path/file2.feature", "b");
Pickl... |
public static Status unblock(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int blockedOffset,
final int tailOffset,
final int termId)
{
Status status = NO_ACTION;
int frameLength = frameLengthVolatile(termBuffer, blockedOffset);
... | @Test
void shouldTakeNoActionIfMessageCompleteAfterScan()
{
final int messageLength = HEADER_LENGTH * 4;
final int termOffset = 0;
final int tailOffset = messageLength * 2;
when(mockTermBuffer.getIntVolatile(termOffset))
.thenReturn(0)
.thenReturn(message... |
public static FormValidation validateRequired(String value) {
if (Util.fixEmptyAndTrim(value) == null)
return error(Messages.FormValidation_ValidateRequired());
return ok();
} | @Test
public void testValidateRequired_Empty() {
FormValidation actual = FormValidation.validateRequired(" ");
assertNotNull(actual);
assertEquals(FormValidation.Kind.ERROR, actual.kind);
} |
private static Forest createForest() {
Plant grass = new Plant("Grass", "Herb");
Plant oak = new Plant("Oak", "Tree");
Animal zebra = new Animal("Zebra", Set.of(grass), Collections.emptySet());
Animal buffalo = new Animal("Buffalo", Set.of(grass), Collections.emptySet());
Animal lion = new Animal("... | @Test
void blobSerializerTest() {
Forest forest = createForest();
try (LobSerializer serializer = new BlobSerializer()) {
Object serialized = serializer.serialize(forest);
int id = serializer.persistToDb(1, forest.getName(), serialized);
Object fromDb = serializer.loadFromDb(id, Forest.cla... |
@Override
public Void call() {
RemoteLogReadResult result;
try {
LOGGER.debug("Reading records from remote storage for topic partition {}", fetchInfo.topicPartition);
FetchDataInfo fetchDataInfo = remoteReadTimer.time(() -> rlm.read(fetchInfo));
brokerTopicStats.t... | @Test
public void testRemoteLogReaderWithError() throws RemoteStorageException, IOException {
when(mockRLM.read(any(RemoteStorageFetchInfo.class))).thenThrow(new RuntimeException("error"));
Consumer<RemoteLogReadResult> callback = mock(Consumer.class);
RemoteStorageFetchInfo remoteStorageFe... |
@Override
public String name() {
return icebergTable.toString();
} | @TestTemplate
public void testTableEquality() throws NoSuchTableException {
CatalogManager catalogManager = spark.sessionState().catalogManager();
TableCatalog catalog = (TableCatalog) catalogManager.catalog(catalogName);
Identifier identifier = Identifier.of(tableIdent.namespace().levels(), tableIdent.na... |
public static <T> ExtensionLoader<T> getExtensionLoader(final Class<T> clazz, final ClassLoader cl) {
Objects.requireNonNull(clazz, "extension clazz is null");
if (!clazz.isInterface()) {
throw new IllegalArgumentException("extension clazz (" + clazz + ") is not interface!"... | @Test
public void testLoadClassDuplicateKey() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method loadClassMethod = getLoadClassMethod();
ExtensionLoader<JdbcSPI> extensionLoader = ExtensionLoader.getExtensionLoader(JdbcSPI.class);
Map<String, Class<?>> c... |
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException {
if (StringUtils.isBlank(filter)) {
return true;
}
Script script;
try {
script = ENGINE.createScript(filter);
} catch (JexlException e) {
throw new FeedEntryFilterException("Exception while parsing exp... | @Test
void newIsDisabled() {
Assertions.assertThrows(FeedEntryFilterException.class,
() -> service.filterMatchesEntry("null eq new ('java.lang.String', 'athou')", entry));
} |
public Transfer deserialize(final T serialized) {
final Deserializer<T> dict = factory.create(serialized);
final T hostObj = dict.objectForKey("Host");
if(null == hostObj) {
log.warn("Missing host in transfer");
return null;
}
final Host host = new HostDic... | @Test
public void testSerializeLastSelectedAction() throws Exception {
final Path p = new Path("t", EnumSet.of(Path.Type.directory));
final SyncTransfer transfer = new SyncTransfer(new Host(new TestProtocol()), new TransferItem(p, new NullLocal("p", "t") {
@Override
public bo... |
public static Map<String, Type> getStrKeyMap(Type type){
return Convert.toMap(String.class, Type.class, get(type));
} | @Test
public void getTypeArgumentStrKeyTest(){
final Map<String, Type> typeTypeMap = ActualTypeMapperPool.getStrKeyMap(FinalClass.class);
typeTypeMap.forEach((key, value)->{
if("A".equals(key)){
assertEquals(Character.class, value);
} else if("B".equals(key)){
assertEquals(Boolean.class, value);
}... |
@Override
public void loadData(Priority priority, DataCallback<? super T> callback) {
this.callback = callback;
serializer.startRequest(priority, url, this);
} | @Test
public void testLoadData_createsAndStartsRequest() {
when(cronetRequestFactory.newRequest(
eq(glideUrl.toStringUrl()),
eq(UrlRequest.Builder.REQUEST_PRIORITY_LOWEST),
anyHeaders(),
any(UrlRequest.Callback.class)))
.thenReturn(builder);
fetcher.loa... |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void test_programmability() {
Map<String, String> map = stringStringMap("a", "1", "b", "2", "c", "3");
Query q = map
.entrySet()
.stream()
.map(entry -> Q.p(entry.getKey()).contains(entry.getValue()))
.reduce(Query::and)
... |
public static void getSemanticPropsDualFromString(
DualInputSemanticProperties result,
String[] forwardedFirst,
String[] forwardedSecond,
String[] nonForwardedFirst,
String[] nonForwardedSecond,
String[] readFieldsFirst,
String[] readFi... | @Test
void testNonForwardedDualInvalidTypes2() {
String[] nonForwardedFieldsSecond = {"f1"};
DualInputSemanticProperties dsp = new DualInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsDualFromString... |
public Collection<PluginUpdateAggregate> aggregate(@Nullable Collection<PluginUpdate> pluginUpdates) {
if (pluginUpdates == null || pluginUpdates.isEmpty()) {
return Collections.emptyList();
}
Map<Plugin, PluginUpdateAggregateBuilder> builders = new HashMap<>();
for (PluginUpdate pluginUpdate : p... | @Test
public void aggregates_returns_an_empty_collection_when_plugin_collection_is_null() {
assertThat(underTest.aggregate(null)).isEmpty();
} |
public static <T> CsvReaderFormat<T> forSchema(
CsvSchema schema, TypeInformation<T> typeInformation) {
return forSchema(JacksonMapperFactory::createCsvMapper, ignored -> schema, typeInformation);
} | @Test
void testForSchemaWithMapperSerializability() throws IOException, ClassNotFoundException {
final CsvReaderFormat<Pojo> format =
CsvReaderFormat.forSchema(
() -> new CsvMapper(),
mapper -> mapper.schemaFor(Pojo.class),
... |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
return Collections.emptyList();
} | @Test
void assertNewInstance() throws SQLException {
PostgreSQLComFlushExecutor actual = new PostgreSQLComFlushExecutor();
assertThat(actual.execute(), is(Collections.emptyList()));
} |
public boolean includes(String ipAddress) {
if (all) {
return true;
}
if (ipAddress == null) {
throw new IllegalArgumentException("ipAddress is null.");
}
try {
return includes(addressFactory.getByName(ipAddress));
} catch (UnknownHostException e) {
return fals... | @Test
public void testHostNames() throws UnknownHostException {
// create MachineList with a list of of Hostnames
TestAddressFactory addressFactory = new TestAddressFactory();
addressFactory.put("1.2.3.1", "host1");
addressFactory.put("1.2.3.4", "host4", "differentname");
addressFactory.put("1.2.3... |
@Around("dataPermissionCut()")
public Object around(final ProceedingJoinPoint point) {
// CHECKSTYLE:OFF
try {
return point.proceed(getFilterSQLData(point));
} catch (Throwable throwable) {
throw new ShenyuException(throwable);
}
// CHECKSTYLE:ON
} | @Test
public void aroundTest() throws NoSuchMethodException {
ProceedingJoinPoint point = mock(ProceedingJoinPoint.class);
final MethodSignature signature = mock(MethodSignature.class);
when(point.getSignature()).thenReturn(signature);
final Method method = DataPermissionAspectTest.c... |
@Override
public JobVertexMetricsMessageParameters getUnresolvedMessageParameters() {
return new JobVertexMetricsMessageParameters();
} | @Test
void testMessageParameters() {
assertThat(jobVertexMetricsHeaders.getUnresolvedMessageParameters())
.isInstanceOf(JobVertexMetricsMessageParameters.class);
} |
@Override
public void initialize(ServiceConfiguration config) throws IOException {
String data = config.getProperties().getProperty(CONF_PULSAR_PROPERTY_KEY);
if (StringUtils.isEmpty(data)) {
data = System.getProperty(CONF_SYSTEM_PROPERTY_KEY);
}
if (StringUtils.isEmpty(d... | @Test
public void testLoadFileFromSystemProperties() throws Exception {
@Cleanup
AuthenticationProviderBasic provider = new AuthenticationProviderBasic();
ServiceConfiguration serviceConfiguration = new ServiceConfiguration();
System.setProperty("pulsar.auth.basic.conf", basicAuthCon... |
static BlockStmt getInlineTableVariableDeclaration(final String variableName, final InlineTable inlineTable) {
final MethodDeclaration methodDeclaration = INLINETABLE_TEMPLATE.getMethodsByName(GETKIEPMMLINLINETABLE).get(0).clone();
final BlockStmt inlineTableBody = methodDeclaration.getBody().orElseThro... | @Test
void getInlineTableVariableDeclaration() throws IOException {
String variableName = "variableName";
BlockStmt retrieved = KiePMMLInlineTableFactory.getInlineTableVariableDeclaration(variableName,
INLINETA... |
@ScalarOperator(ADD)
@SqlType(StandardTypes.INTEGER)
public static long add(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right)
{
try {
return Math.addExact((int) left, (int) right);
}
catch (ArithmeticException e) {
throw ne... | @Test
public void testAdd()
{
assertFunction("INTEGER'37' + INTEGER'37'", INTEGER, 37 + 37);
assertFunction("INTEGER'37' + INTEGER'17'", INTEGER, 37 + 17);
assertFunction("INTEGER'17' + INTEGER'37'", INTEGER, 17 + 37);
assertFunction("INTEGER'17' + INTEGER'17'", INTEGER, 17 + 17)... |
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId)
throws IOException, InterruptedException {
// We map the input ConnectionID to a new value to restrict the number of tcp connections
connectionId =
new ConnectionID(
co... | @TestTemplate
void testFailureReportedToSubsequentRequests() {
PartitionRequestClientFactory factory =
new PartitionRequestClientFactory(
new FailingNettyClient(), 2, 1, connectionReuseEnabled);
assertThatThrownBy(
() ->
... |
@Override
public Iterator<InternalFactHandle> iterateFactHandles() {
return new CompositeFactHandleIterator(concreteStores, true);
} | @Test
public void iteratingOverFactHandlesHasSameNumberOfResultsAsIteratingOverObjects() throws Exception {
insertObjectWithFactHandle(new SuperClass());
insertObjectWithFactHandle(new SubClass());
assertThat(collect(underTest.iterateFactHandles(SubClass.class))).hasSize(1);
assertT... |
@Override
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
if (context.validate()) {
try {
String accessKey = context.getAccessKey();
String secretKey = context.getSecretKey();
// STS 临时凭证鉴权的优先级高于 AK... | @Test
void testDoInjectWithEmpty() throws Exception {
resource = RequestResource.namingBuilder().setResource("").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
assertEquals(3, actual.getAllKey().size()... |
public boolean asBoolean() {
checkState(type == Type.BOOLEAN, "Value is not a boolean");
return Boolean.parseBoolean(value);
} | @Test
public void asBoolean() {
ConfigProperty p = defineProperty("foo", BOOLEAN, "true", "Foo Prop");
validate(p, "foo", BOOLEAN, "true", "true");
assertEquals("incorrect value", true, p.asBoolean());
} |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetStreamsConfigProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(
Collections.singletonMap(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, "128"));
final Object result = ksqlConfig.getKsqlStreamConfigProps().get(
StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG... |
File decompress() throws IOException {
return decompress(uncheck(() -> java.nio.file.Files.createTempDirectory("decompress")).toFile());
} | @Test
public void require_that_nested_app_can_be_unpacked() throws IOException, InterruptedException {
File gzFile = createTarGz("src/test/resources/deploy/advancedapp");
assertTrue(gzFile.exists());
File outApp;
try (CompressedApplicationInputStream unpacked = streamFromTarGz(gzFile... |
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) {
validateGroupName(name);
checkNameDoesNotExist(dbSession, name);
GroupDto group = new GroupDto()
.setUuid(uuidFactory.create())
.setName(name)
.setDescription(description);
return gro... | @Test
public void createGroup_whenNameAndDescriptionIsProvided_createsGroup() {
when(uuidFactory.create()).thenReturn("1234");
GroupDto createdGroup = mockGroupDto();
when(dbClient.groupDao().insert(eq(dbSession), any())).thenReturn(createdGroup);
mockDefaultGroup();
groupService.createGroup(dbS... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(false);
}
boolean result = false;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
r... | @Test
void invokeArrayParamReturnFalse() {
FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{Boolean.FALSE, Boolean.FALSE}), false);
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test
public void testMultipartRelatedRequestNoUserAttachments() throws Exception
{
//This test verifies the server's ability to handle a multipart related request that has only one part which is
//the rest.li payload; meaning there are no user defined attachments. Technically the client builders shouldn't ... |
@VisibleForTesting
void validateRoleDuplicate(String name, String code, Long id) {
// 0. 超级管理员,不允许创建
if (RoleCodeEnum.isSuperAdmin(code)) {
throw exception(ROLE_ADMIN_CODE_ERROR, code);
}
// 1. 该 name 名字被其它角色所使用
RoleDO role = roleMapper.selectByName(name);
... | @Test
public void testValidateRoleDuplicate_success() {
// 调用,不会抛异常
roleService.validateRoleDuplicate(randomString(), randomString(), null);
} |
public Map<Long, ProducerStateEntry> activeProducers() {
return Collections.unmodifiableMap(producers);
} | @Test
public void testAcceptAppendWithSequenceGapsOnReplica() {
appendClientEntry(stateManager, producerId, epoch, defaultSequence, 0L, 0, false);
int outOfOrderSequence = 3;
// First we ensure that we raise an OutOfOrderSequenceException is raised when to append comes from a client.
... |
public TemplateAnswerResponse getReviewDetail(long reviewId, String reviewRequestCode, String groupAccessCode) {
ReviewGroup reviewGroup = reviewGroupRepository.findByReviewRequestCode(reviewRequestCode)
.orElseThrow(() -> new ReviewGroupNotFoundByReviewRequestCodeException(reviewRequestCode));
... | @Test
void 잘못된_리뷰_요청_코드로_리뷰를_조회할_경우_예외를_발생한다() {
// given
String reviewRequestCode = "reviewRequestCode";
String groupAccessCode = "groupAccessCode";
ReviewGroup reviewGroup = reviewGroupRepository.save(
new ReviewGroup("테드", "리뷰미 프로젝트", reviewRequestCode, groupAccess... |
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "{namespace}/files/directory")
@Operation(tags = {"Files"}, summary = "Create a directory")
public void createDirectory(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The internal storage uri") ... | @Test
void createDirectory() throws IOException {
client.toBlocking().exchange(HttpRequest.POST("/api/v1/namespaces/" + NAMESPACE + "/files/directory?path=/test", null));
FileAttributes res = storageInterface.getAttributes(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test")));
assert... |
static PMMLRuntimeContext getPMMLRuntimeContext(PMMLRequestData pmmlRequestData,
final Map<String, GeneratedResources> generatedResourcesMap) {
String fileName = (String) pmmlRequestData.getMappedRequestParams().get(PMML_FILE_NAME).getValue();
PMMLRequ... | @Test
void getPMMLRuntimeContextFromMap() {
Map<String, Object> inputData = getInputData(MODEL_NAME, FILE_NAME);
final Random random = new Random();
IntStream.range(0, 3).forEach(value -> inputData.put("Variable_" + value, random.nextInt(10)));
final Map<String, GeneratedResources> g... |
public void dropIndexes() {
delegate.dropIndexes();
} | @Test
void dropIndexes() {
final var collection = jacksonCollection("simple", Simple.class);
collection.createIndex(new BasicDBObject("name", 1));
collection.createIndex(new BasicDBObject("name", 1).append("_id", 1));
assertThat(mongoCollection("simple").listIndexes()).extracting("... |
@Retries.RetryTranslated
public void retry(String action,
String path,
boolean idempotent,
Retried retrying,
InvocationRaisingIOE operation)
throws IOException {
retry(action, path, idempotent, retrying,
() -> {
operation.apply();
return null;
});
... | @Test
public void testSdkXmlParsingExceptionIsTranslatable() throws Throwable {
final AtomicInteger counter = new AtomicInteger(0);
invoker.retry("test", null, false, () -> {
if (counter.incrementAndGet() < ACTIVE_RETRY_LIMIT) {
throw SdkClientException.builder()
.message(EOF_MESSAGE... |
public static int checkMaxCollectionLength(long existing, long items) {
long length = existing + items;
if (existing < 0) {
throw new AvroRuntimeException("Malformed data. Length is negative: " + existing);
}
if (items < 0) {
throw new AvroRuntimeException("Malformed data. Length is negative... | @Test
void testCheckMaxCollectionLengthFromZero() {
helpCheckSystemLimits(l -> checkMaxCollectionLength(0L, l), MAX_COLLECTION_LENGTH_PROPERTY,
ERROR_VM_LIMIT_COLLECTION, "Collection length 1024 exceeds maximum allowed");
} |
@Override
public PageResult<SocialClientDO> getSocialClientPage(SocialClientPageReqVO pageReqVO) {
return socialClientMapper.selectPage(pageReqVO);
} | @Test
public void testGetSocialClientPage() {
// mock 数据
SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class, o -> { // 等会查询到
o.setName("芋头");
o.setSocialType(SocialTypeEnum.GITEE.getType());
o.setUserType(UserTypeEnum.ADMIN.getValue());
o.... |
public static void appendLines(File file, String[] lines) throws IOException {
if (file == null) {
throw new IOException("File is null.");
}
writeLines(new FileOutputStream(file, true), lines);
} | @Test
void testAppendLines(@TempDir Path tmpDir) throws Exception {
File file = tmpDir.getFileName().toAbsolutePath().toFile();
IOUtils.appendLines(file, new String[] {"a", "b", "c"});
String[] lines = IOUtils.readLines(file);
assertThat(lines.length, equalTo(3));
assertThat(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.