focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void move(String noteId, String notePath, String newNotePath, AuthenticationInfo subject) throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(noteId));
BlobId sourceBlobId = makeBlobId(noteId, notePath);
BlobId destinationBlobId = makeBlobId(noteId, newNotePath);
t... | @Test
void testMove_nonexistent() throws IOException {
zConf.setProperty(ConfVars.ZEPPELIN_NOTEBOOK_GCS_STORAGE_DIR.getVarName(), DEFAULT_URL);
this.notebookRepo = new GCSNotebookRepo(zConf, noteParser, storage);
assertThrows(IOException.class, () -> {
notebookRepo.move("id", "/name", "/name_new", A... |
public CompletableFuture<List<SendResult>> sendMessage(ProxyContext ctx, QueueSelector queueSelector,
String producerGroup, int sysFlag, List<Message> messageList, long timeoutMillis) {
CompletableFuture<List<SendResult>> future = new CompletableFuture<>();
long beginTimestampFirst = System.curr... | @Test
public void testSendMessage() throws Throwable {
when(metadataService.getTopicMessageType(any(), eq(TOPIC))).thenReturn(TopicMessageType.NORMAL);
String txId = MessageClientIDSetter.createUniqID();
String msgId = MessageClientIDSetter.createUniqID();
long commitLogOffset = 1000... |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldFailOnUnknownStateBackend() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setStreaming(true);
options.setStateBackend("unknown");
options.setStateBackendStoragePath("/path");
assertThrows(
"State backend was set to 'unknown' but no storage p... |
public static RuleDescriptionSectionContextDto of(String key, String displayName) {
return new RuleDescriptionSectionContextDto(key, displayName);
} | @Test
void equals_with_different_context_keys_should_return_false() {
RuleDescriptionSectionContextDto context1 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME);
RuleDescriptionSectionContextDto context2 = RuleDescriptionSectionContextDto.of(CONTEXT_KEY + "2", CONTEXT_DISPLAY_NAME);
... |
@Override
public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize)
{
checkState(!Thread.holdsLock(this), "Can not get pages while holding a lock on this");
requireNonNull(outputBufferId, "outputBufferId is null");
checkArgument(m... | @Test
public void testDuplicateRequests()
{
BroadcastOutputBuffer buffer = createBroadcastBuffer(
createInitialEmptyOutputBuffers(BROADCAST)
.withBuffer(FIRST, BROADCAST_PARTITION_ID)
.withNoMoreBufferIds(),
sizeOfPages(10))... |
public void write(ImageWriter writer, ImageWriterOptions options) {
for (BrokerRegistration broker : brokers.values()) {
writer.write(broker.toRecord(options));
}
if (!controllers.isEmpty()) {
if (!options.metadataVersion().isControllerRegistrationSupported()) {
... | @Test
public void testHandleLossOfControllerRegistrations() {
ClusterImage testImage = new ClusterImage(Collections.emptyMap(),
Collections.singletonMap(1000, new ControllerRegistration.Builder().
setId(1000).
setIncarnationId(Uuid.fromString("9ABu6HEgRuS-hjHLgC4c... |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testShouldThrowUnknownMemberIdExceptionWhenUnknownStaticMemberLeaves() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicNa... |
public MutableTree<K> beginWrite() {
return new MutableTree<>(this);
} | @Test
public void iterationBenchmark() {
final Persistent23Tree.MutableTree<Integer> tree = new Persistent23Tree<Integer>().beginWrite();
final int count = 100000;
for (int i = 0; i < count; ++i) {
tree.add(i);
}
TestUtil.time("Persistent23Tree iteration", () -> {... |
@VisibleForTesting
static Instant getCreationTime(String configuredCreationTime, ProjectProperties projectProperties)
throws DateTimeParseException, InvalidCreationTimeException {
try {
switch (configuredCreationTime) {
case "EPOCH":
return Instant.EPOCH;
case "USE_CURRENT_T... | @Test
public void testGetCreationTime_isoDateTimeValue() throws InvalidCreationTimeException {
Instant expected = DateTimeFormatter.ISO_DATE_TIME.parse("2011-12-03T01:15:30Z", Instant::from);
List<String> validTimeStamps =
ImmutableList.of(
"2011-12-03T10:15:30+09:00",
"2011-12... |
public Optional<UserDto> authenticate(Credentials credentials, HttpRequest request, AuthenticationEvent.Method method) {
if (realm == null) {
return Optional.empty();
}
return Optional.of(doAuthenticate(fixCase(credentials), request, method));
} | @Test
public void authenticate() {
executeStartWithoutGroupSync();
when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(true);
UserDetails userDetails = new UserDetails();
userDetails.setName("name");
userDetails.setEmail("email");
when(externalUsersProvider.doGetUse... |
public PickTableLayoutForPredicate pickTableLayoutForPredicate()
{
return new PickTableLayoutForPredicate(metadata);
} | @Test
public void ruleAddedNewTableLayoutIfTableScanHasEmptyConstraint()
{
tester().assertThat(pickTableLayout.pickTableLayoutForPredicate())
.on(p -> {
p.variable("orderstatus", createVarcharType(1));
return p.filter(p.rowExpression("orderstatus =... |
@Description("Get the plan ids of given plan node")
@ScalarFunction("json_presto_query_plan_node_children")
@SqlType("ARRAY<VARCHAR>")
@SqlNullable
public static Block jsonPlanNodeChildren(@TypeParameter("ARRAY<VARCHAR>") ArrayType arrayType,
@SqlType(StandardTypes.JSON) Slice jsonPlan,
... | @Test
public void testJsonPlanNodeChildren()
{
assertFunction("json_presto_query_plan_node_children(null, null)", new ArrayType(VARCHAR), null);
assertFunction("json_presto_query_plan_node_children(null, '1')", new ArrayType(VARCHAR), null);
assertFunction("json_presto_query_plan_node_c... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertShort() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.SHORT_TYPE).build();
BasicTypeDefine typeDefine = OracleTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName())... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<DescribeFunction> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final DescribeFunction describeFunction = statement.getSta... | @Test
public void shouldDescribeUDTF() {
// When:
final FunctionDescriptionList functionList = (FunctionDescriptionList)
CustomExecutors.DESCRIBE_FUNCTION.execute(
engine.configure("DESCRIBE FUNCTION TEST_UDTF1;"),
mock(SessionProperties.class),
engine.getEngine(),
... |
public static int[] applyOrder(int[] arr, int[] order) {
if (order.length > arr.length)
throw new IllegalArgumentException("sort order must not be shorter than array");
int[] result = new int[order.length];
for (int i = 0; i < result.length; ++i)
result[i] = arr[order[i]]... | @Test
public void testApplyOrder() {
assertEquals(from(0, 6, 3, 1, 4), from(ArrayUtil.applyOrder(new int[]{3, 4, 6, 0, 1}, new int[]{3, 2, 0, 4, 1})));
} |
@VisibleForTesting
protected static MapOutputFile renameMapOutputForReduce(JobConf conf,
TaskAttemptId mapId, MapOutputFile subMapOutputFile) throws IOException {
FileSystem localFs = FileSystem.getLocal(conf);
// move map output to reduce input
Path mapOut = subMapOutputFile.getOutputFile();
Fi... | @Test
public void testRenameMapOutputForReduce() throws Exception {
final JobConf conf = new JobConf();
final MROutputFiles mrOutputFiles = new MROutputFiles();
mrOutputFiles.setConf(conf);
// make sure both dirs are distinct
//
conf.set(MRConfig.LOCAL_DIR, localDirs[0].toString());
fina... |
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) {
return mRxSharedPreferences.getBoolean(
mResources.getString(prefKey), mResources.getBoolean(defaultValue));
} | @Test
public void testDoesNotSetupFallbackDictionaryToFalseIfWasSetBeforeToTrue() {
SharedPrefsHelper.setPrefsValue("settings_key_always_use_fallback_user_dictionary", true);
SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 11);
SharedPreferences preferences =
PreferenceManage... |
@Override
public Mono<SetRegistrationLockResponse> setRegistrationLock(final SetRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
if (request.getRegistrationLock().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDes... | @Test
void setRegistrationLock() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
final byte[] registrationLockSecret = TestRandomUtil.nextBytes(32);
fina... |
public final void tag(I input, ScopedSpan span) {
if (input == null) throw new NullPointerException("input == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
tag(span, input, span.context());
} | @Test void tag_customizer_withNullContext() {
when(parseValue.apply(eq(input), isNull())).thenReturn("value");
tag.tag(input, null, customizer);
verify(parseValue).apply(input, null);
verifyNoMoreInteractions(parseValue); // doesn't parse twice
verify(customizer).tag("key", "value");
verifyNoM... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
return new AttributedList<Path>(Collections.singletonList(
new MantaAccountHomeInfo(session.getHost().getCredentials().getUs... | @Test(expected = NotfoundException.class)
public void testListNotFoundFolder() throws Exception {
new MantaListService(session).list(new Path(
new MantaHomeFinderFeature(session.getHost()).find(), "notfound", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener());
} |
public Set<String> getPluginsThatSupportsGetUserRoles() {
return getPluginsWithCapabilities(Capabilities::canGetUserRoles);
} | @Test
public void shouldGetPluginsThatSupportsGetUserRolesCall() {
when(plugin1.getCapabilities().canGetUserRoles()).thenReturn(true);
Set<String> pluginsThatSupportsGetUserRoles = store.getPluginsThatSupportsGetUserRoles();
assertThat(pluginsThatSupportsGetUserRoles.size(), is(1));
... |
@Override
public UnitExtension getUnitExtension(String extensionName) {
if (extensionName.equals("CommanderExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this));
}
return super.getUnitExtension(extensionName);
} | @Test
void getUnitExtension() {
final var unit = new CommanderUnit("CommanderUnitName");
assertNull(unit.getUnitExtension("SoldierExtension"));
assertNull(unit.getUnitExtension("SergeantExtension"));
assertNotNull(unit.getUnitExtension("CommanderExtension"));
} |
@Override
public void apply(final Record<KOut, Change<ValueAndTimestamp<VOut>>> record) {
@SuppressWarnings("rawtypes") final ProcessorNode prev = context.currentNode();
context.setCurrentNode(myNode);
try {
context.forward(
record
.withValue(
... | @Test
public void shouldForwardValueTimestampIfNewValueExists() {
@SuppressWarnings("unchecked")
final InternalProcessorContext<String, Change<String>> context = mock(InternalProcessorContext.class);
doNothing().when(context).forward(
new Record<>(
"key",
... |
List<MappingField> resolveFields(
@Nonnull String[] externalName,
@Nullable String dataConnectionName,
@Nonnull Map<String, String> options,
@Nonnull List<MappingField> userFields,
boolean stream
) {
Predicate<MappingField> pkColumnName = Options.g... | @Test
public void testFailsOnNoDatabase() {
String collectionName = "people_3";
FieldResolver resolver = new FieldResolver(null);
Map<String, String> readOpts = new HashMap<>();
readOpts.put("connectionString", mongoContainer.getConnectionString());
try {
resolve... |
public void hasLength(int expectedLength) {
checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength);
check("length()").that(checkNotNull(actual).length()).isEqualTo(expectedLength);
} | @Test
public void hasLengthZero() {
assertThat("").hasLength(0);
} |
public BatchEventData getBatchEventData() {
return batchEventData;
} | @Test
public void testGetBatchEventData() {
assertEquals(batchEventData, batchIMapEvent.getBatchEventData());
} |
@Override
public void execute(ComputationStep.Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) {
@Override
public void visitProject(Component project) {
executeForProject(project);
}
}).visit(tree... | @Test
void rawMeasure_is_updated_if_present_and_new_measures_are_created_if_project_has_measure_for_metric_of_condition() {
int rawValue = 3;
Condition equals2Condition = createLessThanCondition(INT_METRIC_1, "2");
Measure rawMeasure = newMeasureBuilder().create(rawValue, null);
qualityGateHolder.set... |
public void addChild(Entry entry) {
childEntries.add(entry);
entry.setParent(this);
} | @Test
public void findsParentComponent(){
Component component = mock(Component.class);
Entry structureWithEntry = new Entry();
new EntryAccessor().setComponent(structureWithEntry, component);
final Entry child = new Entry();
structureWithEntry.addChild(child);
assertThat(new EntryAccessor().getAncestor... |
@Nonnull
public static <K, V> Sink<ChangeRecord> map(
@Nonnull String mapName,
@Nonnull FunctionEx<? super ChangeRecord, ? extends K> keyFn,
@Nonnull FunctionEx<? super ChangeRecord, ? extends V> valueFn
) {
String name = "mapCdcSink(" + mapName + ')';
return ... | @Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void reordering() {
SupplierEx[] records = {
SYNC1,
UPDATE1,
() -> changeRecord(10, UPDATE, UPDATE1.get().key().toJson(), null,
UPDATE1.get().value().toJson().replace("sthoma... |
@Override
public void handle(SeckillWebMockRequestDTO request) {
// 状态机初始化
stateMachineService.initStateMachine(request.getSeckillId());
// 初始化库存数量
// 使用状态机控制活动状态
if (!stateMachineService.feedMachine(Events.ACTIVITY_RESET, request.getSeckillId())) {
throw new Runt... | @Test
public void shouldThrowExceptionWhenActivityNotEnded() {
SeckillWebMockRequestDTO request = new SeckillWebMockRequestDTO();
request.setSeckillId(123L);
when(stateMachineService.feedMachine(Events.ACTIVITY_RESET, request.getSeckillId())).thenReturn(false);
try {
sta... |
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
} | @Test
public void testGetAnalysisPhaze() {
assertEquals(AnalysisPhase.INFORMATION_COLLECTION, instance.getAnalysisPhase());
} |
@Override
public boolean hasAnySuperAdmin(Collection<Long> ids) {
if (CollectionUtil.isEmpty(ids)) {
return false;
}
RoleServiceImpl self = getSelf();
return ids.stream().anyMatch(id -> {
RoleDO role = self.getRoleFromCache(id);
return role != null... | @Test
public void testHasAnySuperAdmin_true() {
try (MockedStatic<SpringUtil> springUtilMockedStatic = mockStatic(SpringUtil.class)) {
springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(RoleServiceImpl.class)))
.thenReturn(roleService);
// mock 数据
... |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetFloatSchemaForDoubleClass() {
assertThat(
UdfUtil.getSchemaFromType(Double.class),
equalTo(ParamTypes.DOUBLE)
);
} |
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
if (object == null) {
return Collections.emptyMap();
}
ObjectParamMetadata metadata =
classToMetadata.computeIfAbsent(object.getClass(), ObjectParamMetadata::parseObjectType);
return metadata.objectField... | @Test
void defaultEncoder_acceptNullValue() {
assertThat(encoder.encode(null)).as("Empty map should be returned")
.isEqualTo(Collections.EMPTY_MAP);
} |
@DeleteMapping
@TpsControl(pointName = "NamingServiceDeregister", name = "HttpNamingServiceDeregister")
@Secured(action = ActionTypes.WRITE)
public String remove(@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName) throws Exception {
... | @Test
void testRemove() {
try {
String res = serviceController.remove(TEST_NAMESPACE, TEST_SERVICE_NAME);
assertEquals("ok", res);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
} |
@Override
public ConfigDO getConfigByKey(String key) {
return configMapper.selectByKey(key);
} | @Test
public void testGetConfigByKey() {
// mock 数据
ConfigDO dbConfig = randomConfigDO();
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
String key = dbConfig.getConfigKey();
// 调用
ConfigDO config = configService.getConfigByKey(key);
// 断言... |
@Override
public int getOrder() {
return -1;
} | @Test
void shouldOrderToMinusOne() {
ModifyServersOpenApiFilter modifyServersOpenApiFilter = new ModifyServersOpenApiFilter();
assertEquals(modifyServersOpenApiFilter.getOrder(), -1);
} |
@SuppressWarnings("unchecked")
public static <T> Collection<T> getServiceInstances(final Class<T> serviceInterface) {
return (Collection<T>) getRegisteredSPI(serviceInterface).getServiceInstances();
} | @Test
void assertGetServiceInstancesWithMultitonSPI() {
Collection<MultitonSPIFixture> actual = ShardingSphereServiceLoader.getServiceInstances(MultitonSPIFixture.class);
assertThat(actual.size(), is(1));
MultitonSPIFixture actualInstance = actual.iterator().next();
assertThat(actual... |
public void schedule(ExecutableMethod<?, ?> method) {
if (hasParametersOutsideOfJobContext(method.getTargetMethod())) {
throw new IllegalStateException("Methods annotated with " + Recurring.class.getName() + " can only have zero parameters or a single parameter of type JobContext.");
}
... | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationCronAndIntervalWillThrowException() {
final ExecutableMethod executableMethod = mock(ExecutableMethod.class);
final Method method = getRequiredMethod(MyServiceWithRecurringJob.class, "myRecurringMethod");
when(executableMethod.getTar... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testExceptionInFinishAbortsAllOperations() throws Exception {
Operation o1 = Mockito.mock(Operation.class);
Operation o2 = Mockito.mock(Operation.class);
Operation o3 = Mockito.mock(Operation.class);
Mockito.doThrow(new Exception("in finish")).when(o2).finish();
ExecutionStateTr... |
public static String getBasicApiJsonSchema() throws JsonProcessingException {
ObjectMapper mapper = createSchemaObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
DefaultPackageScanClassResolver packageScanClassResolver = new DefaultPackageScanClassResolver();
... | @Test
public void getBasicApiJsonSchema() throws Exception {
// create basic api dto schema
LOG.info("Basic Api Schema...");
String basicApiJsonSchema = JsonUtils.getBasicApiJsonSchema();
LOG.info(basicApiJsonSchema);
// parse schema to validate
ObjectMapper objectM... |
@Override
public PageResult<ProductCommentDO> getCommentPage(AppCommentPageReqVO pageVO, Boolean visible) {
return productCommentMapper.selectPage(pageVO, visible);
} | @Test
public void testGetCommentPage_success() {
// 准备参数
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
o.setUserNickname("王二狗");
o.setSpuName("感冒药");
o.setScores(ProductCommentScoresEnum.FOUR.getScores());
o.setReplyStatus... |
protected static void checkPayload(Channel channel, long size) throws IOException {
int payload = getPayload(channel);
boolean overPayload = isOverPayload(payload, size);
if (overPayload) {
ExceedPayloadLimitException e = new ExceedPayloadLimitException(
"Data len... | @Test
void tesCheckPayloadMinusPayloadNoLimit() throws Exception {
Channel channel = mock(Channel.class);
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1?payload=-1"));
AbstractCodec.checkPayload(channel, 15 * 1024 * 1024);
verify(channel, VerificationModeFactory.at... |
public Pair<IndexEntry, IndexEntry> lookupLastLogIndexAndPosFromTail() {
final long lastLogIndex = getLastLogIndex();
final long firstLogIndex = getFirstLogIndex();
IndexEntry lastSegmentIndex = null, lastConfIndex = null;
long index = lastLogIndex;
while (index >= firstLogIndex)... | @Test
public void testLookupLastLogIndexAndPosFromTail() {
this.indexDB.startServiceManager();
{
this.indexDB.appendIndexAsync(1, 1, IndexType.IndexSegment);
this.indexDB.appendIndexAsync(2, 2, IndexType.IndexSegment);
final Pair<Integer, Long> posPair = this.inde... |
public static ThriftType fromJSON(String json) {
return JSON.fromJSON(json, ThriftType.class);
} | @Test
public void testParseUnionInfo() throws Exception {
StructType st = (StructType)
StructType.fromJSON("{\"id\": \"STRUCT\", \"children\":[], \"structOrUnionType\": \"UNION\"}");
assertEquals(st.getStructOrUnionType(), StructOrUnionType.UNION);
st = (StructType)
StructType.fromJSON("{\... |
public static BadRequestException userNotExists(String userName) {
return new BadRequestException("user not exists for userName:%s", userName);
} | @Test
public void testUserNotExists(){
BadRequestException userNotExists = BadRequestException.userNotExists("user");
assertEquals("user not exists for userName:user", userNotExists.getMessage());
} |
@Override
public Resource parseResource(HttpServletRequest request, Secured secured) {
if (StringUtils.isNotBlank(secured.resource())) {
return parseSpecifiedResource(secured);
}
String type = secured.signType();
if (!resourceParserMap.containsKey(type)) {
Log... | @Test
@Secured(resource = "testResource")
void testParseResourceWithSpecifiedResource() throws NoSuchMethodException {
Secured secured = getMethodSecure("testParseResourceWithSpecifiedResource");
Resource actual = httpProtocolAuthService.parseResource(request, secured);
assertEquals("tes... |
public void writeEncodedValue(EncodedValue encodedValue) throws IOException {
switch (encodedValue.getValueType()) {
case ValueType.BOOLEAN:
writer.write(Boolean.toString(((BooleanEncodedValue) encodedValue).getValue()));
break;
case ValueType.BYTE:
... | @Test
public void testWriteEncodedValue_type() throws IOException {
DexFormattedWriter writer = new DexFormattedWriter(output);
writer.writeEncodedValue(new ImmutableTypeEncodedValue("Ltest/type;"));
Assert.assertEquals(
"Ltest/type;",
output.toString());
... |
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("type", type)
.add("key", key)
.add("value", value instanceof byte[] ? new ByteArraySizeHashPrinter((byte[]) value) : value)
.add("version", version)
.toString();
... | @Test
public void testToString() {
assertThat(stats1.toString(), is(stats1.toString()));
} |
public String toXmlPartial(Object domainObject) {
bombIf(!isAnnotationPresent(domainObject.getClass(), ConfigTag.class), () -> "Object " + domainObject + " does not have a ConfigTag");
Element element = elementFor(domainObject.getClass());
write(domainObject, element, configCache, registry);
... | @Test
public void shouldWriteEmptyOnCancelTaskWhenDefined() throws Exception {
String partial = """
<job name="functional">
<tasks>
<exec command="echo">
<oncancel />
</exec>
</tasks>
... |
@DELETE
@Path("status")
public Response deleteStatusUpdate(
@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,
@QueryParam("value") String newStatusValue,
@QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
try {
if (registry.... | @Test
public void testStatusOverrideDeleteReturnsNotFoundErrorCodeIfInstanceNotRegistered() throws Exception {
Response response = instanceResource.deleteStatusUpdate(InstanceStatus.OUT_OF_SERVICE.name(), "false", "0");
assertThat(response.getStatus(), is(equalTo(Status.NOT_FOUND.getStatusCode())));... |
@Override
public boolean supportsCoreSQLGrammar() {
return false;
} | @Test
void assertSupportsCoreSQLGrammar() {
assertFalse(metaData.supportsCoreSQLGrammar());
} |
public static Optional<String> getTargetFieldName(final List<Field<?>> fields, Model model) {
return getTargetFields(fields, model).stream().map(KiePMMLNameOpType::getName).findFirst();
} | @Test
void getTargetFieldName() {
final String fieldName = "fieldName";
MiningField.UsageType usageType = MiningField.UsageType.ACTIVE;
MiningField miningField = getMiningField(fieldName, usageType);
final DataField dataField = getDataField(fieldName, OpType.CATEGORICAL, DataType.STR... |
@SuppressWarnings("unchecked")
@Override
public boolean setFlushListener(final CacheFlushListener<Windowed<K>, V> listener,
final boolean sendOldValues) {
final SessionStore<Bytes, byte[]> wrapped = wrapped();
if (wrapped instanceof CachedStateStore) {
... | @Test
public void shouldNotSetFlushListenerOnWrappedNoneCachingStore() {
setUpWithoutContext();
assertFalse(store.setFlushListener(null, false));
} |
@Override
public Double getDoubleAndRemove(K name) {
return null;
} | @Test
public void testGetDoubleAndRemove() {
assertNull(HEADERS.getDoubleAndRemove("name1"));
} |
@Override
public Option<IndexedRecord> combineAndGetUpdateValue(IndexedRecord currentValue, Schema schema, Properties properties) throws IOException {
// Specific to Postgres: If the updated record has TOASTED columns,
// we will need to keep the previous value for those columns
// see https://debezium.io... | @Test
public void testMergeWithDelete() throws IOException {
GenericRecord deleteRecord = createRecord(2, Operation.DELETE, 100L);
PostgresDebeziumAvroPayload payload = new PostgresDebeziumAvroPayload(deleteRecord, 100L);
assertTrue(payload.isDeleted(avroSchema, new Properties()));
GenericRecord exis... |
@Override
public int getOrder() {
return PluginEnum.HYSTRIX.getCode();
} | @Test
public void testGetOrder() {
assertEquals(hystrixPlugin.getOrder(), PluginEnum.HYSTRIX.getCode());
} |
public JdbcUrl parse(final String jdbcUrl) {
Matcher matcher = CONNECTION_URL_PATTERN.matcher(jdbcUrl);
ShardingSpherePreconditions.checkState(matcher.matches(), () -> new UnrecognizedDatabaseURLException(jdbcUrl, CONNECTION_URL_PATTERN.pattern().replaceAll("%", "%%")));
String authority = match... | @Test
void assertParseIncorrectURL() {
assertThrows(UnrecognizedDatabaseURLException.class, () -> new StandardJdbcUrlParser().parse("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
} |
@Override
public void iterateStatus(AlluxioURI path, ListStatusPOptions options,
Consumer<? super URIStatus> action)
throws FileDoesNotExistException, IOException, AlluxioException {
if (options.getRecursive()) {
// Do not cache results of recursive list status,
// because some results mig... | @Test
public void iterateStatusRecursive() throws Exception {
mFs.iterateStatus(DIR, LIST_STATUS_OPTIONS.toBuilder().setRecursive(true).build(), ignored -> {
});
assertEquals(1, mRpcCountingFs.listStatusRpcCount(DIR));
mFs.iterateStatus(DIR, LIST_STATUS_OPTIONS.toBuilder().setRecursive(true).build(), ... |
@Override
public void execute(Context context) {
try (CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) {
while (issues.hasNext()) {
DefaultIssue issue = issues.next();
if (shouldUpdateIndexForIssue(issue)) {
changedIssuesRepository.addIssueKey(issue.key());
... | @Test
public void execute_whenIssueIssCopied_shouldLoadIssue() {
protoIssueCache.newAppender()
.append(newDefaultIssue().setCopied(true))
.close();
underTest.execute(mock(ComputationStep.Context.class));
verify(changedIssuesRepository).addIssueKey("issueKey1");
} |
public static SeaTunnelDataType<?> covertHiveTypeToSeaTunnelType(String name, String hiveType) {
if (hiveType.contains("varchar")) {
return BasicType.STRING_TYPE;
}
if (hiveType.contains("char")) {
throw CommonError.convertToSeaTunnelTypeError(
HiveCon... | @Test
void convertHiveStructType() {
SeaTunnelDataType<?> structType =
HiveTypeConvertor.covertHiveTypeToSeaTunnelType(
"structType", "struct<country:String,city:String>");
assertEquals(SqlType.ROW, structType.getSqlType());
SeaTunnelRowType seaTunnelR... |
public static Optional<Integer> getPreviousSequence(final List<Integer> sequences, final int currentSequence) {
if (sequences.size() <= 1) {
return Optional.empty();
}
sequences.sort(Integer::compareTo);
Integer index = null;
for (int i = 0; i < sequences.size(); i++)... | @Test
void assertGetPreviousSequence() {
List<Integer> sequences = Arrays.asList(2, 3, 1);
Optional<Integer> previousSequence = ConsistencyCheckSequence.getPreviousSequence(sequences, 3);
assertTrue(previousSequence.isPresent());
assertThat(previousSequence.get(), is(2));
pre... |
public static int read(
final UnsafeBuffer termBuffer,
final int termOffset,
final FragmentHandler handler,
final int fragmentsLimit,
final Header header,
final ErrorHandler errorHandler,
final long currentPosition,
final Position subscriberPosition)
{... | @Test
void shouldNotReadPastTail()
{
final int termOffset = 0;
final int readOutcome = TermReader.read(
termBuffer, termOffset, handler, Integer.MAX_VALUE, header, errorHandler, 0, subscriberPosition);
assertEquals(0, readOutcome);
verify(subscriberPosition, never())... |
public void ready() {
sync.releaseShared(UNUSED);
} | @Test
public void testAwaitAfterReady() throws InterruptedException {
StartingGun sg = new StartingGun();
sg.ready();
Thread[] threads = startWaitingThreads(sg);
allThreadsDead(threads);
} |
public boolean transitionToFailed(Throwable throwable)
{
requireNonNull(throwable, "throwable is null");
failureCause.compareAndSet(null, Failures.toFailure(throwable));
boolean failed = state.setIf(FAILED, currentState -> !currentState.isDone());
if (failed) {
log.error... | @Test
public void testFailed()
{
StageExecutionStateMachine stateMachine = createStageStateMachine();
assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE));
assertFinalState(stateMachine, StageExecutionState.FAILED);
} |
@Override
public StoredEntityListPreferences get(final StoredEntityListPreferencesId preferencesId) {
return this.db.findOneById(preferencesId);
} | @Test
public void returnsNullWhenFetchingPreferenceFromEmptyDB() {
final StoredEntityListPreferences storedEntityListPreferences = toTest.get(wrongId);
assertNull(storedEntityListPreferences);
} |
@Override
public void write(final PostgreSQLPacketPayload payload, final Object value) {
throw new UnsupportedSQLOperationException("PostgreSQLInt4ArrayBinaryProtocolValue.write()");
} | @Test
void assertWrite() {
assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().write(new PostgreSQLPacketPayload(null, StandardCharsets.UTF_8), "val"));
} |
public Strength getScore(final String password) {
if(StringUtils.isEmpty(password)) {
return Strength.veryweak;
}
else {
final int score = zxcvbn.measure(password, Collections.singletonList(
PreferencesFactory.get().getProperty("application.name"))).ge... | @Test
public void testGetScore() {
assertEquals(PasswordStrengthValidator.Strength.veryweak, new PasswordStrengthValidator().getScore(""));
assertEquals(PasswordStrengthValidator.Strength.veryweak, new PasswordStrengthValidator().getScore("Cyberduck"));
assertEquals(PasswordStrengthValidator... |
@Override
public String id() {
return blob.getGeneratedId();
} | @Test
public void testId() {
String id = "test-id";
when(blob.getGeneratedId()).thenReturn(id);
assertThat(artifact.id()).isEqualTo(id);
} |
@Override
public ResourceAllocationResult tryFulfillRequirements(
Map<JobID, Collection<ResourceRequirement>> missingResources,
TaskManagerResourceInfoProvider taskManagerResourceInfoProvider,
BlockedTaskManagerChecker blockedTaskManagerChecker) {
final ResourceAllocation... | @Test
void testFulfillRequirementWithRegisteredResourcesEvenly() {
final TaskManagerInfo taskManager1 =
new TestingTaskManagerInfo(
DEFAULT_SLOT_RESOURCE.multiply(10),
DEFAULT_SLOT_RESOURCE.multiply(10),
DEFAULT_SLOT_RES... |
public final synchronized List<E> getAllAddOns() {
Logger.d(mTag, "getAllAddOns has %d add on for %s", mAddOns.size(), getClass().getName());
if (mAddOns.size() == 0) {
loadAddOns();
}
Logger.d(
mTag, "getAllAddOns will return %d add on for %s", mAddOns.size(), getClass().getName());
r... | @Test(expected = IllegalStateException.class)
public void testMustSupplyNoneEmptyBuiltIns() throws Exception {
AddOnsFactory.SingleAddOnsFactory<TestAddOn> singleAddOnsFactory =
new AddOnsFactory.SingleAddOnsFactory<>(
getApplicationContext(),
SharedPrefsHelper.getSharedPreferences... |
public static int checkPositiveOrZero(int i, String name) {
if (i < INT_ZERO) {
throw new IllegalArgumentException(name + " : " + i + " (expected: >= 0)");
}
return i;
} | @Test
public void testCheckPositiveOrZeroIntString() {
Exception actualEx = null;
try {
ObjectUtil.checkPositiveOrZero(POS_ONE_INT, NUM_POS_NAME);
} catch (Exception e) {
actualEx = e;
}
assertNull(actualEx, TEST_RESULT_NULLEX_NOK);
actualEx =... |
@Override
public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) {
String githubApiUrl = characteristics.get(DEVOPS_PLATFORM_URL);
String githubRepository = characteristics.get(DEVOPS_PLATFORM_PROJECT_IDENTIFIER);
if (githubApiUrl == null ||... | @Test
public void getDevOpsProjectCreatorFromImport_shouldInstantiateDevOpsProjectCreator() {
AlmSettingDto mockAlmSettingDto = mockAlmSettingDto(true);
mockAlmPatDto(mockAlmSettingDto);
mockSuccessfulGithubInteraction();
when(devOpsProjectService.create(mockAlmSettingDto, GITHUB_PROJECT_DESCRIPTOR)... |
@VisibleForTesting
void checkSourceFileField( String sourceFilenameFieldName, SFTPPutData data ) throws KettleStepException {
// Sourcefilename field
sourceFilenameFieldName = environmentSubstitute( sourceFilenameFieldName );
if ( Utils.isEmpty( sourceFilenameFieldName ) ) {
// source filename field... | @Test( expected = KettleStepException.class )
public void checkSourceFileField_NameIsSet_NotFound() throws Exception {
step.setInputRowMeta( new RowMeta() );
step.checkSourceFileField( "sourceFile", new SFTPPutData() );
} |
public static MacAddress valueOf(final String address) {
if (!isValid(address)) {
throw new IllegalArgumentException(
"Specified MAC Address must contain 12 hex digits"
+ " separated pairwise by :'s.");
}
final String[] elements = addre... | @Test(expected = IllegalArgumentException.class)
public void testValueOfInvalidByte() throws Exception {
MacAddress.valueOf(INVALID_BYTE);
} |
@Override
public Sensor addLatencyRateTotalSensor(final String scopeName,
final String entityName,
final String operationName,
final Sensor.RecordingLevel recordingLevel,
... | @Test
public void shouldThrowIfLatencyRateTotalSensorIsAddedWithOddTags() {
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> streamsMetrics.addLatencyRateTotalSensor(
SCOPE_NAME,
ENTITY_NAME,
... |
@Override
public Set<String> findClassNames(String pluginId) {
Set<String> classNames = getEntries().get(pluginId);
if (classNames == null) {
return Collections.emptySet();
}
return classNames;
} | @Test
public void testFindClassNames() {
ExtensionFinder instance = new AbstractExtensionFinder(pluginManager) {
@Override
public Map<String, Set<String>> readPluginsStorages() {
Map<String, Set<String>> entries = new LinkedHashMap<>();
Set<String> b... |
public boolean containsDataSource() {
return !resourceMetaData.getStorageUnits().isEmpty();
} | @Test
void assertNotContainsDataSource() {
ResourceMetaData resourceMetaData = new ResourceMetaData(Collections.emptyMap());
RuleMetaData ruleMetaData = new RuleMetaData(Collections.singleton(mock(ShardingSphereRule.class)));
assertFalse(new ShardingSphereDatabase("foo_db", mock(DatabaseType... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchUdpDstMaskedTest() {
Criterion criterion = Criteria.matchUdpDstMasked(tpPort, tpPortMask);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@PostConstruct
public void applyPluginMetadata() {
if (taskPreference() != null) {
for (ConfigurationProperty configurationProperty : configuration) {
if (isValidPluginConfiguration(configurationProperty.getConfigKeyName())) {
Boolean isSecure = pluginConfigur... | @Test
public void postConstructShouldDoNothingForAInvalidConfigurationProperty() throws Exception {
TaskPreference taskPreference = mock(TaskPreference.class);
ConfigurationProperty configurationProperty = ConfigurationPropertyMother.create("KEY1");
Configuration configuration = new Configur... |
@Override
public void execute(SensorContext context) {
for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) {
processSignificantCodeFile(file, context);
}
} | @Test
public void testNoExceptionIfNoFileWithOffsets() {
context.fileSystem().add(inputFile);
sensor.execute(context);
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MultiValuedTimestamp)) {
return false;
}
MultiValuedTimestamp that = (MultiValuedTimestamp) obj;
return Objects.equals(this.value1, that.value1... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(stats1, stats1)
.addEqualityGroup(stats2)
.testEquals();
} |
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) {
return drlxParse(patternType, bindingId, expression, false);
} | @Test
public void testNullSafeExpressionsWithIn() {
SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "address!.city in (\"Milan\", \"Tokyo\")");
List<Expression> nullSafeExpressions = result.getNullSafeExpressions();
assertThat(nullSafeExpression... |
@Override
public void reconcileExecutionDeployments(
ResourceID taskExecutorHost,
ExecutionDeploymentReport executionDeploymentReport,
Map<ExecutionAttemptID, ExecutionDeploymentState> expectedDeployedExecutions) {
final Set<ExecutionAttemptID> unknownExecutions =
... | @Test
void testPendingDeployments() {
TestingExecutionDeploymentReconciliationHandler handler =
new TestingExecutionDeploymentReconciliationHandler();
DefaultExecutionDeploymentReconciler reconciler =
new DefaultExecutionDeploymentReconciler(handler);
Resour... |
@VisibleForTesting
static RowGroup createRowGroup(int groupId, long rowsInStripe, long rowsInRowGroup, Map<StreamId, List<RowGroupIndex>> columnIndexes, Map<StreamId, ValueInputStream<?>> valueStreams, Map<StreamId, StreamCheckpoint> checkpoints)
{
long totalRowGroupBytes = columnIndexes
... | @Test(expectedExceptions = ArithmeticException.class)
public void testRowGroupOverflow()
{
StripeReader.createRowGroup(Integer.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of());
} |
@Override
public void handlerPlugin(final PluginData pluginData) {
if (Objects.nonNull(pluginData) && Boolean.TRUE.equals(pluginData.getEnabled())) {
//init redis
RedisConfigProperties redisConfigProperties = GsonUtils.getInstance().fromJson(pluginData.getConfig(), RedisConfigPropert... | @Test
public void handlerPluginTest() {
RedisConfigProperties redisConfigProperties = generateRedisConfig(generateDefaultUrl());
PluginData pluginData = new PluginData();
pluginData.setEnabled(true);
pluginData.setConfig(GsonUtils.getInstance().toJson(redisConfigProperties));
... |
public Map<String, Map<String, String>> getConfigAsMap() {
Map<String, Map<String, String>> configMap = new HashMap<>();
for (ConfigurationProperty property : configuration) {
Map<String, String> mapValue = new HashMap<>();
mapValue.put(VALUE_KEY, property.getValue());
... | @Test
void shouldGetConfigAsMap() throws Exception {
PluginConfiguration pluginConfiguration = new PluginConfiguration("test-plugin-id", "13.4");
GoCipher cipher = new GoCipher();
List<String> keys = List.of("Avengers 1", "Avengers 2", "Avengers 3", "Avengers 4");
List<String> value... |
public static Metric metric(String name) {
return MetricsImpl.metric(name, Unit.COUNT);
} | @Test
public void metricsDisabled() {
Long[] input = {0L, 1L, 2L, 3L, 4L};
pipeline.readFrom(TestSources.items(input))
.map(l -> {
Metrics.metric("mapped").increment();
Metrics.metric("total", Unit.COUNT).set(input.length);
... |
@Override
protected String selectorHandler(final MetaDataRegisterDTO metaDataDTO) {
return "";
} | @Test
public void testSelectorHandler() {
MetaDataRegisterDTO metaDataRegisterDTO = MetaDataRegisterDTO.builder().build();
assertEquals(StringUtils.EMPTY, shenyuClientRegisterDivideService.selectorHandler(metaDataRegisterDTO));
} |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
String methodName) throws Throwable {
RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter);
Object returnValue = proceedingJoinPoint.proceed();
return executeR... | @Test
public void testReactorTypes() throws Throwable {
RateLimiter rateLimiter = RateLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(
rxJava2RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod"))
... |
public static Path getStagingDir(Cluster cluster, Configuration conf)
throws IOException, InterruptedException {
UserGroupInformation user = UserGroupInformation.getLoginUser();
return getStagingDir(cluster, conf, user);
} | @Test(expected = IOException.class)
public void testGetStagingWhenFileOwnerNameAndCurrentUserNameDoesNotMatch()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
String stagingDirOwner = "someuser";
Path stagingPath = mock... |
public synchronized <U> Versioned<U> map(Function<V, U> transformer) {
return new Versioned<>(value != null ? transformer.apply(value) : null, version, creationTime);
} | @Test
public void testMap() {
Versioned<String> tempObj = stats1.map(VersionedTest::transform);
assertThat(tempObj.value(), is("1"));
} |
@Override
public void initSession(T param) throws ExtensionException {
// remove session before init
session.remove();
IBusiness<T> matchedBusiness = null;
List<String> matchedBusinessCodes = new ArrayList<>();
for (IBusiness<T> business : businessManager.listAllBusinesses()... | @Test
public void testInitSession() throws Exception {
ExtensionException e;
DefaultExtContext<Object> context = new DefaultExtContext<>(false, true);
context.registerBusiness(new BusinessX());
context.registerBusiness(new BusinessY());
context.registerBusiness(new BusinessZ... |
public List<String> tokenize(String text)
{
List<String> tokens = new ArrayList<>();
Matcher regexMatcher = regexExpression.matcher(text);
int lastIndexOfPrevMatch = 0;
while (regexMatcher.find(lastIndexOfPrevMatch)) // this is where the magic happens:
... | @Test
void testTokenize_happyPath_7()
{
// given
CompoundCharacterTokenizer tokenizer = new CompoundCharacterTokenizer(
new HashSet<>(Arrays.asList("_100_101_", "_102_", "_103_104_")));
String text = "_100_101_102_103_104_";
// when
List<String> tokens =... |
Flux<Post> findAll() {
return Flux.fromIterable(data.values());
} | @Test
public void testGetAllPosts() {
StepVerifier.create(posts.findAll())
.consumeNextWith(p -> assertTrue(p.getTitle().equals("post one")))
.consumeNextWith(p -> assertTrue(p.getTitle().equals("post two")))
.expectComplete()
.verify();
} |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testWithEmptyResultArray() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.callback(new Callable<Result[]>() {
@Override
public Result[] call() throws Exception {
return new Resu... |
public List<ResContainer> makeResourcesXml(JadxArgs args) {
Map<String, ICodeWriter> contMap = new HashMap<>();
for (ResourceEntry ri : resStorage.getResources()) {
if (SKIP_RES_TYPES.contains(ri.getTypeName())) {
continue;
}
String fn = getFileName(ri);
ICodeWriter cw = contMap.get(fn);
if (cw =... | @Test
void testString() {
ResourceStorage resStorage = new ResourceStorage();
ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "string", "app_name", "");
re.setSimpleValue(new RawValue(3, 0));
re.setNamedValues(Lists.list());
resStorage.add(re);
BinaryXMLStrings strings = new BinaryXMLStri... |
@Override
public RecoverableFsDataOutputStream open(Path path) throws IOException {
LOGGER.trace("Opening output stream for path {}", path);
Preconditions.checkNotNull(path);
GSBlobIdentifier finalBlobIdentifier = BlobUtils.parseUri(path.toUri());
return new GSRecoverableFsDataOutpu... | @Test
public void testOpen() throws IOException {
Path path = new Path("gs://foo/bar");
GSRecoverableFsDataOutputStream stream =
(GSRecoverableFsDataOutputStream) writer.open(path);
assertNotNull(stream);
} |
@Override
public Duration convert(String source) {
try {
if (ISO8601.matcher(source).matches()) {
return Duration.parse(source);
}
Matcher matcher = SIMPLE.matcher(source);
Assert.state(matcher.matches(), "'" + source + "' is not a valid durati... | @Test
public void convertWhenSimpleMillisShouldReturnDuration() {
assertThat(convert("10ms")).isEqualTo(Duration.ofMillis(10));
assertThat(convert("10MS")).isEqualTo(Duration.ofMillis(10));
assertThat(convert("+10ms")).isEqualTo(Duration.ofMillis(10));
assertThat(convert("-10ms")).is... |
public static boolean isCompositeType(LogicalType logicalType) {
if (logicalType instanceof DistinctType) {
return isCompositeType(((DistinctType) logicalType).getSourceType());
}
LogicalTypeRoot typeRoot = logicalType.getTypeRoot();
return typeRoot == STRUCTURED_TYPE || typ... | @Test
void testIsCompositeTypeLegacyCompositeType() {
DataType dataType =
TypeConversions.fromLegacyInfoToDataType(new RowTypeInfo(Types.STRING, Types.INT));
assertThat(LogicalTypeChecks.isCompositeType(dataType.getLogicalType())).isTrue();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.