focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 2) {
onInvalidDataReceived(device, data);
return;
}
// Read the Op Code
final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0);
// Estima... | @Test
public void onCGMSpecificOpsOperationCompleted_withCrc() {
final Data data = new Data(new byte[] { 28, 2, 1, (byte) 0x3C, (byte) 0x3B});
callback.onDataReceived(null, data);
assertTrue(success);
assertTrue(secured);
assertEquals(2, requestCode);
} |
@Override
public ApiResult<AllBrokersStrategy.BrokerKey, Collection<TransactionListing>> handleResponse(
Node broker,
Set<AllBrokersStrategy.BrokerKey> keys,
AbstractResponse abstractResponse
) {
int brokerId = broker.id();
AllBrokersStrategy.BrokerKey key = requireSingle... | @Test
public void testHandleSuccessfulResponse() {
int brokerId = 1;
BrokerKey brokerKey = new BrokerKey(OptionalInt.of(brokerId));
ListTransactionsOptions options = new ListTransactionsOptions();
ListTransactionsHandler handler = new ListTransactionsHandler(options, logContext);
... |
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger... | @Test
void testSubscribeIfUrlNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener = urls -> notified.set(Boolean.TRUE);
URL url = new ServiceConfigUR... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
... | @Test
public void testGetFieldDefinition() {
assertEquals( "FOO DATE",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "DATE",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, false, false ) ); // Note - Rocket U... |
@Transactional
@ApolloAuditLog(type = OpType.CREATE, name = "App.create")
public App createAppAndAddRolePermission(
App app, Set<String> admins
) {
App createdApp = this.createAppInLocal(app);
publisher.publishEvent(new AppCreationEvent(createdApp));
if (!CollectionUtils.isEmpty(admins)) {
... | @Test
void createAppAndAddRolePermission() {
final String userId = "user100";
final String appId = "appId100";
{
UserInfo userInfo = new UserInfo();
userInfo.setUserId(userId);
userInfo.setEmail("xxx@xxx.com");
Mockito.when(userService.findByUserId(Mockito.eq(userId)))
.t... |
public void finish() throws IOException {
if (finished) {
return;
}
flush();
// Finish the stream with the terminatorValue.
VarInt.encode(terminatorValue, os);
if (!BUFFER_POOL.offer(buffer)) {
// The pool is full, we can't store the buffer. We just drop the buffer.
}
finishe... | @Test
public void testBuffersAreTakenAndReturned() throws Exception {
BUFFER_POOL.clear();
BUFFER_POOL.offer(ByteBuffer.allocate(256));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedElementCountingOutputStream os = createAndWriteValues(toBytes("abcdefghij"), baos);
assertEquals... |
public static KiePMMLClusteringModel getKiePMMLClusteringModel(final ClusteringCompilationDTO compilationDTO) {
logger.trace("getKiePMMLClusteringModel {}", compilationDTO);
try {
ClusteringModel clusteringModel = compilationDTO.getModel();
final KiePMMLClusteringModel.ModelClass... | @Test
void getKiePMMLClusteringModel() {
final CommonCompilationDTO<ClusteringModel> compilationDTO =
CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmml,
... |
@Override
public void deleteArticle(Long id) {
// 校验存在
validateArticleExists(id);
// 删除
articleMapper.deleteById(id);
} | @Test
public void testDeleteArticle_success() {
// mock 数据
ArticleDO dbArticle = randomPojo(ArticleDO.class);
articleMapper.insert(dbArticle);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbArticle.getId();
// 调用
articleService.deleteArticle(id);
// 校验数据不存在了... |
public static Map<UUID, PartitionIdSet> createPartitionMap(
NodeEngine nodeEngine,
@Nullable MemberVersion localMemberVersion,
boolean failOnUnassignedPartition
) {
Collection<Partition> parts = nodeEngine.getHazelcastInstance().getPartitionService().getPartitions();
... | @Test
public void testUnassignedPartition_ignore() {
HazelcastInstance member = factory.newHazelcastInstance();
member.getCluster().changeClusterState(ClusterState.FROZEN);
Map<UUID, PartitionIdSet> map = QueryUtils.createPartitionMap(Accessors.getNodeEngineImpl(member), null, false);
... |
@SuppressWarnings("deprecation")
@Override
public ByteBuf asReadOnly() {
if (isReadOnly()) {
return this;
}
return Unpooled.unmodifiableBuffer(this);
} | @Test
public void testReadyOnlyNioBufferWithPositionLength() {
assertReadyOnlyNioBufferWithPositionLength(buffer.asReadOnly());
} |
@Override
public int compareTo(DateTimeStamp dateTimeStamp) {
return comparator.compare(this,dateTimeStamp);
} | @Test
void testCompareNullValue() {
DateTimeStamp smaller = new DateTimeStamp("2018-04-04T09:10:00.586-0100");
assertEquals(-1, smaller.compareTo(null));
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchTopicIdUpgradeDowngrade() {
buildFetcher();
TopicIdPartition fooWithoutId = new TopicIdPartition(Uuid.ZERO_UUID, new TopicPartition("foo", 0));
// Assign foo without a topic id.
subscriptions.assignFromUser(singleton(fooWithoutId.topicPartition()));
... |
public static String get(String urlString, Charset customCharset) {
return HttpRequest.get(urlString).charset(customCharset).execute().body();
} | @Test
@Disabled
public void acplayTest(){
final String body = HttpRequest.get("https://api.acplay.net/api/v2/bangumi/9541")
.execute().body();
Console.log(body);
} |
@Nonnull
public static <T> Sink<T> list(@Nonnull String listName) {
return fromProcessor("listSink(" + listName + ')', writeListP(listName));
} | @Test
public void list_byName() {
// Given
populateList(srcList);
// When
Sink<Object> sink = Sinks.list(sinkName);
// Then
p.readFrom(Sources.list(srcList)).writeTo(sink);
execute();
assertEquals(itemCount, sinkList.size());
} |
public synchronized void setMemoryPool(MemoryPool newMemoryPool)
{
// This method first acquires the monitor of this instance.
// After that in this method if we acquire the monitors of the
// user/revocable memory contexts in the queryMemoryContext instance
// (say, by calling query... | @Test(dataProvider = "testSetMemoryPoolOptions")
public void testSetMemoryPool(boolean useReservedPool)
{
QueryId secondQuery = new QueryId("second");
MemoryPool reservedPool = new MemoryPool(RESERVED_POOL, new DataSize(10, BYTE));
long secondQueryMemory = reservedPool.getMaxBytes() - 1;... |
public static Path getConfigHome() {
return getConfigHome(System.getProperties(), System.getenv());
} | @Test
public void testGetConfigHome_windows() {
Properties fakeProperties = new Properties();
fakeProperties.setProperty("user.home", "nonexistent");
fakeProperties.setProperty("os.name", "os is WiNdOwS");
Map<String, String> fakeEnvironment = ImmutableMap.of("LOCALAPPDATA", fakeConfigHome);
Ass... |
private boolean processBackgroundEvents() {
AtomicReference<KafkaException> firstError = new AtomicReference<>();
LinkedList<BackgroundEvent> events = new LinkedList<>();
backgroundEventQueue.drainTo(events);
for (BackgroundEvent event : events) {
try {
if (... | @Test
public void testProcessBackgroundEventsWithInitialDelay() throws Exception {
consumer = newConsumer();
Time time = new MockTime();
Timer timer = time.timer(1000);
CompletableFuture<?> future = mock(CompletableFuture.class);
CountDownLatch latch = new CountDownLatch(3);
... |
public static String checkNotNullEmpty(String value, String name) throws IllegalArgumentException {
if (isBlank(value)) {
throw new IllegalArgumentException(name + " is null or empty");
}
return value;
} | @Test
public void testCheckNotNullEmptyInputSpaceThrowsException() {
thrown.expect(IllegalArgumentException.class);
EagleEyeCoreUtils.checkNotNullEmpty(" ", "bar");
// Method is not expected to return due to exception thrown
} |
public Optional<Violation> validate(IndexSetConfig newConfig) {
// Don't validate prefix conflicts in case of an update
if (Strings.isNullOrEmpty(newConfig.id())) {
final Violation prefixViolation = validatePrefix(newConfig);
if (prefixViolation != null) {
return... | @Test
public void validateMaxRetentionPeriod() {
when(indexSetRegistry.iterator()).thenReturn(Collections.emptyIterator());
// no max retention period configured
assertThat(validator.validate(testIndexSetConfig())).isNotPresent();
// max retention period >= effective retention peri... |
public <T extends Enum<T>> T getEnumProperty(String key, Class<T> enumClass, T defaultValue) {
return getEnumProperty(key, enumClass, defaultValue, false);
} | @Test
public void testEnumProperty() {
TypedProperties p = createProperties();
assertEquals(COLOR.BLUE, p.getEnumProperty("enum_cast", COLOR.class, COLOR.BLUE));
assertEquals(COLOR.RED, p.getEnumProperty("enum", COLOR.class, COLOR.BLUE));
assertEquals(COLOR.RED, p.getEnumProperty("enum_put_st... |
public static Exception toException(int code, String msg) throws Exception {
if (code == Response.Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException(msg);
} else if (code == Response.Status.NOT_IMPLEMENTED.getStatusCode()) {
throw new ClassNotFoundException(msg);
... | @Test
public void testToExceptionRuntimeException() {
assertThrows(RuntimeException.class, () -> RestExceptionMapper.toException(-1, "Unknown status code"));
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDynamicStructOfDynamicStructWithAdditionalParametersReturn()
throws ClassNotFoundException {
// Return data from 'testInputAndOutput' function of this contract
// https://sepolia.etherscan.io/address/0x009C10396226ECFE3E39b3f1AEFa072E37578e30#readContract
//... |
@Override
public YamlShardingAuditStrategyConfiguration swapToYamlConfiguration(final ShardingAuditStrategyConfiguration data) {
YamlShardingAuditStrategyConfiguration result = new YamlShardingAuditStrategyConfiguration();
result.setAuditorNames(new LinkedList<>(data.getAuditorNames()));
res... | @Test
void assertSwapToYamlConfiguration() {
ShardingAuditStrategyConfiguration data = new ShardingAuditStrategyConfiguration(Collections.singletonList("audit_algorithm"), false);
YamlShardingAuditStrategyConfigurationSwapper swapper = new YamlShardingAuditStrategyConfigurationSwapper();
Yam... |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void anonymous_to_string_uses_default() {
DocString docString = DocString.create("hello world");
assertThat(converter.convert(docString, String.class), is("hello world"));
} |
public static Optional<PMMLModel> getPMMLModel(String fileName, String modelName, PMMLRuntimeContext pmmlContext) {
logger.trace("getPMMLModel {} {}", fileName, modelName);
String fileNameToUse = !fileName.endsWith(PMML_SUFFIX) ? fileName + PMML_SUFFIX : fileName;
return getPMMLModels(pmmlContex... | @Test
void getPMMLModelFromMemoryCLassloader() {
PMMLRuntimeContext pmmlContext = getPMMLContext(FILE_NAME, MODEL_NAME, memoryCompilerClassLoader);
Optional<PMMLModel> retrieved = PMMLRuntimeHelper.getPMMLModel(FILE_NAME,
MODEL_N... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(c,... | @Test
public void compositedKeywordFollowedByOptions() throws ScanException {
{
List<Token> tl = new TokenStream("%d(A){o}",
new AlmostAsIsEscapeUtil()).tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(Token.PERCENT_TOKEN);
witness.add(new Token(Token.COM... |
@Override
public ClusterClientProvider<String> deployApplicationCluster(
final ClusterSpecification clusterSpecification,
final ApplicationConfiguration applicationConfiguration)
throws ClusterDeploymentException {
if (client.getService(ExternalServiceDecorator.getExterna... | @Test
void testDeployApplicationClusterWithClusterAlreadyExists() {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("local:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
mockExpectedService... |
public Optional<DoFn.ProcessContinuation> run(
PartitionRecord partitionRecord,
ChangeStreamRecord record,
RestrictionTracker<StreamProgress, StreamProgress> tracker,
DoFn.OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
... | @Test
public void testCloseStreamResume() {
ChangeStreamContinuationToken changeStreamContinuationToken =
ChangeStreamContinuationToken.create(ByteStringRange.create("a", "b"), "1234");
CloseStream mockCloseStream = Mockito.mock(CloseStream.class);
Status statusProto = Status.newBuilder().setCode(... |
public static <T> T readJsonSR(
@Nonnull final byte[] jsonWithMagic,
final ObjectMapper mapper,
final Class<? extends T> clazz
) throws IOException {
if (!hasMagicByte(jsonWithMagic)) {
// don't log contents of jsonWithMagic to avoid leaking data into the logs
throw new KsqlException... | @Test
public void shouldSetCorrectOffsetWithMagicByte() throws IOException {
// Given:
byte[] json = new byte[]{/* magic */ 0x00, /* id */ 0x00, 0x00, 0x00, 0x01, /* data */ 0x01};
// When:
JsonSerdeUtils.readJsonSR(json, mapper, Object.class);
// Then:
Mockito.verify(mapper, Mockito.times(1... |
public SingleValueHeaders getHeaders() {
return headers;
} | @Test
void deserialize_singleValuedHeaders() throws IOException {
AwsProxyRequest req =
new AwsProxyRequestBuilder().fromJsonString(getSingleValueRequestJson()).build();
assertThat(req.getHeaders().get("accept"), is("*"));
} |
public static Resource subtract(Resource lhs, Resource rhs) {
return subtractFrom(clone(lhs), rhs);
} | @Test
void testSubtract() {
assertEquals(createResource(1, 0),
subtract(createResource(2, 1), createResource(1, 1)));
assertEquals(createResource(0, 1),
subtract(createResource(1, 2), createResource(1, 1)));
assertEquals(createResource(2, 2, 0),
subtract(createResource(3, 3, 0), cr... |
protected abstract SchemaTransform from(ConfigT configuration); | @Test
public void testFrom() {
SchemaTransformProvider provider = new FakeTypedSchemaIOProvider();
SchemaTransformProvider minimalProvider = new FakeMinimalTypedProvider();
Row inputConfig =
Row.withSchema(provider.configurationSchema())
.withFieldValue("string_field", "field1")
... |
@Override
public Configuration toConfiguration(CommandLine commandLine) throws FlinkException {
final Configuration resultingConfiguration = super.toConfiguration(commandLine);
if (commandLine.hasOption(addressOption.getOpt())) {
String addressWithPort = commandLine.getOptionValue(addre... | @Test
void testDynamicPropertyMaterialization() throws Exception {
final String[] args = {
"-D" + PipelineOptions.AUTO_WATERMARK_INTERVAL.key() + "=42",
"-D" + PipelineOptions.AUTO_GENERATE_UIDS.key() + "=true"
};
final AbstractCustomCommandLine defaultCLI = new Defa... |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldReturnNullIfNIsLessThanOne() {
// When:
final String el = elt.elt(0, "a", "b");
// Then:
assertThat(el, is(nullValue()));
} |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(2.0), numOf(1.5)));
assertFalse(criterion.betterThan(numOf(1.5), numOf(2.0)));
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListPlaceholderPlusCharacter() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("us-east-1");
final Path directory = new GoogleStorageDirectoryFeature(session).mk... |
public static StsConfig getInstance() {
return Singleton.INSTANCE;
} | @Test
void testGetInstance() {
StsConfig instance1 = StsConfig.getInstance();
StsConfig instance2 = StsConfig.getInstance();
assertEquals(instance1, instance2);
} |
static BlockStmt getParameterFieldVariableDeclaration(final String variableName, final ParameterField parameterField) {
final MethodDeclaration methodDeclaration = PARAMETER_FIELD_TEMPLATE.getMethodsByName(GEKIEPMMLPARAMETERFIELD).get(0).clone();
final BlockStmt toReturn = methodDeclaration.getBody().or... | @Test
void getParameterFieldVariableDeclaration() throws IOException {
String variableName = "variableName";
ParameterField parameterField = new ParameterField(variableName);
parameterField.setDataType(DataType.DOUBLE);
parameterField.setOpType(OpType.CONTINUOUS);
parameterFi... |
@Operation(summary = "list", description = "list all latest configurations")
@GetMapping("/latest")
public ResponseEntity<List<ServiceConfigVO>> latest(@PathVariable Long clusterId) {
return ResponseEntity.success(configService.latest(clusterId));
} | @Test
void latestReturnsEmptyForInvalidClusterId() {
Long clusterId = 999L;
when(configService.latest(clusterId)).thenReturn(List.of());
ResponseEntity<List<ServiceConfigVO>> response = configController.latest(clusterId);
assertTrue(response.isSuccess());
assertTrue(respons... |
@Override
public void checkOutputSpecs(JobContext context) throws IOException {
Configuration conf = context.getConfiguration();
if (getCommitDirectory(conf) == null) {
throw new IllegalStateException("Commit directory not configured");
}
Path workingPath = getWorkingDirectory(conf);
if (w... | @Test
public void testCheckOutputSpecs() {
try {
OutputFormat outputFormat = new CopyOutputFormat();
Job job = Job.getInstance(new Configuration());
JobID jobID = new JobID("200707121733", 1);
try {
JobContext context = new JobContextImpl(job.getConfiguration(), jobID);
ou... |
public String borrow() {
return String.format("Borrower %s wants to get some money.", name);
} | @Test
void borrowTest() {
var borrowerRole = new BorrowerRole();
borrowerRole.setName("test");
assertEquals("Borrower test wants to get some money.", borrowerRole.borrow());
} |
public static NodesInfo deleteDuplicateNodesInfo(ArrayList<NodeInfo> nodes) {
NodesInfo nodesInfo = new NodesInfo();
Map<String, NodeInfo> nodesMap = new LinkedHashMap<>();
for (NodeInfo node : nodes) {
String nodeId = node.getNodeId();
// If the node already exists, it could be an old instance... | @Test
public void testDeleteDuplicateNodes() {
NodesInfo nodes = new NodesInfo();
NodeInfo node1 = new NodeInfo();
node1.setId(NODE1);
node1.setLastHealthUpdate(0);
nodes.add(node1);
NodeInfo node2 = new NodeInfo();
node2.setId(NODE1);
node2.setLastHealthUpdate(1);
nodes.add(nod... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 1) {
onInvalidDataReceived(device, data);
return;
}
int offset = 0;
while (offset < data.size()) {
// Packet size
final int size = data.... | @Test
public void onContinuousGlucoseMeasurementReceived_crcError() {
final DataReceivedCallback callback = new ContinuousGlucoseMeasurementDataCallback() {
@Override
public void onContinuousGlucoseMeasurementReceived(@NonNull final BluetoothDevice device, final float glucoseConcentration,
@N... |
protected boolean databaseForBothDbInterfacesIsTheSame( DatabaseInterface primary, DatabaseInterface secondary ) {
if ( primary == null || secondary == null ) {
throw new IllegalArgumentException( "DatabaseInterface shouldn't be null!" );
}
if ( primary.getPluginId() == null || secondary.getPluginId(... | @Test
public void databases_WithDifferentDbConnTypes_AreDifferent_IfNonOfThemIsSubsetOfAnother() {
DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta();
mssqlServerDatabaseMeta.setPluginId( "MSSQL" );
DatabaseInterface oracleDatabaseMeta = new OracleDatabaseMeta();
oracleDatabaseM... |
public static byte[] deriveMac(byte[] seed, byte[] nonce) {
final MessageDigest md = DigestUtils.digest("SHA-256");
md.update(seed);
if (nonce != null) md.update(nonce);
md.update(new byte[] {0, 0, 0, 2});
return Arrays.copyOfRange(md.digest(), 0, 32);
} | @Test
public void shouldDeriveMacKey() {
assertEquals(
"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS",
ByteArrayUtils.prettyHex(AESSecureMessaging.deriveMac(Hex.decode("CA"), null))
);
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldValidateNoMigrations() throws Exception {
// Given:
final List<String> versions = ImmutableList.of();
final List<String> checksums = givenExistingMigrationFiles(versions);
givenAppliedMigrations(versions, checksums);
// When:
final int result = command.command(config, ... |
public static boolean containsLocalIp(List<InetSocketAddress> clusterAddresses,
AlluxioConfiguration conf) {
String localAddressIp = getLocalIpAddress((int) conf.getMs(PropertyKey
.NETWORK_HOST_RESOLUTION_TIMEOUT_MS));
for (InetSocketAddress addr : clusterAddresses) {
String clusterNodeIp;
... | @Test
public void TestisNotLocalAddress() {
List<InetSocketAddress> clusterAddresses = new ArrayList<>();
InetSocketAddress raftNodeAddress1 = new InetSocketAddress("host1", 10);
InetSocketAddress raftNodeAddress2 = new InetSocketAddress("host2", 20);
InetSocketAddress raftNodeAddress3 = new InetSocke... |
@Override
@PublicAPI(usage = ACCESS)
public boolean isMetaAnnotatedWith(Class<? extends Annotation> annotationType) {
return isMetaAnnotatedWith(annotationType.getName());
} | @Test
public void isMetaAnnotatedWith_type_on_resolved_target() {
JavaClasses classes = importClassesWithContext(Origin.class, Target.class, QueriedAnnotation.class);
JavaCall<?> call = simulateCall().from(classes.get(Origin.class), "call").to(classes.get(Target.class).getMethod("called"));
... |
public static String format(String source, Object... parameters) {
String current = source;
for (Object parameter : parameters) {
if (!current.contains("{}")) {
return current;
}
current = current.replaceFirst("\\{\\}", String.valueOf(parameter));
... | @Test
public void testFormatNull() {
String fmt = "Some string {} 2 {}";
assertEquals("Some string 1 2 null", format(fmt, 1, null));
} |
public String getShardIterator(
final String streamName,
final String shardId,
final ShardIteratorType shardIteratorType,
final String startingSequenceNumber,
final Instant timestamp)
throws TransientKinesisException {
final Date date = timestamp != null ? timestamp.toDate() : nu... | @Test
public void shouldReturnIteratorStartingWithSequenceNumber() throws Exception {
when(kinesis.getShardIterator(
new GetShardIteratorRequest()
.withStreamName(STREAM)
.withShardId(SHARD_1)
.withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
... |
public static Ip4Address makeMaskPrefix(int prefixLength) {
byte[] mask = IpAddress.makeMaskPrefixArray(VERSION, prefixLength);
return new Ip4Address(mask);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidMakeNegativeMaskPrefixIPv4() {
Ip4Address ipAddress;
ipAddress = Ip4Address.makeMaskPrefix(-1);
} |
@Override
public MessageQueueView getCurrentMessageQueueView(ProxyContext ctx, String topicName) throws Exception {
return getAllMessageQueueView(ctx, topicName);
} | @Test
public void testGetCurrentMessageQueueView() throws Throwable {
ProxyContext ctx = ProxyContext.create();
MQClientException exception = catchThrowableOfType(() -> this.topicRouteService.getCurrentMessageQueueView(ctx, ERR_TOPIC), MQClientException.class);
assertTrue(TopicRouteHelper.is... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testExpiryOfUnsentBatchesShouldNotCauseUnresolvedSequences() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(produc... |
@Override
public StreamDataDecoderResult decode(StreamMessage message) {
assert message.getValue() != null;
try {
_reuse.clear();
GenericRow row = _valueDecoder.decode(message.getValue(), 0, message.getLength(), _reuse);
if (row != null) {
if (message.getKey() != null) {
r... | @Test
public void testDecodeValueOnly()
throws Exception {
TestDecoder messageDecoder = new TestDecoder();
messageDecoder.init(Collections.emptyMap(), ImmutableSet.of(NAME_FIELD), "");
String value = "Alice";
BytesStreamMessage message = new BytesStreamMessage(value.getBytes(StandardCharsets.UTF... |
@Override public SlotAssignmentResult ensure(long key1, int key2) {
return super.ensure0(key1, key2);
} | @Test
public void testPut() {
final long key1 = randomKey();
final int key2 = randomKey();
SlotAssignmentResult slot = insert(key1, key2);
final long valueAddress = slot.address();
assertTrue(slot.isNew());
slot = hsa.ensure(key1, key2);
assertFalse(slot.isNe... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testConsumerGroupOffsetDelete() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup(
"foo",
true
);
con... |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testMovieActorMapReference() throws Exception {
Map<Integer, Actor> idActorMap = new HashMap<>();
idActorMap.put(1, new Actor("Keanu Reeves"));
idActorMap.put(2, new Actor("Laurence Fishburne"));
idActorMap.put(3, new Actor("Carrie-Anne Moss"));
MovieActorMa... |
public Collection<NacosTraceSubscriber> getAllTraceSubscribers() {
return new HashSet<>(traceSubscribers.values());
} | @Test
void testGetAllTraceSubscribers() {
assertFalse(NacosTracePluginManager.getInstance().getAllTraceSubscribers().isEmpty());
assertContainsTestPlugin();
} |
@Nullable static String lastStringHeader(Headers headers, String key) {
Header header = headers.lastHeader(key);
if (header == null || header.value() == null) return null;
return new String(header.value(), UTF_8);
} | @Test void lastStringHeader() {
record.headers().add("b3", new byte[] {'1'});
assertThat(KafkaHeaders.lastStringHeader(record.headers(), "b3"))
.isEqualTo("1");
} |
protected HashMap<String, Double> computeModularity(Graph graph, CommunityStructure theStructure,
int[] comStructure,
double currentResolution, boolean randomized,
... | @Test
public void testGraphWithouLinksModularity() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(5);
UndirectedGraph graph = graphModel.getUndirectedGraph();
Modularity mod = new Modularity();
Modularity.CommunityStructure theStructure = mod.new CommunityStru... |
public String getCopyStrategy() {
return copyStrategy;
} | @Test
public void testCopyStrategy() {
final DistCpOptions.Builder builder = new DistCpOptions.Builder(
new Path("hdfs://localhost:8020/source/first"),
new Path("hdfs://localhost:8020/target/"));
Assert.assertEquals(DistCpConstants.UNIFORMSIZE,
builder.build().getCopyStrategy());
b... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthEstimateGas() throws Exception {
web3j.ethEstimateGas(
Transaction.createEthCallTransaction(
"0xa70e8dd61c5d32be8058bb8eb970870f07233155",
"0x52b93c80364dc2dd4444c146d73b9836bbbb2b3f",
... |
public static MetricName name(Class<?> klass, String... names) {
return name(klass.getName(), names);
} | @Test
public void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() throws Exception {
assertThat(name("one", null, "three"))
.isEqualTo(MetricName.build("one.three"));
} |
public static Matcher<HttpRequest> methodEquals(String method) {
if (method == null) throw new NullPointerException("method == null");
if (method.isEmpty()) throw new NullPointerException("method is empty");
return new MethodEquals(method);
} | @Test void methodEquals_unmatched_mixedCase() {
when(httpRequest.method()).thenReturn("PoSt");
assertThat(methodEquals("POST").matches(httpRequest)).isFalse();
} |
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
} | @Test
public void testEncodeHebrewPersonName() {
assertArrayEquals(HEBREW_PERSON_NAME_BYTE,
iso8859_8().encode(HEBREW_PERSON_NAME, PN_DELIMS));
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertBoolean() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.BOOLEAN_TYPE)
.nullable(true)
.defaultValue(true)
.com... |
public static ScanReport fromJson(String json) {
return JsonUtil.parse(json, ScanReportParser::fromJson);
} | @Test
public void invalidSnapshotId() {
assertThatThrownBy(
() ->
ScanReportParser.fromJson(
"{\"table-name\":\"roundTripTableName\",\"snapshot-id\":\"invalid\"}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse to a long val... |
public boolean supportsPipelineAnalytics() {
return hasSupportFor(PIPELINE_TYPE);
} | @Test
public void shouldSupportPipelineAnalyticsIfPluginListsPipelineMetricsAsCapability() {
assertTrue(new Capabilities(List.of(new SupportedAnalytics("pipeline", "id", "title"))).supportsPipelineAnalytics());
assertTrue(new Capabilities(List.of(new SupportedAnalytics("PipeLine", "id", "title"))).s... |
public static List<ComponentContainers> filterInstances(
ServiceContext context,
ClientAMProtocol.GetCompInstancesRequestProto filterReq) {
Map<String, ComponentContainers> containersByComp = new HashMap<>();
Map<ContainerId, ComponentInstance> instances =
context.scheduler.getLiveInstances... | @Test
public void testFilterWithComp() throws Exception {
GetCompInstancesRequestProto req = GetCompInstancesRequestProto.newBuilder()
.addAllComponentNames(Lists.newArrayList("compa")).build();
List<ComponentContainers> compContainers = FilterUtils.filterInstances(
new MockRunningServiceConte... |
public void execute() {
Profiler stepProfiler = Profiler.create(LOGGER).logTimeLast(true);
boolean allStepsExecuted = false;
try {
executeSteps(stepProfiler);
allStepsExecuted = true;
} finally {
if (listener != null) {
executeListener(allStepsExecuted);
}
}
} | @Test
public void execute_does_not_fail_if_listener_throws_Throwable() {
ComputationStepExecutor.Listener listener = mock(ComputationStepExecutor.Listener.class);
doThrow(new Error("Facking error thrown by Listener"))
.when(listener)
.finished(anyBoolean());
new ComputationStepExecutor(mockCo... |
Bytes toBytes(final KO foreignKey, final K primaryKey) {
//The serialization format - note that primaryKeySerialized may be null, such as when a prefixScan
//key is being created.
//{Integer.BYTES foreignKeyLength}{foreignKeySerialized}{Optional-primaryKeySerialized}
final byte[] foreign... | @Test
public void nullPrimaryKeySerdeTest() {
final CombinedKeySchema<String, Integer> cks = new CombinedKeySchema<>(
() -> "fkTopic", Serdes.String(),
() -> "pkTopic", Serdes.Integer()
);
assertThrows(NullPointerException.class, () -> cks.toBytes("foreignKey", null))... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 10) {
onInvalidDataReceived(device, data);
return;
}
int offset = 0;
final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++);
final ... | @Test
public void onGlucoseMeasurementReceived() {
final Data data = new Data(new byte[] {
(byte) 0b011011, // Time Offset, Type and Location Present, unit: kg/L, Status Annunciation Present, Context follows
1, 0, // Seq = 1
(byte) 0xE3, 0x07, // 2019
2, ... |
@Override
protected int getDefaultPort() {
return (Integer) PropertyKey.MASTER_RPC_PORT.getDefaultValue();
} | @Test
public void defaultPortTest() throws Exception {
// this test ensures that that default port for Alluxio Hadoop file system is the same
// whether in Hadoop 1.x or Hadoop 2.x
int defaultRpcPort = (int) PropertyKey.MASTER_RPC_PORT.getDefaultValue();
Configuration conf = new Configuration();
... |
@Override
public Set<Host> getHostsByIp(IpAddress ip) {
checkNotNull(ip, "IP address cannot be null");
return filter(getHostsColl(), host -> host.ipAddresses().contains(ip));
} | @Test(expected = NullPointerException.class)
public void testGetHostsByNullIp() {
VirtualNetwork vnet = setupVnet();
HostService hostService = manager.get(vnet.id(), HostService.class);
hostService.getHostsByIp(null);
} |
public B addProtocols(List<ProtocolConfig> protocols) {
if (this.protocols == null) {
this.protocols = new ArrayList<>();
}
this.protocols.addAll(protocols);
return getThis();
} | @Test
void addProtocols() {
ProtocolConfig protocol = new ProtocolConfig();
ServiceBuilder builder = new ServiceBuilder();
Assertions.assertNull(builder.build().getProtocols());
builder.addProtocols(Collections.singletonList(protocol));
Assertions.assertNotNull(builder.build(... |
public static <T> List<T> randomEles(final List<T> list, final int count) {
final List<T> result = new ArrayList<>(count);
final int limit = list.size();
while (result.size() < count) {
result.add(randomEle(list, limit));
}
return result;
} | @Test
public void randomElesTest(){
List<Integer> result = RandomUtil.randomEles(CollUtil.newArrayList(1, 2, 3, 4, 5, 6), 2);
assertEquals(result.size(), 2);
} |
@ApiOperation(value = "Sync edge (syncEdge)",
notes = "Starts synchronization process between edge and cloud. \n" +
"All entities that are assigned to particular edge are going to be send to remote edge service." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN... | @Test
public void testSyncEdge() throws Exception {
loginSysAdmin();
// get jwt settings from yaml config
JwtSettings settings = doGet("/api/admin/jwtSettings", JwtSettings.class);
// save jwt settings into db
doPost("/api/admin/jwtSettings", settings).andExpect(status().isOk... |
private ElasticsearchQueryString groupByQueryString(Event event) {
ElasticsearchQueryString result = ElasticsearchQueryString.empty();
if (!config.groupBy().isEmpty()) {
for (String key : event.getGroupByFields().keySet()) {
String value = event.getGroupByFields().get(key);
... | @Test
public void testGroupByQueryString() throws EventProcessorException {
Map<String, String> groupByFields = ImmutableMap.of(
"group_field_one", "one",
"group_field_two", "two"
);
sourceMessagesWithAggregation(groupByFields, 1, emptyList());
String... |
@Override
public void mkdir(final Path dir, final FsPermission permission,
final boolean createParent) throws IOException, UnresolvedLinkException {
myFs.mkdir(fullPath(dir), permission, createParent);
} | @Test
public void testRenameAcrossFs() throws IOException {
fc.mkdir(new Path("/newDir/dirFoo"), FileContext.DEFAULT_PERM, true);
// the root will get interpreted to the root of the chrooted fs.
fc.rename(new Path("/newDir/dirFoo"), new Path("file:///dirFooBar"));
FileContextTestHelper.isDir(fc, new P... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testDefaultExportLowercaseOutputName() throws Exception {
JmxCollector jc =
new JmxCollector("---\nlowercaseOutputName: true").register(prometheusRegistry);
assertNotNull(
getSampleValue(
"java_lang_operatingsystem_processcput... |
public synchronized boolean remove(String key) throws IOException {
checkNotClosed();
Entry entry = lruEntries.get(key);
if (entry == null || entry.currentEditor != null) {
return false;
}
for (int i = 0; i < valueCount; i++) {
File file = entry.getCleanFile(i);
if (file.exists() ... | @Test public void removeAbsentElement() throws Exception {
cache.remove("a");
} |
@Override
public boolean getBooleanValue() {
checkValueType(BOOLEAN);
return measure.getBooleanValue();
} | @Test
public void fail_with_ISE_when_not_boolean_value() {
assertThatThrownBy(() -> {
MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1));
measure.getBooleanValue();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Value can not be converted to bo... |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalBigint() {
assertThat(DEFAULT.format(Schema.OPTIONAL_INT64_SCHEMA), is("BIGINT"));
assertThat(STRICT.format(Schema.OPTIONAL_INT64_SCHEMA), is("BIGINT"));
} |
public static List<LayoutLocation> fromCompactListString(String compactList) {
List<LayoutLocation> locs = new ArrayList<>();
if (!Strings.isNullOrEmpty(compactList)) {
String[] items = compactList.split(TILDE);
for (String s : items) {
locs.add(fromCompactString(... | @Test
public void fromCompactList() {
List<LayoutLocation> locs = fromCompactListString(COMPACT_LIST);
ll = locs.get(0);
ll2 = locs.get(1);
verifyLL1(ll);
verifyLL2(ll2);
} |
byte[] removeEscapedEnclosures( byte[] field, int nrEnclosuresFound ) {
byte[] result = new byte[field.length - nrEnclosuresFound];
int resultIndex = 0;
for ( int i = 0; i < field.length; i++ ) {
result[resultIndex++] = field[i];
if ( field[i] == enclosure[0] && i + 1 < field.length && field[i +... | @Test
public void testRemoveEscapedEnclosuresWithCharacterInTheMiddleOfThem() {
CsvInputData csvInputData = new CsvInputData();
csvInputData.enclosure = "\"".getBytes();
String result = new String( csvInputData.removeEscapedEnclosures( "345\"\"1\"\"abc".getBytes(), 2 ) );
assertEquals( "345\"1\"abc", ... |
@VisibleForTesting
synchronized List<RemoteNode> getLeastLoadedNodes() {
long currTime = System.currentTimeMillis();
if ((currTime - lastCacheUpdateTime > cacheRefreshInterval)
|| (cachedNodes == null)) {
cachedNodes = convertToRemoteNodes(
this.nodeMonitor.selectLeastLoadedNodes(this.... | @Test(timeout = 60000)
public void testContainerPromoteAfterContainerStart() throws Exception {
HashMap<NodeId, MockNM> nodes = new HashMap<>();
MockNM nm1 = new MockNM("h1:1234", 4096, rm.getResourceTrackerService());
nodes.put(nm1.getNodeId(), nm1);
MockNM nm2 = new MockNM("h2:1234", 4096, rm.getRes... |
@Override
public void check(Collection<? extends T> collection, ConditionEvents events) {
ViolatedAndSatisfiedConditionEvents subEvents = new ViolatedAndSatisfiedConditionEvents();
for (T item : collection) {
condition.check(item, subEvents);
}
if (!subEvents.getAllowed()... | @Test
public void if_there_are_no_input_events_no_ContainsOnlyEvent_is_added() {
ViolatedAndSatisfiedConditionEvents events = new ViolatedAndSatisfiedConditionEvents();
containOnlyElementsThat(IS_SERIALIZABLE).check(emptyList(), events);
assertThat(events.getAllowed()).as("allowed events").i... |
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
} | @Test
public void generate_scm_info_when_nothing_in_db_and_report_is_has_no_changesets() {
when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.empty());
addFileSourceInReport(3);
ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
assertThat(scmInfo.getAllChangesets()).hasSize(3);
for (int i = 1;... |
@ScalarOperator(CAST)
@SqlType(StandardTypes.SMALLINT)
public static long castToSmallint(@SqlType(StandardTypes.INTEGER) long value)
{
try {
return Shorts.checkedCast(value);
}
catch (IllegalArgumentException e) {
throw new PrestoException(NUMERIC_VALUE_OUT_OF... | @Test
public void testCastToSmallint()
{
assertFunction("cast(INTEGER'37' as smallint)", SMALLINT, (short) 37);
assertFunction("cast(INTEGER'17' as smallint)", SMALLINT, (short) 17);
} |
@Override
public KsqlSecurityContext provide(final ApiSecurityContext apiSecurityContext) {
final Optional<KsqlPrincipal> principal = apiSecurityContext.getPrincipal();
final Optional<String> authHeader = apiSecurityContext.getAuthHeader();
final List<Entry<String, String>> requestHeaders = apiSecurityCo... | @Test
public void shouldPassRequestHeadersToUserFactory() {
// Given:
when(securityExtension.getUserContextProvider()).thenReturn(Optional.of(userContextProvider));
// When:
ksqlSecurityContextProvider.provide(apiSecurityContext);
// Then:
verify(userServiceContextFactory)
.create(an... |
public static String toUnderlineCase(CharSequence str) {
return toSymbolCase(str, CharUtil.UNDERLINE);
} | @Test
public void toUnderLineCaseTest() {
Dict.create()
.set("Table_Test_Of_day", "table_test_of_day")
.set("_Table_Test_Of_day_", "_table_test_of_day_")
.set("_Table_Test_Of_DAY_", "_table_test_of_DAY_")
.set("_TableTestOfDAYToday", "_table_test_of_DAY_today")
.set("HelloWorld_test", "hello_worl... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForSetResourceGroup() {
MySQLSetResourceGroupStatement resourceGroupStatement = mock(MySQLSetResourceGroupStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(resourceGroupStatement);
QueryContext queryContext = new QueryContext(sqlStatementCon... |
@VisibleForTesting
synchronized List<StorageDirectory> addStorageLocations(DataNode datanode,
NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
StartupOption startOpt) throws IOException {
final int numThreads = getParallelVolumeLoadThreadsNum(
dataDirs.size(), datanode.getConf());
... | @Test
public void testMissingVersion() throws IOException,
URISyntaxException {
final int numLocations = 1;
final int numNamespace = 1;
List<StorageLocation> locations = createStorageLocations(numLocations);
StorageLocation firstStorage = locations.get(0);
Storage.StorageDirectory sd = new ... |
@Override
public @NonNull TrustedSectoralIdpStep redirectToSectoralIdp(@NonNull String sectoralIdpIss) {
var trustedIdpEntityStatement = fedMasterClient.establishIdpTrust(URI.create(sectoralIdpIss));
// start PAR with sectoral IdP
// https://datatracker.ietf.org/doc/html/rfc9126
var parBody =
... | @Test
void redirectToSectoralIdp() {
var self = URI.create("https://fachdienst.example.com");
var callbackUri = self.resolve("/callback");
var fedmasterClient = mock(FederationMasterClient.class);
var openIdClient = mock(OpenIdClient.class);
var sut =
new SelectSectoralIdpStepImpl(
... |
static public ObjectName register(String serviceName, String nameName,
Object theMbean) {
return register(serviceName, nameName, Collections.emptyMap(), theMbean);
} | @Test
public void testRegister() throws Exception {
ObjectName objectName = null;
try {
counter = 23;
objectName = MBeans.register("UnitTest",
"RegisterTest", this);
MBeanServer platformMBeanServer =
ManagementFactory.getPlatformMBeanServer();
int jmxCounter = (in... |
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
startNewTableIfLimitReached(buf);
boolean odd = true;
if (((counter++) & 1) == 0) {
odd = false;
}
String level = event.getLevel().toString().toLowerCase();
buf.a... | @Test
public void layoutWithException() throws Exception {
layout.setPattern("%level %thread %msg %ex");
LoggingEvent le = createLoggingEvent();
le.setThrowableProxy(new ThrowableProxy(new Exception("test Exception")));
String result = layout.doLayout(le);
String stringToPar... |
public static ByteBuf buffer() {
return ALLOC.heapBuffer();
} | @SuppressWarnings("deprecation")
@Test
public void littleEndianWriteOnLittleEndianBufferMustStoreLittleEndianValue() {
ByteBuf b = buffer(1024).order(ByteOrder.LITTLE_ENDIAN);
b.writeShortLE(0x0102);
assertEquals((short) 0x0102, b.getShortLE(0));
assertEquals((short) 0x0102, b.g... |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = MinionConstants.UpsertCompactionTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
if (!validate(tableConfig)) {
LO... | @Test
public void testGenerateTasksValidatesTableConfigs() {
UpsertCompactionTaskGenerator taskGenerator = new UpsertCompactionTaskGenerator();
TableConfig offlineTableConfig =
new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).setTimeColumnName(TIME_COLUMN_NAME)
.build... |
private LayoutLocation(String id, Type locType, double latOrY, double longOrX) {
this.id = id;
this.latOrY = latOrY;
this.longOrX = longOrX;
this.locType = locType;
} | @Test(expected = IllegalArgumentException.class)
public void badType() {
layoutLocation(SOME_ID, "foo", ZERO, PI);
} |
@Override
public AdjacencyList setWeight(int source, int target, double weight) {
if (digraph) {
for (Edge edge : graph[source]) {
if (edge.v2 == target) {
edge.weight = weight;
return this;
}
}
} else {
... | @Test
public void testSetWeight() {
System.out.println("setWeight");
g4.setWeight(1, 4, 5.7);
assertEquals(5.7, g4.getWeight(1, 4), 1E-10);
assertEquals(1.0, g4.getWeight(4, 1), 1E-10);
g8.setWeight(1, 4, 5.7);
assertEquals(5.7, g8.getWeight(1, 4), 1E-10);
as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.