focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public FEELFnResult<Boolean> invoke(@ParameterName( "range" ) Range range, @ParameterName( "point" ) Comparable point) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamsCantBeCompared() {
FunctionTestUtil.assertResultError( startedByFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, 1, 2, Range.RangeBoundary.CLOSED ) ), Invalid... |
protected static List<UnidirectionalEvent> parseUnidirectionalEventTemplateOutput(String content) throws Exception {
List<UnidirectionalEvent> results = new ArrayList<>();
JsonNode root = YAML_MAPPER.readTree(sanitizeYamlContent(content));
if (root.getNodeType() == JsonNodeType.ARRAY) {
Iter... | @Test
void testParseEventMessageOutputYaml() {
String aiResponse = """
- example: 1
message:
headers:
my-app-header: 42
payload:
id: "12345"
sendAt: "2022-01-01T10:00:00Z"
fullName:... |
@Override
public void destroy() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testDestroy() {
context.destroy();
} |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldMatchExistingStringJsonPath() {
assertThat(BOOKS_JSON, withJsonPath("$.expensive"));
assertThat(BOOKS_JSON, withJsonPath("$.store.bicycle"));
assertThat(BOOKS_JSON, withJsonPath("$.store.book[2].title"));
assertThat(BOOKS_JSON, withJsonPath("$.store.book[*].au... |
public static Map<String, Object> toMap(final Object object) {
try {
String json = MAPPER.writeValueAsString(object);
final MapType mapType = MAPPER.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, Object.class);
return MAPPER.readValue(json, mapType);
... | @Test
public void testToMap() {
TestObject testObject = JsonUtils.jsonToObject(EXPECTED_JSON, TestObject.class);
Map<String, Object> testObjectMap = JsonUtils.toMap(testObject);
assertNotNull(testObjectMap);
assertEquals(testObjectMap.get("name"), "test object");
} |
public void assignStates() {
checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks);
Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates);
// find the states of all operators belonging to this task and compute additional
// information in f... | @Test
void testChannelStateAssignmentUpscaling() throws JobException, JobExecutionException {
List<OperatorID> operatorIds = buildOperatorIds(2);
Map<OperatorID, OperatorState> states = buildOperatorStates(operatorIds, 2);
Map<OperatorID, ExecutionJobVertex> vertices =
build... |
public static String createToken(Map<String, Object> payload, byte[] key) {
return createToken(null, payload, key);
} | @Test
public void createTest(){
byte[] key = "1234".getBytes();
Map<String, Object> map = new HashMap<String, Object>() {
private static final long serialVersionUID = 1L;
{
put("uid", Integer.parseInt("123"));
put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
}
};
JW... |
static URL[] saveFilesLocally(String driverJars) {
List<String> listOfJarPaths = Splitter.on(',').trimResults().splitToList(driverJars);
final String destRoot = Files.createTempDir().getAbsolutePath();
List<URL> driverJarUrls = new ArrayList<>();
listOfJarPaths.stream()
.forEach(
ja... | @Test
public void testSavesFilesAsExpected() throws IOException {
File tempFile1 = temporaryFolder.newFile();
File tempFile2 = temporaryFolder.newFile();
String expectedContent1 = "hello world";
String expectedContent2 = "hello world 2";
Files.write(tempFile1.toPath(), expectedContent1.getBytes(St... |
@Override
public void accept(final MeterEntity entity, final BucketedValues value) {
if (dataset.size() > 0) {
if (!value.isCompatible(dataset)) {
throw new IllegalArgumentException(
"Incompatible BucketedValues [" + value + "] for current HistogramFunction[" ... | @Test
public void testFunction() {
HistogramFunctionInst inst = new HistogramFunctionInst();
inst.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
new BucketedValues(
BUCKETS, new long[] {
0,
4,
10,... |
@VisibleForTesting
List<String> getFuseInfo() {
return mFuseInfo;
} | @Test
public void localKernelDataCacheDisabled() {
Assume.assumeTrue(Configuration.getInt(PropertyKey.FUSE_JNIFUSE_LIBFUSE_VERSION) == 2);
try (FuseUpdateChecker checker = getUpdateCheckerWithMountOptions("direct_io")) {
Assert.assertFalse(containsTargetInfo(checker.getFuseInfo(),
FuseUpdateCh... |
public static boolean unblock(
final UnsafeBuffer[] termBuffers,
final UnsafeBuffer logMetaDataBuffer,
final long blockedPosition,
final int termLength)
{
final int positionBitsToShift = LogBufferDescriptor.positionBitsToShift(termLength);
final int blockedTermCount =... | @Test
void shouldNotUnblockWhenPositionHasCompleteMessage()
{
final int blockedOffset = HEADER_LENGTH * 4;
final long blockedPosition = computePosition(TERM_ID_1, blockedOffset, positionBitsToShift, TERM_ID_1);
final int activeIndex = indexByPosition(blockedPosition, positionBitsToShift)... |
public static BinaryTag readTag(final @NotNull ByteBuf buf) {
final byte id = buf.readByte();
if (id >= BINARY_TAG_TYPES.length) {
throw new DecoderException("Invalid binary tag id: " + id);
}
final BinaryTagType<? extends BinaryTag> type = BINARY_TAG_TYPES[id];
try {... | @Test
void testReadInvalidTagId() {
this.buf.writeByte(BinaryTagTypes.LONG_ARRAY.id() + 1);
assertThrows(DecoderException.class, () -> BufUtil.readTag(this.buf));
} |
@Override
public String buildContext() {
final String selector = ((Collection<?>) getSource())
.stream()
.map(s -> ((SelectorDO) s).getName())
.collect(Collectors.joining(","));
return String.format("the selector[%s] is %s", selector, StringUtils.lower... | @Test
void buildContext() {
String expectMsg = String.format("the selector[%s] is %s", selectorDO.getName(), StringUtils.lowerCase(batchSelectorDeletedEvent.getType().getType().toString()));
String actualMsg = batchSelectorDeletedEvent.buildContext();
assertEquals(expectMsg, actualMsg);
... |
public void processPriorCommands(final PersistentQueryCleanupImpl queryCleanup) {
try {
final List<QueuedCommand> restoreCommands = commandStore.getRestoreCommands();
final List<QueuedCommand> compatibleCommands = checkForIncompatibleCommands(restoreCommands);
LOG.info("Restoring previous state f... | @Test
public void shouldNotCleanUpInDegradedMode() {
// Given:
when(commandStore.corruptionDetected()).thenReturn(true);
givenQueuedCommands(queuedCommand1, queuedCommand2, queuedCommand3);
when(ksqlEngine.getPersistentQueries()).thenReturn(ImmutableList.of(queryMetadata1, queryMetadata2, queryMetadat... |
public List<AclInfo> listAcl(String addr, String subjectFilter, String resourceFilter, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
ListAclsRequestHeader requestHeader = new ListAclsRequestHeader(subjectFilter, re... | @Test
public void assertListAcl() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
setResponseBody(Collections.singletonList(createAclInfo()));
List<AclInfo> actual = mqClientAPI.listAcl(defaultBrokerAddr, "", "", defaultTimeout);
assertNotNull(ac... |
@Override
protected Byte parseSerializeType(String serialization) {
Byte serializeType;
if (SERIALIZE_HESSIAN.equals(serialization)
|| SERIALIZE_HESSIAN2.equals(serialization)) {
serializeType = RemotingConstants.SERIALIZE_CODE_HESSIAN;
} else if (SERIALIZE_PROTOBUF.e... | @Test(expected = SofaRpcRuntimeException.class)
public void testParseSerializeTypeException() {
ConsumerConfig consumerConfig = new ConsumerConfig().setProtocol("bolt");
ConsumerBootstrap bootstrap = Bootstraps.from(consumerConfig);
BoltClientProxyInvoker invoker = new BoltClientProxyInvoker... |
public CompletableFuture<Optional<Account>> getByPhoneNumberIdentifierAsync(final UUID pni) {
return checkRedisThenAccountsAsync(
getByNumberTimer,
() -> redisGetBySecondaryKeyAsync(getAccountMapKey(pni.toString()), redisPniGetTimer),
() -> accounts.getByPhoneNumberIdentifierAsync(pni)
)... | @Test
void testGetAccountByPniBrokenCacheAsync() {
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(asyncCommands.get(... |
@Override
public int getTotalNumberOfRecords(Configuration conf) throws HiveJdbcDatabaseAccessException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
initializeDatabaseConnection(conf);
String tableName = getQualifiedTableName(conf);
// Always use... | @Test(expected = HiveJdbcDatabaseAccessException.class)
public void testGetTotalNumberOfRecords_invalidQuery() throws HiveJdbcDatabaseAccessException {
Configuration conf = buildConfiguration();
conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select * from strategyx where strategy_id = '5'");
Databas... |
@Override
public String getDescription() {
return "Webhooks";
} | @Test
public void has_description() {
assertThat(underTest.getDescription()).isNotEmpty();
} |
public void shutdown() {
// Now that segments can't report metric, destroy metric for this table
_scheduledExecutor.shutdown(); // ScheduledExecutor is installed in constructor so must always be cancelled
if (!_isServerReadyToServeQueries.get()) {
// Do not update the tracker state during server start... | @Test
public void testShutdown() {
final long maxTestDelay = 100;
IngestionDelayTracker ingestionDelayTracker = createTracker();
// Use fixed clock so samples don't age
Instant now = Instant.now();
ZoneId zoneId = ZoneId.systemDefault();
Clock clock = Clock.fixed(now, zoneId);
ingestionDe... |
@Override
public int getOrder() {
return PluginEnum.GLOBAL.getCode();
} | @Test
public void testGetOrder() {
assertEquals(-1, globalPlugin.getOrder());
} |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void locateInNSunexistent() {
final Import i = makeImport("nsA", null, "boh");
final List<QName> available = Arrays.asList(new QName("nsA", "m1"),
new QName("nsA", "m2"),
new QName("nsB", "m... |
@Override
public WhitelistedSite saveNew(WhitelistedSite whitelistedSite) {
if (whitelistedSite.getId() != null) {
throw new IllegalArgumentException("A new whitelisted site cannot be created with an id value already set: " + whitelistedSite.getId());
}
return repository.save(whitelistedSite);
} | @Test
public void saveNew_success() {
WhitelistedSite site = Mockito.mock(WhitelistedSite.class);
Mockito.when(site.getId()).thenReturn(null);
service.saveNew(site);
Mockito.verify(repository).save(site);
} |
@Override
public void build(DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, TaskExtension taskExtension, ArtifactExtension artifactExtension, PluginRequestProcessorRegistry pluginRequestProcessorRegistry, Charset consoleLogCharset) {
downloadMetadataFile(publisher);
... | @Test
public void shouldUpdateEnvironmentVariableContextAfterFetchingArtifact() {
final FetchPluggableArtifactBuilder builder = new FetchPluggableArtifactBuilder(new RunIfConfigs(), new NullBuilder(), "", jobIdentifier, artifactStore, fetchPluggableArtifactTask.getConfiguration(), fetchPluggableArtifactTask... |
public static Map<String, ShardingSphereSchema> build(final String databaseName, final DatabaseType databaseType, final ConfigurationProperties props) {
SystemDatabase systemDatabase = new SystemDatabase(databaseType);
Map<String, ShardingSphereSchema> result = new LinkedHashMap<>(systemDatabase.getSyst... | @Test
void assertBuildForMySQL() {
DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL");
ConfigurationProperties configProps = new ConfigurationProperties(new Properties());
Map<String, ShardingSphereSchema> actualInformationSchema = SystemSchemaBuilder.build("i... |
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header)
{
final byte flags = header.flags();
if ((flags & UNFRAGMENTED) == UNFRAGMENTED)
{
delegate.onFragment(buffer, offset, length, header);
}
else
{
... | @Test
void shouldDoNotingIfEndArrivesWithoutBegin()
{
when(header.flags()).thenReturn(FrameDescriptor.END_FRAG_FLAG);
final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]);
final int offset = 0;
final int length = srcBuffer.capacity() / 2;
assembler.onFragment(... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testSettingFlexRS() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setFlexRSGoal(DataflowPipelineOptions.FlexResourceSchedulingGoal.COST_OPTIMIZED);
Pipeline p = Pipeline.create(options);
p.run();
ArgumentCaptor<Job> jobCaptor = ArgumentC... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return this.resourcesByName.equals(((ResourceVector) o).resourcesByName);
} | @Test
public void testEquals() {
ResourceVector resourceVector = ResourceVector.of(13);
ResourceVector resourceVectorOther = ResourceVector.of(14);
Resource resource = Resource.newInstance(13, 13);
Assert.assertNotEquals(null, resourceVector);
Assert.assertNotEquals(resourceVectorOther, resourceV... |
public void addSpeaker(BgpSpeakerConfig speaker) {
// Create the new speaker node and set the parameters
ObjectNode speakerNode = JsonNodeFactory.instance.objectNode();
speakerNode.put(NAME, speaker.name().get());
speakerNode.put(VLAN, speaker.vlan().toString());
speakerNode.put(... | @Test
public void testAddSpeaker() throws Exception {
int initialSize = bgpConfig.bgpSpeakers().size();
BgpConfig.BgpSpeakerConfig newSpeaker = createNewSpeaker();
bgpConfig.addSpeaker(newSpeaker);
assertEquals(initialSize + 1, bgpConfig.bgpSpeakers().size());
speakers.add(ne... |
@Nullable public String getValue(@Nullable TraceContext context) {
if (context == null) return null;
return this.context.getValue(this, context);
} | @Test void getValue_extracted_doesntExist() {
assertThat(AMZN_TRACE_ID.getValue(requestIdExtraction))
.isNull();
assertThat(AMZN_TRACE_ID.getValue(emptyExtraction))
.isNull();
assertThat(AMZN_TRACE_ID.getValue(TraceContextOrSamplingFlags.EMPTY))
.isNull();
} |
@Udf
public boolean check(@UdfParameter(description = "The input JSON string") final String input) {
if (input == null) {
return false;
}
try {
return !UdfJsonMapper.parseJson(input).isMissingNode();
} catch (KsqlFunctionException e) {
return false;
}
} | @Test
public void shouldInterpretNullString() {
assertTrue(udf.check("null"));
} |
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to spli... | @Test
public void shouldSplitAndAddEmptySpacesIfDelimiterBytesIsFoundAtTheBeginningOrEnd() {
final ByteBuffer aBytes = ByteBuffer.wrap(new byte[]{'A'});
final ByteBuffer bBytes = ByteBuffer.wrap(new byte[]{'B'});
final ByteBuffer dollarBytes = ByteBuffer.wrap(new byte[]{'$'});
assertThat(
spl... |
public void insertBulk(final List<MemberCoupon> memberCoupons) {
String sql = "INSERT IGNORE INTO member_coupon (member_id, coupon_id, created_at, updated_at)" +
" VALUES (:memberId, :couponId, :createdAt, :updatedAt)";
namedParameterJdbcTemplate.batchUpdate(sql, chargeStationSqlParamet... | @Test
void 멤버_쿠폰을_벌크_저장한다() {
// given
MemberCoupon memberCoupon = 멤버_쿠폰_생성();
// when & then
Assertions.assertDoesNotThrow(() -> memberCouponJdbcRepository.insertBulk(List.of(memberCoupon, memberCoupon, memberCoupon)));
} |
@SuppressWarnings("checkstyle:npathcomplexity")
public void verify() {
List<String> enabledDiscoveries = new ArrayList<>();
int countEnabled = 0;
if (getTcpIpConfig().isEnabled()) {
countEnabled++;
enabledDiscoveries.add("TCP/IP");
}
if (getMulticastCo... | @Test
public void testEqualsAndHashCode() {
assumeDifferentHashCodes();
EqualsVerifier.forClass(JoinConfig.class)
.usingGetClass()
.suppress(Warning.NONFINAL_FIELDS)
.verify();
} |
@Override
public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) {
log.trace("compiling {} {}", intent, installable);
ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint();
ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint();
... | @Test
public void testKeyRGBandwidthConstrainedIntentAllocation() {
final double bpsTotal = 1000.0;
String[] hops = {S1, S2, S3};
final ResourceService resourceService =
MockResourceService.makeCustomBandwidthResourceService(bpsTotal);
final List<Constraint> constra... |
@Override
public String toString(final RouteUnit routeUnit) {
Map<String, String> logicAndActualTables = getLogicAndActualTables(routeUnit);
StringBuilder result = new StringBuilder();
int index = 0;
for (Projection each : projections) {
if (index > 0) {
r... | @Test
void assertToStringWithSubqueryProjection() {
Collection<Projection> projections = Arrays.asList(new ColumnProjection(new IdentifierValue("temp", QuoteCharacter.BACK_QUOTE),
new IdentifierValue("id", QuoteCharacter.BACK_QUOTE), new IdentifierValue("id", QuoteCharacter.BACK_QUOTE), mock... |
public static Schema project(Schema schema, Set<Integer> fieldIds) {
Preconditions.checkNotNull(schema, "Schema cannot be null");
Types.StructType result = project(schema.asStruct(), fieldIds);
if (schema.asStruct().equals(result)) {
return schema;
} else if (result != null) {
if (schema.ge... | @Test
public void testProjectNaturallyEmpty() {
Schema schema =
new Schema(
Lists.newArrayList(
required(
12,
"someStruct",
Types.StructType.of(
required(
15,
... |
@Override
public String toString() {
if (command != null) {
return "SmppMessage: " + command;
} else {
return "SmppMessage: " + getBody();
}
} | @Test
public void toStringShouldReturnTheShortMessageIfTheCommandIsNotNull() {
DeliverSm command = new DeliverSm();
command.setShortMessage("Hello SMPP world!".getBytes());
message = new SmppMessage(camelContext, command, new SmppConfiguration());
assertEquals("SmppMessage: PDUHeade... |
public static int realCompare(float a, float b)
{
// these three ifs can only be true if neither value is NaN
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
// this check ensure floatCompare(+0, -0) will return 0
// if we just did f... | @Test
public void testRealCompare()
{
assertEquals(realCompare(0, Float.parseFloat("-0")), 0);
assertEquals(realCompare(Float.NaN, Float.NaN), 0);
// 0x7fc01234 is a different representation of NaN
assertEquals(realCompare(Float.NaN, intBitsToFloat(0x7fc01234)), 0);
} |
public T setEnableSource(boolean enableSource) {
attributes.put("_source", ImmutableSortedMap.of(ENABLED, enableSource));
return castThis();
} | @Test
@UseDataProvider("indexWithAndWithoutRelations")
public void index_with_source(Index index) {
NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration);
newIndex.setEnableSource(true);
assertThat(newIndex).isNotNull();
assertThat(getAttributeAsMap(ne... |
protected boolean isValidRequestor(HttpServletRequest request, Configuration conf)
throws IOException {
UserGroupInformation ugi = getUGI(request, conf);
if (LOG.isDebugEnabled()) {
LOG.debug("Validating request made by " + ugi.getUserName() +
" / " + ugi.getShortUserName() + ". This user... | @Test
public void testRequestNameNode() throws IOException, ServletException {
// Test: Make a request from a namenode
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter(UserParam.NAME)).thenReturn("nn/localhost@REALM.TLD");
boolean isValid = SERVLET.isValidRequesto... |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationInvalidRecurrenceExpression() {
// first check recurrence expression
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3, "123abc");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(r... |
@Udf
public <T> Map<String, T> union(
@UdfParameter(description = "first map to union") final Map<String, T> map1,
@UdfParameter(description = "second map to union") final Map<String, T> map2) {
final List<Map<String, T>> nonNullInputs =
Stream.of(map1, map2)
.filter(Objects::nonNull)... | @Test
public void shouldHandleComplexValueTypes() {
final Map<String, List<Double>> input1 = Maps.newHashMap();
input1.put("apple", Arrays.asList(Double.valueOf(12.34), Double.valueOf(56.78)));
input1.put("banana", Arrays.asList(Double.valueOf(43.21), Double.valueOf(87.65)));
final Map<String, List<D... |
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
BlockingQueue<Runnable> workQueue = executor.getQueue();
Runnable firstWork = workQueue.poll();
boolean newTaskAdd = workQueue.offer(r);
... | @Test
public void testRejectedExecutionWhenExecutorIsShutDown() {
when(threadPoolExecutor.isShutdown()).thenReturn(true);
runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor);
verify(threadPoolExecutor, never()).execute(runnable);
verify(runnable, never()).run();
... |
@Override
public Cursor<Tuple> zScan(byte[] key, ScanOptions options) {
return new KeyBoundCursor<Tuple>(key, 0, options) {
private RedisClient client;
@Override
protected ScanIteration<Tuple> doScan(byte[] key, long cursorId, ScanOptions options) {
if (... | @Test
public void testZScan() {
connection.zAdd("key".getBytes(), 1, "value1".getBytes());
connection.zAdd("key".getBytes(), 2, "value2".getBytes());
Cursor<RedisZSetCommands.Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build());
assertThat(t.hasNext()).is... |
@Deprecated
public RemotingCommand getConsumeStatus(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetConsumerStatusRequestHeader requestHeader =
(GetConsume... | @Test
public void testGetConsumeStatus() throws Exception {
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
RemotingCommand request = mock(RemotingCommand.class);
when(request.getCode()).thenReturn(RequestCode.GET_CONSUMER_STATUS_FROM_CLIENT);
GetConsumerStatusRequestH... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowSt... | @Test
@SuppressWarnings("unchecked")
public void shouldCloseIterator() {
// When:
final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> partitionResult = new StateQueryResult<>();
final QueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> result = QueryResult.forResult(fe... |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty()) {
return new GroupAssignment(Collections.emptyMap());
} else if (groupSpec.subscr... | @Test
public void testOneMemberNoTopic() {
SubscribedTopicDescriberImpl subscribedTopicMetadata = new SubscribedTopicDescriberImpl(
Collections.singletonMap(
topic1Uuid,
new TopicMetadata(
topic1Uuid,
topic1Name,
... |
public static byte[] getValue(byte[] raw) {
try (final Asn1InputStream is = new Asn1InputStream(raw)) {
is.readTag();
return is.read(is.readLength());
}
} | @Test
public void getValueShouldSkipTagAndLength() {
assertArrayEquals(new byte[] { 0x31 }, Asn1Utils.getValue(new byte[] { 0x10, 1, 0x31}));
} |
@VisibleForTesting
void startKsql(final KsqlConfig ksqlConfigWithPort) {
cleanupOldState();
initialize(ksqlConfigWithPort);
} | @Test
public void shouldRecordStartLatency() {
// When:
app.startKsql(ksqlConfig);
// Then:
long duration = Duration.between(start, Instant.now()).toMillis();
final Metric metric = metricCollectors.getMetrics().metric(
metricCollectors.getMetrics().metricName("startup-time-ms", "ksql-rest... |
public static void smooth(PointList pointList, double maxElevationDelta) {
internSmooth(pointList, 0, pointList.size() - 1, maxElevationDelta);
} | @Test
public void smoothRamerNoMaximumFound() {
PointList pl2 = new PointList(3, true);
pl2.add(60.03307, 20.82262, 5.35);
pl2.add(60.03309, 20.82269, 5.42);
pl2.add(60.03307, 20.82262, 5.35);
EdgeElevationSmoothingRamer.smooth(pl2, 10);
assertEquals(3, pl2.size());
... |
@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 synchronizationCallsExceptionHandlerOnFailure() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
consumer.setExceptionHandler(exceptionHandler);
consumer.doStart();
verify(client).start();
verify(c... |
public String toBaseMessageIdString(Object messageId) {
if (messageId == null) {
return null;
} else if (messageId instanceof String) {
String stringId = (String) messageId;
// If the given string has a type encoding prefix,
// we need to escape it as an ... | @Test
public void testToBaseMessageIdStringWithStringBeginningWithEncodingPrefixForBinary() {
String binaryStringMessageId = AMQPMessageIdHelper.AMQP_BINARY_PREFIX + "0123456789ABCDEF";
String expected = AMQPMessageIdHelper.AMQP_STRING_PREFIX + binaryStringMessageId;
String baseMessageIdStr... |
public void isTrue() {
if (actual == null) {
isEqualTo(true); // fails
} else if (!actual) {
failWithoutActual(simpleFact("expected to be true"));
}
} | @Test
public void nullIsTrueFailing() {
expectFailureWhenTestingThat(null).isTrue();
assertFailureKeys("expected", "but was");
assertFailureValue("expected", "true");
assertFailureValue("but was", "null");
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testPrivateFinishBundle() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("finishBundle()");
thrown.expectMessage("Must be public");
thrown.expectMessage(getClass().getName() + "$");
DoFnSignatures.getSignature(
new DoFn<String, Stri... |
public List<ScimGroupDto> findAll(DbSession dbSession) {
return mapper(dbSession).findAll();
} | @Test
void findAll_ifNoData_returnsEmptyList() {
assertThat(scimGroupDao.findAll(db.getSession())).isEmpty();
} |
@Override
protected Map<String, Object> getPredictedValues(PMML4Result pmml4Result, DMNResult dmnr) {
Map<String, Object> toReturn = new HashMap<>();
String resultName = pmml4Result.getResultObjectName();
Object value = pmml4Result.getResultVariables().get(resultName);
toReturn.put(r... | @Test
void getPredictedValues() {
List<Object> values = getValues();
values.forEach(value -> {
PMML4Result result = getPMML4Result(value);
Map<String, Object> retrieved = dmnKiePMMLTrustyInvocationEvaluator.getPredictedValues(result, null);
assertThat(retrieved).c... |
@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... |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldValidateSuccessfullyWithEmptyInternalTopics() {
setupTopicInMockAdminClient(topic1, repartitionTopicConfig());
final ValidationResult validationResult = internalTopicManager.validate(Collections.emptyMap());
assertThat(validationResult.missingTopics(), empty());
... |
protected static Number findMultiplicationPattern(BigDecimal[] numbers) {
if ( numbers == null || numbers.length < MIN_NUMBER_OF_RESTRICTIONS ) {
return null;
}
try {
BigDecimal gap;
Number missingNumber = null;
BigDecimal a = numbers[0];
... | @Test
void testFindMultiplicationPattern() {
// Multiplication
// *2 missing number 4
assertThat(FindMissingNumber.findMultiplicationPattern(
new BigDecimal[]{BigDecimal.valueOf(2),
BigDecimal.valueOf(8), BigDecimal.valueOf(16),
... |
@GetMapping("/export")
@RequiresPermissions("system:manager:exportConfig")
public ResponseEntity<byte[]> exportConfigs(final HttpServletResponse response) {
ShenyuAdminResult result = configsService.configsExport();
if (!Objects.equals(CommonErrorCode.SUCCESSFUL, result.getCode())) {
... | @Test
public void testExportConfigs() throws Exception {
when(this.configsService.configsExport()).thenReturn(
ShenyuAdminResult.success(ShenyuResultMessage.SUCCESS));
// Run the test
final MockHttpServletResponse response = mockMvc.perform(get("/configs/export")
... |
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAME... | @Test
void testInitNamespaceFromDefaultNamespaceWithCloudParsing() {
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true");
String actual = InitUtils.initNamespaceForNaming(properties... |
public Set<MessageQueue> lockBatchMQ(
final String addr,
final LockBatchRequestBody requestBody,
final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.LOCK_BATCH_MQ, new Loc... | @Test
public void assertLockBatchMQ() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
LockBatchRequestBody responseBody = new LockBatchRequestBody();
setResponseBody(responseBody);
Set<MessageQueue> actual = mqClientAPI.lockBatchMQ(defaultBrokerA... |
@Override
public int size() {
return partitionMaps.values().stream().mapToInt(Map::size).sum();
} | @Test
public void testSize() {
PartitionMap<String> map = PartitionMap.create(SPECS);
map.put(UNPARTITIONED_SPEC.specId(), null, "v1");
map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v2");
map.put(BY_DATA_SPEC.specId(), Row.of("bbb"), "v3");
map.put(BY_DATA_CATEGORY_BUCKET_SPEC.specId(), Row.of("c... |
public static String indexToColName(int index) {
if (index < 0) {
return null;
}
final StringBuilder colName = StrUtil.builder();
do {
if (colName.length() > 0) {
index--;
}
int remainder = index % 26;
colName.append((char) (remainder + 'A'));
index = (index - remainder) / 26;
} while (i... | @Test
public void indexToColNameTest() {
assertEquals("A", ExcelUtil.indexToColName(0));
assertEquals("B", ExcelUtil.indexToColName(1));
assertEquals("C", ExcelUtil.indexToColName(2));
assertEquals("AA", ExcelUtil.indexToColName(26));
assertEquals("AB", ExcelUtil.indexToColName(27));
assertEquals("AC", Ex... |
static QueryId buildId(
final Statement statement,
final EngineContext engineContext,
final QueryIdGenerator idGenerator,
final OutputNode outputNode,
final boolean createOrReplaceEnabled,
final Optional<String> withQueryId) {
if (withQueryId.isPresent()) {
final String que... | @Test
public void shouldComputeQueryIdCorrectlyForNewSourceTable() {
// Given:
final CreateTable createTableStmt = mock(CreateTable.class);
when(createTableStmt.getName()).thenReturn(SourceName.of("FOO"));
when(createTableStmt.isSource()).thenReturn(true);
when(idGenerator.getNext()).thenReturn("1... |
@Override
public ObjectNode encode(KubevirtFloatingIp fip, CodecContext context) {
checkNotNull(fip, "Kubevirt floating IP cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(ID, fip.id())
.put(ROUTER_NAME, fip.routerName())
... | @Test
public void testKubevirtFloatingIpEncode() {
KubevirtFloatingIp floatingIp = DefaultKubevirtFloatingIp.builder()
.id("fip-id")
.routerName("router-1")
.networkName("flat-1")
.floatingIp(IpAddress.valueOf("10.10.10.10"))
.p... |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void givenRow_whenLoad_thenReturnSingleColumn() {
ObjectSpec spec = objectProvider.createObject(mapName);
objectProvider.insertItems(spec, 1);
mapLoaderSingleColumn = createMapLoaderSingleColumn();
String name = mapLoaderSingleColumn.load(0);
assertThat(name).i... |
public Optional<Group> takeGroup(Set<Integer> rejectedGroups) {
synchronized (this) {
Optional<GroupStatus> best = scheduler.takeNextGroup(rejectedGroups);
if (best.isPresent()) {
GroupStatus gs = best.get();
gs.allocate();
Group ret = gs.... | @Test
void requireThatLoadBalancerServesMultiGroupSetups() {
Node n1 = new Node("test", 0, "test-node1", 0);
Node n2 = new Node("test", 1, "test-node2", 1);
LoadBalancer lb = new LoadBalancer(List.of(new Group(0, List.of(n1)), new Group(1,List.of(n2))), LoadBalancer.Policy.ROUNDROBIN);
... |
public static Key of(String key, ApplicationId appId) {
return new StringKey(key, appId);
} | @Test
public void stringKeyCompare() {
Key stringKey1 = Key.of(KEY_1, NetTestTools.APP_ID);
Key copyOfStringKey1 = Key.of(KEY_1, NetTestTools.APP_ID);
Key stringKey2 = Key.of(KEY_2, NetTestTools.APP_ID);
Key copyOfStringKey2 = Key.of(KEY_2, NetTestTools.APP_ID);
Key stringKey... |
@Override
protected int rsv(WebSocketFrame msg) {
return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame?
msg.rsv() | WebSocketExtension.RSV1 : msg.rsv();
} | @Test
public void testFragmentedFrame() {
EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false,
NEVER_SKIP));
EmbeddedChannel decoderChannel = new EmbeddedChannel(
... |
@Override
public Note get(String noteId, String notePath, AuthenticationInfo subject) throws IOException {
BlobId blobId = makeBlobId(noteId, notePath);
byte[] contents;
try {
contents = storage.readAllBytes(blobId);
} catch (StorageException se) {
throw new IOException("Could not read " +... | @Test
void testGet_nonexistent() throws Exception {
zConf.setProperty(ConfVars.ZEPPELIN_NOTEBOOK_GCS_STORAGE_DIR.getVarName(), DEFAULT_URL);
this.notebookRepo = new GCSNotebookRepo(zConf, noteParser, storage);
assertThrows(IOException.class, () -> {
notebookRepo.get("id", "", AUTH_INFO);
});
} |
@Override
public boolean isReachable(DeviceId deviceId) {
SnmpDevice snmpDevice = controller.getDevice(deviceId);
if (snmpDevice == null) {
log.warn("BAD REQUEST: the requested device id: "
+ deviceId.toString()
+ " is not associ... | @Test
public void eventNotRelevant() {
assertFalse("Event should not be relevant", provider.cfgLister.isRelevant(deviceAddedIrrelevantEvent));
assertFalse("Device should not be reachable", provider.isReachable(wrongDeviceId));
} |
@RequestMapping("/error")
public ModelAndView handleError(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
ModelAndView modelAndView = new ModelAndView();
if (status != null) {
int statusCode = Integer.parseInt(status.toStr... | @Test
void handleError_ReturnsModelAndViewWithNullStatus() {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).thenReturn(null);
ModelAndView modelAndView = new FrontendRedirector().handleError(request);
ass... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComDaemonPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_DAEMON, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
@Override
public List<AwsEndpoint> getClusterEndpoints() {
List<AwsEndpoint> result = new ArrayList<>();
EurekaHttpClient client = null;
try {
client = clientFactory.newClient();
EurekaHttpResponse<Applications> response = client.getVip(vipAddress);
if (v... | @Test
public void testErrorResponseFromRemoteServer() {
when(httpClient.getVip(vipAddress)).thenReturn(EurekaHttpResponse.anEurekaHttpResponse(500, (Applications)null).build());
List<AwsEndpoint> endpoints = resolver.getClusterEndpoints();
assertThat(endpoints.isEmpty(), is(true));
... |
public ServiceInfo processServiceInfo(String json) {
ServiceInfo serviceInfo = JacksonUtils.toObj(json, ServiceInfo.class);
serviceInfo.setJsonFromServer(json);
return processServiceInfo(serviceInfo);
} | @Test
void testProcessServiceInfo2() {
String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}";
ServiceInfo actual = holder.processServiceInfo(json);
ServiceInfo expect = new ServiceInfo("a@@b@@c");
expect.setJsonFromServer(json);
assertEquals(expect.... |
@Override
public boolean add(E element) {
return add(element, element.hashCode());
} | @Test
public void testIsEmpty() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
assertTrue("Set should be empty", set.isEmpty());
set.add(1);
assertFalse("Set should not be empty", set.isEmpty());
} |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void mdcWithDefaultValue() {
String pattern = "%msg %mdc{foo} %mdc{bar:-[null]}";
pl.setPattern(OptionHelper.substVars(pattern, lc));
pl.start();
MDC.put("foo", "foo");
try {
String val = pl.doLayout(getEventObject());
assertEquals("Some message foo [null]", val);
} fi... |
@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
Host current = null;
String line;
wh... | @Test(expected = AccessDeniedException.class)
public void testParseNotFound() throws Exception {
new TotalCommanderBookmarkCollection().parse(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f"));
} |
public static <K, V> AsMultimap<K, V> asMultimap() {
return new AsMultimap<>(false);
} | @Test
@Category(ValidatesRunner.class)
public void testMultimapAsEntrySetSideInput() {
final PCollectionView<Map<String, Iterable<Integer>>> view =
pipeline
.apply(
"CreateSideInput",
Create.of(KV.of("a", 1), KV.of("a", 1), KV.of("a", 2), KV.of("b", 3)))
... |
public String formatSourceAndFixImports(String input) throws FormatterException {
input = ImportOrderer.reorderImports(input, options.style());
input = RemoveUnusedImports.removeUnusedImports(input);
String formatted = formatSource(input);
formatted = StringWrapper.wrap(formatted, this);
return form... | @Test
public void importsFixedIfRequested() throws FormatterException {
String input =
"package com.google.example;\n"
+ UNORDERED_IMPORTS
+ "\npublic class ExampleTest {\n"
+ " @Nullable List<?> xs;\n"
+ "}\n";
String output = new Formatter().formatSou... |
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
if (traceContext.tracer() != null) {
request = traceContext.tracer().inject(request);
}
ClientHttpResponse response = execution.execute(request, body);
... | @Test
public void testInterceptor() throws IOException {
ClientHttpRequestExecution execution = Mockito.mock(ClientHttpRequestExecution.class);
HttpRequest request = Mockito.mock(HttpRequest.class);
byte[] body = new byte[]{};
ApolloAuditTracer tracer = Mockito.mock(ApolloAuditTracer.class);
HttpR... |
@Nonnull
public static List<JetSqlRow> evaluate(
@Nullable Expression<Boolean> predicate,
@Nullable List<Expression<?>> projection,
@Nonnull Stream<JetSqlRow> rows,
@Nonnull ExpressionEvalContext context
) {
return rows
.map(row -> evaluate... | @Test
public void test_evaluateWithPredicate() {
List<Object[]> rows = asList(new Object[]{0, "a"}, new Object[]{1, "b"}, new Object[]{2, "c"});
Expression<Boolean> predicate = new FunctionalPredicateExpression(row -> {
int value = row.get(0);
return value != 1;
});
... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldPropagateErrorOnFailureToPlanQuery() {
// Given:
givenStatement("CREATE STREAM sink WITH(value_format='AVRO') AS SELECT * FROM SOURCE;");
doThrow(new KsqlException("fail!")).when(executionSandbox).plan(any(), eq(statement));
// When:
final Exception e = assertThrows(
... |
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void stdin() {
assertThat(CommandLineOptionsParser.parse(Arrays.asList("-")).stdin()).isTrue();
} |
public static JsonNode buildTypeSchemaFromJson(String jsonText) throws IOException {
return buildTypeSchemaFromJson(JsonSchemaValidator.getJsonNode(jsonText));
} | @Test
void testBuildTypeSchemaFromJson() {
JsonNode jsonNode = null;
ObjectMapper mapper = new ObjectMapper();
String jsonText = "{\"foo\": \"bar\", \"flag\": true, " + "\"list\": [1, 2], " + "\"obj\": {\"fizz\": \"bar\"}, "
+ "\"objList\": [{\"number\": 1}, {\"number\": 2}]}";
... |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getSqlRecordIteratorBatchLeftExcludedRightIncludedAscending() {
var expectedKeyOrder = List.of(1, 4, 7);
var result = store.getSqlRecordIteratorBatch(0, false, 1, true, false);
assertResult(expectedKeyOrder, result);
} |
public boolean createJob(BusinessJobConfig jobConfig) {
if (null == jobConfig) {
log.info("参数jobConfig 不能为空!");
return false;
} else if (!StringUtils.isBlank(jobConfig.getServiceName()) && !StringUtils.isBlank(jobConfig.getMethodName()) && !StringUtils.isBlank(jobConfig.getCronEx... | @Test
public void should_create_job() throws Exception {
BusinessJobConfig jobConfig = new BusinessJobConfig();
jobConfig.setServiceName("testApp");
jobConfig.setMethodName("run");
jobConfig.setId("testApp");
jobConfig.setCronExpression("0/5 * * * * ?");
jobConfig.set... |
@Override
public OAuth2AccessTokenDO refreshAccessToken(String refreshToken, String clientId) {
// 查询访问令牌
OAuth2RefreshTokenDO refreshTokenDO = oauth2RefreshTokenMapper.selectByRefreshToken(refreshToken);
if (refreshTokenDO == null) {
throw exception0(GlobalErrorCodeConstants.BAD... | @Test
public void testRefreshAccessToken_null() {
// 准备参数
String refreshToken = randomString();
String clientId = randomString();
// mock 方法
// 调用,并断言
assertServiceException(() -> oauth2TokenService.refreshAccessToken(refreshToken, clientId),
new Erro... |
public static double shuffleCompressionRatio(
SparkSession spark, FileFormat outputFileFormat, String outputCodec) {
if (outputFileFormat == FileFormat.ORC || outputFileFormat == FileFormat.PARQUET) {
return columnarCompression(shuffleCodec(spark), outputCodec);
} else if (outputFileFormat == FileFo... | @Test
public void testNullFileCodec() {
configureShuffle("lz4", true);
double ratio1 = shuffleCompressionRatio(PARQUET, null);
assertThat(ratio1).isEqualTo(2.0);
double ratio2 = shuffleCompressionRatio(ORC, null);
assertThat(ratio2).isEqualTo(2.0);
double ratio3 = shuffleCompressionRatio(AV... |
protected void validateMessageType(Type expected) {
if (expected != messageType) {
throw new IllegalArgumentException("Message type is expected to be "
+ expected + " but got " + messageType);
}
} | @Test(expected = IllegalArgumentException.class)
public void testValidateMessageException() {
RpcMessage msg = getRpcMessage(0, RpcMessage.Type.RPC_CALL);
msg.validateMessageType(RpcMessage.Type.RPC_REPLY);
} |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final long shortSendsBefore = shortSen... | @Test
void shouldNotBeAbleToSendAfterUsingUpYourWindow()
{
final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(PAYLOAD.length));
buffer.putBytes(0, PAYLOAD);
appendUnfragmentedMessage(rawLog, 0, INITIAL_TERM_ID, 0, headerWriter, buffer, 0, PAYLOAD.length);
fin... |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final S3Object object = this.getDetails(file, status);
final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttp... | @Test
public void testWritePublicReadCannedAcl() throws Exception {
final Path container = new Path("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 <T> List<T> list(boolean isLinked) {
return ListUtil.list(isLinked);
} | @Test
public void listTest2() {
final List<String> list1 = CollUtil.list(false, "a", "b", "c");
final List<String> list2 = CollUtil.list(true, "a", "b", "c");
assertEquals("[a, b, c]", list1.toString());
assertEquals("[a, b, c]", list2.toString());
} |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTPClient.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getRep... | @Test
public void testWriteContentRange() throws Exception {
final FTPWriteFeature feature = new FTPWriteFeature(session);
final Path test = new Path(new FTPWorkdirService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final byte[] content = Ran... |
@VisibleForTesting
static Optional<DoubleRange> calculateRange(Type type, List<HiveColumnStatistics> columnStatistics)
{
if (!isRangeSupported(type)) {
return Optional.empty();
}
return columnStatistics.stream()
.map(statistics -> createRange(type, statistics)... | @Test
public void testCalculateRange()
{
assertEquals(calculateRange(VARCHAR, ImmutableList.of()), Optional.empty());
assertEquals(calculateRange(VARCHAR, ImmutableList.of(integerRange(OptionalLong.empty(), OptionalLong.empty()))), Optional.empty());
assertEquals(calculateRange(VARCHAR, ... |
@Override
public boolean rejoinNeededOrPending() {
if (!subscriptions.hasAutoAssignedPartitions())
return false;
// we need to rejoin if we performed the assignment and metadata has changed;
// also for those owned-but-no-longer-existed partitions we should drop them as lost
... | @Test
public void testPatternJoinGroupFollower() {
final Set<String> subscription = Utils.mkSet(topic1, topic2);
final List<TopicPartition> owned = Collections.emptyList();
final List<TopicPartition> assigned = Arrays.asList(t1p, t2p);
subscriptions.subscribe(Pattern.compile("test.*... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testExceptionInStartAbortsAllOperations() 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 start")).when(o2).start();
ExecutionStateTrack... |
public DecoderResult decode(AztecDetectorResult detectorResult) throws FormatException {
ddata = detectorResult;
BitMatrix matrix = detectorResult.getBits();
boolean[] rawbits = extractBits(matrix);
CorrectedBitsResult correctedBits = correctBits(rawbits);
byte[] rawBytes = convertBoolArrayToByteArr... | @Test
public void testAztecResult() throws FormatException {
BitMatrix matrix = BitMatrix.parse(
"X X X X X X X X X X X X X X \n" +
"X X X X X X X X X X X X X X X \n" +
" X X X X X X X X X X X X \n" +
" X X X X X X ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.