focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
} | @Test
public void when_attachDuplicateFileWithPath_then_throwsException() throws Exception {
// Given
String resourceId = "resource";
String path1 = createFile("path/to/" + resourceId).toString();
String path2 = createFile("path/to/another/" + resourceId).toString();
config.a... |
@Override
public int serializePartitionKV(DataOutputStream out, int partitionId,
SizedWritable<?> key, SizedWritable<?> value)
throws IOException {
if (key.length == SizedWritable.INVALID_LENGTH ||
value.length == SizedWritable.INVALID_LENGTH) {
updateLength(key, value);
}
fina... | @Test
public void testSerializePartitionKV() throws IOException {
final DataOutputStream dataOut = Mockito.mock(DataOutputStream.class);
Mockito.when(dataOut.hasUnFlushedData()).thenReturn(true);
Mockito.when(
dataOut
.shortOfSpace(key.length + value.length +
Constan... |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void duplicateKey() {
ConstraintViolationException exception = assertThrows(
ConstraintViolationException.class,
() -> this.parse("flows/invalids/duplicate-key.yaml")
);
assertThat(exception.getConstraintViolations().size(), is(1));
assertThat(new Array... |
public Map<TaskId, Long> getTaskOffsetSums() {
final Map<TaskId, Long> taskOffsetSums = new HashMap<>();
// Not all tasks will create directories, and there may be directories for tasks we don't currently own,
// so we consider all tasks that are either owned or on disk. This includes stateless... | @Test
public void shouldComputeOffsetSumForRunningStatefulTaskAndRestoringTaskWithStateUpdater() {
final StreamTask runningStatefulTask = statefulTask(taskId00, taskId00ChangelogPartitions)
.inState(State.RUNNING).build();
final StreamTask restoringStatefulTask = statefulTask(taskId01, t... |
List<AlternativeInfo> calcAlternatives(final int s, final int t) {
// First, do a regular bidirectional route search
checkAlreadyRun();
init(s, 0, t, 0);
runAlgo();
final Path bestPath = extractPath();
if (!bestPath.isFound()) {
return Collections.emptyList();... | @Test
public void testCalcAlternatives() {
BaseGraph g = createTestGraph(em);
PMap hints = new PMap();
hints.putObject("alternative_route.max_weight_factor", 2.3);
hints.putObject("alternative_route.local_optimality_factor", 0.5);
hints.putObject("alternative_route.max_paths"... |
public CreateTableCommand createTableCommand(
final KsqlStructuredDataOutputNode outputNode,
final Optional<RefinementInfo> emitStrategy
) {
Optional<WindowInfo> windowInfo =
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo();
if (windowInfo.isPresent() && emitStrategy.isPresent()) ... | @Test
public void shouldNotThrowWhenThereAreElementsInCreateTable() {
// Given:
final CreateTable statement =
new CreateTable(SOME_NAME, TABLE_ELEMENTS_1_VALUE,
false, true, withProperties, false);
// When:
createSourceFactory.createTableCommand(statement, ksqlConfig);
// The... |
@Override
public void startScheduling() {
final Set<SchedulingPipelinedRegion> sourceRegions =
IterableUtils.toStream(schedulingTopology.getAllPipelinedRegions())
.filter(this::isSourceRegion)
.collect(Collectors.toSet());
maybeSchedule... | @Test
void testSchedulingRegionWithInnerNonPipelinedEdge() throws Exception {
final JobVertex v1 = createJobVertex("v1", 1);
final JobVertex v2 = createJobVertex("v2", 1);
final JobVertex v3 = createJobVertex("v3", 1);
final JobVertex v4 = createJobVertex("v4", 1);
final JobV... |
public TopicList getHasUnitSubUnUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST, null);
RemotingCo... | @Test
public void assertGetHasUnitSubUnUnitTopicList() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
TopicList responseBody = new TopicList();
responseBody.getTopicList().add(defaultTopic);
setResponseBody(responseBody);
TopicList actua... |
public void heartbeat(InstanceHeartbeatRequest heartbeatRequest) {
heartbeatExecutor.scheduleWithFixedDelay(() -> {
try {
// If the health check passes, the heartbeat will be reported.
// If it does not pass, the heartbeat will not be reported.
Map<String, String> headers = new HashMap<>(1);
header... | @Test
void testHeartbeat() {
this.contextRunner2.run(context -> {
PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class);
PolarisRegistration registration = Mockito.mock(PolarisRegistration.class);
when(registration.getHost()).thenReturn("127.0.0.1");
when(registration.getPort())... |
public static void hookPendingIntentGetForegroundService(PendingIntent pendingIntent, Context context, int requestCode, Intent intent, int flags) {
hookPendingIntent(intent, pendingIntent);
} | @Test
public void hookPendingIntentGetForegroundService() {
PushAutoTrackHelper.hookPendingIntentGetForegroundService(MockDataTest.mockPendingIntent(), mApplication, 100, null, 100);
} |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNonEmpty_Collection_bothNullFirst_FieldAndParentIsNonEmptyMultiResult_nullValueFirst_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", null, new InnerObject("inner", null, 0, 1, 2, 3));
Getter parentG... |
public synchronized @Nullable WorkItemServiceState reportUpdate(
@Nullable DynamicSplitResult dynamicSplitResult, Duration requestedLeaseDuration)
throws Exception {
checkState(worker != null, "setWorker should be called before reportUpdate");
checkState(!finalStateSent, "cannot reportUpdates after ... | @Test
public void reportUpdate() throws Exception {
when(worker.extractMetricUpdates()).thenReturn(Collections.emptyList());
statusClient.setWorker(worker, executionContext);
statusClient.reportUpdate(null, LEASE_DURATION);
verify(workUnitClient).reportWorkItemStatus(statusCaptor.capture());
Work... |
public static Optional<KsqlAuthorizationValidator> create(
final KsqlConfig ksqlConfig,
final ServiceContext serviceContext,
final Optional<KsqlAuthorizationProvider> externalAuthorizationProvider
) {
final Optional<KsqlAccessValidator> accessValidator = getAccessValidator(
ksqlConfig,
... | @Test
public void shouldReturnEmptyValidatorIfKafkaBrokerVersionTooLowButAuthorizerClassConfigIsSet() {
// Given:
givenSingleNode();
givenAuthorizerClass("a-class");
when(adminClient.describeCluster(any())).thenThrow(new UnsupportedVersionException("too old"));
// When:
final Optional<KsqlAut... |
public static Field[] getFields(Class<?> beanClass) throws SecurityException {
Assert.notNull(beanClass);
return FIELDS_CACHE.computeIfAbsent(beanClass, () -> getFieldsDirectly(beanClass, true));
} | @Test
public void getFieldsTest() {
// 能够获取到父类字段
final Field[] fields = ReflectUtil.getFields(TestSubClass.class);
assertEquals(4, fields.length);
} |
@Override
public ResultSet getProcedureColumns(final String catalog, final String schemaPattern, final String procedureNamePattern, final String columnNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getProcedureColumns(getActualCatalog(catalog), getActualSchem... | @Test
void assertGetProcedureColumns() throws SQLException {
when(databaseMetaData.getProcedureColumns("test", null, null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getProcedureColumns("test", null, null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
Record deserialize(Object data) {
return (Record) fieldDeserializer.value(data);
} | @Test
public void testNullDeserialize() {
Deserializer deserializer = new Deserializer.Builder()
.schema(HiveIcebergTestUtils.FULL_SCHEMA)
.writerInspector((StructObjectInspector) IcebergObjectInspector.create(HiveIcebergTestUtils.FULL_SCHEMA))
.sourceInspector(HiveIcebergTestUtils.FULL_SC... |
public Result runIndexOrPartitionScanQueryOnOwnedPartitions(Query query) {
Result result = runIndexOrPartitionScanQueryOnOwnedPartitions(query, true);
assert result != null;
return result;
} | @Test
public void verifyFullScanFailureWhileMigratingInFlight() {
EqualPredicate predicate = new EqualPredicate("this", value) {
@Override
protected boolean applyForSingleAttributeValue(Comparable attributeValue) {
// start a new migration while executing a full scan
... |
public void parse(InputStream inputStream, ContentHandler contentHandler, Metadata metadata,
ParseContext parseContext) throws IOException, SAXException, TikaException {
if (!initialized) {
initialize(parseContext);
}
if (!available) {
return;
... | @Test
public void testParse() throws Exception {
//test config is added to resources directory
try (InputStream is = getResourceAsStream(CONFIG_FILE)) {
TikaConfig config = new TikaConfig(is);
Tika tika = new Tika(config);
String text = "I am student at Universit... |
@Override
public void subscribe(String serviceName, EventListener listener) throws NacosException {
subscribe(serviceName, new ArrayList<>(), listener);
} | @Test
void testSubscribe2() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
EventListener listener = event -> {
};
//when
client.subscribe(serviceName, groupName, listener);
NamingSelectorWrapper w... |
@Override
public String getName() {
return "Python Package Analyzer";
} | @Test
public void testAnalyzeSourceMetadata() throws AnalysisException {
boolean found = false;
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "python/eggtest/__init__.py"));
analyzer.analyze(result, null);
assertTrue("Expected vendor evide... |
@Override
public FileEntity upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
if(status.getLength() > 0) {
return new BrickUploadFeature(session,... | @Test
public void testUpload() throws Exception {
final BrickThresholdUploadFeature feature = new BrickThresholdUploadFeature(session);
final Path root = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final String name = new AlphanumericRandomStringService().random();
... |
@SuppressWarnings("unchecked")
protected Class<? extends OptionalParameter> determineTypeClass(Tag tag)
throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
// we have to use reflection because the type field is private
Field f = tag.getClass... | @Test
public void determineTypeClass() throws Exception {
assertSame(OptionalParameter.Source_subaddress.class, command.determineTypeClass(Tag.SOURCE_SUBADDRESS));
assertSame(OptionalParameter.Additional_status_info_text.class,
command.determineTypeClass(Tag.ADDITIONAL_STATUS_INFO_TE... |
public static void stringNotEmptyAndThenExecute(String source, Runnable runnable) {
if (StringUtils.isNotEmpty(source)) {
try {
runnable.run();
} catch (Exception e) {
LogUtils.NAMING_LOGGER.error("string not empty and then execute ca... | @Test
void testStringNotEmptyAndThenExecuteFail() {
String word = "";
Runnable task = Mockito.mock(Runnable.class);
TemplateUtils.stringNotEmptyAndThenExecute(word, task);
Mockito.verify(task, Mockito.times(0)).run();
} |
@CanIgnoreReturnValue
public GsonBuilder setStrictness(Strictness strictness) {
this.strictness = Objects.requireNonNull(strictness);
return this;
} | @Test
public void testSetStrictness() throws IOException {
final Strictness STRICTNESS = Strictness.STRICT;
GsonBuilder builder = new GsonBuilder();
builder.setStrictness(STRICTNESS);
Gson gson = builder.create();
assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness()).isEqualTo(STR... |
@Operation(summary = "start Id check with the wid checker app", tags = { SwaggerConfig.WIDCHECKER_RAISE_TO_SUB }, operationId = "id_check_with_wid_checker_start",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")})
... | @Test
void validateIfCorrectProcessesAreCalledStartIdCheckWithWidchecker() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
AppSessionRequest request = new AppSessionRequest();
activationController.startIdCheckWithWid... |
public static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return !hasUnsafe() || !unalignedAccess() ?
ConstantTimeUtils.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) :
PlatformDependent0.equalsConstantTim... | @Test
public void testEqualsConsistentTime() {
testEquals(new EqualityChecker() {
@Override
public boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return PlatformDependent.equalsConstantTime(bytes1, startPos1, bytes2, startPos2... |
@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 testSetOptionAsFloat()
throws Exception {
Properties props = new Properties();
props.put(QueryOptionKey.USE_MULTISTAGE_ENGINE, "2.5");
PinotConnection pinotConnection =
new PinotConnection(props, "dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTransport);... |
@UdafFactory(description = "Compute sample standard deviation of column with type Integer.",
aggregateSchema = "STRUCT<SUM integer, COUNT bigint, M2 double>")
public static TableUdaf<Integer, Struct, Double> stdDevInt() {
return getStdDevImplementation(
0,
STRUCT_INT,
(agg, newValue)... | @Test
public void shouldIgnoreNull() {
final TableUdaf<Integer, Struct, Double> udaf = stdDevInt();
Struct agg = udaf.initialize();
final Integer[] values = new Integer[] {60, 64, 70};
for (final int thisValue : values) {
agg = udaf.aggregate(thisValue, agg);
}
agg = udaf.aggregate(null,... |
UriEndpoint createUriEndpoint(String url, boolean isWs) {
return createUriEndpoint(url, isWs, connectAddress);
} | @Test
void createUriEndpointRelativeSslSupport() {
String test1 = this.builder.sslSupport()
.build()
.createUriEndpoint("/foo", false)
.toExternalForm();
String test2 = this.builder.sslSupport()
.build()
.createUriEndpoint("/foo", true)
.toExternalForm();
assertThat(test1).isEqualTo("htt... |
public WorkProcessor<Page> merge(List<Type> keyTypes, List<Type> allTypes, List<WorkProcessor<Page>> pages, DriverYieldSignal driverYieldSignal)
{
return merge(keyTypes, null, allTypes, pages, driverYieldSignal);
} | @Test
public void testBinaryMergeIteratorOverPageWithDifferentHashes()
{
Page page = rowPagesBuilder(BIGINT)
.row(42)
.row(42)
.row(52)
.row(60)
.build().get(0);
WorkProcessor<Page> mergedPages = new MergeHashSort(n... |
@VisibleForTesting
static Configuration getConfiguration() {
Configuration conf = new HdfsConfiguration();
conf.addResource(FedBalance.FED_BALANCE_DEFAULT_XML);
conf.addResource(FedBalance.FED_BALANCE_SITE_XML);
return conf;
} | @Test
public void testDefaultConfigs() {
Configuration configuration = DFSRouter.getConfiguration();
String journalUri =
configuration.get(FedBalanceConfigs.SCHEDULER_JOURNAL_URI);
int workerThreads =
configuration.getInt(FedBalanceConfigs.WORK_THREAD_NUM, -1);
Assert.assertEquals("hdf... |
public boolean messageOffsetOnly() {
return segmentBaseOffset == UNIFIED_LOG_UNKNOWN_OFFSET && relativePositionInSegment == UNKNOWN_FILE_POSITION;
} | @Test
void testMessageOffsetOnly() {
LogOffsetMetadata metadata1 = new LogOffsetMetadata(1L);
LogOffsetMetadata metadata2 = new LogOffsetMetadata(1L, 0L, 1);
assertTrue(UNKNOWN_OFFSET_METADATA.messageOffsetOnly());
assertFalse(metadata2.messageOffsetOnly());
assertTrue(metada... |
public List<PartitionAssignment> assignments() {
return assignments;
} | @Test
public void testTopicAssignmentReplicas() {
List<Integer> replicasP0 = Arrays.asList(0, 1, 2);
List<Integer> replicasP1 = Arrays.asList(1, 2, 0);
List<PartitionAssignment> partitionAssignments = Arrays.asList(
partitionAssignment(replicasP0),
partitionAssignment... |
public static <T extends Serializable> SerializableCoder<T> of(TypeDescriptor<T> type) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) type.getRawType();
return new SerializableCoder<>(clazz, type);
} | @Test
public <T extends Serializable> void testSerializableCoderIsSerializableWithGenericTypeToken()
throws Exception {
SerializableCoder<T> coder = SerializableCoder.of(new TypeDescriptor<T>() {});
CoderProperties.coderSerializable(coder);
} |
public static NormalKey createFromSpec(String spec) {
if (spec == null || !spec.contains(":")) {
throw new IllegalArgumentException("Invalid spec format");
}
String[] parts = spec.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid... | @Test
public void testCreateFromSpec_InvalidBase64Key() {
assertThrows(IllegalArgumentException.class, () -> {
NormalKey.createFromSpec("AES_128:invalid_base64");
});
} |
public static TriState from(String booleanLike) {
if (StringUtils.isBlank(booleanLike)) {
return UNSET;
}
if (booleanLike.equalsIgnoreCase("false")) {
return FALSE;
}
if (booleanLike.equalsIgnoreCase("true")) {
return TRUE;
}
th... | @Test
public void testBadStringShouldRaiseError() {
assertThrows(IllegalArgumentException.class, () -> TriState.from("foo"));
} |
static JobVertexInputInfo computeVertexInputInfoForPointwise(
int sourceCount,
int targetCount,
Function<Integer, Integer> numOfSubpartitionsRetriever,
boolean isDynamicGraph) {
final List<ExecutionVertexInputInfo> executionVertexInputInfos = new ArrayList<>();
... | @Test
void testComputeVertexInputInfoForPointwiseWithNonDynamicGraph() {
final JobVertexInputInfo jobVertexInputInfo =
computeVertexInputInfoForPointwise(2, 3, ignored -> 3, false);
assertThat(jobVertexInputInfo.getExecutionVertexInputInfos())
.containsExactlyInAnyOrd... |
@Override
public ApplicationId
submitApplication(ApplicationSubmissionContext appContext)
throws YarnException, IOException {
ApplicationId applicationId = appContext.getApplicationId();
if (applicationId == null) {
throw new ApplicationIdNotProvidedException(
"ApplicationId is... | @Test
public void testAutomaitcLogAggregationDelegationToken()
throws Exception {
Configuration conf = getConf();
SecurityUtil.setAuthenticationMethod(
UserGroupInformation.AuthenticationMethod.KERBEROS, conf);
conf.set(YarnConfiguration.RM_PRINCIPAL, YARN_RM);
String remoteRootLogPath =... |
@Override
public Table getTable(String dbName, String tblName) {
TableIdentifier identifier = TableIdentifier.of(dbName, tblName);
if (tables.containsKey(identifier)) {
return tables.get(identifier);
}
try {
org.apache.iceberg.Table icebergTable = icebergCata... | @Test
public void testNotExistTable(@Mocked IcebergHiveCatalog icebergHiveCatalog,
@Mocked HiveTableOperations hiveTableOperations) {
new Expectations() {
{
icebergHiveCatalog.getTable("db", "tbl");
result = new BaseTable(hiveTabl... |
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
writer.keyword("CREATE");
if (getReplace()) {
writer.keyword("OR REPLACE");
}
writer.keyword("EXTERNAL MAPPING");
if (ifNotExists) {
writer.keyword("IF NOT EXISTS");
... | @Test
public void test_unparse() {
Mapping mapping = new Mapping(
"name",
"external-name",
null,
"Type",
null,
asList(
new MappingField("field1", QueryDataType.VARCHAR, "__key.field1"),
... |
public void addIfValid(String headerName, String value) {
Objects.requireNonNull(headerName, "headerName");
Objects.requireNonNull(value, "value");
if (isValid(headerName) && isValid(value)) {
String normalName = HeaderName.normalize(headerName);
addNormal(headerName, nor... | @Test
void addIfValid() {
Headers headers = new Headers();
headers.addIfValid("Via", "duct");
headers.addIfValid("Cookie", "abc=def");
headers.addIfValid("cookie", "uvw=xyz");
Truth.assertThat(headers.getAll("Via")).containsExactly("duct");
Truth.assertThat(headers.g... |
@JsonCreator
public static ContentPackInstallationRequest create(
@JsonProperty("parameters") @Nullable Map<String, ValueReference> parameters,
@JsonProperty("comment") @Nullable String comment) {
final Map<String, ValueReference> parameterMap = parameters == null ? Collections.empty... | @Test
public void testSerialisation() {
final ImmutableMap<String, ValueReference> parameters = ImmutableMap.of(
"param1", ValueReference.of("string"),
"param2", ValueReference.of(42),
"param3", ValueReference.of(3.14d),
"param4", ValueReferenc... |
@Override
public boolean isAvailable() {
return sonarRuntime.getEdition() == ENTERPRISE || sonarRuntime.getEdition() == DATACENTER;
} | @Test
@UseDataProvider("editionsAndMultipleAlmAvailability")
public void isEnabled_shouldOnlyBeEnabledInEnterpriseEditionPlus(SonarEdition edition, boolean shouldBeEnabled) {
when(sonarRuntime.getEdition()).thenReturn(edition);
boolean isAvailable = underTest.isAvailable();
assertThat(isAvailable).isE... |
@Override
public UndoLogDeleteRequestProto convert2Proto(UndoLogDeleteRequest undoLogDeleteRequest) {
final short typeCode = undoLogDeleteRequest.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNumber(type... | @Test
public void convert2Proto() {
UndoLogDeleteRequest undoLogDeleteRequest = new UndoLogDeleteRequest();
undoLogDeleteRequest.setBranchType(BranchType.AT);
undoLogDeleteRequest.setResourceId(RESOURCE_ID);
undoLogDeleteRequest.setSaveDays(SAVE_DAYS);
UndoLogDeleteRequestC... |
@Override
@PublicAPI(usage = ACCESS)
public Set<? extends JavaAnnotation<JavaPackage>> getAnnotations() {
return packageInfo
.map(it -> it.getAnnotations().stream().map(withSelfAsOwner).collect(toSet()))
.orElse(emptySet());
} | @Test
public void test_getAnnotations() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
JavaAnnotation<JavaPackage> annotation = getOnlyElement(annotatedPackage.getAnnotations());
assert... |
public static ByteBuf copiedBuffer(byte[] array) {
if (array.length == 0) {
return EMPTY_BUFFER;
}
return wrappedBuffer(array.clone());
} | @Test
public void testCopiedBuffer() {
ByteBuf copied = copiedBuffer(ByteBuffer.allocateDirect(16));
assertEquals(16, copied.capacity());
copied.release();
assertEqualsAndRelease(wrappedBuffer(new byte[] { 1, 2, 3 }),
copiedBuffer(new byte[][] { new byte[] { 1, 2, 3 ... |
@Override public Table alterTable(String catName, String dbName, String tblName, Table newTable, String validWriteIds)
throws InvalidObjectException, MetaException {
newTable = rawStore.alterTable(catName, dbName, tblName, newTable, validWriteIds);
// in case of event based cache update, cache will be upd... | @Test public void testAlterTable() throws Exception {
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true);
MetastoreConf.setVar(conf, MetastoreConf.ConfVars.CACHED_RAW_STORE_MAX_CACHE_MEMORY, "-1Kb");
MetaStoreTestUtils.setConf... |
@Operation(summary = "Start the process and generate the session ids")
@PostMapping(value = "new", consumes = "application/json", produces = "application/json")
public StartProcessResponse startProcessRestService(@Valid @RequestBody StartProcessRequest request) {
StartProcessResponse response = new Star... | @Test
public void testStartProcessRestService() {
StartProcessRequest request = new StartProcessRequest();
request.setReturnUrl("http://localhost");
request.setConfirmId("confirmId");
// the test
StartProcessResponse response = controller.startProcessRestService(request);
... |
@Override
public SchemaAndValue get(final ProcessingLogConfig config) {
final Struct struct = new Struct(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA)
.put(ProcessingLogMessageSchema.TYPE, MessageType.DESERIALIZATION_ERROR.getTypeId())
.put(ProcessingLogMessageSchema.DESERIALIZATION_ERROR, des... | @Test
public void shouldSetNullRecordToNull() {
// Given:
final DeserializationError deserError = new DeserializationError(
error,
Optional.empty(),
"topic",
false
);
// When:
final SchemaAndValue msg = deserError.get(config);
// Then:
final Struct struct ... |
@Override
public boolean match(Message msg, StreamRule rule) {
Object rawField = msg.getField(rule.getField());
if (rawField == null) {
return rule.getInverted();
}
if (rawField instanceof String) {
String field = (String) rawField;
Boolean resul... | @Test
public void testInvertedBasicNonMatch() throws Exception {
StreamRule rule = getSampleRule();
rule.setField("nonexistentField");
rule.setType(StreamRuleType.PRESENCE);
rule.setInverted(true);
Message message = getSampleMessage();
StreamRuleMatcher matcher = ge... |
public static boolean isValidRootUrl(String url) {
UrlValidator validator = new CustomUrlValidator();
return validator.isValid(url);
} | @Test
public void ipv4Allowed() {
assertTrue(UrlHelper.isValidRootUrl("http://172.52.125.12"));
assertTrue(UrlHelper.isValidRootUrl("http://172.52.125.12/jenkins"));
assertTrue(UrlHelper.isValidRootUrl("http://172.52.125.12:8080"));
assertTrue(UrlHelper.isValidRootUrl("http://172.52.... |
public static Type getArrayElementType(Type type) {
return GenericTypeReflector.getArrayComponentType(type);
} | @Test
public void getArrayElementType() {
assertThat(Reflection.getArrayElementType(int[].class)).isEqualTo(int.class);
assertThat(Reflection.getArrayElementType(Person[].class)).isEqualTo(Person.class);
var containerOfPerson = Types.parameterizedType(Container.class, Person.class);
assertThat(Reflec... |
public void setInputChannels(InputChannel... channels) {
if (channels.length != numberOfInputChannels) {
throw new IllegalArgumentException(
"Expected "
+ numberOfInputChannels
+ " channels, "
+ "... | @Test
void testPartitionNotFoundExceptionWhileGetNextBuffer() throws Exception {
final SingleInputGate inputGate = InputChannelTestUtils.createSingleInputGate(1);
final LocalInputChannel localChannel =
createLocalInputChannel(inputGate, new ResultPartitionManager());
final Re... |
String getUrl() {
return "http://" + this.httpServer.getInetAddress().getHostAddress() + ":" + this.httpServer.getLocalPort();
} | @Test
public void return_http_response_with_code_500_and_exception_message_as_body_when_action_throws_exception() throws IOException {
Response response = call(underTest.getUrl() + "/failing");
assertThat(response.code()).isEqualTo(500);
assertThat(response.body().string()).isEqualTo(FAILING_ACTION.getMe... |
@Override
public boolean contains(String word) {
return dict.contains(word);
} | @Test
public void testContains() {
System.out.println("contains");
assertTrue(EnglishPunctuations.getInstance().contains("["));
assertTrue(EnglishPunctuations.getInstance().contains("]"));
assertTrue(EnglishPunctuations.getInstance().contains("("));
assertTrue(EnglishPunctuat... |
public float toFloat(String name) {
return toFloat(name, 0.0f);
} | @Test
public void testToFloat_String_float() {
System.out.println("toFloat");
float expResult;
float result;
Properties props = new Properties();
props.put("value1", "12345.6789");
props.put("value2", "-9000.001");
props.put("empty", "");
props.put("s... |
public abstract IOStreamPair execContainer(ContainerExecContext ctx)
throws ContainerExecutionException; | @Test
public void testExecContainer() throws Exception {
Container container = mock(Container.class);
try {
ContainerExecContext.Builder builder = new ContainerExecContext.Builder();
builder.setUser("foo").setAppId("app1").setContainer(container);
ContainerExecContext ctx = builder.build();
... |
@VisibleForTesting
Entity exportNativeEntity(Output output, EntityDescriptorIds entityDescriptorIds) {
final OutputEntity outputEntity = OutputEntity.create(
ValueReference.of(output.getTitle()),
ValueReference.of(output.getType()),
toReferenceMap(output.getCo... | @Test
@MongoDBFixtures("OutputFacadeTest.json")
public void exportNativeEntity() throws NotFoundException {
final Output output = outputService.load("5adf239e4b900a0fdb4e5197");
final EntityDescriptor descriptor = EntityDescriptor.create(output.getId(), ModelTypes.OUTPUT_V1);
final Enti... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
try {
Alarm alarm = JacksonUtil.fromString(msg.getData(), Alarm.class);
Objects.requireNonNull(alarm, "alarm is null");
ListenableFuture<Alarm> latest = ctx.getAlarmService().findAlarmByIdAsync... | @Test
void givenDeletedAlarm_whenOnMsg_then_Failure() throws TbNodeException {
// GIVEN
var alarm = new Alarm();
alarm.setId(ALARM_ID);
alarm.setOriginator(DEVICE_ID);
alarm.setType("General Alarm");
alarm.setCleared(true);
String msgData = JacksonUtil.toStri... |
static long sizeOf(Mutation m) {
if (m.getOperation() == Mutation.Op.DELETE) {
return sizeOf(m.getKeySet());
}
long result = 0;
for (Value v : m.getValues()) {
switch (v.getType().getCode()) {
case ARRAY:
result += estimateArrayValue(v);
break;
case STRUCT... | @Test
public void dates() throws Exception {
Mutation timestamp =
Mutation.newInsertOrUpdateBuilder("test").set("one").to(Timestamp.now()).build();
Mutation nullTimestamp =
Mutation.newInsertOrUpdateBuilder("test").set("one").to((Timestamp) null).build();
Mutation date =
Mutation.n... |
@Override
public PipelineState getLatestCheckpointByJobIdAndPipelineId(String jobId, String pipelineId)
throws CheckpointStorageException {
String parentPath = getStorageParentDirectory() + jobId;
Collection<File> fileList = new ArrayList<>();
try {
fileList = FileUt... | @Test
public void testGetLatestCheckpointByJobIdAndPipelineId() throws CheckpointStorageException {
PipelineState state = STORAGE.getLatestCheckpointByJobIdAndPipelineId(JOB_ID, "1");
Assertions.assertEquals(2, state.getCheckpointId());
} |
@Override
public void close() {
nameResolver.close();
} | @Test
public void testCloseDelegates() {
@SuppressWarnings("unchecked")
NameResolver<InetAddress> nameResolver = mock(NameResolver.class);
InetSocketAddressResolver resolver = new InetSocketAddressResolver(
ImmediateEventExecutor.INSTANCE, nameResolver);
resolver.clos... |
DataTableType lookupTableTypeByType(Type type) {
return lookupTableTypeByType(type, Function.identity());
} | @Test
void null_integer_transformed_to_null() {
DataTableTypeRegistry registry = new DataTableTypeRegistry(Locale.ENGLISH);
DataTableType dataTableType = registry.lookupTableTypeByType(LIST_OF_LIST_OF_INTEGER);
assertEquals(
singletonList(singletonList(null)),
dataTab... |
@Override
public Collection<ParameterRewriter> getParameterRewriters() {
Collection<ParameterRewriter> result = new LinkedList<>();
addParameterRewriter(result, new GeneratedKeyInsertValueParameterRewriter());
addParameterRewriter(result, new ShardingPaginationParameterRewriter());
r... | @Test
void assertGetParameterRewritersWhenPaginationIsNotNeedRewrite() {
RouteContext routeContext = mock(RouteContext.class);
when(routeContext.isSingleRouting()).thenReturn(true);
SelectStatementContext statementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when... |
@Override
public V get()
throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new ExecutionException(e);
}
} | @Test
public void completeDelegate_getWithTimeout_delegateAsked() throws Exception {
delegateFuture.run();
assertEquals(DELEGATE_RESULT, delegateFuture.get(10, TimeUnit.MILLISECONDS));
} |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testKerberosKeytabSecret() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final Secret resultSecret =
(Secret)
... |
public void ready() {
sync.releaseShared(UNUSED);
} | @Test
public void testStartingGunInterruptions() throws InterruptedException {
StartingGun sg = new StartingGun();
Thread[] threads = startWaitingThreads(sg);
Thread.sleep(PAUSE);
allThreadsAlive(threads);
for (Thread thread : threads) thread.interrupt();
Thread.sleep(PAUSE);
sg.ready... |
@Override
public String getRootLoggerName() {
return ROOT_LOGGER_NAME;
} | @Test
public void getRootLoggerName_returns_rootLogger() {
assertThat(newLog4JPropertiesBuilder().getRootLoggerName()).isEqualTo("rootLogger");
} |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
// Only outputting the MIME type as metadata
metadata.set(Metadata.CONTENT_TYPE, ENVI_MIME_TYPE);
// The ... | @Test
public void testParseGlobalMetadata() throws Exception {
try (InputStream stream = EnviHeaderParser.class
.getResourceAsStream("/test-documents/envi_test_header.hdr")) {
assertNotNull(stream, "Test ENVI file 'envi_test_header.hdr' not found");
parser.parse(stre... |
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (WriteToLogMeta) smi;
data = (WriteToLogData) sdi;
Object[] r = getRow(); // get row, set busy!
if ( r == null ) { // no more input to be expected...
setOutputDone();
return false;
... | @Test
public void processRow_NullRow() throws Exception {
WriteToLog writeToLogSpy = spy( writeToLog );
doReturn( null ).when( writeToLogSpy ).getRow();
WriteToLogMeta meta = mock( WriteToLogMeta.class );
WriteToLogData data = mock( WriteToLogData.class );
assertFalse( writeToLogSpy.processRow( m... |
static byte eightBitCharacter(final String asciiCharacter)
{
Verify.notNull(asciiCharacter, "asciiCharacter");
final byte[] bytes = asciiCharacter.getBytes(StandardCharsets.US_ASCII);
if (bytes.length != 1)
{
throw new IllegalArgumentException(
"String val... | @Test
void emptyParamToEightBitCharacterThrowsIAE()
{
assertThrows(IllegalArgumentException.class, () -> RustUtil.eightBitCharacter(""));
} |
@Override
public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId,
String appName, final String content) {
String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName;
String tenantTmp = StringUtils.isBlank(tenant) ... | @Test
void testAddAggrConfigInfoOfException() {
String dataId = "dataId111";
String group = "group";
String tenant = "tenant";
String datumId = "datumId";
String appName = "appname1234";
String content = "content1234";
//mock query datumId and throw E... |
public static String renderTemplate(String template, Map<String, Object> newContext)
throws IOException, ClassNotFoundException {
Map<String, Object> contextMap = getDefaultContextMap();
contextMap.putAll(newContext);
String templateRendered = GROOVY_TEMPLATE_ENGINE.createTemplate(template).make(conte... | @Test
public void testRenderTemplateWithGivenContextMap()
throws IOException, ClassNotFoundException {
Map<String, Object> contextMap = new HashMap<>();
contextMap.put("first_date_2020", "2020-01-01");
contextMap.put("name", "xiang");
contextMap.put("ts", 1577836800);
contextMap.put("yyyy", ... |
public boolean addMetadataString(String rawMetadata) throws UnmarshallingException {
InputStream inputStream = new ByteArrayInputStream(rawMetadata.getBytes(UTF_8));
XMLObject metadata = super.unmarshallMetadata(inputStream);
if (!isValid(metadata)) {
return false;
}
... | @Test
public void addInvalidMetadataStringTest() throws UnmarshallingException {
assertFalse(stringMetadataResolver.addMetadataString(invalidMetadata));
} |
@Override
public ExecuteContext before(ExecuteContext context) {
RequestTag requestTag = ThreadLocalUtils.getRequestTag();
if (requestTag != null) {
requestTag.getTag().forEach((key, value) ->
RequestContext.getCurrentContext().addZuulRequestHeader(key, value.get(0)))... | @Test
public void testBefore() {
// RequestTag is null
interceptor.before(null);
Assert.assertEquals(0, RequestContext.getCurrentContext().getZuulRequestHeaders().size());
// rRequestTag is not null
ThreadLocalUtils.addRequestTag(Collections.singletonMap("bar", Collections.s... |
public void showPerspective( final String perspectiveId ) {
changePerspectiveVisibility( perspectiveId, false );
} | @Test
public void showPerspective() {
SpoonPerspectiveManager.PerspectiveManager perspectiveManager = perspectiveManagerMap.get( perspective );
spoonPerspectiveManager.showPerspective( perspective.getId() );
verify( perspectiveManager ).setPerspectiveHidden( PERSPECTIVE_NAME, false );
} |
@Override
public void updateNextNode(int level, long node) {
Preconditions.checkArgument(
level >= 0 && level <= topLevel,
"invalid level " + level + " current top level is " + topLevel);
if (level == 0) {
nextNode = node;
} else {
lev... | @Test
void testUpdateNextNode() {
// test update next node of level 0
int level = 0;
long node1 = random.nextLong(Long.MAX_VALUE);
heapHeadIndex.updateNextNode(level, node1);
assertThat(heapHeadIndex.getNextNode(level)).isEqualTo(node1);
// Increase one level and make... |
public boolean filter(Message message) {
if (!enabled) {
return false;
}
List<String> ipFields = getIpAddressFields(message);
for (String key : ipFields) {
Object fieldValue = message.getField(key);
final InetAddress address = getValidRoutableInetAdd... | @Test
public void testFilterIpInfo() {
when(ipInfoAsnResolver.isEnabled()).thenReturn(true);
when(ipInfoAsnResolver.getGeoIpData(publicIp)).thenReturn(Optional.of(ipInfoAsnInfo));
when(ipInfoCityResolver.isEnabled()).thenReturn(true);
when(ipInfoCityResolver.getGeoIpData(publicIp)).... |
@SuppressWarnings("unchecked")
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request) throws YarnException,
IOException {
NodeId nodeId = request.getNodeId();
String host = nodeId.getHost();
int cmPort = nodeId.getPort();
int httpPort = requ... | @Test
public void testNodeRegistrationWithInvalidLabels() throws Exception {
writeToHostsFile("host2");
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH,
hostFile.getAbsolutePath());
conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE,
... |
@Override
public void error(String code, String cause, String extendedInformation, String msg) {
if (getDisabled()) {
return;
}
try {
getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg));
} catch (Throwable t) {
... | @Test
void testInstructionShownOrNot() {
LoggerFactory.setLoggerAdapter(FrameworkModel.defaultModel(), "jdk");
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailsafeErrorTypeAwareLoggerTest.class);
logger.error(
REGISTRY_ADDRESS_INVALID,
... |
@Override
public CompletableFuture<SchemaVersion> putSchemaIfAbsent(String schemaId,
SchemaData schema,
SchemaCompatibilityStrategy strategy) {
try {
SchemaDataValidator.va... | @Test
public void testPutSchemaIfAbsentWithGoodSchemaData() {
String schemaId = "test-schema-id";
SchemaCompatibilityStrategy strategy = SchemaCompatibilityStrategy.FULL;
CompletableFuture<SchemaVersion> future = new CompletableFuture<>();
when(underlyingService.putSchemaIfAbsent(eq(... |
public void setMinimalWidth() {
int nrNonEmptyFields = wFields.nrNonEmpty();
for ( int i = 0; i < nrNonEmptyFields; i++ ) {
TableItem item = wFields.getNonEmpty( i );
item.setText( 5, "" );
item.setText( 6, "" );
item.setText( 12, ValueMetaString.getTrimTypeDesc( ValueMetaInterface.TRIM... | @Test
public void testMinimalWidth_PDI_14253() throws Exception {
final String virtualFile = "ram://pdi-14253.txt";
KettleVFS.getFileObject( virtualFile ).createFile();
final String content = "r1c1, r1c2\nr2c1 , r2c2 ";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write( conte... |
@Override
public TimestampedKeyValueStore<K, V> build() {
KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof TimestampedBytesStore)) {
if (store.persistent()) {
store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store);
} e... | @Test
public void shouldNotHaveChangeLoggingStoreWhenDisabled() {
setUp();
final TimestampedKeyValueStore<String, String> store = builder.withLoggingDisabled().build();
final StateStore next = ((WrappedStateStore) store).wrapped();
assertThat(next, CoreMatchers.equalTo(inner));
} |
@Nonnull
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification =
"False positive on try-with-resources as of JDK11")
public static Resources resourcesOf(String... packages) {
String[] paths = stream(packages).map(ReflectionUtils::toPath).toArray(String[]:... | @Test
public void when_resourcesOf_then_returnsAllResources() throws ClassNotFoundException {
// When
Resources resources = ReflectionUtils.resourcesOf(OuterClass.class.getPackage().getName());
// Then
Collection<ClassResource> classes = resources.classes().collect(toList());
... |
@Override
public void close() {
try {
LOG.debug("Closing JMS connection.");
session.close();
connection.close();
} catch (JMSException e) {
LOG.warn("Error closing JMS connection.", e);
}
} | @Test
public void testSerializability() throws IOException {
JmsSpout spout = new JmsSpout();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(spout);
oos.close();
assertTrue(out.toByteArray... |
@Override
public void saveProperty(DbSession session, PropertyDto property, @Nullable String userLogin,
@Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) {
// do nothing
} | @Test
public void saveProperty() {
underTest.saveProperty(oldPropertyDto);
assertNoInteraction();
} |
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.get(sessionId);
} | @Test
public void require_that_local_sessions_belong_to_a_tenant() throws Exception {
setup();
// tenant is "default"
long firstSessionId = deploy();
long secondSessionId = deploy();
assertNotNull(sessionRepository.getLocalSession(firstSessionId));
assertNotNull(sess... |
public static PTransformMatcher stateOrTimerParDo() {
return new PTransformMatcher() {
@Override
public boolean matches(AppliedPTransform<?, ?, ?> application) {
if (PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(
PTransformTranslation.urnForTransformOrNull(application.getTransfor... | @Test
public void parDoWithState() {
AppliedPTransform<?, ?, ?> statefulApplication =
getAppliedTransform(
ParDo.of(doFnWithState).withOutputTags(new TupleTag<>(), TupleTagList.empty()));
assertThat(PTransformMatchers.stateOrTimerParDo().matches(statefulApplication), is(true));
Applie... |
static List<InetAddress> filterPreferredAddresses(InetAddress[] allAddresses) {
List<InetAddress> preferredAddresses = new ArrayList<>();
Class<? extends InetAddress> clazz = null;
for (InetAddress address : allAddresses) {
if (clazz == null) {
clazz = address.getClas... | @Test
public void testFilterPreferredAddresses() throws UnknownHostException {
InetAddress ipv4 = InetAddress.getByName("192.0.0.1");
InetAddress ipv6 = InetAddress.getByName("::1");
InetAddress[] ipv4First = new InetAddress[]{ipv4, ipv6, ipv4};
List<InetAddress> result = ClientUtil... |
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) {
//FIXME this is a total hack but it works around a number of issues related to vertical map
//replication and horiztonal replication that can cause polygons to completely disappear when
//panning
if (pZoom < 3)
... | @Test
public void testOverlapsDateLine() {
// ________________
// | | |
// |** | **|
// |-*----+-----*-|
// |** | **|
// | | |
// ----------------
//box is notated as *
//test area is notated as ?
... |
public static String packageNameOfResource(String classpathResourceName) {
Path parent = Paths.get(classpathResourceName).getParent();
if (parent == null) {
return DEFAULT_PACKAGE_NAME;
}
String pathSeparator = parent.getFileSystem().getSeparator();
return parent.toSt... | @Test
void packageNameOfResource() {
String packageName = ClasspathSupport.packageNameOfResource("com/example/app.feature");
assertEquals("com.example", packageName);
} |
public static String generateDatabaseId(String baseString) {
checkArgument(baseString.length() != 0, "baseString cannot be empty!");
String databaseId =
generateResourceId(
baseString,
ILLEGAL_DATABASE_CHARS,
REPLACE_DATABASE_CHAR,
MAX_DATABASE_ID_LENGTH,... | @Test
public void testGenerateDatabaseIdShouldReplaceDotWithUnderscore() {
String testBaseString = "test.database";
String actual = generateDatabaseId(testBaseString);
assertThat(actual).matches("test_da_\\d{8}_\\d{6}_\\d{6}");
} |
@VisibleForTesting
Schema convertSchema(org.apache.avro.Schema schema) {
return Schema.of(getFields(schema));
} | @Test
void convertSchema_lists() {
Field intListField = Field.newBuilder("intList", StandardSQLTypeName.INT64).setMode(Field.Mode.REPEATED).build();
Field requiredDoubleField = Field.newBuilder("requiredDouble", StandardSQLTypeName.FLOAT64)
.setMode(Field.Mode.REQUIRED)
.build();
Field op... |
@Override
public Collection<String> split(String text) {
return Arrays.asList(text.split(splitPattern));
} | @Test
public void testSplit() {
Collection<String> split = patternSplitStrategy.split("hello" + PATTERN + "world");
assertEquals(2, split.size());
assertEquals("world", new ArrayList<>(split).get(1));
} |
public void appendTimestampToResponse(OutputStream outputStream) throws IOException {
AbstractMessageLite messageLite = protobufObjectGenerator.generateTimestampMessage(system2.now());
messageLite.writeDelimitedTo(outputStream);
} | @Test
public void appendTimestampToResponse_outputStreamIsCalledAtLeastOnce() throws IOException {
OutputStream outputStream = mock(OutputStream.class);
underTest.appendTimestampToResponse(outputStream);
verify(outputStream, atLeastOnce()).write(any(byte[].class), anyInt(), anyInt());
} |
public synchronized void createInstance(List<BigtableResourceManagerCluster> clusters)
throws BigtableResourceManagerException {
// Check to see if instance already exists, and throw error if it does
if (hasInstance) {
LOG.warn(
"Skipping instance creation. Instance was already created or... | @Test
public void testCreateInstanceShouldWorkWhenBigtableDoesNotThrowAnyError() {
testManager.createInstance(cluster);
verify(bigtableResourceManagerClientFactory.bigtableInstanceAdminClient())
.createInstance(any());
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PiMatchKey)) {
return false;
}
PiMatchKey that = (PiMatchKey) o;
return Objects.equal(fieldMatches, that.fieldMatches);
} | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(piMatchKey1, sameAsPiMatchKey1)
.addEqualityGroup(PiMatchKey.EMPTY, PiMatchKey.EMPTY)
.addEqualityGroup(piMatchKey2)
.testEquals();
} |
public byte[] getTail() {
int size = (int) Math.min(tailSize, bytesRead);
byte[] result = new byte[size];
System.arraycopy(tailBuffer, currentIndex, result, 0, size - currentIndex);
System.arraycopy(tailBuffer, 0, result, size - currentIndex, currentIndex);
return result;
} | @Test
public void testTailSingleByteReads() throws IOException {
final int count = 128;
TailStream stream = new TailStream(generateStream(0, 2 * count), count);
readStream(stream);
assertEquals(generateText(count, count), new String(stream.getTail(), UTF_8),
"Wrong bu... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final P4PacketMetadataModel other = (P4PacketMetadataModel) obj;
return Objects.equals(this.id, o... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(metadataModel, sameAsMetadataModel)
.addEqualityGroup(metadataModel2)
.addEqualityGroup(metadataModel3)
.testEquals();
} |
@ScalarFunction
@Description("Calculates the great-circle distance between two points on the Earth's surface in kilometers")
@SqlType(DOUBLE)
public static double greatCircleDistance(
@SqlType(DOUBLE) double latitude1,
@SqlType(DOUBLE) double longitude1,
@SqlType(DOUBLE) ... | @Test
public void testGreatCircleDistance()
{
assertFunctionWithError("great_circle_distance(36.12, -86.67, 33.94, -118.40)", DOUBLE, 2886.448973436703);
assertFunctionWithError("great_circle_distance(33.94, -118.40, 36.12, -86.67)", DOUBLE, 2886.448973436703);
assertFunctionWithError("g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.