focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String getMetricName(String name) {
if (name.startsWith(CLUSTER)) {
return name;
}
switch (CommonUtils.PROCESS_TYPE.get()) {
case CLIENT:
return getClientMetricName(name);
case MASTER:
return getMasterMetricName(name);
case PROXY:
return getProxy... | @Test
public void getMetricNameTest() {
assertEquals("Cluster.counter", MetricsSystem.getMetricName("Cluster.counter"));
assertEquals("Master.timer", MetricsSystem.getMetricName("Master.timer"));
String workerGaugeName = "Worker.gauge";
assertEquals(workerGaugeName, MetricsSystem.getMetricName(workerG... |
@Override
public TransformResultMetadata getResultMetadata() {
return BOOLEAN_SV_NO_DICTIONARY_METADATA;
} | @Test
public void testLogicalOperatorNullLiteral() {
ExpressionContext intEqualsExpr =
RequestContextUtils.getExpression(String.format("EQUALS(%s, null)", INT_SV_COLUMN));
ExpressionContext longEqualsExpr =
RequestContextUtils.getExpression(String.format("EQUALS(%s, null)", LONG_SV_COLUMN));
... |
public static Optional<UserAgent> getUserAgent() {
return Optional.ofNullable(USER_AGENT_CONTEXT_KEY.get());
} | @Test
void getUserAgent() throws UnrecognizedUserAgentException {
when(clientConnectionManager.getUserAgent(any()))
.thenReturn(Optional.empty());
assertFalse(getRequestAttributes().hasUserAgent());
final UserAgent userAgent = UserAgentUtil.parseUserAgentString("Signal-Desktop/1.2.3 Linux");
... |
public static Future<Void> maybeUpdateMetadataVersion(
Reconciliation reconciliation,
Vertx vertx,
TlsPemIdentity coTlsPemIdentity,
AdminClientProvider adminClientProvider,
String desiredMetadataVersion,
KafkaStatus status
) {
String bo... | @Test
public void testNoMetadataVersionChange(VertxTestContext context) {
// Mock the Admin client
Admin mockAdminClient = mock(Admin.class);
// Mock describing the current metadata version
mockDescribeVersion(mockAdminClient);
// Mock the Admin client provider
Ad... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Node node = (Node) o;
return Objects.equals(getControl(), node.getControl()) && Objects.equals(getTransac... | @Test
public void testContains() {
NamingServerNode node1 = new NamingServerNode();
node1.setControl(new Node.Endpoint("111.11.11.1",123));
node1.setTransaction(new Node.Endpoint("111.11.11.1",124));
Node node2 = new Node();
node2.setControl(new Node.Endpoint("111.11.11.1",12... |
CoordinatorResult<Void, CoordinatorRecord> prepareRebalance(
ClassicGroup group,
String reason
) {
// If any members are awaiting sync, cancel their request and have them rejoin.
if (group.isInState(COMPLETING_REBALANCE)) {
resetAndPropagateAssignmentWithError(group, Erro... | @Test
public void testCompleteJoinPhaseNoMembersRejoinedExtendsJoinPhase() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
ClassicGroup group = context.createClassicGroup("group-id");
JoinGroupRequestData reque... |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testArrayOfArrayOfInt64() throws Exception {
Schema schema =
Schema.of(Schema.Field.of("f0", FieldType.array(FieldType.array(FieldType.INT64))));
Row row1 =
Row.withSchema(schema)
.addValue(
Arrays.asList(Arrays.asList(1L, 2L), Arrays.asList(2L, 3L... |
public long betweenYear(boolean isReset) {
final Calendar beginCal = DateUtil.calendar(begin);
final Calendar endCal = DateUtil.calendar(end);
int result = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR);
if (false == isReset) {
final int beginMonthBase0 = beginCal.get(Calendar.MONTH);
final int ... | @Test
public void issueI97U3JTest(){
String dateStr1 = "2024-02-29 23:59:59";
Date sdate = DateUtil.parse(dateStr1);
String dateStr2 = "2023-03-01 00:00:00";
Date edate = DateUtil.parse(dateStr2);
long result = DateUtil.betweenYear(sdate, edate, false);
assertEquals(0, result);
} |
@Override
public IndexRange get(String index) throws NotFoundException {
final DBQuery.Query query = DBQuery.and(
DBQuery.notExists("start"),
DBQuery.is(IndexRange.FIELD_INDEX_NAME, index));
final MongoIndexRange indexRange = collection.findOne(query);
if (ind... | @Test
@MongoDBFixtures("MongoIndexRangeServiceTest.json")
public void getReturnsExistingIndexRange() throws Exception {
IndexRange indexRange = indexRangeService.get("graylog_1");
assertThat(indexRange.indexName()).isEqualTo("graylog_1");
assertThat(indexRange.begin()).isEqualTo(new Dat... |
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (msg instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) msg;
encoder().writeData(ctx, dataFrame.stream().id(), dataFrame.content(),
dataFrame.padd... | @Test
public void sendSettingsFrame() {
Http2Settings settings = new Http2Settings();
channel.write(new DefaultHttp2SettingsFrame(settings));
verify(frameWriter).writeSettings(eqFrameCodecCtx(), same(settings), any(ChannelPromise.class));
} |
public boolean validatePatternIfPresent(Retention retention, TableUri tableUri, String schema) {
if (retention.getColumnPattern() != null) {
if (retention.getColumnPattern().getColumnName() != null
&& !columnExists(
getSchemaFromSchemaJson(schema), retention.getColumnPattern().getColum... | @Test
void testValidatePatternNegative() {
RetentionColumnPattern malformedPattern =
RetentionColumnPattern.builder().pattern("random_pattern").columnName("aa").build();
Retention testRetention =
Retention.builder()
.columnPattern(malformedPattern)
.count(1)
... |
public static <T> T xmlToBean(String xml, Class<T> c) {
return xmlToBean(StrUtil.getReader(xml), c);
} | @Test
public void xmlToBeanTest() {
final SchoolVo schoolVo = JAXBUtil.xmlToBean(xmlStr, SchoolVo.class);
assertNotNull(schoolVo);
assertEquals("西安市第一中学", schoolVo.getSchoolName());
assertEquals("西安市雁塔区长安堡一号", schoolVo.getSchoolAddress());
assertEquals("101教室", schoolVo.getRoom().getRoomName());
assertEqu... |
@Nullable
@SuppressWarnings("unchecked")
public <E> E get(@Nonnull Tag<E> tag) {
Object got = map.getOrDefault(tag, NONE);
if (got == NONE) {
throw new IllegalArgumentException("No value associated with " + tag);
}
return (E) got;
} | @Test(expected = IllegalArgumentException.class)
public void when_getNonexistent_then_exception() {
ibt.get(tag1());
} |
public static VerificationMode never() {
return times(0);
} | @Test
public void should_monitor_server_behavior() throws Exception {
final MocoMonitor monitor = mock(MocoMonitor.class);
final HttpServer server = httpServer(port(), monitor);
server.get(by(uri("/foo"))).response("bar");
running(server, () -> assertThat(helper.get(remoteUrl("/foo"... |
protected Destination createDestination(String destName) throws JMSException {
String simpleName = getSimpleName(destName);
byte destinationType = getDestinationType(destName);
if (destinationType == ActiveMQDestination.QUEUE_TYPE) {
LOG.info("Creating queue: {}", destName);
... | @Test
public void testCreateDestination_tempTopic() throws JMSException {
assertDestinationType(TEMP_TOPIC_TYPE,
asAmqDest(jmsClient.createDestination("temp-topic://dest")));
} |
public void heartbeat(String fileOffset) throws IOException {
logProgress(fileOffset, true);
} | @Test
public void testHeartbeat() throws Exception {
Path file1 = new Path(filesDir + Path.SEPARATOR + "file1");
fs.create(file1).close();
// acquire lock on file1
FileLock lock1 = FileLock.tryLock(fs, file1, locksDir, "spout1");
assertNotNull(lock1);
assertTrue(fs.e... |
public ProtocolBuilder iothreads(Integer iothreads) {
this.iothreads = iothreads;
return getThis();
} | @Test
void iothreads() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.iothreads(25);
Assertions.assertEquals(25, builder.build().getIothreads());
} |
public static InternalRequestSignature fromHeaders(Crypto crypto, byte[] requestBody, HttpHeaders headers) {
if (headers == null) {
return null;
}
String signatureAlgorithm = headers.getHeaderString(SIGNATURE_ALGORITHM_HEADER);
String encodedSignature = headers.getHeaderStri... | @Test
public void fromHeadersShouldReturnNullIfSignatureAlgorithmHeaderMissing() {
assertNull(InternalRequestSignature.fromHeaders(crypto, REQUEST_BODY, internalRequestHeaders(ENCODED_SIGNATURE, null)));
} |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_object() {
Object original = new SerializableObject("value");
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
@Override
public ExplodedPlugin explode(PluginInfo pluginInfo) {
File tempDir = new File(fs.getTempDir(), TEMP_RELATIVE_PATH);
File toDir = new File(tempDir, pluginInfo.getKey());
try {
org.sonar.core.util.FileUtils.cleanDirectory(toDir);
File jarSource = pluginInfo.getNonNullJarFile();
... | @Test
public void explode_is_reentrant() throws Exception {
PluginInfo info = PluginInfo.create(plugin1Jar());
ExplodedPlugin exploded1 = underTest.explode(info);
long dirSize1 = sizeOfDirectory(exploded1.getMain().getParentFile());
ExplodedPlugin exploded2 = underTest.explode(info);
long dirSiz... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the TIMESTAMP value."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.")
public Timestamp parseTimestamp(
@UdfParameter(
descrip... | @Test
public void shouldThrowIfFormatInvalid() {
// When:
final KsqlFunctionException e = assertThrows(
KsqlFunctionException.class,
() -> udf.parseTimestamp("2021-12-01 12:10:11.123", "invalid")
);
// Then:
assertThat(e.getMessage(), containsString("Unknown pattern letter: i"));
... |
public OptExpression next() {
// For logic scan to physical scan, we only need to match once
if (isPatternWithoutChildren && groupExpressionIndex.get(0) > 0) {
return null;
}
OptExpression expression;
do {
this.groupTraceKey = 0;
// Match wit... | @Test
public void testBinderMultiDepth2Repeat2() {
OptExpression expr1 = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN, 0),
OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN, 1)),
OptExpression.create(new MockOperator(OperatorType.LOGICAL_... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
if (userSession.hasSession() && userSession.isLoggedIn() && userSession.shouldResetPassword()) {
redirectTo(response, request.getContextPath() + RESET_PASSWORD_PATH);
}
chain.doFilter(... | @Test
public void redirect_if_request_uri_ends_with_slash() throws Exception {
when(request.getRequestURI()).thenReturn("/projects/");
when(request.getContextPath()).thenReturn("/sonarqube");
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sonarqube/account/reset_passwo... |
public Collection<ServerPluginInfo> loadPlugins() {
Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>();
for (ServerPluginInfo bundled : getBundledPluginsMetadata()) {
failIfContains(bundledPluginsByKey, bundled,
plugin -> MessageException.of(format("Found two versions of the... | @Test
public void plugin_is_ignored_if_required_plugin_is_too_old_at_startup() throws Exception {
copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir());
copyTestPluginTo("test-requirenew-plugin", fs.getInstalledExternalPluginsDir());
// the plugin "requirenew" is not installed as it r... |
@Override
String simpleTypeName() {
if (isRoot()) {
return "Root";
}
return lastComponent().getClass().getSimpleName();
} | @Test
public void testSimpleTypeNameOfRoot() {
assertThat(ResourceId.ROOT.simpleTypeName(), is("Root"));
} |
static void urlEncode(String str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {
char c = str.charAt(idx);
if ('+' == c) {
sb.append("%2B");
} else if ('%' == c) {
sb.append("%25");
} else {
sb.ap... | @Test
void testUrlEncodeByPercent() {
// Arrange
final StringBuilder sb = new StringBuilder("??????");
// Act
GroupKey.urlEncode("%", sb);
// Assert side effects
assertNotNull(sb);
assertEquals("??????%25", sb.toString());
} |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCorrectCodeForIntervalUnit() {
// Given:
final IntervalUnit intervalUnit = new IntervalUnit(TimeUnit.DAYS);
// When:
final String java = sqlToJavaVisitor.process(intervalUnit);
// Then:
assertThat(java, containsString("TimeUnit.DAYS"));
} |
@Override
public PayloadSerializer getSerializer(Schema schema, Map<String, Object> tableParams) {
Class<? extends TBase> thriftClass = getMessageClass(tableParams);
TProtocolFactory protocolFactory = getProtocolFactory(tableParams);
inferAndVerifySchema(thriftClass, schema);
return getPayloadSerializ... | @Test
public void deserialize() throws Exception {
Row row =
provider
.getSerializer(
SHUFFLED_SCHEMA,
ImmutableMap.of(
"thriftClass", TestThriftMessage.class.getName(),
"thriftProtocolFactoryClass", TCompactProtocol.Facto... |
public static Ip4Address valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new Ip4Address(bytes);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfIncorrectString() {
Ip4Address ipAddress;
String fromString = "NoSuchIpAddress";
ipAddress = Ip4Address.valueOf(fromString);
} |
public static void close(final Collection<DataSource> dataSources) {
Collection<Exception> causes = new LinkedList<>();
for (DataSource each : dataSources) {
if (each instanceof AutoCloseable) {
try {
((AutoCloseable) each).close();
// ... | @Test
void assertClose() throws Exception {
DataSource dataSource0 = mock(DataSource.class, withSettings().extraInterfaces(AutoCloseable.class));
DataSource dataSource1 = mock(DataSource.class, withSettings().extraInterfaces(AutoCloseable.class));
doThrow(new SQLException("test")).when((Auto... |
@Override
public Enumeration<String> getKeys() {
if ( parent == null ) {
return Collections.enumeration( contents.keySet() );
}
Set<String> keySet = newHashSet( contents.keySet() );
keySet.addAll( Collections.list( parent.getKeys() ) );
return Collections.enumeration( keySet );
} | @Test
public void aggregateBundleWithNoSourceBundlesContainsNoKeys() {
ResourceBundle aggregateBundle = new AggregateResourceBundle( Collections.<ResourceBundle>emptyList() );
assertTrue( getAsSet( aggregateBundle.getKeys() ).isEmpty() );
} |
public static String removeLeadingSlashes(String path) {
return SLASH_PREFIX_PATTERN.matcher(path).replaceFirst("");
} | @Test
public void removeLeadingSlashes_whenNoLeadingSlashes_returnsOriginal() {
assertThat(removeLeadingSlashes("a/b/c/")).isEqualTo("a/b/c/");
} |
@SuppressLint("HardwareIds")
public static String getIdentifier(Context context) {
try {
if (!isAndroidIDEnabled) {
SALog.i(TAG, "SensorsData getAndroidID is disabled");
return "";
}
if (SAPropertyManager.getInstance().isLimitKey(LimitKey.A... | @Test
public void getIdentifier() {
String androidID = SensorsDataUtils.getIdentifier(mApplication);
System.out.println("androidID = " + androidID);
} |
@Override
public void onWorkflowFinalized(Workflow workflow) {
WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput());
WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow);
String reason = workflow.getReasonForIncompletion();
LOG.inf... | @Test
public void testPublishErrorOnWorkflowFinalized() {
when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.TERMINATED);
when(instanceDao.getWorkflowInstanceStatus(eq("test-workflow-id"), anyLong(), anyLong()))
.thenReturn(WorkflowInstance.Status.IN_PROGRESS);
doCallRealMethod().when(p... |
public GpuAllocation assignGpus(Container container)
throws ResourceHandlerException {
GpuAllocation allocation = internalAssignGpus(container);
// Wait for a maximum of waitPeriodForResource seconds if no
// available GPU are there which are yet to be released.
int timeWaiting = 0;
while (al... | @Test
public void testRequestMoreThanAvailableGpu()
throws ResourceHandlerException {
addGpus(new GpuDevice(1, 1));
Container container = createMockContainer(2, 5L);
exception.expect(ResourceHandlerException.class);
exception.expectMessage("Failed to find enough GPUs");
testSubject.assignGp... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testHadoopConfConfigMap() throws IOException {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParame... |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseCl... | @Test
void getExceptionWithMessageAndNestedExceptionWithMessage() {
final FailedState failedState = new FailedState("JobRunr message", new CustomException("custom exception message", new CustomException("other exception")));
assertThat(failedState.getException())
.isInstanceOf(Custo... |
public static DLPReidentifyText.Builder newBuilder() {
return new AutoValue_DLPReidentifyText.Builder();
} | @Test
public void throwsExceptionWhenDelimiterIsSetAndHeadersAreNot() {
assertThrows(
"Column headers should be supplied when delimiter is present.",
IllegalArgumentException.class,
() ->
DLPReidentifyText.newBuilder()
.setProjectId(PROJECT_ID)
.... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
for(String scheme : host.getProtocol().getSchemes()) {
if(Arrays.stream(Scheme.values()).noneMatch(s -> s.name().equals(scheme))) {
list.add(new Descriptive... | @Test
public void testCustomSchemes() {
Host host = new Host(new TestProtocol() {
public String[] getSchemes() {
return new String[]{"c1", "c2"};
}
}, "localhost");
Path path = new Path("/file", EnumSet.of(Path.Type.file));
final DescriptiveUrl... |
@Transactional(readOnly = true)
public void existsGeneralSignUpUser(String phone) {
readGeneralSignUpUser(phone);
} | @DisplayName("정상적인 비밀번호 찾기 인증요청일 경우 SuccessResponse.noContent()를 반환한다.")
@Test
void findPasswordVerification() {
// given
String phone = "010-1234-5678";
User user = UserFixture.GENERAL_USER.toUser();
given(userService.readUserByPhone(phone)).willReturn(Optional.of(user));
... |
public String getJobCompletionRequestBody(String elasticAgentId, JobIdentifier jobIdentifier, Map<String, String> elasticProfileConfiguration, Map<String, String> clusterProfileConfiguration) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("elastic_agent_id", elasticAgentId);
... | @Test
public void shouldJSONizeJobCompletionRequestBody() throws Exception {
HashMap<String, String> elasticProfileConfiguration = new HashMap<>();
elasticProfileConfiguration.put("property_name", "property_value");
HashMap<String, String> clusterProfileConfiguration = new HashMap<>();
... |
public static TraceContextOrSamplingFlags create(TraceContext context) {
return new TraceContextOrSamplingFlags(1, context, emptyList());
} | @Test void equalsAndHashCode_samplingFlags() {
equalsAndHashCode(
() -> TraceContextOrSamplingFlags.create(SAMPLED),
() -> TraceContextOrSamplingFlags.create(NOT_SAMPLED),
() -> TraceContextOrSamplingFlags.create(context)
);
} |
public abstract int status(HttpServletResponse response); | @Test void servlet25_status() {
assertThat(servlet25.status(new HttpServletResponseImpl()))
.isEqualTo(200);
} |
public boolean schemaEquals(Object obj) {
return equals(obj) && Arrays.equals(fieldNames, ((RowTypeInfo) obj).fieldNames);
} | @Test
void testSchemaEquals() {
final RowTypeInfo row1 =
new RowTypeInfo(
new TypeInformation[] {
BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO
},
new String[] {"field1", "field2... |
@ApiOperation(value = "获取功能按钮列表")
@GetMapping
public ApiResult<List<BaseAction>> list(){
return ApiResult.success(baseActionService.list());
} | @Test
@DisplayName("操作列表")
void list() {
} |
public static SqlMap of(final SqlType keyType, final SqlType valueType) {
return new SqlMap(keyType, valueType);
} | @Test
public void shouldReturnBaseType() {
assertThat(SqlMap.of(SOME_TYPE, OTHER_TYPE).baseType(), is(SqlBaseType.MAP));
} |
public String decompress(String compressorName, String compressedString) throws IOException {
Checks.notNull(compressedString, "compressedString cannot be null");
Compressor compressor = getCompressor(compressorName);
return new String(compressor.decompress(base64Decode(compressedString)), DEFAULT_ENCODING)... | @Test
public void testDecompress() throws IOException {
assertEquals("aaaaaaa", stringCodec.decompress("gzip", "H4sIAAAAAAAAAEtMBAMAdCCLWwcAAAA="));
} |
AwsCredentials credentials() {
if (!StringUtil.isNullOrEmptyAfterTrim(awsConfig.getAccessKey())) {
return AwsCredentials.builder()
.setAccessKey(awsConfig.getAccessKey())
.setSecretKey(awsConfig.getSecretKey())
.build();
}
if (!StringUt... | @Test
public void credentialsAccessKey() {
// given
AwsConfig awsConfig = AwsConfig.builder()
.setAccessKey(ACCESS_KEY)
.setSecretKey(SECRET_KEY)
.build();
AwsCredentialsProvider credentialsProvider = new AwsCredentialsProvider(awsConfig, awsMetadataApi, e... |
static SegmentStatus getSegmentStatus(Path path) {
try (RecordIOReader ioReader = new RecordIOReader(path)) {
boolean moreEvents = true;
SegmentStatus segmentStatus = SegmentStatus.EMPTY;
while (moreEvents) {
// If all events in the segment can be read, then a... | @Test
public void testEmptySegment() throws Exception {
try(RecordIOWriter writer = new RecordIOWriter(file)){
// Do nothing. Creating a new writer is the same behaviour as starting and closing
// This line avoids a compiler warning.
writer.toString();
}
a... |
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions());
checkArgument(!StringUtils.isNullOrEmpty(conf.getString(FlinkOptions.PATH)),
"Option [path] should not be empty.");
setupTableOptions(conf.... | @Test
void testSetupCleaningOptionsForSink() {
// definition with simple primary key and partition path
ResolvedSchema schema1 = SchemaBuilder.instance()
.field("f0", DataTypes.INT().notNull())
.field("f1", DataTypes.VARCHAR(20))
.field("f2", DataTypes.TIMESTAMP(3))
.field("ts"... |
public static String parsingEndpointRule(String endpointUrl) {
// If entered in the configuration file, the priority in ENV will be given priority.
if (endpointUrl == null || !PATTERN.matcher(endpointUrl).find()) {
// skip retrieve from system property and retrieve directly from system env
... | @Test
void testParsingEndpointRule() {
String url = "${test:www.example.com}";
String actual = ParamUtil.parsingEndpointRule(url);
assertEquals("www.example.com", actual);
} |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldOverwriteAFileCalledGoPluginActivatorInLibWithOurOwnGoPluginActivatorEvenIfItExists() throws Exception {
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
File expectedBundleDirectory = new File(bundleDir, PLUGIN_JAR_FILE_NAME);
File activatorFileLocation =... |
@NonNull
public SelectSectoralIdpStep start(@NonNull Session session) {
return new SelectSectoralIdpStepImpl(
selfIssuer,
federationMasterClient,
openIdClient,
relyingPartyKeySupplier,
session.callbackUri(),
session.nonce(),
session.codeChallengeS256(),
... | @Test
void start() {
var self = URI.create("https://fachdienst.example.com");
var fedmasterClient = mock(FederationMasterClient.class);
var openIdClient = mock(OpenIdClient.class);
var keySupplier = mock(KeySupplier.class);
var flow = new AuthenticationFlow(self, fedmasterClient, openIdClient, ke... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test
public void testBuildArgsHappyPath()
{
//test integer association key integer
String param1Key = "param1";
Parameter<Integer> param1 = new Parameter<>(param1Key, Integer.class, DataTemplateUtil.getSchema(Integer.class),
false, null, Parameter.ParamType.ASS... |
@Override
public int hashCode() {
return Objects.hash(
partitionToken,
commitTimestamp,
serverTransactionId,
isLastRecordInTransactionInPartition,
recordSequence,
tableName,
rowType,
mods,
modType,
valueCaptureType,
numberOfRe... | @Test
public void testMetadataShouldNotInterfereInEquality() {
final DataChangeRecord record1 =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeMicroseconds(1L),
"serverTransactionId",
true,
"recordSequence",
"tableName",
... |
public JobMetaDataParameterObject processJobMultipart(JobMultiPartParameterObject parameterObject)
throws IOException, NoSuchAlgorithmException {
// Change the timestamp in the beginning to avoid expiration
changeLastUpdatedTime();
validateReceivedParameters(parameterObject);
... | @Test
public void testInvalidSHA256() {
byte[] partData = new byte[]{1};
JobMultiPartParameterObject jobMultiPartParameterObject = new JobMultiPartParameterObject();
jobMultiPartParameterObject.setSessionId(UUID.randomUUID());
jobMultiPartParameterObject.setCurrentPartNumber(1);
... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testInvalidCreateTimeNonCompressedV2() {
long now = System.currentTimeMillis();
MemoryRecords records = createRecords(
RecordBatch.MAGIC_VALUE_V2,
now - 1001L,
Compression.NONE
);
assertThrows(RecordValidationExceptio... |
@Override
public void start() throws Exception {
LOG.info("Process starting.");
mRunning = true;
mJournalSystem.start();
startMasterComponents(false);
mServices.forEach(SimpleService::start);
// Perform the initial catchup before joining leader election,
// to avoid potential delay if thi... | @Test
public void startStopPrimary() throws Exception {
AlluxioMasterProcess master = new AlluxioMasterProcess(new NoopJournalSystem(),
new UfsJournalSingleMasterPrimarySelector());
master.registerService(
RpcServerService.Factory.create(master.getRpcBindAddress(), master, master.getRegistry()... |
@Override
public MetadataNode child(String name) {
if (name.equals(ClusterImageBrokersNode.NAME)) {
return new ClusterImageBrokersNode(image);
} else if (name.equals(ClusterImageControllersNode.NAME)) {
return new ClusterImageControllersNode(image);
} else {
... | @Test
public void testUnknownChild() {
assertNull(NODE.child("unknown"));
} |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final ReadOnlyKeyValueStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore
.store(QueryableStoreTypes.timestampedKeyValueSt... | @Test
public void shouldReturnValuesFullTableScan() {
// Given:
when(tableStore.all()).thenReturn(keyValueIterator);
when(keyValueIterator.hasNext()).thenReturn(true, true, false);
when(keyValueIterator.next())
.thenReturn(KEY_VALUE1)
.thenReturn(KEY_VALUE2);
// When:
final It... |
static void setTableInputInformation(
TableInput.Builder tableInputBuilder, TableMetadata metadata) {
setTableInputInformation(tableInputBuilder, metadata, null);
} | @Test
public void testSetTableInputInformationWithExistingTable() {
// Actual TableInput
TableInput.Builder actualTableInputBuilder = TableInput.builder();
Schema schema =
new Schema(
Types.NestedField.required(1, "x", Types.StringType.get()),
Types.NestedField.required(2, ... |
@GET
@Path("/health")
@Operation(summary = "Health check endpoint to verify worker readiness and liveness")
public Response healthCheck() throws Throwable {
WorkerStatus workerStatus;
int statusCode;
try {
FutureCallback<Void> cb = new FutureCallback<>();
herd... | @Test
public void testHealthCheckUnhealthy() throws Throwable {
expectHealthCheck(new TimeoutException());
when(herder.isReady()).thenReturn(true);
Response response = rootResource.healthCheck();
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus(... |
boolean isWriteEnclosureForValueMetaInterface( ValueMetaInterface v ) {
return ( isWriteEnclosed( v ) )
|| isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( v.getName().getBytes() );
} | @Test
public void testWriteEnclosedForValueMetaInterfaceWithEnclosureFixDisabled() {
TextFileOutputData data = new TextFileOutputData();
data.binaryEnclosure = new byte[1];
data.writer = new ByteArrayOutputStream();
TextFileOutputMeta meta = getTextFileOutputMeta();
meta.setEnclosureForced(false);... |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseMicroMessengerTest() {
final String uaString = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Mobile/15A372 MicroMessenger/7.0.17(0x17001127) NetType/WIFI Language/zh_CN";
final UserAgent ua = UserAgentUtil.parse(uaString);
assertEquals("Mi... |
@Override
public Iterator<RawUnionValue> call(Iterator<WindowedValue<InputT>> inputs) throws Exception {
SparkPipelineOptions options = pipelineOptions.get().as(SparkPipelineOptions.class);
// Register standard file systems.
FileSystems.setDefaultPipelineOptions(options);
// Do not call processElemen... | @Test
public void testNoCallOnEmptyInputIterator() throws Exception {
SparkExecutableStageFunction<Integer, ?> function = getFunction(Collections.emptyMap());
function.call(Collections.emptyIterator());
verifyZeroInteractions(stageBundleFactory);
} |
@Override
public CompletableFuture<Void> write(
TieredStoragePartitionId partitionId, List<SubpartitionBufferContext> buffersToWrite) {
List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
buffersToWrite.forEach(
subpartitionBuffers -> {
... | @Test
void testWrite() throws IOException {
TieredStoragePartitionId partitionId =
TieredStorageIdMappingUtils.convertId(new ResultPartitionID());
int numSubpartitions = 5;
int numSegments = 10;
int numBuffersPerSegment = 10;
int bufferSizeBytes = 3;
... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void neoforgeForestOptiFineIncompatible() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/mod/neoforgeforest_optifine_incompatibility.txt")),
CrashReportAnalyzer.Rule.NEOFORGE_FOREST_OP... |
@Override
public final void close() throws Exception {
try {
doClose();
} finally {
doFinally();
}
} | @Test
void testClose() throws Exception {
configuration.close();
} |
public static void checkRowIDPartitionComponent(List<HiveColumnHandle> columns, Optional<byte[]> rowIdPartitionComponent)
{
boolean supplyRowIDs = columns.stream().anyMatch(column -> HiveColumnHandle.isRowIdColumnHandle(column));
if (supplyRowIDs) {
checkArgument(rowIdPartitionComponent.... | @Test
public void testCheckRowIDPartitionComponent_rowID()
{
HiveColumnHandle handle = HiveColumnHandle.rowIdColumnHandle();
List<HiveColumnHandle> columns = ImmutableList.of(handle);
checkRowIDPartitionComponent(columns, Optional.of(new byte[0]));
} |
protected GelfMessage toGELFMessage(final Message message) {
final DateTime timestamp;
final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP);
if (fieldTimeStamp instanceof DateTime) {
timestamp = (DateTime) fieldTimeStamp;
} else {
timestamp = To... | @Test
public void testToGELFMessageWithInvalidNumericStringLevel() throws Exception {
final GelfTransport transport = mock(GelfTransport.class);
final GelfOutput gelfOutput = new GelfOutput(transport);
final DateTime now = DateTime.now(DateTimeZone.UTC);
final Message message = messa... |
@Override
protected ConfigData<AppAuthData> fromJson(final JsonObject data) {
return GsonUtils.getGson().fromJson(data, new TypeToken<ConfigData<AppAuthData>>() {
}.getType());
} | @Test
public void testFromJson() {
ConfigData<AppAuthData> appAuthDataConfigData = new ConfigData<>();
AppAuthData appAuthData = new AppAuthData();
appAuthDataConfigData.setData(Collections.singletonList(appAuthData));
JsonObject jsonObject = GsonUtils.getGson().fromJson(GsonUtils.ge... |
@Override
public ResourceCounter calculateRequiredSlots(
Iterable<JobInformation.VertexInformation> vertices) {
int numTotalRequiredSlots = 0;
for (SlotSharingGroupMetaInfo slotSharingGroupMetaInfo :
SlotSharingGroupMetaInfo.from(vertices).values()) {
numTotal... | @Test
void testCalculateRequiredSlots() {
final SlotSharingSlotAllocator slotAllocator =
SlotSharingSlotAllocator.createSlotSharingSlotAllocator(
TEST_RESERVE_SLOT_FUNCTION,
TEST_FREE_SLOT_FUNCTION,
TEST_IS_SLOT_FREE_FUN... |
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
} | @Test
void testDoInject() {
injector.doInject(null, null, null);
} |
@Udf
public Long trunc(@UdfParameter final Long val) {
return val;
} | @Test
public void shouldHandleNullDecimalPlaces() {
assertThat(udf.trunc(1.75d, null), is(nullValue()));
assertThat(udf.trunc(new BigDecimal("1.75"), null), is(nullValue()));
} |
@GetMapping("/detail")
@RequiresPermissions("system:authen:editResourceDetails")
public ShenyuAdminResult detail(@RequestParam("id")
@Existed(message = "app key not existed",
provider = AppAuthMapper.class) final String id) {
... | @Test
public void testDetail() throws Exception {
given(this.appAuthService.findById("0001")).willReturn(appAuthVO);
this.mockMvc.perform(MockMvcRequestBuilders.get("/appAuth/detail")
.param("id", "0001"))
.andExpect(status().isOk())
.andExpect(jsonPat... |
public static GtidSet fixRestoredGtidSet(GtidSet serverGtidSet, GtidSet restoredGtidSet) {
Map<String, GtidSet.UUIDSet> newSet = new HashMap<>();
serverGtidSet.getUUIDSets().forEach(uuidSet -> newSet.put(uuidSet.getUUID(), uuidSet));
for (GtidSet.UUIDSet uuidSet : restoredGtidSet.getUUIDSets()) ... | @Test
void testFixingRestoredGtidSet() {
GtidSet serverGtidSet = new GtidSet("A:1-100");
GtidSet restoredGtidSet = new GtidSet("A:30-100");
assertThat(fixRestoredGtidSet(serverGtidSet, restoredGtidSet).toString())
.isEqualTo("A:1-100");
serverGtidSet = new GtidSet("A... |
public static Schema mergeWideningNullable(Schema schema1, Schema schema2) {
if (schema1.getFieldCount() != schema2.getFieldCount()) {
throw new IllegalArgumentException(
"Cannot merge schemas with different numbers of fields. "
+ "schema1: "
+ schema1
+ " s... | @Test
public void testWidenArray() {
Schema schema1 = Schema.builder().addArrayField("field1", FieldType.INT32).build();
Schema schema2 =
Schema.builder().addArrayField("field1", FieldType.INT32.withNullable(true)).build();
Schema expected =
Schema.builder().addArrayField("field1", FieldTy... |
@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
return isWebSocketUpgrade(exchange.getRequest().getHeaders()) ? match() : notMatch();
} | @Test
void shouldNotMatchIfNotWebSocketProtocol() {
var httpRequest = MockServerHttpRequest.get("")
.header(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE)
.header(HttpHeaders.UPGRADE, "not-a-websocket")
.build();
var wsExchange = MockServerWebExchange.from(httpReque... |
public Component buildProject(ScannerReport.Component project, String scmBasePath) {
this.rootComponent = project;
this.scmBasePath = trimToNull(scmBasePath);
Node root = createProjectHierarchy(project);
return buildComponent(root, "", "");
} | @Test
void project_description_is_loaded_from_report_if_present_and_on_main_branch() {
String reportDescription = randomAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setDescription(reportDescription)
.build();
Component root = newUnderTest(SOME_P... |
@Override
public boolean accept(final Path file) {
if(list.find(new SimplePathPredicate(file)) != null) {
return true;
}
for(Path f : list) {
if(f.isChild(file)) {
return true;
}
}
if(log.isDebugEnabled()) {
log.... | @Test
public void testAcceptDirectoryChildrenOnly() {
final RecursiveSearchFilter f = new RecursiveSearchFilter(new AttributedList<>(Arrays.asList(
new Path("/d/f", EnumSet.of(Path.Type.file)))
));
assertTrue(f.accept(new Path("/d", EnumSet.of(Path.Type.directory))));
... |
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_withContext_ignoredErrorParsing() {
when(parseValue.apply(input, context)).thenThrow(new Error());
tag.tag(input, context, customizer);
verify(parseValue).apply(input, context);
verifyNoMoreInteractions(parseValue); // doesn't parse twice
verifyNoMoreInteractions(customiz... |
@Override
public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (Objects.nonNull(methodClass)) {
groups.add(methodCl... | @Test
public void testItWithCollectionArg() throws Exception {
apacheDubboClientValidatorUnderTest
.validate(
"methodFour",
new Class<?>[]{List.class},
new Object[]{Collections.singletonList("parameter")});
} |
@Override
public Num calculate(BarSeries series, Position position) {
return position.hasProfit() ? series.one() : series.zero();
} | @Test
public void calculateWithTwoLongPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series)... |
@Override
public String getTypeAsString() {
String type;
if (!value.isEmpty() && StructType.class.isAssignableFrom(value.get(0).getClass())) {
type = value.get(0).getTypeAsString();
} else {
type = AbiTypes.getTypeAString(getComponentType());
}
return ... | @Test
public void testEmptyStaticArray() {
final StaticArray<Address> array =
new StaticArray0<>(Address.class, Collections.emptyList());
assertEquals(Address.TYPE_NAME + "[0]", array.getTypeAsString());
} |
public static <T> ThrowingConsumer<StreamRecord<T>, Exception> getRecordProcessor2(
TwoInputStreamOperator<?, T, ?> operator) {
boolean canOmitSetKeyContext;
if (operator instanceof AbstractStreamOperator) {
canOmitSetKeyContext = canOmitSetKeyContext((AbstractStreamOperator<?>) ... | @Test
void testGetRecordProcessor2() throws Exception {
TestOperator operator1 = new TestOperator();
TestOperator operator2 = new TestKeyContextHandlerOperator(true, true);
TestOperator operator3 = new TestKeyContextHandlerOperator(true, false);
RecordProcessorUtils.getRecordProcess... |
public void wrap(final byte[] buffer)
{
capacity = buffer.length;
addressOffset = ARRAY_BASE_OFFSET;
byteBuffer = null;
wrapAdjustment = 0;
if (buffer != byteArray)
{
byteArray = buffer;
}
} | @Test
void shouldNotWrapInValidRange()
{
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[8]);
final UnsafeBuffer slice = new UnsafeBuffer();
assertThrows(IllegalArgumentException.class, () -> slice.wrap(buffer, -1, 0));
assertThrows(IllegalArgumentException.class, () -> sl... |
public static Expression convert(Filter[] filters) {
Expression expression = Expressions.alwaysTrue();
for (Filter filter : filters) {
Expression converted = convert(filter);
Preconditions.checkArgument(
converted != null, "Cannot convert filter to Iceberg: %s", filter);
expression =... | @Test
public void testDateFilterConversion() {
LocalDate localDate = LocalDate.parse("2018-10-18");
Date date = Date.valueOf(localDate);
long epochDay = localDate.toEpochDay();
Expression localDateExpression = SparkFilters.convert(GreaterThan.apply("x", localDate));
Expression dateExpression = Sp... |
@Override
protected void processOptions(LinkedList<String> args) {
CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE,
OPTION_QUOTA, OPTION_HUMAN, OPTION_HEADER, OPTION_QUOTA_AND_USAGE,
OPTION_EXCLUDE_SNAPSHOT,
OPTION_ECPOLICY, OPTION_SNAPSHOT_COUNT);
cf.addOptionWithValue(OPTIO... | @Test
public void processPathWithQuotasByQTVH() throws Exception {
Path path = new Path("mockfs:/test");
when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);
PrintStream out = mock(PrintStream.class);
Count count = new Count();
count.out = out;
LinkedList<String> options = new Linked... |
public static StackTraceElement[] extract(Throwable t,
String fqnOfInvokingClass, final int maxDepth,
List<String> frameworkPackageList) {
if (t == null) {
return null;
}
StackTraceElement[] steArray = t.getStackT... | @Test
public void testBasic() {
Throwable t = new Throwable();
StackTraceElement[] steArray = t.getStackTrace();
StackTraceElement[] cda = CallerData.extract(t, CallerDataTest.class.getName(), 50, null);
assertNotNull(cda);
assertTrue(cda.length > 0);
assertEquals(steArray.length - 1, cda... |
@Override
public Long createAiVideoTemplate(AiVideoTemplateCreateReqVO createReqVO) {
// 插入
AiVideoTemplateDO aiVideoTemplate = AiVideoTemplateConvert.INSTANCE.convert(createReqVO);
aiVideoTemplateMapper.insert(aiVideoTemplate);
// 返回
return aiVideoTemplate.getId();
} | @Test
public void testCreateAiVideoTemplate_success() {
// 准备参数
AiVideoTemplateCreateReqVO reqVO = randomPojo(AiVideoTemplateCreateReqVO.class);
// 调用
Long aiVideoTemplateId = aiVideoTemplateService.createAiVideoTemplate(reqVO);
// 断言
assertNotNull(aiVideoTemplateId)... |
@Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
Map<String, Subscription> subscriptions) {
Map<String, List<TopicPartition>> assignment = new HashMap<>();
List<MemberInfo> memberInfoList = new Arra... | @Test
public void testOneConsumerMultipleTopics() {
Map<String, Integer> partitionsPerTopic = setupPartitionsPerTopicWithTwoTopics(1, 2);
Map<String, List<TopicPartition>> assignment = assignor.assign(partitionsPerTopic,
Collections.singletonMap(consumerId, new Subscription(topics(t... |
@Override
public List<String> getServices() {
return polarisServiceDiscovery.getServices();
} | @Test
public void testGetServices() {
when(polarisServiceDiscovery.getServices()).thenReturn(singletonList(SERVICE_PROVIDER));
List<String> services = client.getServices();
assertThat(services).contains(SERVICE_PROVIDER).size().isEqualTo(1);
} |
@Override
public SmsTemplateDO getSmsTemplate(Long id) {
return smsTemplateMapper.selectById(id);
} | @Test
public void testGetSmsTemplate() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO();
smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbSmsTemplate.getId();
// 调用
SmsTemplateDO smsTemplate = smsTemplateService... |
@Override
protected String convertToString(final Integer value) {
return value.toString();
} | @Test
void testConvertToString() throws Exception {
assertThat(subtaskIndexPathParameter.convertToString(Integer.MAX_VALUE))
.isEqualTo("2147483647");
} |
public synchronized void addVulnerableSoftwareIdentifier(Identifier identifier) {
this.vulnerableSoftwareIdentifiers.add(identifier);
} | @Test
public void testAddVulnerableSoftwareIdentifier() throws Exception {
CpeBuilder builder = new CpeBuilder();
Cpe cpe = builder.part(Part.APPLICATION).vendor("apache").product("struts").version("2.1.2").build();
CpeIdentifier id = new CpeIdentifier(cpe, Confidence.HIGHEST);
cpe ... |
public final void containsNoneOf(
@Nullable Object firstExcluded,
@Nullable Object secondExcluded,
@Nullable Object @Nullable ... restOfExcluded) {
containsNoneIn(accumulate(firstExcluded, secondExcluded, restOfExcluded));
} | @Test
public void iterableContainsNoneOf() {
assertThat(asList(1, 2, 3)).containsNoneOf(4, 5, 6);
} |
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) {
if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) {
throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'.");
}
return loadManagerWrapper.get();... | @Test
public void testLookupOptions() throws Exception {
Pair<TopicName, NamespaceBundle> topicAndBundle =
getBundleIsNotOwnByChangeEventTopic("test-lookup-options");
TopicName topicName = topicAndBundle.getLeft();
NamespaceBundle bundle = topicAndBundle.getRight();
... |
@Override
public boolean shouldSample() {
// This load might race with the store below, causing multiple threads to get a sample
// since the new timestamp has not been written yet, but it is extremely unlikely and
// the consequences are not severe since this is a probabilistic sampler that... | @Test
void zero_desired_sample_rate_returns_false() {
var clock = MockUtils.mockedClockReturning(ms2ns(10_000));
var rng = MockUtils.mockedRandomReturning(0.99999999); // [0, 1)
var sampler = new ProbabilisticSampleRate(clock, () -> rng, 0.0);
assertFalse(sampler.shouldSample());
... |
@Override
public ResultSet executeQuery(String sql)
throws SQLException {
validateState();
try {
if (!DriverUtils.queryContainsLimitStatement(sql)) {
sql += " " + LIMIT_STATEMENT + " " + _maxRows;
}
String enabledSql = DriverUtils.enableQueryOptions(sql, _connection.getQueryOpt... | @Test
public void testSetDisableNullHandling()
throws Exception {
Properties props = new Properties();
props.put(QueryOptionKey.ENABLE_NULL_HANDLING, "false");
PinotConnection pinotConnection =
new PinotConnection(props, "dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTran... |
@Override
public void logAfterExecution(StatementContext context) {
log(context);
} | @Test
public void logsExecutionTime() {
final MetricRegistry mockRegistry = mock(MetricRegistry.class);
final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class);
final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy);
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.