focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void close() throws IOException {
super.close();
this.closed = true;
if (stream != null) {
stream.close();
}
} | @Test
public void testClose() throws Exception {
setupData(randomData(2));
SeekableInputStream closed =
new ADLSInputStream(fileClient(), null, azureProperties, MetricsContext.nullMetrics());
closed.close();
assertThatThrownBy(() -> closed.seek(0))
.isInstanceOf(IllegalStateException.c... |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldSingleSelectWithReadPermissionsAllowed() {
// Given:
final Statement statement = givenStatement("SELECT * FROM " + KAFKA_STREAM_TOPIC + ";");
// When/Then:
authorizationValidator.checkAuthorization(securityContext, metaStore, statement);
} |
@Udf
public String chr(@UdfParameter(
description = "Decimal codepoint") final Integer decimalCode) {
if (decimalCode == null) {
return null;
}
if (!Character.isValidCodePoint(decimalCode)) {
return null;
}
final char[] resultChars = Character.toChars(decimalCode);
return Str... | @Test
public void shouldReturnNullForEmptyStringInput() {
final String result = udf.chr("");
assertThat(result, is(nullValue()));
} |
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filte... | @Test
public void shouldRemoveBrokenNestedRefsKeepArray() throws IOException {
final OpenAPI openAPI = getOpenAPI31(RESOURCE_PATH_LIST);
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, re... |
@SuppressWarnings("rawtypes")
public Collection<RuleConfiguration> swapToRuleConfigurations(final Collection<YamlRuleConfiguration> yamlRuleConfigs) {
Collection<RuleConfiguration> result = new LinkedList<>();
Collection<Class<?>> ruleConfigTypes = yamlRuleConfigs.stream().map(YamlRuleConfiguration:... | @Test
void assertSwapToRuleConfigurations() {
YamlRuleConfigurationFixture yamlRuleConfig = new YamlRuleConfigurationFixture();
yamlRuleConfig.setName("test");
Collection<RuleConfiguration> actual = new YamlRuleConfigurationSwapperEngine().swapToRuleConfigurations(Collections.singleton(yamlR... |
public static String escapeAll(CharSequence content) {
return escape(content, c -> true);
} | @Test
public void escapeAllTest(){
String str = "*@-_+./(123你好)ABCabc";
String escape = EscapeUtil.escapeAll(str);
assertEquals("%2a%40%2d%5f%2b%2e%2f%28%31%32%33%u4f60%u597d%29%41%42%43%61%62%63", escape);
String unescape = EscapeUtil.unescape(escape);
assertEquals(str, unescape);
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
if(new SMBPat... | @Test
public void testFindNotFound() throws Exception {
assertFalse(new SMBFindFeature(session).find(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))));
} |
public void onBlock(
final DirectBuffer termBuffer, final int termOffset, final int length, final int sessionId, final int termId)
{
try
{
final boolean isPaddingFrame = termBuffer.getShort(typeOffset(termOffset)) == PADDING_FRAME_TYPE;
final int dataLength = isPaddin... | @Test
void onBlockThrowsNullPointerExceptionIfInitWasNotCalled()
{
final Image image = mockImage(0L);
final RecordingWriter recordingWriter = new RecordingWriter(
1,
0,
SEGMENT_LENGTH,
image,
new Context().archiveDir(archiveDir),
... |
public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) {
Subject subject = request.getSubject();
Flag[] flags = request.getFlags();
if (isCacheIgnored.test(name)) {
throw logger.cacheUnavailable(name);
}
if ... | @Test
public void shouldReuseEncodedCaches() {
EmbeddedCacheManager embeddedCacheManager = Mockito.spy(cacheManager);
RestCacheManager<Object> restCacheManager = new RestCacheManager<>(embeddedCacheManager, c -> Boolean.FALSE);
Map<String, CacheInfo<Object, Object>> knownCaches = TestingUtil.extrac... |
public static Object convertAvroFormat(
FieldType beamFieldType, Object avroValue, BigQueryUtils.ConversionOptions options) {
TypeName beamFieldTypeName = beamFieldType.getTypeName();
if (avroValue == null) {
if (beamFieldType.getNullable()) {
return null;
} else {
throw new Il... | @Test
public void testNumericType() {
// BigQuery NUMERIC type has precision 38 and scale 9
BigDecimal n = new BigDecimal("123456789.987654321").setScale(9);
assertThat(
BigQueryUtils.convertAvroFormat(
FieldType.DECIMAL,
new Conversions.DecimalConversion().toBytes(n, null,... |
public static boolean isOnList(@Nonnull final Set<String> list, @Nonnull final String ipAddress) {
Ipv4 remoteIpv4;
try {
remoteIpv4 = Ipv4.of(ipAddress);
} catch (IllegalArgumentException e) {
Log.trace("Address '{}' is not an IPv4 address.", ipAddress);
remo... | @Test
public void ipOnListRange() throws Exception {
// Setup test fixture.
final String input = "203.0.113.251";
final Set<String> list = new HashSet<>();
list.add("203.0.113.25-203.0.113.251");
// Execute system under test.
final boolean result = AuthCheckFilter.is... |
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return delegate.invokeAny(tasks);
} | @Test
public void invokeAny2() throws InterruptedException, ExecutionException, TimeoutException {
underTest.invokeAny(callables, timeout, SECONDS);
verify(executorService).invokeAny(callables, timeout, SECONDS);
} |
@Override
public Collection<Permission> getPermissions(Action action) {
if (!(action instanceof DestinationAction)) {
throw new IllegalArgumentException("Action argument must be a " + DestinationAction.class.getName() + " instance.");
}
DestinationAction da = (DestinationAction) ... | @Test
public void testGetPermissionsWithTemporaryTopic() {
ActiveMQTempTopic topic = new ActiveMQTempTopic("myTempTopic");
DestinationAction action = new DestinationAction(new ConnectionContext(), topic, "remove");
Collection<Permission> perms = resolver.getPermissions(action);
asser... |
@Override
public PrimitiveTypeEncoding<UTF8Buffer> getCanonicalEncoding() {
return largeBufferEncoding;
} | @Test
public void testGetCanonicalEncoding() {
assertNotNull(utf8BufferEncoding.getCanonicalEncoding());
} |
@VisibleForTesting
public ProcessContinuation run(
RestrictionTracker<OffsetRange, Long> tracker,
OutputReceiver<PartitionRecord> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
InitialPipelineState initialPipelineState)
throws Exception {
LOG.debug("DNP: Watermark: "... | @Test
public void testProcessMergeNewPartitions() throws Exception {
// Avoid 0 and multiples of 2 so that we can specifically test just reading new partitions.
OffsetRange offsetRange = new OffsetRange(1, Long.MAX_VALUE);
when(tracker.currentRestriction()).thenReturn(offsetRange);
when(tracker.tryCla... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionMap) {
// Skip this test if NOSASL
if (mConf.get(PropertyKey.SECURITY_AUTHENTICATION_TYPE)
.equals(AuthType.NOSASL)) {
return new ValidationTaskResult(ValidationUtils.State.SKIPPED, getName(),
String.f... | @Test
public void missingProxyUser() {
String userName = System.getProperty("user.name");
// No proxy user definition in core-site.xml
prepareHdfsConfFiles(ImmutableMap.of("key1", "value1"));
HdfsProxyUserValidationTask task =
new HdfsProxyUserValidationTask("hdfs://namenode:9000/alluxio... |
public static void deleteTaskMetadata(HelixPropertyStore<ZNRecord> propertyStore, String taskType,
String tableNameWithType) {
String newPath = ZKMetadataProvider.constructPropertyStorePathForMinionTaskMetadata(tableNameWithType, taskType);
String oldPath =
ZKMetadataProvider.constructPropertyStor... | @Test
public void testDeleteTaskMetadataWithException() {
// Test happy path. No exceptions thrown.
HelixPropertyStore<ZNRecord> mockPropertyStore = Mockito.mock(HelixPropertyStore.class);
when(mockPropertyStore.remove(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt())).thenReturn(true);
MinionT... |
public static Map<String, String> decodeProperties(ByteBuffer byteBuffer) {
int sysFlag = byteBuffer.getInt(SYSFLAG_POSITION);
int magicCode = byteBuffer.getInt(MESSAGE_MAGIC_CODE_POSITION);
MessageVersion version = MessageVersion.valueOfMagicCode(magicCode);
int bornhostLength = (sysFl... | @Test
public void testDecodeProperties() {
MessageExt messageExt = new MessageExt();
messageExt.setMsgId("645100FA00002A9F000000489A3AA09E");
messageExt.setTopic("abc");
messageExt.setBody("hello!q!".getBytes());
try {
messageExt.setBornHost(new InetSocketAddress... |
static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) {
config.put(configPrefix + "alias", cluster.getAlias());
config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
... | @Test
public void testAddClusterToMirrorMaker2ConnectorConfigWithPlain() {
Map<String, Object> config = new HashMap<>();
KafkaMirrorMaker2ClusterSpec cluster = new KafkaMirrorMaker2ClusterSpecBuilder()
.withAlias("sourceClusterAlias")
.withBootstrapServers("sourceClus... |
@Override
public void track(String eventName, JSONObject properties) {
} | @Test
public void testTrack() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return typesMatch(type, genericType) && MoreMediaTypes.TEXT_CSV_TYPE.isCompatible(mediaType);
} | @Test
void isWritableForSimpleMessages() {
boolean isWritable = sut.isWriteable(SimpleMessageChunk.class, null, null, MoreMediaTypes.TEXT_CSV_TYPE);
assertThat(isWritable).isTrue();
} |
public static InternalLogger getInstance(Class<?> clazz) {
return getInstance(clazz.getName());
} | @Test
public void testWarnWithException() {
final InternalLogger logger = InternalLoggerFactory.getInstance("mock");
logger.warn("a", e);
verify(mockLogger).warn("a", e);
} |
static Map<String, Object> addTag(Map<String, Object> e, List<Object> tags) {
Event tempEvent = new org.logstash.Event(e);
addTag(tempEvent, tags);
return tempEvent.getData();
} | @Test
public void testAddTag() {
// add tag to empty event
Event e = new Event();
String testTag = "test_tag";
CommonActions.addTag(e, Collections.singletonList(testTag));
Object value = e.getField(TAGS);
Assert.assertTrue(value instanceof List);
Assert.asser... |
public Optional<Account> getByAccountIdentifier(final UUID uuid) {
return checkRedisThenAccounts(
getByUuidTimer,
() -> redisGetByAccountIdentifier(uuid),
() -> accounts.getByAccountIdentifier(uuid)
);
} | @Test
void testGetAccountByUuidBrokenCache() {
UUID uuid = UUID.randomUUID();
UUID pni = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
when(commands.get(eq("Accoun... |
public void insert(UUID destinationUuid, byte destinationDevice, Envelope message) {
final UUID messageGuid = UUID.randomUUID();
messagesCache.insert(messageGuid, destinationUuid, destinationDevice, message);
if (message.hasSourceUuid() && !destinationUuid.toString().equals(message.getSourceUuid())) {
... | @Test
void insert() {
final UUID sourceAci = UUID.randomUUID();
final Envelope message = Envelope.newBuilder()
.setSourceUuid(sourceAci.toString())
.build();
final UUID destinationUuid = UUID.randomUUID();
messagesManager.insert(destinationUuid, Device.PRIMARY_ID, message);
veri... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
this.trash(files, prompt, callback);
for(Path f : files.keySet()) {
fileid.cache(f, null);
}
} | @Test
public void testDeleteMultipleFiles() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path folder = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory));
final Path file1 = new Path(folder, n... |
public static byte[] readEntry(ZipFile archive, String entryName, ObservationRegistry observations) {
return Observation.createNotStarted("ArchiveUtil#readEntry", observations).observe(() -> {
var entry = archive.getEntry(entryName);
if (entry == null)
return null;
... | @Test
public void testTodoTree() throws Exception {
var packageUrl = getClass().getResource("todo-tree.zip");
assertThat(packageUrl.getProtocol()).isEqualTo("file");
try (
var archive = new ZipFile(packageUrl.getPath());
) {
var packageJson = ArchiveUtil.readE... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void structToJson() {
Schema schema = SchemaBuilder.struct().field("field1", Schema.BOOLEAN_SCHEMA).field("field2", Schema.STRING_SCHEMA).field("field3", Schema.STRING_SCHEMA).field("field4", Schema.BOOLEAN_SCHEMA).build();
Struct input = new Struct(schema).put("field1", true).put("fiel... |
public static Map<Integer, Uuid> createAssignmentMap(int[] replicas, Uuid[] directories) {
if (replicas.length != directories.length) {
throw new IllegalArgumentException("The lengths for replicas and directories do not match.");
}
Map<Integer, Uuid> assignments = new HashMap<>();
... | @Test
void testCreateAssignmentMap() {
assertThrows(IllegalArgumentException.class, () ->
DirectoryId.createAssignmentMap(new int[]{1, 2}, DirectoryId.unassignedArray(3)));
assertEquals(
new HashMap<Integer, Uuid>() {{
put(1, Uuid.fromString("upjfkCrUR... |
@Override
public boolean canDecrypt(String cipherText) {
if (isBlank(cipherText)) {
return false;
}
String[] splits = cipherText.split(":");
return splits.length == 3 && "AES".equals(splits[0]) && isNotBlank(splits[1]) && isNotBlank(splits[2]);
} | @Test
public void canDecryptShouldAnswerTrueIfPasswordLooksLikeAES() {
assertThat(aesEncrypter.canDecrypt("AES:foo:bar")).isTrue();
assertThat(aesEncrypter.canDecrypt("aes:bar:baz")).isFalse();
assertThat(aesEncrypter.canDecrypt("")).isFalse();
assertThat(aesEncrypter.canDecrypt("\t... |
public static String toString(long unixTime, String pattern) {
return Instant.ofEpochSecond(unixTime).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(pattern));
} | @Test
public void testToString() {
String dateStr = DateKit.toString(date, "yyyy-MM-dd");
Assert.assertEquals("2017-09-20", dateStr);
} |
@Override
public void setMonochrome(boolean monochrome) {
formats = monochrome ? monochrome() : ansi();
} | @Test
void should_print_output_from_before_hooks() {
Feature feature = TestFeatureParser.parse("path/test.feature", "" +
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n");
ByteArrayOutputStream out = new ByteArrayOu... |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null;
taskId = context.taskId();
initStoreSerde(context);
s... | @Test
public void shouldDelegateInit() {
final MeteredWindowStore<String, String> outer = new MeteredWindowStore<>(
innerStoreMock,
WINDOW_SIZE_MS, // any size
STORE_TYPE,
new MockTime(),
Serdes.String(),
new SerdeThatDoesntHandleNull()... |
public static String byteCountToDisplaySize(long size) {
if (size < 1024L) {
return String.valueOf(size) + (size > 1 ? " bytes" : " byte");
}
long exp = (long) (Math.log(size) / Math.log((long) 1024));
double value = size / Math.pow((long) 1024, exp);
char unit = "KMG... | @Test
public void shouldConvertBytesToGiga() {
long twoGiga = 2L * 1024 * 1024 * 1024 + 512 * 1024 * 1024;
assertThat(FileSizeUtils.byteCountToDisplaySize(twoGiga), is("2.5 GB"));
} |
@Override
public void createPod(Pod pod) {
checkNotNull(pod, ERR_NULL_POD);
checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()),
ERR_NULL_POD_UID);
kubevirtPodStore.createPod(pod);
log.debug(String.format(MSG_POD, pod.getMetadata().getName(), MSG_CREATE... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicatePod() {
target.createPod(POD);
target.createPod(POD);
} |
@Override
public double readDouble() {
return Double.longBitsToDouble(readLong());
} | @Test
public void testReadDoubleAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readDouble();
}
});
} |
@Override
public Long createMailTemplate(MailTemplateSaveReqVO createReqVO) {
// 校验 code 是否唯一
validateCodeUnique(null, createReqVO.getCode());
// 插入
MailTemplateDO template = BeanUtils.toBean(createReqVO, MailTemplateDO.class)
.setParams(parseTemplateContentParams(cr... | @Test
public void testCreateMailTemplate_success() {
// 准备参数
MailTemplateSaveReqVO reqVO = randomPojo(MailTemplateSaveReqVO.class)
.setId(null); // 防止 id 被赋值
// 调用
Long mailTemplateId = mailTemplateService.createMailTemplate(reqVO);
// 断言
assertNotNul... |
@Override
public RetryStrategy getNextRetryStrategy() {
int nextRemainingRetries = remainingRetries - 1;
Preconditions.checkState(
nextRemainingRetries >= 0, "The number of remaining retries must not be negative");
return new FixedRetryStrategy(nextRemainingRetries, retryDela... | @Test
void testRetryFailure() {
assertThatThrownBy(
() ->
new FixedRetryStrategy(0, Duration.ofMillis(5L))
.getNextRetryStrategy())
.isInstanceOf(IllegalStateException.class);
} |
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY).get();
if ((service == null || service.length() == 0) && (args == null || args.length == 0)) {
ret... | @Test
void test() throws Exception {
String methodName = "sayHello";
RpcStatus.removeStatus(url, methodName);
String[] args = new String[] {"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"};
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExt... |
@Override
public MapperResult findChangeConfig(MapperContext context) {
String sql =
"SELECT id, data_id, group_id, tenant_id, app_name, content, gmt_modified, encrypted_data_key FROM config_info WHERE "
+ "gmt_modified >= ? and id > ? order by id OFFSET 0 ROWS FETCH ... | @Test
void testFindChangeConfig() {
MapperResult mapperResult = configInfoMapperByDerby.findChangeConfig(context);
assertEquals(mapperResult.getSql(),
"SELECT id, data_id, group_id, tenant_id, app_name, content, gmt_modified, encrypted_data_key FROM config_info "
... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldCreateWithNoExplicitVersionAndEmptyMigrationsDir() {
// Given:
command = PARSER.parse(DESCRIPTION);
// When:
final int result = command.command(migrationsDir);
// Then:
assertThat(result, is(0));
final File expectedFile = new File(Paths.get(migrationsDir, "V00000... |
public static AggregateFunctionInitArguments createAggregateFunctionInitArgs(
final int numInitArgs,
final FunctionCall functionCall
) {
return createAggregateFunctionInitArgs(
numInitArgs,
Collections.emptyList(),
functionCall,
KsqlConfig.empty(... | @Test
public void shouldNotThrowIfFirstParamNotALiteral() {
// Given:
when(functionCall.getArguments()).thenReturn(ImmutableList.of(
new UnqualifiedColumnReferenceExp(ColumnName.of("Bob")),
new StringLiteral("No issue here")
));
// When:
UdafUtil.createAggregateFunctionInitArgs(
... |
@Override
public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) {
if (RequestCode.GET_ROUTEINFO_BY_TOPIC != request.getCode()) {
return;
}
if (response == null || response.getBody() == null || ResponseCode.SUCCESS != response.getCode())... | @Test
public void testDoAfterResponseWithNoZoneMode() {
RemotingCommand request1 = RemotingCommand.createRequestCommand(106,null);
zoneRouteRPCHook.doAfterResponse("", request1, null);
HashMap<String, String> extFields = new HashMap<>();
extFields.put(MixAll.ZONE_MODE, "false");
... |
public static Instant later(Instant time1, Instant time2) {
return time1.isAfter(time2) ? time1 : time2;
} | @Test
public void later() {
Instant t1 = Instant.now(); // earlier
Instant t2 = t1.plusSeconds(1); // later
assertEquals(t2, TimeUtils.later(t1, t2));
assertEquals(t2, TimeUtils.later(t2, t1));
assertEquals(t1, TimeUtils.later(t1, t1));
assertEquals(t2, TimeUtils.late... |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void same_docstring_content_type_can_convert_to_different_registered_doc_string_types() {
registry.defineDocStringType(new DocStringType(
Greet.class,
"text",
Greet::new));
registry.defineDocStringType(new DocStringType(
Meet.class,
... |
@Override
public void lock() {
try {
lock(-1, null, false);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testUnlockFail() {
Assertions.assertThrows(IllegalMonitorStateException.class, () -> {
RLock lock = redisson.getLock("lock");
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
... |
@Override
public <T extends ComponentRoot> T get(Class<T> providerId) {
try {
return providerId.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
} | @Test
void get() {
String fileName = "fileName";
String name = "name";
LocalUri retrieved = appRoot.get(ComponentRootA.class)
.get(fileName, name)
.toLocalId()
.asLocalUri();
appRoot.get(ComponentRootA.class)
.get(fileN... |
@VisibleForTesting
void validateDictTypeNameUnique(Long id, String name) {
DictTypeDO dictType = dictTypeMapper.selectByName(name);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if (id == null) {
throw exception(DICT_TYPE_NAME_DUPL... | @Test
public void testValidateDictTypNameUnique_success() {
// 调用,成功
dictTypeService.validateDictTypeNameUnique(randomLongId(), randomString());
} |
public static Object fillInDataDefault(DataSchema schema, Object dataWithoutDefault)
{
try
{
switch (schema.getType())
{
case RECORD:
return fillInDefaultOnRecord((RecordDataSchema) schema, (DataMap) dataWithoutDefault);
case TYPEREF:
return fillInDefaultOnTyper... | @Test(dataProvider = "default_serialization")
public void testGetAbsentFieldsDefaultValues(String caseFilename)
{
try
{
MultiFormatDataSchemaResolver schemaResolver = MultiFormatDataSchemaResolver.withBuiltinFormats(resolverDir);
String expectedDataJsonFile = Files.readFile(new File(pegasusDir +... |
private PartitionedByError<ReconcilableTopic, Void> createTopics(List<ReconcilableTopic> kts) {
var newTopics = kts.stream().map(reconcilableTopic -> {
// Admin create
return buildNewTopic(reconcilableTopic.kt(), reconcilableTopic.topicName());
}).collect(Collectors.toSet());
... | @Test
public void shouldHandleInterruptedExceptionFromCreateTopics(KafkaCluster cluster) throws ExecutionException, InterruptedException {
var topicName = "my-topic";
kafkaAdminClient[0] = Admin.create(Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers()));
var ka... |
public void saveUserInfo( IUser user ) throws KettleException {
normalizeUserInfo( user );
if ( !validateUserInfo( user ) ) {
throw new KettleException( BaseMessages.getString( PurRepositorySecurityManager.class,
"PurRepositorySecurityManager.ERROR_0001_INVALID_NAME" ) );
}
userRoleDeleg... | @Test( expected = KettleException.class )
public void saveUserInfo_NormalizesInfo_FailsIfStillBreaches() throws Exception {
UserInfo info = new UserInfo( " " );
manager.saveUserInfo( info );
} |
@Override
protected void doStart() throws Exception {
super.doStart();
LOG.debug("Creating connection to Azure ServiceBus");
client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(),
this::processMessage, this::processError);
... | @Test
void synchronizationCompletesMessageOnSuccess() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
when(configuration.getServiceBusReceiveMode()).thenReturn(ServiceBusReceiveMode.PEEK_LOCK);
consumer.doStart();
verif... |
@Override
public String toString()
{
return getClass().getSimpleName() + "[" + debugFontName + "]";
} | @Test
void testFontMatrix()
{
List<Number> fontMatrix = testCFFType1Font.getFontMatrix();
assertNotNull(fontMatrix, "FontMatrix must not be null");
assertNumberList("FontMatrix values are different than expected" + fontMatrix.toString(),
new float[] { 0.001f, 0.0f, 0.0f, ... |
@Override
public String getSQL() {
return sql;
} | @Test
void assertNew() {
when(payload.readStringEOF()).thenReturn("SELECT id FROM tbl WHERE id=?");
MySQLComStmtPreparePacket actual = new MySQLComStmtPreparePacket(payload);
assertThat(actual.getSQL(), is("SELECT id FROM tbl WHERE id=?"));
} |
Collection<OutputFile> compile() {
List<OutputFile> out = new ArrayList<>(queue.size() + 1);
for (Schema schema : queue) {
out.add(compile(schema));
}
if (protocol != null) {
out.add(compileInterface(protocol));
}
return out;
} | @Test
void fieldWithUnderscore_avro3826() {
String jsonSchema = "{\n" + " \"name\": \"Value\",\n" + " \"type\": \"record\",\n" + " \"fields\": [\n"
+ " { \"name\": \"__deleted\", \"type\": \"string\"\n" + " }\n" + " ]\n" + "}";
Collection<SpecificCompiler.OutputFile> outputs = new SpecificC... |
public AdvancedNetworkConfig getAdvancedNetworkConfig() {
return advancedNetworkConfig;
} | @Test
public void testEndpointConfig() {
String name = randomName();
EndpointQualifier qualifier = EndpointQualifier.resolve(WAN, name);
ServerSocketEndpointConfig endpointConfig = new ServerSocketEndpointConfig();
endpointConfig.setName(name);
endpointConfig.setProtocolType(... |
public static boolean isBasicInfoChanged(Member actual, Member expected) {
if (null == expected) {
return null != actual;
}
if (!expected.getIp().equals(actual.getIp())) {
return true;
}
if (expected.getPort() != actual.getPort()) {
return true... | @Test
void testIsBasicInfoChangedForChangedBasicExtendInfo() {
Member newMember = buildMember();
newMember.setExtendVal(MemberMetaDataConstants.WEIGHT, "100");
assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember));
} |
public static boolean publishEvent(final Event event) {
try {
return publishEvent(event.getClass(), event);
} catch (Throwable ex) {
LOGGER.error("There was an exception to the message publishing : ", ex);
return false;
}
} | @Test
void testPublishEventByNoPublisher() {
for (int i = 0; i < 3; i++) {
assertFalse(NotifyCenter.publishEvent(new NoPublisherEvent()));
}
} |
@Override
public String getDescription() {
return "Load prioritized rules";
} | @Test
void getDescription_shouldReturnValue() {
assertThat(underTest.getDescription()).isEqualTo("Load prioritized rules");
} |
@Override
public boolean checkCredentials(String username, String password) {
return this.username.equals(username) && this.password.equals(password);
} | @Test
public void test() {
BasicAuthenticator plainTextAuthenticator =
new PlaintextAuthenticator("/", VALID_USERNAME, VALID_PASSWORD);
for (String username : TEST_USERNAMES) {
for (String password : TEST_PASSWORDS) {
boolean expectedIsAuthenticated =
... |
public static DiffResult diff(Graph left, Graph right) {
List<Edge> removedEdges = left.edges().filter(e -> !right.hasEquivalentEdge(e)).collect(Collectors.toList());
List<Vertex> removedVertices = left.vertices().filter(v -> !right.hasEquivalentVertex(v)).collect(Collectors.toList());
List<Edge... | @Test
public void testDifferentSimpleGraphs() throws InvalidIRException {
Graph left = simpleGraph();
Graph right = left.copy();
Vertex new1 = createTestVertex("new1");
right.addVertex(new1);
right.chainVerticesById("t3", "new1");
GraphDiff.DiffResult result = Graph... |
public static MetadataUpdate fromJson(String json) {
return JsonUtil.parse(json, MetadataUpdateParser::fromJson);
} | @Test
public void testBranchFromJsonAllFields() {
String action = MetadataUpdateParser.SET_SNAPSHOT_REF;
long snapshotId = 1L;
SnapshotRefType type = SnapshotRefType.BRANCH;
String refName = "hank";
Integer minSnapshotsToKeep = 2;
Long maxSnapshotAgeMs = 3L;
Long maxRefAgeMs = 4L;
Stri... |
@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getCustomChildChannelHandlers(MessageInput input) {
final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>(super.getCustomChildChannelHandlers(input));
handlers.put("beats", BeatsFra... | @Test
public void customChildChannelHandlersContainBeatsHandler() {
final NettyTransportConfiguration nettyTransportConfiguration = new NettyTransportConfiguration("nio", "jdk", 1);
final EventLoopGroupFactory eventLoopGroupFactory = new EventLoopGroupFactory(nettyTransportConfiguration);
fi... |
public boolean isFound() {
return found;
} | @Test
public void testCalcDistanceDetails() {
Weighting weighting = new SpeedWeighting(carAvSpeedEnc);
Path p = new Dijkstra(pathDetailGraph, weighting, TraversalMode.NODE_BASED).calcPath(1, 5);
assertTrue(p.isFound());
Map<String, List<PathDetail>> details = PathDetailsFromEdges.ca... |
public static <T> List<T> move(List<T> list, T element, int newPosition) {
Assert.notNull(list);
if (false == list.contains(element)) {
list.add(newPosition, element);
} else {
list.remove(element);
list.add(newPosition, element);
}
return list;
} | @Test
public void testMoveElementToPosition() {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
// Move "B" to position 2
List<String> expectedResult1 = new ArrayList<>(Arrays.asList("A", "C", "B", "D"));
assertEquals(expectedResult1, ListUtil.move(list, "B", 2));
list = new ArrayLi... |
public static void extractFiles(File archive, File extractTo) throws ExtractionException {
extractFiles(archive, extractTo, null);
} | @Test(expected = org.owasp.dependencycheck.utils.ExtractionException.class)
public void testExtractFiles_3args() throws Exception {
File destination = getSettings().getTempDirectory();
File archive = BaseTest.getResourceAsFile(this, "evil.zip");
Engine engine = null;
ExtractionUtil.e... |
public static Object parse(Payload payload) {
Class classType = PayloadRegistry.getClassByType(payload.getMetadata().getType());
if (classType != null) {
ByteString byteString = payload.getBody().getValue();
ByteBuffer byteBuffer = byteString.asReadOnlyByteBuffer();
O... | @Test
void testParseNullType() {
assertThrows(RemoteException.class, () -> {
Payload mockPayload = mock(Payload.class);
Metadata mockMetadata = mock(Metadata.class);
when(mockPayload.getMetadata()).thenReturn(mockMetadata);
GrpcUtils.parse(mockPayload);
... |
@Override
public void revert(final Path file) throws BackgroundException {
// To restore a version all that needs to be done is to move a version the special restore folder at /remote.php/dav/versions/USER/restore
try {
session.getClient().move(URIEncoder.encode(file.getAbsolute()),
... | @Test
public void testRevert() throws Exception {
final Path directory = new DAVDirectoryFeature(session, new NextcloudAttributesFinderFeature(session)).mkdir(new Path(new DefaultHomeFinderService(session).find(),
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory... |
static long sizeOf(Mutation m) {
if (m.getOperation() == Mutation.Op.DELETE) {
return sizeOf(m.getKeySet());
}
long result = 0;
for (Value v : m.getValues()) {
switch (v.getType().getCode()) {
case ARRAY:
result += estimateArrayValue(v);
break;
case STRUCT... | @Test
public void jsons() throws Exception {
Mutation empty =
Mutation.newInsertOrUpdateBuilder("test").set("one").to(Value.json("{}")).build();
Mutation nullValue =
Mutation.newInsertOrUpdateBuilder("test").set("one").to(Value.json((String) null)).build();
Mutation sample =
Mutati... |
@Override
public List<ValidationMessage> validate(ValidationContext context) {
return context.query().tokens().stream()
.filter(this::isInvalidOperator)
.map(token -> {
final String errorMessage = String.format(Locale.ROOT, "Query contains invalid operator... | @Test
void testInvalidOperatorNoOperatorPresent() {
final ValidationContext context = TestValidationContext.create("foo:bar baz")
.build();
assertThat(sut.validate(context)).isEmpty();
} |
public MultiMap<Value, T, List<T>> get(final KeyDefinition keyDefinition) {
return tree.get(keyDefinition);
} | @Test
void testFindByName() throws Exception {
MultiMap<Value, Person, List<Person>> multiMap = map.get(KeyDefinition.newKeyDefinition()
.withId("name")
.build());
assertThat(multiMap.keySet()).extracting(x -> x.getComparable()).containsExactl... |
public IterableSubject factKeys() {
if (!(actual instanceof ErrorWithFacts)) {
failWithActual(simpleFact("expected a failure thrown by Truth's failure API"));
return ignoreCheck().that(ImmutableList.of());
}
ErrorWithFacts error = (ErrorWithFacts) actual;
return check("factKeys()").that(getF... | @Test
public void factKeysNoValue() {
assertThat(simpleFact("foo")).factKeys().containsExactly("foo");
} |
public static StrimziPodSet createPodSet(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
ResourceTemplate template,
int replicas,
Map<String, String> annotations,
Labels selectorLabels,
... | @Test
public void testCreateStrimziPodSetFromNodeReferencesWithNullTemplate() {
List<String> podNames = new ArrayList<>();
StrimziPodSet sps = WorkloadUtils.createPodSet(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
null,... |
public static File generate(String content, int width, int height, File targetFile) {
String extName = FileUtil.extName(targetFile);
switch (extName) {
case QR_TYPE_SVG:
String svg = generateAsSvg(content, new QrConfig(width, height));
FileUtil.writeString(svg, targetFile, StandardCharsets.UTF_8);
br... | @Test
public void pdf417Test() {
final BufferedImage image = QrCodeUtil.generate("content111", BarcodeFormat.PDF_417, QrConfig.create());
Assert.notNull(image);
} |
@Override
public Map<String, String> getMetadata(final Path file) throws BackgroundException {
return new S3AttributesFinderFeature(session, acl).find(file).getMetadata();
} | @Test
public void testGetMetadataFile() throws Exception {
final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testBuildEventOfArrayOfDynamicStruct() throws ClassNotFoundException {
// The full event signature is
//
// Stamp3(uint256 indexed stampId, address indexed caller, bool odd,
// (uint256,bool,string) topMessage, (uint256,bool,string)[] messages),
//
... |
@Bean("ScmChangedFiles")
public ScmChangedFiles provide(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
Path rootBaseDir = project.getBaseDir();
Set<ChangedFile> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDi... | @Test
public void testFailIfRelativePath() {
when(branchConfiguration.targetBranchName()).thenReturn("target");
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(scmConfiguration.provider()).thenReturn(scmProvider);
when(scmProvider.branchChangedFiles("target", rootBaseDir)).thenReturn(... |
@Override
public void writeSpecialized(int i) {
if (current == null) {
current = i;
} else {
Integer currentI = this.ofSameTypeOrThrow(current, Integer.class);
current = currentI + i;
}
} | @Test
void invalidAddition() throws IOException {
try (TypedObjectWriter writer = new TypedObjectWriter()){
writer.writeSpecialized(1);
IllegalArgumentException illegalArgumentException = Assertions.assertThrows(IllegalArgumentException.class, () -> writer.writeSpecialized('a'));
... |
static long sizeOf(Mutation m) {
if (m.getOperation() == Mutation.Op.DELETE) {
return sizeOf(m.getKeySet());
}
long result = 0;
for (Value v : m.getValues()) {
switch (v.getType().getCode()) {
case ARRAY:
result += estimateArrayValue(v);
break;
case STRUCT... | @Test
public void primitives() throws Exception {
Mutation int64 = Mutation.newInsertOrUpdateBuilder("test").set("one").to(1).build();
Mutation float32 = Mutation.newInsertOrUpdateBuilder("test").set("one").to(1.3f).build();
Mutation float64 = Mutation.newInsertOrUpdateBuilder("test").set("one").to(2.9).b... |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
if (stream == null) {
throw new NullPointerException("null stream");
}
Throwable t;
boolean alive =... | @Test
public void testRPWWithMainDocNPE() throws Exception {
Parser parser = new AutoDetectParser();
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(parser);
RecursiveParserWrapperHandler handler = new RecursiveParserWrapperHandler(
new BasicContentHandlerFactory(... |
@VisibleForTesting
static String formatLevel(int level)
{
if (level < 10000)
{
return Integer.toString(level);
}
else
{
return (level / 1000) + "k";
}
} | @Test
public void testFormatLevel()
{
assertEquals("398", formatLevel(398));
assertEquals("5000", formatLevel(5000));
assertEquals("7682", formatLevel(7682));
assertEquals("12k", formatLevel(12398));
assertEquals("219k", formatLevel(219824));
} |
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> acknowledge(
String memberId,
String groupId,
Map<TopicIdPartition, List<ShareAcknowledgementBatch>> acknowledgeTopics
) {
log.trace("Acknowledge request for topicIdPartitions: {} with groupId... | @Test
public void testAcknowledgeMultiplePartition() {
String groupId = "grp";
String memberId = Uuid.randomUuid().toString();
TopicIdPartition tp1 = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo1", 0));
TopicIdPartition tp2 = new TopicIdPartition(Uuid.randomUuid()... |
@Override
public TaskManagerMetricsMessageParameters getUnresolvedMessageParameters() {
return new TaskManagerMetricsMessageParameters();
} | @Test
void testMessageParameters() {
assertThat(taskManagerMetricsHeaders.getUnresolvedMessageParameters())
.isInstanceOf(TaskManagerMetricsMessageParameters.class);
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TtlBucket)) {
return false;
}
TtlBucket that = (TtlBucket) o;
return mTtlIntervalStartTimeMs == that.mTtlIntervalStartTimeMs;
} | @Test
public void equals() {
TtlBucket firstBucket = new TtlBucket(0);
TtlBucket secondBucket = new TtlBucket(0);
TtlBucket thirdBucket = new TtlBucket(1);
Assert.assertNotEquals(firstBucket, null);
Assert.assertEquals(firstBucket, firstBucket);
Assert.assertEquals(firstBucket, secondBucket);... |
public void extractTablesFromSelect(final SelectStatement selectStatement) {
if (selectStatement.getCombine().isPresent()) {
CombineSegment combineSegment = selectStatement.getCombine().get();
extractTablesFromSelect(combineSegment.getLeft().getSelect());
extractTablesFromSel... | @Test
void assertExtractTablesFromCombineSegment() {
SelectStatement selectStatement = createSelectStatement("t_order");
SubquerySegment left = new SubquerySegment(0, 0, createSelectStatement("t_order"), "");
SubquerySegment right = new SubquerySegment(0, 0, createSelectStatement("t_order_it... |
@Override
public boolean isEmpty() {
return true;
} | @Test
public void testIsEmpty() {
assertThat(sut.isEmpty(), is(true));
} |
@NonNull
static String getImageUrl(List<FastDocumentFile> files, Uri folderUri) {
// look for special file names
for (String iconLocation : PREFERRED_FEED_IMAGE_FILENAMES) {
for (FastDocumentFile file : files) {
if (iconLocation.equals(file.getName())) {
... | @Test
public void testGetImageUrl_PreferredImagesFilenames() {
for (String filename : LocalFeedUpdater.PREFERRED_FEED_IMAGE_FILENAMES) {
List<FastDocumentFile> folder = Arrays.asList(mockDocumentFile("audio.mp3", "audio/mp3"),
mockDocumentFile(filename, "image/jpeg")); // ima... |
@PublicAPI(usage = ACCESS)
public static Set<Location> ofPackage(String pkg) {
ImmutableSet.Builder<Location> result = ImmutableSet.builder();
for (Location location : getLocationsOf(asResourceName(pkg))) {
result.add(location);
}
return result.build();
} | @Test
public void locations_of_packages_within_file_URIs() throws Exception {
Set<Location> locations = Locations.ofPackage("com.tngtech.archunit.core.importer");
assertThat(urisOf(locations)).contains(
uriOfFolderOf(getClass()),
uriOfFolderOf(Locations.class)
... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
return FEELFnResult.ofResult( BigDecimal.valueOf( list.size() ) );
} | @Test
void invokeParamArrayNonEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(new Object[]{1, 2, "test"}), BigDecimal.valueOf(3));
} |
public static MemberVersion of(int major, int minor, int patch) {
if (major == 0 && minor == 0 && patch == 0) {
return MemberVersion.UNKNOWN;
} else {
return new MemberVersion(major, minor, patch);
}
} | @Test
public void testVersionOf_whenVersionStringIsNull() {
assertEquals(MemberVersion.UNKNOWN, MemberVersion.of(null));
} |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationHasDisabledCronExpressionButNotSpecifiedIdShouldBeOmitted() {
new ApplicationContextRunner()
.withBean(RecurringJobPostProcessor.class)
.withBean(JobScheduler.class, () -> jobScheduler)
.withPropertyVa... |
public static void retryWithBackoff(
final int maxRetries,
final int initialWaitMs,
final int maxWaitMs,
final Runnable runnable,
final Class<?>... passThroughExceptions) {
retryWithBackoff(
maxRetries,
initialWaitMs,
maxWaitMs,
runnable,
() -> f... | @Test
public void shouldBackoffOnFailure() {
doThrow(new RuntimeException("error")).when(runnable).run();
try {
RetryUtil.retryWithBackoff(3, 1, 100, runnable, sleep, () -> false, Collections.emptyList());
fail("retry should have thrown");
} catch (final RuntimeException e) {
}
verify(... |
public static Configuration readSSLConfiguration(Configuration conf,
Mode mode) {
Configuration sslConf = new Configuration(false);
sslConf.setBoolean(SSL_REQUIRE_CLIENT_CERT_KEY, conf.getBoolean(
SSL_REQUIRE_CLIENT_CERT_KEY, SSL_REQUIRE_CLIENT_CERT_DEF... | @Test
public void testSslConfFallback() throws Exception {
Configuration conf = new Configuration(FAKE_SSL_CONFIG);
// Set non-exist-ssl-client.xml that fails to load.
// This triggers fallback to SSL config from input conf.
conf.set(SSL_CLIENT_CONF_KEY, "non-exist-ssl-client.xml");
Configuration... |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
try {
if(null != status.getModified()) {
// We must both set the accessed and modified time. See AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME
// All times a... | @Test
public void testSetTimestampDirectory() throws Exception {
final Path home = new SFTPHomeDirectoryService(session).find();
final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory));
new SFTPDirectoryFeature(session).mkdir(test, new TransferStatus()... |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testNotParenOr()
{
final Predicate parsed = PredicateExpressionParser.parse("!(com.linkedin.data.it.AlwaysTruePredicate | com.linkedin.data.it.AlwaysFalsePredicate)");
Assert.assertEquals(parsed.getClass(), NotPredicate.class);
final Predicate intermediate = ((NotPredicate) parsed).ge... |
public String getName() {
if (elements.isEmpty()) return "";
return elements.get(elements.size() - 1);
} | @Test
public void testGetName() {
assertEquals("baz", getAbsolutePath().getName());
assertEquals("baz", getRelativePath().getName());
assertEquals("baz", getWithSlashes().getName());
assertEquals("baz", getAppended().getName());
assertEquals("foo", getOne().getName());
} |
@VisibleForTesting
@Nonnull
Map<String, Object> prepareContextForPaginatedResponse(@Nonnull List<RuleDao> rules) {
final Map<String, RuleDao> ruleTitleMap = rules
.stream()
.collect(Collectors.toMap(RuleDao::title, dao -> dao));
final Map<String, List<PipelineCom... | @Test
public void prepareContextForPaginatedResponse_returnsEmptyMapOnEmptyListOfRules() {
assertThat(underTest.prepareContextForPaginatedResponse(List.of()))
.isEqualTo(Map.of("used_in_pipelines", Map.of()));
} |
@Override
public void removeDevice(DeviceId did) {
snmpDeviceMap.remove(did);
} | @Test
public void removeDevice() {
addDevice();
snmpController.removeDevice(device.deviceId());
assertNull("Device shoudl not be present", snmpController.getDevice(device.deviceId()));
} |
public static RLESparseResourceAllocation merge(ResourceCalculator resCalc,
Resource clusterResource, RLESparseResourceAllocation a,
RLESparseResourceAllocation b, RLEOperator operator, long start, long end)
throws PlanningException {
NavigableMap<Long, Resource> cumA =
a.getRangeOverlappi... | @Test
public void testMergeMax() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResou... |
boolean readBuffers(Queue<MemorySegment> buffers, BufferRecycler recycler) throws IOException {
return fileReader.readCurrentRegion(buffers, recycler, this::addBuffer);
} | @Test
void testReadBuffers() throws Exception {
CountingAvailabilityListener listener = new CountingAvailabilityListener();
SortMergeSubpartitionReader subpartitionReader =
createSortMergeSubpartitionReader(listener);
assertThat(listener.numNotifications).isZero();
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.