focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String getInputParameters(Properties properties) {
boolean logAllParameters = ConvertUtils.toBoolean(properties.getProperty(PropertyKeyConst.LOG_ALL_PROPERTIES),
false);
StringBuilder result = new StringBuilder();
if (logAllParameters) {
result.append(
... | @Test
void testGetInputParameters() {
Properties properties = new Properties();
properties.setProperty("testKey", "testValue");
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(prop... |
@VisibleForTesting
public ConfigDO validateConfigExists(Long id) {
if (id == null) {
return null;
}
ConfigDO config = configMapper.selectById(id);
if (config == null) {
throw exception(CONFIG_NOT_EXISTS);
}
return config;
} | @Test
public void testValidateConfigExist_notExists() {
assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS);
} |
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "/labels/by-query")
@Operation(tags = {"Executions"}, summary = "Set label on executions filter by query parameters")
public HttpResponse<?> setLabelsByQuery(
@Parameter(description = "A string filter") @Nullable @QueryValue(value = "q") String query,
... | @Test
void setLabelsByQuery() {
Execution result1 = triggerInputsFlowExecution(true);
Execution result2 = triggerInputsFlowExecution(true);
Execution result3 = triggerInputsFlowExecution(true);
BulkResponse response = client.toBlocking().retrieve(
HttpRequest.POST("/api/... |
protected final void safeRegister(final Class type, final Serializer serializer) {
safeRegister(type, createSerializerAdapter(serializer));
} | @Test(expected = IllegalArgumentException.class)
public void testSafeRegister_ConstantType() {
abstractSerializationService.safeRegister(Integer.class, new StringBufferSerializer(true));
} |
public static void initSSL(Properties consumerProps) {
// Check if one-way SSL is enabled. In this scenario, the client validates the server certificate.
String trustStoreLocation = consumerProps.getProperty(SSL_TRUSTSTORE_LOCATION);
String trustStorePassword = consumerProps.getProperty(SSL_TRUSTSTORE_PASSW... | @Test
public void testInitSSLTrustStoreAndKeyStore()
throws CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException,
KeyStoreException, IOException {
Properties consumerProps = new Properties();
setTrustStoreProps(consumerProps);
setKeyStorePro... |
@Override
public WebhookPayload create(ProjectAnalysis analysis) {
Writer string = new StringWriter();
try (JsonWriter writer = JsonWriter.of(string)) {
writer.beginObject();
writeServer(writer);
writeTask(writer, analysis.getCeTask());
writeAnalysis(writer, analysis, system2);
w... | @Test
public void create_payload_for_successful_analysis() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
Condition condition = new Condition("coverage", Condition.Operator.GREATER_THAN, "70.0");
EvaluatedQualityGate gate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate(... |
public Set<PropertyKey> keySet() {
Set<PropertyKey> keySet = new HashSet<>(PropertyKey.defaultKeys());
keySet.addAll(mUserProps.keySet());
return Collections.unmodifiableSet(keySet);
} | @Test
public void keySet() {
Set<PropertyKey> expected = new HashSet<>(PropertyKey.defaultKeys());
assertThat(mProperties.keySet(), is(expected));
PropertyKey newKey = stringBuilder("keySetNew").build();
mProperties.put(newKey, "value", Source.RUNTIME);
expected.add(newKey);
assertThat(mProper... |
@Override
public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) {
repositoryMetadataStore.removeMetadata(pluginDescriptor.id());
packageMetadataStore.removeMetadata(pluginDescriptor.id());
} | @Test
public void shouldRemoveMetadataOnPluginUnLoadedCallback() throws Exception {
RepositoryMetadataStore.getInstance().addMetadataFor(pluginDescriptor.id(), new PackageConfigurations());
PackageMetadataStore.getInstance().addMetadataFor(pluginDescriptor.id(), new PackageConfigurations());
... |
public static ColumnSegment bind(final ColumnSegment segment, final SegmentType parentSegmentType, final SQLStatementBinderContext binderContext,
final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) ... | @Test
void assertBindWithMultiTablesJoinAndNoOwner() {
Map<String, TableSegmentBinderContext> tableBinderContexts = new LinkedHashMap<>(2, 1F);
ColumnSegment boundOrderIdColumn = new ColumnSegment(0, 0, new IdentifierValue("order_id"));
boundOrderIdColumn.setColumnBoundInfo(new ColumnSegment... |
public static boolean isAllNotEmpty(CharSequence... args) {
return !hasEmpty(args);
} | @Test
public void isAllNotEmpty() {
String strings = "str";
Assert.assertTrue(StringUtil.isAllNotEmpty(strings));
} |
public byte[] data()
{
return sha1.digest();
} | @Test
public void testData()
{
byte[] buf = new byte[1024];
Arrays.fill(buf, (byte) 0xAA);
ZDigest digest = new ZDigest();
digest.update(buf);
byte[] data = digest.data();
assertThat(byt(data[0]), is(0xDE));
assertThat(byt(data[1]), is(0xB2));
as... |
public static <T> Read<T> read() {
return new AutoValue_CassandraIO_Read.Builder<T>().build();
} | @Test
public void testReadWithMapper() throws Exception {
counter.set(0);
SerializableFunction<Session, Mapper> factory = new NOOPMapperFactory();
pipeline.apply(
CassandraIO.<String>read()
.withHosts(Collections.singletonList(CASSANDRA_HOST))
.withPort(cassandraPort)
... |
static ProcessorSupplier readMapIndexSupplier(MapIndexScanMetadata indexScanMetadata) {
return new MapIndexScanProcessorSupplier(indexScanMetadata);
} | @Test
public void test_pointLookup_hashed() {
List<JetSqlRow> expected = new ArrayList<>();
for (int i = count; i > 0; i--) {
map.put(i, new Person("value-" + i, i));
}
expected.add(jetRow((5), "value-5", 5));
IndexConfig indexConfig = new IndexConfig(IndexType.H... |
@Override
public String toString() {
StringBuilder stringVector = new StringBuilder();
stringVector.append(START_PARENTHESES);
int resourceCount = 0;
for (Map.Entry<String, Double> resourceEntry : resource) {
resourceCount++;
stringVector.append(resourceEntry.getKey())
.append(V... | @Test
public void testToString() {
QueueCapacityVector capacityVector = QueueCapacityVector.newInstance();
capacityVector.setResource(MEMORY_URI, 10, ResourceUnitCapacityType.WEIGHT);
capacityVector.setResource(VCORES_URI, 6, ResourceUnitCapacityType.PERCENTAGE);
capacityVector.setResource(CUSTOM_RES... |
public String encode() {
StringBuilder sb = new StringBuilder();
//[0]
sb.append(this.topicName);
sb.append(SEPARATOR);
//[1]
sb.append(this.readQueueNums);
sb.append(SEPARATOR);
//[2]
sb.append(this.writeQueueNums);
sb.append(SEPARATOR);
... | @Test
public void testEncode() {
TopicConfig topicConfig = new TopicConfig();
topicConfig.setTopicName(topicName);
topicConfig.setReadQueueNums(queueNums);
topicConfig.setWriteQueueNums(queueNums);
topicConfig.setPerm(perm);
topicConfig.setTopicFilterType(topicFilterT... |
@Override
public void post(Event event) {
if (!getDispatcher(event).add(event)) {
log.error("Unable to post event {}", event);
}
} | @Test
public void postEventWithNoSink() throws Exception {
dispatcher.post(new Thing("boom"));
validate(gooSink);
validate(prickleSink);
} |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsMeterValues() throws Exception {
final Meter meter = mock(Meter.class);
when(meter.getCount()).thenReturn(1L);
when(meter.getMeanRate()).thenReturn(2.0);
when(meter.getOneMinuteRate()).thenReturn(3.0);
when(meter.getFiveMinuteRate()).thenReturn(4.0);
... |
public AmazonInfo build() {
return new AmazonInfo(Name.Amazon.name(), metadata);
} | @Test
public void payloadWithClassAndMetadata() throws IOException {
String json = "{"
+ " \"@class\": \"com.netflix.appinfo.AmazonInfo\","
+ " \"metadata\": {"
+ " \"instance-id\": \"i-12345\""
+ " }"
+ "}";
... |
public static boolean equals(String a, String b) {
if (a == null) {
return b == null;
}
return a.equals(b);
} | @Test
void testEquals() {
Assertions.assertTrue(StringUtils.equals("1", "1"));
Assertions.assertFalse(StringUtils.equals("1", "2"));
Assertions.assertFalse(StringUtils.equals(null, "1"));
Assertions.assertFalse(StringUtils.equals("1", null));
Assertions.assertFalse(StringUtil... |
public void completeExceptionally(Throwable value) {
checkNotNull(value);
if (this.value != EMPTY) {
throw new IllegalStateException("Promise is already completed");
}
this.value = value;
this.exceptional = true;
for (BiConsumer<E, Throwable> consumer : cons... | @Test(expected = IllegalStateException.class)
public void test_completeExceptionally_whenAlreadyCompleted() {
Promise<String> promise = new Promise<>(reactor.eventloop);
promise.completeExceptionally(new Throwable());
promise.completeExceptionally(new Throwable());
} |
@Override
public String call() throws RemoteServiceException {
var currentTime = System.nanoTime();
//Since currentTime and serverStartTime are both in nanoseconds, we convert it to
//seconds by diving by 10e9 and ensure floating point division by multiplying it
//with 1.0 first. We then check if it i... | @Test
void testDefaultConstructor() throws RemoteServiceException {
Assertions.assertThrows(RemoteServiceException.class, () -> {
var obj = new DelayedRemoteService();
obj.call();
});
} |
public Optional<DbEntityCatalogEntry> getByCollectionName(final String collection) {
return Optional.ofNullable(entitiesByCollectionName.get(collection));
} | @Test
void returnsProperDataFromCatalog() {
DbEntitiesCatalog catalog = new DbEntitiesCatalog(List.of(new DbEntityCatalogEntry("streams", "title", StreamImpl.class, "streams:read")));
assertThat(catalog.getByCollectionName("streams"))
.isEqualTo(Optional.of(
... |
public Flowable<V> takeFirstElements() {
return ElementsStream.takeElements(queue::takeFirstAsync);
} | @Test
public void testTakeFirstElements() {
RBlockingDequeRx<Integer> queue = redisson.getBlockingDeque("test");
List<Integer> elements = new ArrayList<>();
queue.takeFirstElements().subscribe(new Subscriber<Integer>() {
@Override
public void onSubscribe(Subscription... |
public void writeReference(Reference reference) throws IOException {
if (reference instanceof StringReference) {
writeQuotedString((StringReference) reference);
} else if (reference instanceof TypeReference) {
writeType((TypeReference) reference);
} else if (reference ins... | @Test
public void testWriteReference_string() throws IOException {
DexFormattedWriter writer = new DexFormattedWriter(output);
writer.writeReference(new ImmutableStringReference("string value"));
Assert.assertEquals(
"\"string value\"",
output.toString());
... |
@Restricted(NoExternalUse.class)
public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException {
// Anything larger is a file type, not a permission.
int PERMISSIONS_MASK = 07777;
// setgid/setuid/sticky are not supported.
int MAX_SUPPORTED_MODE = 0777;
... | @Test
public void testModeToPermissions() throws Exception {
assertEquals(PosixFilePermissions.fromString("rwxrwxrwx"), Util.modeToPermissions(0777));
assertEquals(PosixFilePermissions.fromString("rwxr-xrwx"), Util.modeToPermissions(0757));
assertEquals(PosixFilePermissions.fromString("rwxr-... |
public static JavaRuntimeInfo getJavaRuntimeInfo() {
return Singleton.get(JavaRuntimeInfo.class);
} | @Test
public void getJavaRuntimeInfoTest() {
final JavaRuntimeInfo info = SystemUtil.getJavaRuntimeInfo();
assertNotNull(info);
} |
public void start() {
executorService.scheduleWithFixedDelay(this::refresh, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
} | @Test
void start_adds_runnable_with_10_second_delay_and_initial_delay_putting_NodeHealth_from_provider_into_SharedHealthState() {
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
NodeHealth[] nodeHealths = {
testSupport.randomNodeHealth(),
testSupport.randomNodeHe... |
@Override
public DirectoryTimestamp getDirectoryTimestamp() {
return DirectoryTimestamp.explicit;
} | @Test
public void testFeatures() {
assertEquals(Protocol.Case.sensitive, new HubicProtocol().getCaseSensitivity());
assertEquals(Protocol.DirectoryTimestamp.explicit, new HubicProtocol().getDirectoryTimestamp());
} |
@VisibleForTesting
int persistNextQueues(final Instant currentTime) {
final int slot = messagesCache.getNextSlotToPersist();
List<String> queuesToPersist;
int queuesPersisted = 0;
do {
queuesToPersist = getQueuesTimer.record(
() -> messagesCache.getQueuesToPersist(slot, currentTime.m... | @Test
void testPersistNextQueuesSingleQueueTooSoon() {
final String queueName = new String(
MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8);
final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7;
final Instant now = Insta... |
@Override
public void reset() {
Iterator<T> iter = snapshottableIterator(SnapshottableHashTable.LATEST_EPOCH);
while (iter.hasNext()) {
iter.next();
iter.remove();
}
} | @Test
public void testReset() {
SnapshotRegistry registry = new SnapshotRegistry(new LogContext());
SnapshottableHashTable<TestElement> table =
new SnapshottableHashTable<>(registry, 1);
assertNull(table.snapshottableAddOrReplace(E_1A));
assertNull(table.snapshottableAddO... |
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch)
{
trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch);
} | @Test
public void testRecord() throws CloneNotSupportedException
{
RecordBar bar = new RecordBar();
bar.setLocation("mountain view");
RecordBar expected = bar.copy();
// Introduce bad elements
bar.data().put("SF", "CA");
Assert.assertEquals(bar.data().size(), 2);
RestUtils.trimRecordTe... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_Longer() {
expectFailureWhenTestingThat(array(2.2d, 3.3d)).isEqualTo(array(2.2d, 3.3d, 4.4d));
assertFailureKeys("expected", "but was", "wrong length", "expected", "but was");
assertFailureValueIndexed("expected", 1, "3");
assertFailureValueIn... |
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.quick_keys_popup_close:
mKeyboardActionListener.onKey(KeyCodes.CANCEL, null, 0, null, true);
break;
case R.id.quick_keys_popup_backspace:
mKeyboardActionListener.onKey(KeyCodes.DELETE, null, 0, null, true);
... | @Test
public void testOnClickSetting() throws Exception {
OnKeyboardActionListener keyboardActionListener = Mockito.mock(OnKeyboardActionListener.class);
FrameKeyboardViewClickListener listener =
new FrameKeyboardViewClickListener(keyboardActionListener);
Mockito.verifyZeroInteractions(keyboardAct... |
@SafeVarargs
public static Optional<Predicate<Throwable>> createExceptionsPredicate(
Predicate<Throwable> exceptionPredicate,
Class<? extends Throwable>... exceptions) {
return PredicateCreator.createExceptionsPredicate(exceptions)
.map(predicate -> exceptionPredicate == null ? p... | @Test
public void buildComplexRecordExceptionsPredicateWithoutClasses() {
Predicate<Throwable> exceptionPredicate = t -> t instanceof IOException || t instanceof RuntimeException;
Predicate<Throwable> predicate = PredicateCreator
.createExceptionsPredicate(exceptionPredicate)
... |
public String getEndpointsInfo() {
return loggingListener.getEndpointsInfo();
} | @Test
void logsNoEndpointsWhenNoResourcesAreRegistered() {
runJersey();
assertThat(rc.getEndpointsInfo()).contains(" NONE");
} |
public RebalanceProtocol rebalanceProtocol() {
final String upgradeFrom = streamsConfig.getString(StreamsConfig.UPGRADE_FROM_CONFIG);
if (upgradeFrom != null) {
switch (UpgradeFromValues.fromString(upgradeFrom)) {
case UPGRADE_FROM_0100:
case UPGRADE_FROM_0101... | @Test
public void rebalanceProtocolShouldSupportAllUpgradeFromVersions() {
for (final UpgradeFromValues upgradeFrom : UpgradeFromValues.values()) {
config.put(StreamsConfig.UPGRADE_FROM_CONFIG, upgradeFrom.toString());
final AssignorConfiguration assignorConfiguration = new AssignorC... |
static int decodeULE128(ByteBuf in, int result) throws Http2Exception {
final int readerIndex = in.readerIndex();
final long v = decodeULE128(in, (long) result);
if (v > Integer.MAX_VALUE) {
// the maximum value that can be represented by a signed 32 bit number is:
// [0x... | @Test
public void testDecodeULE128IntMax() throws Http2Exception {
byte[] input = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x07};
ByteBuf in = Unpooled.wrappedBuffer(input);
try {
assertEquals(MAX_VALUE, decodeULE128(in, 0));
} finally {
in.... |
boolean openNextFile() {
try {
if ( meta.getFileInFields() ) {
data.readrow = getRow(); // Grab another row ...
if ( data.readrow == null ) { // finished processing!
if ( isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "LoadFileInput.Log.FinishedProcessing" )... | @Test
public void testOpenNextFile_0() {
assertFalse( stepMetaInterface.isIgnoreEmptyFile() ); // ensure default value
stepInputFiles.addFile( getFile( "input0.txt" ) );
assertTrue( stepLoadFileInput.openNextFile() );
assertFalse( stepLoadFileInput.openNextFile() );
} |
@Description("current timestamp without time zone")
@ScalarFunction("localtimestamp")
@SqlType(StandardTypes.TIMESTAMP)
public static long localTimestamp(SqlFunctionProperties properties)
{
if (properties.isLegacyTimestamp()) {
return properties.getSessionStartTime();
}
... | @Test
public void testLocalTimestamp()
{
Session localSession = Session.builder(session)
.setStartTime(new DateTime(2017, 3, 1, 14, 30, 0, 0, DATE_TIME_ZONE).getMillis())
.build();
try (FunctionAssertions localAssertion = new FunctionAssertions(localSession)) {
... |
public int run(final String[] args) throws Exception {
if (!localTarget.isAutoFailoverEnabled()) {
LOG.error("Automatic failover is not enabled for " + localTarget + "." +
" Please ensure that automatic failover is enabled in the " +
"configuration before running the ZK failover controller... | @Test
public void testFormatOneClusterLeavesOtherClustersAlone() throws Exception {
DummyHAService svc = cluster.getService(1);
DummyZKFC zkfcInOtherCluster = new DummyZKFC(conf, cluster.getService(1)) {
@Override
protected String getScopeInsideParentNode() {
return "other-scope";
}... |
public String getMethod() {
return this.method;
} | @Test
public void testGetMethod() {
Assert.assertEquals("Signature", authorizationHeader.getMethod());
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBit() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("bit(1)")
.dataType("bit")
.length(1L)
.build(... |
@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 testInvertedBasicMatch() throws Exception {
StreamRule rule = getSampleRule();
rule.setField("message");
rule.setType(StreamRuleType.PRESENCE);
rule.setInverted(true);
Message message = getSampleMessage();
StreamRuleMatcher matcher = getMatcher(rul... |
@VisibleForTesting
public List<ProjectionContext> planRemoteAssignments(Assignments assignments, VariableAllocator variableAllocator)
{
ImmutableList.Builder<List<ProjectionContext>> assignmentProjections = ImmutableList.builder();
for (Map.Entry<VariableReferenceExpression, RowExpression> entry... | @Test
void testRemoteOnly()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
PlanRemoteProjections rule = new PlanRemoteProjections(getFunctionAndTypeManager());
List<ProjectionContext> rewritten = rule.planRemoteAssignments(Assignment... |
@Override
public final ChannelPipeline remove(ChannelHandler handler) {
remove(getContextOrDie(handler));
return this;
} | @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testRemoveAndForwardOutbound() throws Exception {
final BufferedTestHandler handler1 = new BufferedTestHandler();
final BufferedTestHandler handler2 = new BufferedTestHandler();
setUp(handler1, handler2);
s... |
public void clearPendingTasks() {
final long stamp = this.stampedLock.writeLock();
try {
this.pendingMetaQueue.clear();
this.pendingIndex = 0;
this.closureQueue.clear();
} finally {
this.stampedLock.unlockWrite(stamp);
}
} | @Test
public void testClearPendingTasks() {
testAppendPendingTask();
this.box.clearPendingTasks();
assertTrue(this.box.getPendingMetaQueue().isEmpty());
assertTrue(this.closureQueue.getQueue().isEmpty());
assertEquals(0, closureQueue.getFirstIndex());
} |
public static List<String> listMatchedFilesWithRecursiveOption(PinotFS pinotFs, URI fileUri,
@Nullable String includePattern, @Nullable String excludePattern, boolean searchRecursively)
throws Exception {
String[] files;
// listFiles throws IOException
files = pinotFs.listFiles(fileUri, searchRe... | @Test
public void testMatchFilesRecursiveSearchOnRecursiveInputFilePattern()
throws Exception {
File testDir = makeTestDir();
File inputDir = new File(testDir, "input");
File inputSubDir1 = new File(inputDir, "2009");
inputSubDir1.mkdirs();
File inputFile1 = new File(inputDir, "input.csv");... |
public static ByteArrayCoder of() {
return INSTANCE;
} | @Test
public void testRegisterByteSizeObserver() throws Exception {
CoderProperties.testByteCount(
ByteArrayCoder.of(), Coder.Context.OUTER, new byte[][] {{0xa, 0xb, 0xc}});
CoderProperties.testByteCount(
ByteArrayCoder.of(),
Coder.Context.NESTED,
new byte[][] {{0xa, 0xb, 0xc}... |
@Override
public void add(Event event) {
events.add(requireNonNull(event));
} | @Test
public void add_throws_NPE_if_even_arg_is_null() {
assertThatThrownBy(() -> underTest.add(null))
.isInstanceOf(NullPointerException.class);
} |
@Override
@TpsControl(pointName = "RemoteNamingInstanceBatchRegister", name = "RemoteNamingInstanceBatchRegister")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(rpcExtractor = BatchInstanceRequestParamExtractor.class)
public BatchInstanceResponse handle(BatchInstanceRequest request, R... | @Test
void testHandle() throws NacosException {
BatchInstanceRequest batchInstanceRequest = new BatchInstanceRequest();
batchInstanceRequest.setType(NamingRemoteConstants.BATCH_REGISTER_INSTANCE);
batchInstanceRequest.setServiceName("service1");
batchInstanceRequest.setGroupName("gro... |
@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 shouldFormatArray() {
// Given:
final Schema schema = SchemaBuilder
.array(Schema.FLOAT64_SCHEMA)
.build();
// Then:
assertThat(DEFAULT.format(schema),
is("ARRAY<DOUBLE>"));
assertThat(STRICT.format(schema),
is("ARRAY<DOUBLE NOT NULL> NOT NULL"));... |
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
final V result = super.computeIfAbsent(key, mappingFunction);
resetInverseMap();
return result;
} | @Test
public void computeIfAbsentTest(){
final BiMap<String, Integer> biMap = new BiMap<>(new HashMap<>());
biMap.put("aaa", 111);
biMap.put("bbb", 222);
biMap.computeIfAbsent("ccc", s -> 333);
assertEquals(new Integer(333), biMap.get("ccc"));
assertEquals("ccc", biMap.getKey(333));
} |
@Override
public String getUUID() throws LocalAccessDeniedException {
try {
final NetworkInterface in = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
if(null == in) {
return this.enumerate();
}
final byte[] address = in.getHard... | @Test
public void getUUID() throws Exception {
assertNotNull(new MacUniqueIdService().getUUID());
} |
static Schema getSchema(Class<? extends Message> clazz) {
return getSchema(ProtobufUtil.getDescriptorForClass(clazz));
} | @Test
public void testReversedOneOfSchema() {
assertEquals(
TestProtoSchemas.REVERSED_ONEOF_SCHEMA,
ProtoSchemaTranslator.getSchema(Proto3SchemaMessages.ReversedOneOf.class));
} |
public static void addSortedParams(UriBuilder uriBuilder, DataMap params, ProtocolVersion version)
{
if(version.compareTo(AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion()) >= 0)
{
addSortedParams(uriBuilder, params);
}
else
{
QueryParamsDataMap.addSortedParams(uriBuilder,... | @Test
public void addSortedParams()
{
DataMap queryParams = new DataMap();
DataMap aParamMap = new DataMap();
aParamMap.put("someField", "someValue");
aParamMap.put("foo", "bar");
aParamMap.put("empty", new DataMap());
DataList bParamList = new DataList();
bParamList.add("x");
bParam... |
@Override
public ObjectNode encode(MaintenanceAssociation ma, CodecContext context) {
checkNotNull(ma, "Maintenance Association cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(MA_NAME, ma.maId().toString())
.put(MA_NAME_TYPE, ma.maId().n... | @Test
public void testEncodeMa5() throws CfmConfigException {
MaintenanceAssociation ma1 = DefaultMaintenanceAssociation.builder(MAID5_Y1731, 10)
.maNumericId((short) 5)
.build();
ObjectNode node = mapper.createObjectNode();
node.set("ma", context.codec(Maint... |
@Override
public boolean test(Pickle pickle) {
String name = pickle.getName();
return patterns.stream().anyMatch(pattern -> pattern.matcher(name).find());
} | @Test
void non_anchored_name_pattern_matches_part_of_name() {
Pickle pickle = createPickleWithName("a pickle name with suffix");
NamePredicate predicate = new NamePredicate(singletonList(Pattern.compile("a pickle name")));
assertTrue(predicate.test(pickle));
} |
@Override
public boolean isAllowedTaskMovement(final ClientState source, final ClientState destination) {
final Map<String, String> sourceClientTags = clientTagFunction.apply(source.processId(), source);
final Map<String, String> destinationClientTags = clientTagFunction.apply(destination.processId(... | @Test
public void shouldDeclineTaskMovementWhenClientTagsDoNotMatch() {
final ClientState source = createClientStateWithCapacity(PID_1, 1, mkMap(mkEntry(ZONE_TAG, ZONE_1), mkEntry(CLUSTER_TAG, CLUSTER_1)));
final ClientState destination = createClientStateWithCapacity(PID_2, 1, mkMap(mkEntry(ZONE_TA... |
public static <T> Point<T> interpolate(Point<T> p1, Point<T> p2, Instant targetTime) {
checkNotNull(p1, "Cannot perform interpolation when the first input points is null");
checkNotNull(p2, "Cannot perform interpolation when the second input points is null");
checkNotNull(targetTime, "Cannot per... | @Test
public void testInterpolatePoint2() {
/*
* Test the interpolation works properly at the "start" of the timewindow
*/
Point<String> p1 = (new PointBuilder<String>())
.time(Instant.EPOCH)
.altitude(Distance.ofFeet(1000.0))
.courseInDegrees(1... |
@Override
public Object clone() {
StepMeta stepMeta = new StepMeta();
stepMeta.replaceMeta( this );
stepMeta.setObjectId( null );
return stepMeta;
} | @Test
public void cloning() throws Exception {
StepMeta meta = createTestMeta();
StepMeta clone = (StepMeta) meta.clone();
assertEquals( meta, clone );
} |
public static Map<String, Class<?>> compile(Map<String, String> classNameSourceMap, ClassLoader classLoader) {
return compile(classNameSourceMap, classLoader, null);
} | @Test
public void doNotFailOnWarning() throws Exception {
Map<String, String> source = singletonMap("org.kie.memorycompiler.WarningClass", WARNING_CLASS);
Map<String, Class<?>> compiled = KieMemoryCompiler.compile(source, this.getClass().getClassLoader());
Class<?> exampleClazz = compiled.g... |
public ConfigTransformerResult transform(Map<String, String> configs) {
Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>();
Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>();
// Collect the variables from the given configs that need transforma... | @Test
public void testReplaceVariable() {
ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "${test:testPath:testKey}"));
Map<String, String> data = result.data();
Map<String, Long> ttls = result.ttls();
assertEquals(TEST_RESULT, data.get(M... |
public ImmutableList<Process> runServerProcesses() {
logger.atInfo().log("Starting language server processes (if any)...");
return commands.stream()
// Filter out commands that don't need server start up
.filter(command -> !Strings.isNullOrEmpty(command.serverCommand()))
.map(
... | @Test
public void runServerProcess_whenServerAddressExistsAndNormalPort_returnsEmptyProcessList() {
ImmutableList<LanguageServerCommand> commands =
ImmutableList.of(
LanguageServerCommand.create(
"",
"127.0.0.1",
"34567",
"34",
... |
@VisibleForTesting
public static JobGraph createJobGraph(StreamGraph streamGraph) {
return new StreamingJobGraphGenerator(
Thread.currentThread().getContextClassLoader(),
streamGraph,
null,
Runnable::run)
... | @Deprecated
@Test
void testSinkSupportConcurrentExecutionAttemptsWithDeprecatedSink() {
final StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment(new Configuration());
env.setRuntimeMode(RuntimeExecutionMode.BATCH);
final DataStream<Intege... |
public static DataNode parseWithSchema(final String text) {
List<String> segments = Splitter.on(".").splitToList(text);
boolean hasSchema = 3 == segments.size();
if (!(2 == segments.size() || hasSchema)) {
throw new InvalidDataNodeFormatException(text);
}
DataNode res... | @Test
void assertParseWithSchema() {
DataNode actual = DataNodeUtils.parseWithSchema("ds_0.public.tbl_0");
assertThat(actual.getDataSourceName(), is("ds_0"));
assertThat(actual.getSchemaName(), is("public"));
assertThat(actual.getTableName(), is("tbl_0"));
} |
public static <T> List<LocalProperty<T>> grouped(Collection<T> columns)
{
return ImmutableList.of(new GroupingProperty<>(columns));
} | @Test
public void testPartialConstantGroup()
{
List<LocalProperty<String>> actual = builder()
.constant("a")
.grouped("a", "b")
.build();
assertMatch(
actual,
builder().grouped("a", "b", "c").build(),
... |
@ShellMethod(key = {"temp_delete", "temp delete"}, value = "Delete view name")
public String delete(
@ShellOption(value = {"--view"}, help = "view name") final String tableName) {
try {
HoodieCLI.getTempViewProvider().deleteTable(tableName);
return String.format("Delete view %s successfully!", ... | @Test
public void testDelete() {
Object result = shell.evaluate(() -> String.format("temp delete --view %s", tableName));
assertTrue(result.toString().endsWith("successfully!"));
// after delete, we can not access table yet.
assertThrows(HoodieException.class, () -> HoodieCLI.getTempViewProvider().ru... |
public static ByteBuffer sliceByteBuffer(ByteBuffer buffer, int position, int length) {
ByteBuffer slicedBuffer = ((ByteBuffer) buffer.duplicate().position(position)).slice();
slicedBuffer.limit(length);
return slicedBuffer;
} | @Test
public void sliceByteBuffer() {
final int size = 100;
final ByteBuffer buf = BufferUtils.getIncreasingByteBuffer(size);
for (int slicePosition : new int[] {0, 1, size / 2, size - 1}) {
// Slice a ByteBuffer of length 1
ByteBuffer slicedBuffer = BufferUtils.sliceByteBuffer(buf, slicePosit... |
@Override
public Iterator<T> iterator() {
return new LinkedSetIterator();
} | @Test
public void testMultiBasic() {
LOG.info("Test multi element basic");
// add once
for (Integer i : list) {
assertTrue(set.add(i));
}
assertEquals(list.size(), set.size());
// check if the elements are in the set
for (Integer i : list) {
assertTrue(set.contains(i));
}
... |
public static String toString(final Host bookmark) {
return toString(bookmark, false);
} | @Test
public void testToStringNoDefaultHostname() {
final TestProtocol protocol = new TestProtocol(Scheme.file) {
@Override
public String getName() {
return "Disk";
}
@Override
public String getDefaultHostname() {
r... |
@GetMapping(
path = "/api/{namespace}/{extension}",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
@Operation(summary = "Provides metadata of the latest version of an extension")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description =... | @Test
public void testInactiveExtension() throws Exception {
var extVersion = mockExtension();
extVersion.setActive(false);
extVersion.getExtension().setActive(false);
mockMvc.perform(get("/api/{namespace}/{extension}", "foo", "bar"))
.andExpect(status().isNotFound()... |
@EventListener
void updateTask(TaskChangeEvent event) {
removeTaskFromScheduler(event.getTask().getId());
if (!event.isRemoved() && event.getTask().getActive()) {
addTaskToScheduler(event.getTask().getId(), new SimpleTaskRunnable(event.getTask(), clientFactory.getClientForApplication(event.ge... | @Test
public void updatedTaskIsRemovedAndAddedToScheduleWhenActive() {
Task taskA = new Task();
taskA.setId(1l);
taskA.setName("old");
taskA.setCron("0 0 * * * *");
Map<Long, ScheduledFuture<?>> jobsMap = new HashMap<>();
ScheduledFuture mockA = mock(ScheduledFuture.... |
BrokerInterceptorWithClassLoader load(BrokerInterceptorMetadata metadata, String narExtractionDirectory)
throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
.narFile(narFile)
... | @Test(expectedExceptions = IOException.class)
public void testLoadBrokerEventListenerWithBlankListenerClass() throws Exception {
BrokerInterceptorDefinition def = new BrokerInterceptorDefinition();
def.setDescription("test-broker-listener");
String archivePath = "/path/to/broker/listener/na... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, INIT_CONTEXT);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void do_filter_on_auth2_identity_provider() {
when(request.getRequestURI()).thenReturn("/sessions/init/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
underTest.doFilter(request, response, chain);
assertOAuth2InitCalled();
verifyNoIn... |
public String generatePrimitiveTypeColumnTask(long tableId, long dbId, String tableName, String dbName,
List<ColumnStats> primitiveTypeStats,
TabletSampleManager manager) {
String prefix = "INSERT INTO " + STATIS... | @Test
public void generatePrimitiveTypeColumnTask() {
SampleInfo sampleInfo = tabletSampleManager.generateSampleInfo("test", "t_struct");
List<String> columnNames = table.getColumns().stream().map(Column::getName).collect(Collectors.toList());
List<Type> columnTypes = table.getColumns().stre... |
public static long calculateIntervalEnd(long startTs, IntervalType intervalType, ZoneId tzId) {
var startTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(startTs), tzId);
switch (intervalType) {
case WEEK:
return startTime.truncatedTo(ChronoUnit.DAYS).with(WeekFields.SUNDA... | @Test
void testQuarterEnd() {
long ts = 1704899727000L; // Wednesday, January 10 15:15:27 GMT
assertThat(TimeUtils.calculateIntervalEnd(ts, IntervalType.QUARTER, ZoneId.of("Europe/Kyiv"))).isEqualTo(1711918800000L); // Monday, April 1, 2024 0:00:00 GMT+03:00 DST
assertThat(TimeUtils.calculat... |
static VersionInfo parseVersionInfo(String str) throws ParseException {
Map<String, String> map = Util.parseMap(str);
VersionInfo.Builder vib = new VersionInfo.Builder();
for (Map.Entry<String, String> entry: map.entrySet()) {
switch (entry.getKey()) {
case "major" -... | @Test
public void versionInfoFromMapUnknownFieldIsIgnored(VertxTestContext context) throws ParseException {
String version = """
major=1
minor=16
gitVersion=v1.16.2
gitCommit=c97fe5036ef3df2967d086711e6c0c405941e14b
gitTreeState... |
CodeEmitter<T> emit(final Parameter parameter) {
emitter.emit("param");
emit("name", parameter.getName());
final String parameterType = parameter.getIn();
if (ObjectHelper.isNotEmpty(parameterType)) {
emit("type", RestParamType.valueOf(parameterType));
}
if (... | @Test
public void shouldEmitCodeForOas3PathParameter() {
final Builder method = MethodSpec.methodBuilder("configure");
final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method);
final OperationVisitor<?> visitor = new OperationVisitor<>(emitter, null, null, null, nu... |
RequestQueue<WriteRequest> getWriteRequestQueue(FileIOChannel.ID channelID) {
return this.writers[channelID.getThreadNum()].requestQueue;
} | @Test
void testExceptionInCallbackWrite() throws Exception {
final AtomicBoolean handlerCalled = new AtomicBoolean();
WriteRequest regularRequest =
new WriteRequest() {
@Override
public void requestDone(IOException ioex) {
... |
@Override
public long extract(
final ConsumerRecord<Object, Object> record,
final long previousTimestamp
) {
return timestampExtractor.extract(record, previousTimestamp);
} | @Test
public void shouldCallInternalTimestampExtractorOnExtract() {
// Given
final MetadataTimestampExtractor metadataTimestampExtractor =
new MetadataTimestampExtractor(timestampExtractor);
// When
metadataTimestampExtractor.extract(record, 1);
// Then
Mockito.verify(timestampExtrac... |
public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) {
final String configuredPoolingType = MetastoreConf.getVar(hdpConfig,
MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE);
return Iterables.tryFind(FACTORIES, factory -> {
String poolingType = factory.getPoolingT... | @Test
public void testCreateHikariCpDataSource() throws SQLException {
MetastoreConf.setVar(conf, ConfVars.CONNECTION_POOLING_TYPE, HikariCPDataSourceProvider.HIKARI);
// This is needed to prevent the HikariDataSource from trying to connect to the DB
conf.set(HikariCPDataSourceProvider.HIKARI + ".initial... |
public static Timestamp next(Timestamp timestamp) {
if (timestamp.equals(Timestamp.MAX_VALUE)) {
return timestamp;
}
final int nanos = timestamp.getNanos();
final long seconds = timestamp.getSeconds();
if (nanos + 1 >= NANOS_PER_SECOND) {
return Timestamp.ofTimeSecondsAndNanos(seconds +... | @Test
public void testNextReturnsMaxWhenTimestampIsAlreadyMax() {
assertEquals(Timestamp.MAX_VALUE, TimestampUtils.next(Timestamp.MAX_VALUE));
} |
public String parseString(String name) {
String property = getProperties().getProperty(name);
if (property == null) {
throw new NullPointerException();
}
return property;
} | @Test
public void testParseString() {
System.out.println("parseString");
String expResult;
String result;
Properties props = new Properties();
props.put("value1", "sTr1");
props.put("value2", "str_2");
props.put("empty", "");
props.put("str", "abc");
... |
public synchronized ValuesAndExtrapolations aggregate(SortedSet<Long> windowIndices, MetricDef metricDef) {
return aggregate(windowIndices, metricDef, true);
} | @Test
public void testExtrapolationAdjacentAvgAtLeftEdge() {
RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS);
prepareWindowMissingAtIndex(rawValues, 0);
ValuesAndExtrapolations valuesAndExtrapolations = aggregate(rawValues, allWindowIndices(0))... |
public int releaseMessageNotificationBatch() {
int batch = getIntProperty("apollo.release-message.notification.batch", DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH);
return checkInt(batch, 1, Integer.MAX_VALUE, DEFAULT_RELEASE_MESSAGE_NOTIFICATION_BATCH);
} | @Test
public void testReleaseMessageNotificationBatch() throws Exception {
int someBatch = 20;
when(environment.getProperty("apollo.release-message.notification.batch")).thenReturn(String.valueOf(someBatch));
assertEquals(someBatch, bizConfig.releaseMessageNotificationBatch());
} |
@Override
public double read() {
return gaugeSource.read();
} | @Test
public void whenCacheDynamicMetricSourceGcdReadsDefault() {
NullableDynamicMetricsProvider metricsProvider = new NullableDynamicMetricsProvider();
WeakReference<SomeObject> someObjectWeakRef = new WeakReference<>(metricsProvider.someObject);
metricsProvider.someObject.doubleField = 42.... |
public static <T> Iterable<T> nullToEmpty(Iterable<T> iterable) {
return iterable == null ? Collections.emptyList() : iterable;
} | @Test
public void testIterableIsEmpty_whenNullUsed() {
assertEquals(emptyList(), IterableUtil.nullToEmpty(null));
assertEquals(numbers, IterableUtil.nullToEmpty(numbers));
} |
public static Map<String, String> configureFromPulsar1AuthParamString(String authParamsString) {
Map<String, String> authParams = new HashMap<>();
if (isNotBlank(authParamsString)) {
String[] params = authParamsString.split(",");
for (String p : params) {
// The ... | @Test
public void testConfigureAuthParamString() {
Map<String, String> params = AuthenticationUtil.configureFromPulsar1AuthParamString(
"key:value,path:C:\\path\\to\\file,null-key:,:null-value,:,key:value-2");
assertEquals(params.size(), 3);
assertEquals(params.get("key"), "v... |
public static String[] split(final String str, final String separatorChars) {
if (str == null) {
return null;
}
if (isBlank(str)) {
return EMPTY_ARRAY;
}
if (isBlank(separatorChars)) {
return str.split(" ");
}
return str.split(s... | @Test
public void split() {
String str1 = null;
String separator1 = "*";
String[] res1 = StringUtil.split(str1, separator1);
assert res1 == null;
String str2 = "";
String separator2 = "*";
String[] res2 = StringUtil.split(str2, separator2);
Assert.ass... |
static Set<Set<Integer>> computeStronglyConnectedComponents(
final int numVertex, final List<List<Integer>> outEdges) {
final Set<Set<Integer>> stronglyConnectedComponents = new HashSet<>();
// a vertex will be added into this stack when it is visited for the first time
final Deque<... | @Test
void testWithCycles() {
final List<List<Integer>> edges =
Arrays.asList(
Arrays.asList(2, 3),
Arrays.asList(0),
Arrays.asList(1),
Arrays.asList(4),
Collections.emptyL... |
@Override
public void execute() {
UpdateItemResponse result = ddbClient.updateItem(UpdateItemRequest.builder().tableName(determineTableName())
.key(determineKey()).attributeUpdates(determineUpdateValues())
.expected(determineUpdateCondition()).returnValues(determineReturnValu... | @Test
public void execute() {
Map<String, AttributeValue> key = new HashMap<>();
key.put("1", AttributeValue.builder().s("Key_1").build());
exchange.getIn().setHeader(Ddb2Constants.KEY, key);
Map<String, AttributeValueUpdate> attributeMap = new HashMap<>();
AttributeValueUpd... |
@Override
public CRTask deserialize(JsonElement json,
Type type,
JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldInstantiateATaskForTypeRake() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "rake");
taskTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext);
verify(jsonDeserializationContext).deserialize(jsonObject, CRBuildTask... |
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks,
final Map<TaskId, Set<TopicPartition>> standbyTasks) {
log.info("Handle new assignment with:\n" +
"\tNew active tasks: {}\n" +
"\tNew standby tasks: {}\n" +... | @Test
public void shouldAssignMultipleTasksInStateUpdater() {
final StreamTask activeTaskToClose = statefulTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RESTORING)
.withInputPartitions(taskId03Partitions).build();
final StandbyTask standbyTaskToRecycle = standbyT... |
static Method getGetter(final Class<?> clazz, final String propertyName) {
final String getterName = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
final String iserName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
try {... | @Test
public void findBooleanGetter() throws Exception {
final Method getter = ReflectionUtils.getGetter(Foo.class, "b");
assertNotNull(getter);
assertEquals("isB", getter.getName());
} |
public void sparsePrint(PrintStream stream) {
if (mSeries.isEmpty()) {
return;
}
long start = mSeries.firstKey();
stream.printf("Time series starts at %d with width %d.%n", start, mWidthNano);
for (Map.Entry<Long, Integer> entry : mSeries.entrySet()) {
stream.printf("%d %d%n", (entry.ge... | @Test
public void sparsePrintTest() {
TimeSeries timeSeries = new TimeSeries();
timeSeries.record(mBase);
timeSeries.record(mBase + 8L * Constants.SECOND_NANO);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
timeSerie... |
@Override
public float readFloat() throws EOFException {
return Float.intBitsToFloat(readInt());
} | @Test
public void testReadFloat() throws Exception {
double readFloat = in.readFloat();
int intB = Bits.readInt(INIT_DATA, 0, byteOrder == BIG_ENDIAN);
double aFloat = Float.intBitsToFloat(intB);
assertEquals(aFloat, readFloat, 0);
} |
static void setConfig(String configName) throws Exception {
config = HandlerConfig.load(configName);
initHandlers();
initChains();
initPaths();
} | @Test(expected = Exception.class)
public void invalidMethod_init_throws() throws Exception {
Handler.setConfig("invalid-method");
} |
@EventListener
void startup(ServerStartupEvent event) {
storageProviderMetricsBinder.ifPresent(x -> LOGGER.debug("JobRunr StorageProvider MicroMeter Metrics enabled"));
backgroundJobServerMetrics.ifPresent(x -> LOGGER.debug("JobRunr BackgroundJobServer MicroMeter Metrics enabled"));
} | @Test
void onStartOptionalsAreCalledToBootstrapBinders() {
final JobRunrMetricsStarter jobRunrMetricsStarter = new JobRunrMetricsStarter(Optional.of(storageProviderMetricsBinder), Optional.of(backgroundJobServerMetricsBinder));
ListAppender<ILoggingEvent> logger = LoggerAssert.initFor(jobRunrMetrics... |
public static void logSQL(final QueryContext queryContext, final boolean showSimple, final ExecutionContext executionContext) {
log("Logic SQL: {}", queryContext.getSql());
if (showSimple) {
logSimpleMode(executionContext.getExecutionUnits());
} else {
logNormalMode(execu... | @Test
void assertLogSimpleSQL() {
SQLLogger.logSQL(queryContext, true, new ExecutionContext(queryContext, executionUnits, mock(RouteContext.class)));
assertThat(appenderList.size(), is(2));
assertTrue(appenderList.stream().allMatch(loggingEvent -> Level.INFO == loggingEvent.getLevel()));
... |
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) {
V pluginVersion = parseVersion(actualVersion);
// Treat a single version "1.4" as a left bound, equivalent to "[1.4,)"
if (acceptableVersionRange.matches(VERSION_REGEX)) {
return ge(pluginVersion, parseVersion(acc... | @Test
public void testRange_invalid() {
for (String rangeSpec :
new String[] {"[]", "[,]", "(,]", "[,)", "(,)", "[1,2,3]", "[1]", "foo", "{,2.3)", ""}) {
try {
checker.compatibleVersion(rangeSpec, "1.3");
Assert.fail("should have thrown an exception for " + rangeSpec);
} catch ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.