focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void addSessionVariables(final Map<String, String> vars) {
sessionVariables.putAll(vars);
} | @Test
public void testAddVariablesToCli() {
// Given
localCli.addSessionVariables(ImmutableMap.of("env", "qa"));
// Then
assertRunListCommand("variables", hasRows(
row(
"env",
"qa"
)
));
} |
@Override
@Transactional(value="defaultTransactionManager")
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException {
if (Strings.isNullOrEmpty(refreshTokenValue)) {
// throw an invalid token exception if there's no refresh token val... | @Test(expected = InvalidTokenException.class)
public void refreshAccessToken_expired() {
when(refreshToken.isExpired()).thenReturn(true);
service.refreshAccessToken(refreshTokenValue, tokenRequest);
} |
private static Row selectRow(
Row input,
FieldAccessDescriptor fieldAccessDescriptor,
Schema inputSchema,
Schema outputSchema) {
if (fieldAccessDescriptor.getAllFields()) {
return input;
}
Row.Builder output = Row.withSchema(outputSchema);
selectIntoRow(inputSchema, input,... | @Test
public void testSelectNullableNestedRowArray() {
FieldAccessDescriptor fieldAccessDescriptor1 =
FieldAccessDescriptor.withFieldNames("nestedArray.field1").resolve(NESTED_NULLABLE_SCHEMA);
Row out1 =
selectRow(
NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1, Row.nullRow(NESTED... |
public abstract boolean isDirectory(); | @Test
public void testApplicationFileIsDirectory() throws Exception {
assertFalse(getApplicationFile(Path.fromString("vespa-services.xml")).isDirectory());
assertTrue(getApplicationFile(Path.fromString("searchdefinitions")).isDirectory());
assertFalse(getApplicationFile(Path.fromString("sear... |
@Override
public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) {
if (stateManager.taskType() != TaskType.ACTIVE) {
throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ... | @Test
public void shouldAddAndGetProcessorKeyValue() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(ta... |
public static Read read(Schema schema) {
return new AutoValue_ParquetIO_Read.Builder()
.setSchema(schema)
.setInferBeamSchema(false)
.build();
} | @Test
public void testReadDisplayData() {
Configuration configuration = new Configuration();
configuration.set("parquet.foo", "foo");
DisplayData displayData =
DisplayData.from(
ParquetIO.read(SCHEMA)
.from("foo.parquet")
.withProjection(REQUESTED_SCHEMA... |
@Override
public <T> Optional<T> getProperty(String key, Class<T> targetType) {
var targetKey = targetPropertyName(key);
var result = binder.bind(targetKey, Bindable.of(targetType));
return result.isBound() ? Optional.of(result.get()) : Optional.empty();
} | @Test
void resolvedSingleValueProperties() {
env.setProperty("prop.0.strProp", "testStr");
env.setProperty("prop.0.intProp", "123");
var resolver = new PropertyResolverImpl(env);
assertThat(resolver.getProperty("prop.0.strProp", String.class))
.hasValue("testStr");
assertThat(resolver.get... |
@GetMapping("/{id}")
public ResponseEntity<Hotel> obtenerHotel (@PathVariable String id) {
Hotel Hotel = hotelRepository.getHotel(id);
return ResponseEntity.ok(Hotel);
} | @Test
void testObtenerHotel() {
String hotelId = "1";
Hotel hotel = new Hotel(hotelId, "Hotel Test", "Info Test", "Ubicacion Test");
when(hotelService.getHotel(hotelId)).thenReturn(hotel);
// When (Cuando)
ResponseEntity<Hotel> responseEntity = hotelController.obtenerHotel(h... |
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
Entry entry = null;
try {
entry = SphU.entry(resourceName, entryType);
// If the SphU.entry() does not throw `BlockException`, it means that the
// request can pass.
return toRun.get();
}
catch (BlockException ex) {
... | @Test
public void testCreateDirectlyThenRun() {
// Create a circuit breaker without any circuit breaking rules.
CircuitBreaker cb = new SentinelCircuitBreaker(
"testSentinelCreateDirectlyThenRunA");
assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel");
assertThat(DegradeRuleManager.hasConfig("testSen... |
@Override
public void finishSink(String dbName, String tableName, List<TSinkCommitInfo> commitInfos, String branch) {
if (commitInfos.isEmpty()) {
LOG.warn("No commit info on {}.{} after hive sink", dbName, tableName);
return;
}
HiveTable table = (HiveTable) getTable(... | @Test
public void testOverwritePartition() throws Exception {
String stagingDir = "hdfs://127.0.0.1:10000/tmp/starrocks/queryid";
THiveFileInfo fileInfo = new THiveFileInfo();
fileInfo.setFile_name("myfile.parquet");
fileInfo.setPartition_path("hdfs://127.0.0.1:10000/tmp/starrocks/qu... |
@VisibleForTesting
String makeUserAgent() {
if (!JibSystemProperties.isUserAgentEnabled()) {
return "";
}
StringBuilder userAgentBuilder = new StringBuilder("jib");
userAgentBuilder.append(" ").append(toolVersion);
userAgentBuilder.append(" ").append(toolName);
if (!Strings.isNullOrEmpt... | @Test
public void testGetUserAgent_unset() throws CacheDirectoryCreationException {
BuildContext buildContext = createBasicTestBuilder().build();
String generatedUserAgent = buildContext.makeUserAgent();
Assert.assertEquals("jib null jib", generatedUserAgent);
} |
@Udf(description = "Converts the number of days since 1970-01-01 00:00:00 UTC/GMT to a date "
+ "string using the given format pattern. The format pattern should be in the format"
+ " expected by java.time.format.DateTimeFormatter")
public String dateToString(
@UdfParameter(
description = ... | @Test
public void shouldThrowIfFormatInvalid() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.dateToString(44444, "invalid")
);
// Then:
assertThat(e.getMessage(), containsString("Failed to format date 44444 with formatter 'invalid'"));
} |
public void export(String resolverPath, String inputPath, File outputDir) throws IOException
{
List<DataSchema> dataSchemas = parseDataSchema(resolverPath, inputPath);
for (DataSchema dataSchema : dataSchemas)
{
writeSnapshotFile(outputDir, ((NamedDataSchema) dataSchema).getFullName(), dataSchema);
... | @Test
public void testExportSnapshot() throws Exception
{
String[] expectedFiles = new String[]
{
"BirthInfo.pdl",
"FullName.pdl",
"Date.pdl"
};
String inputDir = pegasusDir + "com/linkedin/restli/tools/pegasusSchemaSnapshotTest";
PegasusSchemaSnapsho... |
public static <X extends Throwable> void isTrue(boolean expression, Supplier<? extends X> supplier) throws X {
if (false == expression) {
throw supplier.get();
}
} | @Test
public void isTrueTest3() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
int i = -1;
//noinspection ConstantConditions
Assert.isTrue(i > 0, () -> new IndexOutOfBoundsException("relation message to return"));
});
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchDisconnected() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0), true);
consumerClient.poll(time.ti... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void renameNestedFields() {
Schema nestedSchema = Schema.builder().addStringField("field1").addInt32Field("field2").build();
Schema schema =
Schema.builder().addStringField("field1").addRowField("nested", nestedSchema).build();
PCollection<Row> renamed ... |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_inlineArray() {
Row beamRow = BigQueryUtils.toBeamRow(ARRAY_TYPE, BQ_INLINE_ARRAY_ROW);
assertEquals(ARRAY_ROW, beamRow);
} |
public static long convertTimeUnitValueToSecond(long value, TimeUnit unit) {
return TimeUnit.SECONDS.convert(value, unit);
} | @Test
public void testConvertTimeUnitValuetoSecond() {
long dayRes = TimeUtils.convertTimeUnitValueToSecond(2, TimeUnit.DAYS);
long hourRes = TimeUtils.convertTimeUnitValueToSecond(2, TimeUnit.HOURS);
long minuteRes = TimeUtils.convertTimeUnitValueToSecond(2, TimeUnit.MINUTES);
long ... |
public static Boolean judge(final ConditionData conditionData, final String realData) {
if (Objects.isNull(conditionData) || StringUtils.isBlank(conditionData.getOperator())) {
return false;
}
PredicateJudge predicateJudge = newInstance(conditionData.getOperator());
if (!(pre... | @Test
public void testConditionDataIsNull() {
assertFalse(PredicateJudgeFactory.judge(null, "testRealData"));
} |
public static Map<String, ResourceModel> buildResourceModels(final Set<Class<?>> restliAnnotatedClasses)
{
Map<String, ResourceModel> rootResourceModels = new HashMap<>();
Map<Class<?>, ResourceModel> resourceModels = new HashMap<>();
for (Class<?> annotatedClass : restliAnnotatedClasses)
{
pro... | @Test(dataProvider = "resourcesWithNoClashingNamesDataProvider")
public void testResourceNameNoClash(Class<?>[] classes)
{
Set<Class<?>> resourceClasses = new HashSet<>(Arrays.asList(classes));
Map<String, ResourceModel> resourceModels = RestLiApiBuilder.buildResourceModels(resourceClasses);
Assert.asse... |
@Override
public void configure(Map<String, ?> configs) {
final SimpleConfig simpleConfig = new SimpleConfig(CONFIG_DEF, configs);
final String field = simpleConfig.getString(FIELD_CONFIG);
final String type = simpleConfig.getString(TARGET_TYPE_CONFIG);
String formatPattern = simpleC... | @Test
public void testConfigInvalidFormat() {
Map<String, String> config = new HashMap<>();
config.put(TimestampConverter.TARGET_TYPE_CONFIG, "string");
config.put(TimestampConverter.FORMAT_CONFIG, "bad-format");
assertThrows(ConfigException.class, () -> xformValue.configure(config))... |
@Override
public CurrentStateInformation trigger(MigrationStep step, Map<String, Object> args) {
context.setCurrentStep(step);
if (Objects.nonNull(args) && !args.isEmpty()) {
context.addActionArguments(step, args);
}
String errorMessage = null;
try {
s... | @Test
public void smPassesArgumentsToAction() {
StateMachine<MigrationState, MigrationStep> stateMachine = testStateMachineWithAction((context) -> {
assertThat(context.getActionArgument("arg1", String.class)).isEqualTo("v1");
assertThat(context.getActionArgument("arg2", Integer.class... |
@Override
public void doRun() {
if (isServerInPreflightMode.get()) {
// we don't want to automatically trigger CSRs during preflight, don't run it if the preflight is still not finished or skipped
LOG.debug("Datanode still in preflight mode, skipping cert renewal task");
... | @Test
void testAlreadyExpired() throws Exception {
final DatanodeKeystore datanodeKeystore = datanodeKeystore(Duration.ofNanos(1));
final CsrRequester csrRequester = Mockito.mock(CsrRequester.class);
final DataNodeCertRenewalPeriodical periodical = new DataNodeCertRenewalPeriodical(
... |
@SuppressWarnings("unchecked")
public <T extends Expression> T rewrite(final T expression, final C context) {
return (T) rewriter.process(expression, context);
} | @Test
public void shouldRewriteArithmeticUnary() {
// Given:
final ArithmeticUnaryExpression parsed = parseExpression("-(1)");
when(processor.apply(parsed.getValue(), context)).thenReturn(expr1);
// When:
final Expression rewritten = expressionRewriter.rewrite(parsed, context);
// Then:
... |
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) {
List<String> diagramLines = filterOutComments(rawDiagramLines);
Set<PlantUmlComponent> components = parseComponents(diagramLines);
PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components);
List<Parse... | @Test
public void ignores_components_that_are_not_yet_defined() {
File file = TestDiagram.in(temporaryFolder)
.dependencyFrom("[NotYetDefined]").to("[AlsoNotYetDefined]")
.write();
PlantUmlDiagram diagram = createDiagram(file);
assertThat(diagram.getComponen... |
@Override public long putIfAbsent(long key, long value) {
assert value != nullValue : "putIfAbsent() called with null-sentinel value " + nullValue;
SlotAssignmentResult slot = hsa.ensure(key);
if (slot.isNew()) {
mem.putLong(slot.address(), value);
return nullValue;
... | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void test_putIfAbsent_invalidValue() {
map.putIfAbsent(newKey(), MISSING_VALUE);
} |
public List<Long> list(ListAllPOptions options) {
try (JobMasterAuditContext auditContext =
createAuditContext("list")) {
List<Long> ids = new ArrayList<>();
ids.addAll(mPlanTracker.findJobs(options.getName(),
options.getStatusList().stream()
.map(status -> Status.va... | @Test
public void list() throws Exception {
try (MockedStatic<PlanCoordinator> mockStaticPlanCoordinator = mockPlanCoordinator()) {
TestPlanConfig jobConfig = new TestPlanConfig("/test");
List<Long> jobIdList = new ArrayList<>();
for (long i = 0; i < TEST_JOB_MASTER_JOB_CAPACITY; i++) {
... |
@Override
public T getMetaForStep( Repository rep, IMetaStore metaStore, VariableSpace space )
throws KettleException {
// Note - was a synchronized static method, but as no static variables are manipulated, this is entirely unnecessary
// baseStepMeta.getParentStepMeta() or getParantTransMeta() is only ... | @Test
//A Transformation getting the jobMeta from the filesystem
public void getMetaForStepAsJobFromFileSystemTest() throws Exception {
setupJobExecutorMeta();
specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
MetaFileLoaderImpl metaFileLoader = new MetaFileLoaderImpl<JobMeta>( baseStepM... |
@JsonCreator
public static ModelId of(String id) {
Preconditions.checkArgument(StringUtils.isNotBlank(id), "ID must not be blank");
return new AutoValue_ModelId(id);
} | @Test
public void deserialize() {
final ModelId modelId = ModelId.of("foobar");
final JsonNode jsonNode = objectMapper.convertValue(modelId, JsonNode.class);
assertThat(jsonNode.isTextual()).isTrue();
assertThat(jsonNode.asText()).isEqualTo("foobar");
} |
@Override
public Map<String, String> loadNamespaceMetadata(Namespace namespace)
throws NoSuchNamespaceException {
String databaseName =
IcebergToGlueConverter.toDatabaseName(
namespace, awsProperties.glueCatalogSkipNameValidation());
try {
Database database =
glue.get... | @Test
public void testLoadNamespaceMetadata() {
Map<String, String> parameters = Maps.newHashMap();
parameters.put("key", "val");
parameters.put(IcebergToGlueConverter.GLUE_DB_LOCATION_KEY, "s3://bucket2/db");
Mockito.doReturn(
GetDatabaseResponse.builder()
.database(
... |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test
public void testIndexingDoubleTypeFieldWithNullValues() throws Exception {
mapper.add(new TypeDouble(null));
mapper.add(new TypeDouble(-8.0));
roundTripSnapshot();
HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeDouble", "", "data.value");
Assert.ass... |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_null() {
// 调用,并断言
assertServiceException(() -> oauth2CodeService.consumeAuthorizationCode(randomString()),
OAUTH2_CODE_NOT_EXISTS);
} |
@EventListener
public void handleRedisKeyExpiredEvent(RedisKeyExpiredEvent<EidSession> event) {
if (event.getValue() instanceof EidSession) {
EidSession session = (EidSession) event.getValue();
confirmService.sendError(session.getReturnUrl(), session.getConfirmId(), session.getConfir... | @Test
public void testHandleRedisKeyExpiredEvent() {
EidSession session = new EidSession();
session.setReturnUrl("http://localhost");
session.setId("id");
session.setConfirmId("app_session_id");
session.setConfirmSecret("secret");
Mockito.when(event.getValue()).thenRe... |
@Nullable
@Override
public RoaringBitmap getNullBitmap(ValueBlock valueBlock) {
int length = valueBlock.getNumDocs();
RoaringBitmap result = new RoaringBitmap();
RoaringBitmap mainFunctionNullBitmap = _mainFunction.getNullBitmap(valueBlock);
if (mainFunctionNullBitmap != null) {
result.or(main... | @Test
public void testInTransformFunctionIdentifierNotInAllLiteralValuesThatContainNullReturnsNull() {
String expressionStr =
String.format("%s IN (%s, %s, NULL)", INT_SV_COLUMN, _intSVValues[0] + 1, _intSVValues[0] + 2);
ExpressionContext expression = RequestContextUtils.getExpression(expressionStr);... |
@VisibleForTesting
public void validateNoticeExists(Long id) {
if (id == null) {
return;
}
NoticeDO notice = noticeMapper.selectById(id);
if (notice == null) {
throw exception(NOTICE_NOT_FOUND);
}
} | @Test
public void testValidateNoticeExists_success() {
// 插入前置数据
NoticeDO dbNotice = randomPojo(NoticeDO.class);
noticeMapper.insert(dbNotice);
// 成功调用
noticeService.validateNoticeExists(dbNotice.getId());
} |
@Override
public MailLogDO getMailLog(Long id) {
return mailLogMapper.selectById(id);
} | @Test
public void testGetMailLog() {
// mock 数据
MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> o.setTemplateParams(randomTemplateParams()));
mailLogMapper.insert(dbMailLog);
// 准备参数
Long id = dbMailLog.getId();
// 调用
MailLogDO mailLog = mailLogService... |
public static void environmentInit() throws KettleException {
// Workaround for a Mac OS/X Leopard issue where getContextClassLoader() is returning
// null when run from the eclipse IDE
// http://lists.apple.com/archives/java-dev/2007/Nov/msg00385.html - DM
// Moving this hack to the first place where t... | @Test
public void vfsUserDirIsRoot_IsPublishedOnInitialisation() throws Exception {
EnvUtil.environmentInit();
//See PDI-14522, PDI-14821
// don't check the exact value, because the initialisation depends on local settings
// instead, simply check the value exists
assertNotNull( Variables.getADefa... |
static ControllerResult<Void> recordsForNonEmptyLog(
Consumer<String> activationMessageConsumer,
long transactionStartOffset,
boolean zkMigrationEnabled,
FeatureControlManager featureControl,
MetadataVersion metadataVersion
) {
StringBuilder logMessageBuilder = new St... | @Test
public void testActivationMessageForNonEmptyLogNoMigrations() {
ControllerResult<Void> result;
result = ActivationRecordsGenerator.recordsForNonEmptyLog(
logMsg -> assertEquals("Performing controller activation. No metadata.version feature level " +
"record was fou... |
@CanIgnoreReturnValue
public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
ListMultimap<?, ?> extra = difference(actual, expectedMult... | @Test
public void containsExactlyRespectsDuplicatesFailure() {
ImmutableListMultimap<Integer, String> actual =
ImmutableListMultimap.of(3, "one", 3, "two", 3, "one", 4, "five", 4, "five");
ImmutableSetMultimap<Integer, String> expected = ImmutableSetMultimap.copyOf(actual);
expectFailureWhenTesti... |
public void ensureCapacity(@NonNegative long maximumSize) {
requireArgument(maximumSize >= 0);
int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1);
if ((table != null) && (table.length >= maximum)) {
return;
}
table = new long[Math.max(Caffeine.ceilingPowerOfTwo(maximum), 8)];
... | @Test(dataProvider = "sketch", groups = "isolated")
public void ensureCapacity_maximum(FrequencySketch<Integer> sketch) {
int size = Integer.MAX_VALUE / 10 + 1;
sketch.ensureCapacity(size);
assertThat(sketch.sampleSize).isEqualTo(Integer.MAX_VALUE);
assertThat(sketch.table).hasLength(Caffeine.ceilingP... |
@Override
public void asyncRequest(Request request, final RequestCallBack requestCallBack) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
//set callback .
Futures... | @Test
void testAsyncRequestWithCancelException() throws NacosException, ExecutionException, InterruptedException {
when(future.get()).thenThrow(new CancellationException("test"));
doAnswer(invocationOnMock -> {
((Runnable) invocationOnMock.getArgument(0)).run();
return null;
... |
public W getStateWindow(W window) {
return mapping.get(window);
} | @Test
void testRestoreFromState() throws Exception {
@SuppressWarnings("unchecked")
ListState<Tuple2<TimeWindow, TimeWindow>> mockState = mock(ListState.class);
when(mockState.get())
.thenReturn(
Lists.newArrayList(
new ... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
if (!joinKey.isForeignKey()) {
ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient());
}
final JoinerFactory joinerFactory = new JoinerFactory(
buildContext,
this,
... | @Test
public void shouldPerformStreamToStreamRightJoinWithGracePeriod() {
// Given:
setupStream(left, leftSchemaKStream);
setupStream(right, rightSchemaKStream);
final JoinNode joinNode =
new JoinNode(nodeId, RIGHT, joinKey, true, left, right,
WITHIN_EXPRESSION_WITH_GRACE, "KAFKA"... |
public static List<UpdateRequirement> forReplaceView(
ViewMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid view metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Build... | @Test
public void assignUUIDToView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(
new MetadataUpdate.AssignUUID(viewMetadata.uuid()),
new MetadataUpdate.AssignUUID(UUID.randomUUID().toStr... |
@Override
public boolean isCooperative() {
return doWithClassLoader(context.classLoader(), () -> processor.isCooperative());
} | @Test
public void when_isCooperative_then_true() {
assertTrue(createTasklet().isCooperative());
} |
@Override
public void reportTransaction(GlobalTransaction tx, GlobalStatus globalStatus)
throws TransactionalExecutor.ExecutionException {
try {
tx.globalReport(globalStatus);
triggerAfterCompletion(tx);
} catch (TransactionException txe) {
throw new ... | @Test
public void testReportTransaction() {
MockGlobalTransaction mockGlobalTransaction = new MockGlobalTransaction();
GlobalStatus globalStatus = GlobalStatus.Committed;
Assertions.assertDoesNotThrow(() -> sagaTransactionalTemplate.reportTransaction(mockGlobalTransaction, globalStatus));
... |
public void addColumn(String columnString) {
TemplateColumn column = new DefaultTemplateColumn(templateContainer, columnString);
this.columns.add(column);
} | @Test
public void testAddColumn() {
RuleTemplate rt = new RuleTemplate("rt1", getTemplateContainer());
rt.addColumn("StandardColumn");
rt.addColumn("!NotColumn");
rt.addColumn("ColumnCondition == \"test\"");
rt.addColumn("!NotColumnCondition == \"test2\"");
rt.addColu... |
@Override
public AlterPartitionReassignmentsResult alterPartitionReassignments(
Map<TopicPartition, Optional<NewPartitionReassignment>> reassignments,
AlterPartitionReassignmentsOptions options) {
final Map<TopicPartition, KafkaFutureImpl<Void>> futures = new HashMap<>();
fin... | @Test
public void testAlterPartitionReassignments() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
TopicPartition tp1 = new TopicPartition("A", 0);
TopicPartition tp2 = new TopicPart... |
@VisibleForTesting
String upload(Configuration config, String artifactUriStr)
throws IOException, URISyntaxException {
final URI artifactUri = PackagedProgramUtils.resolveURI(artifactUriStr);
if (!"local".equals(artifactUri.getScheme())) {
return artifactUriStr;
}
... | @Test
void testMissingTargetConf() {
config.removeConfig(KubernetesConfigOptions.LOCAL_UPLOAD_TARGET);
assertThatThrownBy(() -> artifactUploader.upload(config, "local:///tmp/my-artifact.jar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(
... |
public static ParameterizedType iterableOf(Type elementType) {
return parameterizedType(Iterable.class, elementType);
} | @Test
public void createIterableType() {
ParameterizedType type = Types.iterableOf(Person.class);
assertThat(type.getRawType()).isEqualTo(Iterable.class);
assertThat(type.getActualTypeArguments()).isEqualTo(new Type[] {Person.class});
} |
@Override
public CDCJobConfiguration swapToObject(final YamlCDCJobConfiguration yamlConfig) {
List<JobDataNodeLine> jobShardingDataNodes = null == yamlConfig.getJobShardingDataNodes()
? Collections.emptyList()
: yamlConfig.getJobShardingDataNodes().stream().map(JobDataNodeLin... | @Test
void assertSwapToObject() {
YamlCDCJobConfiguration yamlJobConfig = new YamlCDCJobConfiguration();
yamlJobConfig.setJobId("j0302p00007a8bf46da145dc155ba25c710b550220");
yamlJobConfig.setDatabaseName("test_db");
yamlJobConfig.setSchemaTableNames(Arrays.asList("test.t_order", "t_... |
public SchemaMapping map(Schema arrowSchema, MessageType parquetSchema) {
List<TypeMapping> children = map(arrowSchema.getFields(), parquetSchema.getFields());
return new SchemaMapping(arrowSchema, parquetSchema, children);
} | @Test
public void testRepeatedMap() throws IOException {
SchemaMapping map = converter.map(paperArrowSchema, Paper.schema);
Assert.assertEquals("p, s<r<p>, r<p>>, r<s<r<s<p, p>>, p>>", toSummaryString(map));
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testWindowFrameTypeRange()
{
assertFails(INVALID_WINDOW_FRAME, "SELECT array_agg(x) OVER (ORDER BY x RANGE UNBOUNDED FOLLOWING) FROM (VALUES 1) T(x)");
assertFails(INVALID_WINDOW_FRAME, "SELECT array_agg(x) OVER (ORDER BY x RANGE BETWEEN UNBOUNDED FOLLOWING AND 2 FOLLOWING) FRO... |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void no_event_if_no_raw_measure() {
when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.of(newMeasure()));
when(measureRepository.getRawMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.empty());
underTest.exec... |
@Override
public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) {
ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration());
} | @Test
void assertCheckSQLStatementWithDuplicateReadResourceNames() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getResourceMetaData()).thenReturn(resourceMetaData);
ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class);
... |
public static ListenableFuture<CustomerId> findEntityIdAsync(TbContext ctx, EntityId originator) {
switch (originator.getEntityType()) {
case CUSTOMER:
return Futures.immediateFuture((CustomerId) originator);
case USER:
return toCustomerIdAsync(ctx, ctx.ge... | @Test
public void givenUnsupportedEntityTypes_whenFindEntityIdAsync_thenException() {
for (var entityType : EntityType.values()) {
if (!SUPPORTED_ENTITY_TYPES.contains(entityType)) {
var entityId = EntityIdFactory.getByTypeAndUuid(entityType, UUID.randomUUID());
... |
protected String getServiceConfig(final List<ServiceInstance> instances) {
for (final ServiceInstance inst : instances) {
final Map<String, String> metadata = inst.getMetadata();
if (metadata == null || metadata.isEmpty()) {
continue;
}
final Strin... | @Test
void testBrokenServiceConfig() {
TestableListener listener = resolveServiceAndVerify("test2", "intentionally invalid service config");
NameResolver.ConfigOrError serviceConf = listener.getResult().getServiceConfig();
assertThat(serviceConf).isNotNull();
assertThat(serviceConf.g... |
protected boolean compareVersionRange(String targetVersion) {
return compareVersions(this, targetVersion);
} | @Test
public void testCompareVersionRange() throws CpeValidationException {
VulnerableSoftwareBuilder builder = new VulnerableSoftwareBuilder();
VulnerableSoftware instance = builder.version("2.0.0").build();
assertTrue(instance.compareVersionRange("2.0.0"));
assertFalse(instance.com... |
@VisibleForTesting
String getResources(ContainerInfo container) {
Map<String, Long> allocatedResources = container.getAllocatedResources();
StringBuilder sb = new StringBuilder();
sb.append(getResourceAsString(ResourceInformation.MEMORY_URI,
allocatedResources.get(ResourceInformation.MEMORY_URI))... | @Test
public void testRenderResourcesString() {
CustomResourceTypesConfigurationProvider.
initResourceTypes(ResourceInformation.GPU_URI);
Resource resource = ResourceTypesTestHelper.newResource(
DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES... |
@Override
public int read(byte[] bytesBuffer, int offset, int length) throws IOException {
return readInternal(new ByteArrayTargetBuffer(bytesBuffer, offset), offset, length,
ReadType.READ_INTO_BYTE_ARRAY, mPosition, false);
} | @Test
public void readEmptyFileThroughReadByteBuffer() throws Exception {
int fileSize = 0;
byte[] fileData = BufferUtils.getIncreasingByteArray(fileSize);
ByteArrayCacheManager manager = new ByteArrayCacheManager();
LocalCacheFileInStream stream = setupWithSingleFile(fileData, manager);
byte[] r... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object firstExpected,
@Nullable Object secondExpected,
@Nullable Object @Nullable ... restOfExpected) {
return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected));
} | @Test
public void iterableContainsAtLeast() {
assertThat(asList(1, 2, 3)).containsAtLeast(1, 2);
} |
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (key == null) {
return null;
}
return super.computeIfPresent(key, remappingFunction);
} | @Test
public void testComputeIfPresent() {
Assert.assertEquals(VALUE, map.get(KEY));
Assert.assertEquals(null, map.computeIfAbsent(null, key -> ""));
Assert.assertEquals("", map.computeIfPresent(KEY, (key, value) -> ""));
Assert.assertEquals("", map.get(KEY));
} |
public Path getParent() {
if(this.isRoot()) {
return this;
}
return parent;
} | @Test
public void testGetParent() {
assertEquals(new Path("/b/t", EnumSet.of(Path.Type.directory)), new Path("/b/t/f.type", EnumSet.of(Path.Type.file)).getParent());
} |
@Override
protected Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
try {
final Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
... | @Test
void testComponentOnlyIsDefaultForClasses() throws Exception {
assertThatExceptionOfType(ClassNotFoundException.class)
.isThrownBy(
() -> {
TestUrlClassLoader owner =
new TestUrlClassLoader(
... |
@Bean("Configuration")
public Configuration provide(Settings settings) {
return new ServerConfigurationAdapter(settings);
} | @Test
@UseDataProvider("subsequentCommas1")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_subsequent_commas_as_Settings(String subsequentCommas) {
settings.setProperty(nonDeclaredKey, subsequentCommas);
settings.setProperty(nonMultivalueKey, subsequentCommas);
Configuration... |
@Override
public void beforeJob(JobExecution jobExecution) {
LOG.debug("sending before job execution event [{}]...", jobExecution);
producerTemplate.sendBodyAndHeader(endpointUri, jobExecution, EventType.HEADER_KEY, EventType.BEFORE.name());
LOG.debug("sent before job execution event");
... | @Test
public void shouldSendBeforeJobEvent() throws Exception {
// When
jobExecutionListener.beforeJob(jobExecution);
// Then
assertEquals(jobExecution, consumer().receiveBody("seda:eventQueue"));
} |
@Override
public void register(ProviderConfig config) {
String appName = config.getAppName();
if (!registryConfig.isRegister()) {
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
}
r... | @Test
public void testRegister() {
polaris.getNamingService().addService(new ServiceKey(NAMESPACE, SERVICE));
//register
ProviderConfig<?> providerConfig = providerConfig("polaris-test-1", 12200, 12201, 12202);
registry.register(providerConfig);
//check register
Consu... |
public String[] getCNAMEs() {
if(null == cnames) {
return new String[]{};
}
return cnames;
} | @Test
public void testCnames() {
assertNotNull(new Distribution(Distribution.DOWNLOAD, false).getCNAMEs());
} |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
authorizationService.validate();
} | @Test(expected = LoginCanceledException.class)
public void testProjectIdNoAuthorization() throws Exception {
session.getHost().setCredentials(
new Credentials("stellar-perigee-775", "")
);
session.login(new DisabledLoginCallback() {
@Override
public Creden... |
Map<String, Object> sourceProducerConfig(String role) {
Map<String, Object> props = new HashMap<>();
props.putAll(originalsWithPrefix(SOURCE_CLUSTER_PREFIX));
props.keySet().retainAll(MirrorClientConfig.CLIENT_CONFIG_DEF.names());
props.putAll(originalsWithPrefix(PRODUCER_CLIENT_PREFIX))... | @Test
public void testSourceProducerConfig() {
Map<String, String> connectorProps = makeProps(
MirrorConnectorConfig.PRODUCER_CLIENT_PREFIX + "acks", "1"
);
MirrorConnectorConfig config = new TestMirrorConnectorConfig(connectorProps);
Map<String, Object> connectorProd... |
public void matches(@Nullable String regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that matches", regex);
} else if (!actual.matches(regex)) {
if (regex.equals(actual)) {
failWithoutActual(
fact("expected to match", regex),
... | @Test
@GwtIncompatible("Pattern")
public void stringMatchesPatternFailNull() {
expectFailureWhenTestingThat(null).matches(Pattern.compile(".*aaa.*"));
assertFailureValue("expected a string that matches", ".*aaa.*");
} |
@Override
public ChannelFuture writeSettings(ChannelHandlerContext ctx, Http2Settings settings,
ChannelPromise promise) {
outstandingLocalSettingsQueue.add(settings);
try {
Boolean pushEnabled = settings.pushEnabled();
if (pushEnabled != null && connection.isServe... | @Test
public void settingsWriteAfterGoAwayShouldSucceed() throws Exception {
goAwayReceived(0);
ChannelPromise promise = newPromise();
encoder.writeSettings(ctx, new Http2Settings(), promise);
verify(writer).writeSettings(eq(ctx), any(Http2Settings.class), eq(promise));
} |
static <RequestT, ResponseT> Call<RequestT, ResponseT> of(
Caller<RequestT, ResponseT> caller, Coder<ResponseT> responseTCoder) {
caller = SerializableUtils.ensureSerializable(caller);
return new Call<>(
Configuration.<RequestT, ResponseT>builder()
.setCaller(caller)
.setRe... | @Test
public void givenCallerThrowsTimeoutException_emitsFailurePCollection() {
Result<Response> result =
pipeline
.apply(Create.of(new Request("a")))
.apply(Call.of(new CallerThrowsTimeout(), NON_DETERMINISTIC_RESPONSE_CODER));
PCollection<ApiIOError> failures = result.getFai... |
public Predicate convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testNull() {
Predicate result = CONVERTER.convert(null);
Assert.assertNull(result);
} |
public static boolean isS3Url(String prefix) {
return prefix.startsWith("oss://") || prefix.startsWith("s3n://") || prefix.startsWith("s3a://") ||
prefix.startsWith("s3://") || prefix.startsWith("cos://") || prefix.startsWith("cosn://") ||
prefix.startsWith("obs://") || prefix.st... | @Test
public void testIsS3Url() {
Assert.assertTrue(HiveWriteUtils.isS3Url("obs://"));
} |
@Override
protected void copy(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds)
throws IOException {
checkArgument(
srcResourceIds.size() == destResourceIds.size(),
"Number of source files %s must equal number of destination files %s",
srcResourceIds.size()... | @Test
public void testCopyWithExistingSrcFile() throws Exception {
Path srcPath1 = temporaryFolder.newFile().toPath();
Path srcPath2 = temporaryFolder.newFile().toPath();
Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("dest1");
Path destPath2 = srcPath2.resolveS... |
@Override public HashSlotCursor16byteKey cursor() {
return new CursorLongKey2();
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testCursor_valueAddress_withoutAdvance() {
HashSlotCursor16byteKey cursor = hsa.cursor();
cursor.valueAddress();
} |
public static void print(Context context) {
print(context, 0);
} | @Test
public void testBasic() {
Context context = new ContextBase();
context.getStatusManager().add(new InfoStatus("test", this));
StatusPrinter.print(context);
String result = outputStream.toString();
assertTrue(result.contains("|-INFO in "+this.getClass().getName()));
} |
public void removeEdge(V from, V to) {
if (!containsVertex(from)) {
throw new IllegalArgumentException("Nonexistent vertex " + from);
}
if (!containsVertex(to)) {
throw new IllegalArgumentException("Nonexistent vertex " + to);
}
neighbors.get(from).remov... | @Test
void removeEdge() {
graph.removeEdge('B', 'F');
List<Character> result = graph.getNeighbors('B');
List<Character> expected = Arrays.asList('C');
assertEquals(expected, result);
} |
public List<Modification> modifications(ConsoleResult result) {
List<Modification> modifications = new ArrayList<>();
for (String change : result.output()) {
if (!StringUtils.isBlank(change)) {
String description = "";
try {
long revision =... | @Test
void shouldIgnoreBadLinesAndLogThem() {
try (LogFixture logging = logFixtureFor(P4OutputParser.class, Level.DEBUG)) {
final String output = "Change 539921 on 2008/09/24 "
+ "by abc@SomeRefinery_abc_sa1-sgr-xyz-001 'more work in progress on MDC un'\n";
final ... |
void push(SelType obj) {
stack[++top] = obj;
} | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void testPushStackOverflow() {
state.push(SelString.of("foo"));
state.push(SelString.of("foo"));
state.push(SelString.of("foo"));
} |
@Override
protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException {
if(null == digest) {
log.warn("MD5 calculation disabled");
return super.decorate(in, null);
}
else {
return new DigestInputStream(in, digest);
... | @Test
public void testDecorate() throws Exception {
final NullInputStream n = new NullInputStream(1L);
final S3Session session = new S3Session(new Host(new S3Protocol()));
assertSame(NullInputStream.class, new S3SingleUploadService(session,
new S3WriteFeature(session, new S3A... |
@Override
public Long createConfig(ConfigSaveReqVO createReqVO) {
// 校验参数配置 key 的唯一性
validateConfigKeyUnique(null, createReqVO.getKey());
// 插入参数配置
ConfigDO config = ConfigConvert.INSTANCE.convert(createReqVO);
config.setType(ConfigTypeEnum.CUSTOM.getType());
configM... | @Test
public void testCreateConfig_success() {
// 准备参数
ConfigSaveReqVO reqVO = randomPojo(ConfigSaveReqVO.class)
.setId(null); // 防止 id 被赋值,导致唯一性校验失败
// 调用
Long configId = configService.createConfig(reqVO);
// 断言
assertNotNull(configId);
// 校验... |
public static boolean isValidRootUrl(String url) {
UrlValidator validator = new CustomUrlValidator();
return validator.isValid(url);
} | @Test
@Issue("JENKINS-51064")
public void withCustomDomain() {
assertTrue(UrlHelper.isValidRootUrl("http://my-server:8080/jenkins"));
assertTrue(UrlHelper.isValidRootUrl("http://jenkins.internal/"));
assertTrue(UrlHelper.isValidRootUrl("http://jenkins.otherDomain/"));
assertTrue(... |
@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
NAMING_LOGGER.info("{} do shutdown begin", className);
serviceInfoUpdateService.shutdown();
serverListManager.shutdown();
httpClientProxy.shutdown();
grpcClientProxy... | @Test
void testShutdown() throws NacosException {
delegate.shutdown();
verify(mockGrpcClient, times(1)).shutdown();
} |
@Nonnull
public static <K, V> BatchSource<Entry<K, V>> map(@Nonnull String mapName) {
return batchFromProcessor("mapSource(" + mapName + ')', readMapP(mapName));
} | @Test(expected = IllegalStateException.class)
public void when_batchSourceUsedTwice_then_throwException() {
// Given
BatchSource<Entry<Object, Object>> source = Sources.map(srcName);
p.readFrom(source);
// When-Then
p.readFrom(source);
} |
@Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(Envelope.class, this::write);
} | @Test
void ignores_step_definitions() throws Throwable {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
HtmlFormatter formatter = new HtmlFormatter(bytes);
EventBus bus = new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID);
formatter.setEventPublisher(bus);
... |
@VisibleForTesting
DictTypeDO validateDictTypeExists(Long id) {
if (id == null) {
return null;
}
DictTypeDO dictType = dictTypeMapper.selectById(id);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
return dictType;
} | @Test
public void testValidateDictDataExists_success() {
// mock 数据
DictTypeDO dbDictType = randomDictTypeDO();
dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据
// 调用成功
dictTypeService.validateDictTypeExists(dbDictType.getId());
} |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final Credentials credentials = authentication.get();
if(credentials.isAnonymousLogin()) {
if(log.isDebugEnabled()) {
log.debug(String.format("Connect with no... | @Test
public void testInteroperabilityMinio() throws Exception {
final Host host = new Host(new S3Protocol(), "play.min.io", new Credentials(
"Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"
)) {
@Override
public String getProperty(final Stri... |
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 testStateWithFullyFinishedOperators() throws JobException, JobExecutionException {
List<OperatorID> operatorIds = buildOperatorIds(2);
Map<OperatorID, OperatorState> states =
buildOperatorStates(Collections.singletonList(operatorIds.get(1)), 3);
// Create an opera... |
public void createUser(String addr, UserInfo userInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
CreateUserRequestHeader requestHeader = new CreateUserRequestHeader(userInfo.getUsername());
RemotingComm... | @Test
public void testCreateUser() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
mqClientAPI.createUser(defaultBrokerAddr, new UserInfo(), defaultTimeout);
} |
@Override
public Collection<DatabasePacket> execute() {
// TODO consider what severity and error code to use
PostgreSQLErrorResponsePacket packet = PostgreSQLErrorResponsePacket.newBuilder(PostgreSQLMessageSeverityLevel.ERROR, PostgreSQLVendorError.FEATURE_NOT_SUPPORTED,
PostgreSQLVe... | @Test
void assertExecute() {
PostgreSQLUnsupportedCommandExecutor commandExecutor = new PostgreSQLUnsupportedCommandExecutor();
Collection<DatabasePacket> actual = commandExecutor.execute();
assertThat(actual.size(), is(1));
assertThat(actual.iterator().next(), instanceOf(PostgreSQLE... |
@Override
public Collection<String> getHeaderNames() {
return stream.response().getHeaderNames();
} | @Test
public void get_header_names() {
underTest.getHeaderNames();
verify(response).getHeaderNames();
} |
@Override
@Nonnull
public Version getClusterVersion() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void getClusterVersion() {
client().getCluster().getClusterVersion();
} |
@Override
public Object getInitialAggregatedValue(byte[] rawValue) {
Sketch<IntegerSummary> initialValue = deserializeAggregatedValue(rawValue);
Union tupleUnion = new Union<>(_nominalEntries, new IntegerSummarySetOperations(_mode, _mode));
tupleUnion.union(initialValue);
return tupleUnion;
} | @Test
public void initialShouldParseASketch() {
IntegerTupleSketchValueAggregator agg = new IntegerTupleSketchValueAggregator(IntegerSummary.Mode.Sum);
assertEquals(toSketch(agg.getInitialAggregatedValue(sketchContaining("hello world", 1))).getEstimate(), 1.0);
} |
@Override
public float get(int i, int j) {
return A[index(i, j)];
} | @Test
public void testGet() {
System.out.println("get");
assertEquals(0.9f, matrix.get(0, 0), 1E-6f);
assertEquals(0.8f, matrix.get(2, 2), 1E-6f);
assertEquals(0.5f, matrix.get(1, 1), 1E-6f);
assertEquals(0.0f, matrix.get(2, 0), 1E-6f);
assertEquals(0.0f, matrix.get(0... |
@Override
public boolean hasViewPermission(CaseInsensitiveString username, UserRoleMatcher userRoleMatcher, boolean everyoneIsAllowedToViewIfNoAuthIsDefined) {
return this.getAuthorizationPart().hasViewPermission(username, userRoleMatcher, everyoneIsAllowedToViewIfNoAuthIsDefined);
} | @Test
public void shouldUseDefaultPermissionsForViewPermissionIfAuthorizationIsNotDefined_When2ConfigParts() {
BasicPipelineConfigs filePart = new BasicPipelineConfigs();
filePart.setOrigin(new FileConfigOrigin());
MergePipelineConfigs merge = new MergePipelineConfigs(new BasicPipelineConfi... |
public static HostAndPort toHostAndPort(NetworkEndpoint networkEndpoint) {
switch (networkEndpoint.getType()) {
case IP:
return HostAndPort.fromHost(networkEndpoint.getIpAddress().getAddress());
case IP_PORT:
return HostAndPort.fromParts(
networkEndpoint.getIpAddress().getAdd... | @Test
public void toHostAndPort_withHostname_returnsHostWithHostname() {
NetworkEndpoint hostnameEndpoint =
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.HOSTNAME)
.setHostname(Hostname.newBuilder().setName("localhost"))
.build();
assertThat(NetworkEndp... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void retryOnNonAbortedRequests() {
HttpGet request = new HttpGet("/");
assertThat(retryStrategy.retryRequest(request, new IOException(), 1, null)).isTrue();
} |
@Override
public Authenticator create(KeycloakSession session) {
logger.info("Trying to create {} via factory.", this.getClass().getSimpleName());
return SINGLETON;
} | @Test
public void testCreateMethod() {
KeycloakSession session = mock(KeycloakSession.class);
Authenticator authenticator = factory.create(session);
assertTrue(authenticator instanceof IndividualEdsLoginAuthenticator, "The created Authenticator is not an instance of IndividualEdsLoginAuthent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.