focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@ApiOperation(value = "Assign entity view to edge (assignEntityViewToEdge)",
notes = "Creates assignment of an existing entity view to an instance of The Edge. " +
EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION +
"Second, remote edge service will receive a copy of assignmen... | @Test
public void testAssignEntityViewToEdge() throws Exception {
Edge edge = constructEdge("My edge", "default");
Edge savedEdge = doPost("/api/edge", edge, Edge.class);
EntityView savedEntityView = getNewSavedEntityView("My entityView");
doPost("/api/edge/" + savedEdge.getId().ge... |
@Override
public ParDoFn create(
PipelineOptions options,
CloudObject cloudUserFn,
List<SideInputInfo> sideInputInfos,
TupleTag<?> mainOutputTag,
Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices,
DataflowExecutionContext<?> executionContext,
DataflowOperationContext... | @Test
public void testConversionOfRecord() throws Exception {
ParDoFn parDoFn =
new PairWithConstantKeyDoFnFactory()
.create(
null /* pipeline options */,
CloudObject.fromSpec(
ImmutableMap.of(
PropertyNames.OBJECT_TYP... |
@Override
public final ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
return addBefore(null, baseName, name, handler);
} | @Test
@Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
public void testAddBefore() throws Throwable {
ChannelPipeline pipeline1 = new LocalChannel().pipeline();
ChannelPipeline pipeline2 = new LocalChannel().pipeline();
EventLoopGroup defaultGroup = new DefaultEventLoopGroup(2);
... |
@Override
public void registerStore(final StateStore store,
final StateRestoreCallback stateRestoreCallback,
final CommitCallback commitCallback) {
final String storeName = store.name();
// TODO (KAFKA-12887): we should not trigger user's ... | @Test
public void shouldPreserveStreamsExceptionOnCloseIfStoreThrows() {
final StreamsException exception = new StreamsException("KABOOM!");
final ProcessorStateManager stateManager = getStateManager(Task.TaskType.ACTIVE);
final MockKeyValueStore stateStore = new MockKeyValueStore(persistent... |
@Override
public LoginIdentityContext getLoginIdentityContext(RequestResource resource) {
LoginIdentityContext result = new LoginIdentityContext();
if (!ramContext.validate() || notFountInjector(resource.getType())) {
return result;
}
resourceInjectors.get(resource.getTyp... | @Test
void testGetLoginIdentityContextWithoutLogin() {
LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource);
assertTrue(actual.getAllKey().isEmpty());
verify(mockResourceInjector, never()).doInject(resource, ramContext, actual);
} |
public EvictionConfig getEvictionConfig() {
return evictionConfig;
} | @Test(expected = IllegalArgumentException.class)
public void testMaxSize_whenValueIsNegative_thenThrowException() {
config.getEvictionConfig().setSize(-1);
} |
@Override
public void close() throws IOException {
close(true);
} | @Test
public void testStagingDirectoryCreation() throws IOException {
S3FileIOProperties newStagingDirectoryAwsProperties =
new S3FileIOProperties(
ImmutableMap.of(S3FileIOProperties.STAGING_DIRECTORY, newTmpDirectory));
S3OutputStream stream =
new S3OutputStream(s3, randomURI(), n... |
public OkHttpClient get(boolean keepAlive, boolean skipTLSVerify) {
try {
return cache.get(Parameters.fromBoolean(keepAlive, skipTLSVerify));
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | @Test
public void testWithTlsVerifyNoKeepAlive() throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
final ParameterizedHttpClientProvider provider = new ParameterizedHttpClientProvider(client(null), clientCertificates.sslSocketFactory(), clientCertificates.trustManager... |
@Override
public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
DeviceId deviceId,
DeviceDescription deviceDescription) {
NodeId localNode = clusterService.getLocalNode().i... | @Test
public final void testCreateOrUpdateDevice() throws IOException {
DeviceDescription description =
new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR,
HW, SW1, SN, CID);
Capture<InternalDeviceEvent> message = Capture.newInstance();
Capture<Messa... |
@Override
@SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"})
public E poll() {
final E[] buffer = consumerBuffer;
final long index = consumerIndex;
final long mask = consumerMask;
final long offset = modifiedCalcElementOffset(index, mask);
Object e = lvElement(buffer, off... | @Test(dataProvider = "empty")
public void poll_whenEmpty(MpscGrowableArrayQueue<Integer> queue) {
assertThat(queue.poll()).isNull();
} |
public ScalarFn loadScalarFunction(List<String> functionPath, String jarPath) {
String functionFullName = String.join(".", functionPath);
try {
FunctionDefinitions functionDefinitions = loadJar(jarPath);
if (!functionDefinitions.scalarFunctions().containsKey(functionPath)) {
throw new Illega... | @Test
public void testLoadUnregisteredScalarFunctionThrowsRuntimeException() {
JavaUdfLoader udfLoader = new JavaUdfLoader();
thrown.expect(RuntimeException.class);
thrown.expectMessage(
String.format("No implementation of scalar function notRegistered found in %s.", jarPath));
udfLoader.loadS... |
public Collection<DatabaseType> getAllBranchDatabaseTypes() {
return ShardingSphereServiceLoader.getServiceInstances(DatabaseType.class)
.stream().filter(each -> each.getTrunkDatabaseType().map(optional -> optional == databaseType).orElse(false)).collect(Collectors.toList());
} | @Test
void assertGetAllBranchDatabaseTypes() {
Collection<DatabaseType> actual = new DatabaseTypeRegistry(TypedSPILoader.getService(DatabaseType.class, "TRUNK")).getAllBranchDatabaseTypes();
assertThat(actual, is(Collections.singletonList(TypedSPILoader.getService(DatabaseType.class, "BRANCH"))));
... |
@Override
public boolean match(String attributeValue) {
if (attributeValue == null) {
return false;
}
switch (type) {
case Equals:
return attributeValue.equals(value);
case StartsWith:
return (length == -1 || length == attributeValue.length()) && ... | @Test
public void testEscapeChar() {
assertTrue(new LikeCondition("a\\%b").match("a%b"));
assertFalse(new LikeCondition("a\\%b").match("aXb"));
assertFalse(new LikeCondition("a\\%b").match("ab"));
assertTrue(new LikeCondition("a\\\\b").match("a\\b"));
assertTrue(new LikeCondition("a~%b"... |
@Override
public String toString() {
return namespace + "/" + name;
} | @Test
public void testToString() {
NamespaceAndName nan = new NamespaceAndName("namespace1", "name1");
assertThat(nan.toString(), is("namespace1/name1"));
} |
@Override
public void writeTo(ByteBuf byteBuf) throws LispWriterException {
WRITER.writeTo(byteBuf, this);
} | @Test
public void testSerialization() throws LispReaderException, LispWriterException,
LispParseError, DeserializationException {
ByteBuf byteBuf = Unpooled.buffer();
ReferralRecordWriter writer = new ReferralRecordWriter();
writer.writeTo(byteBuf, record... |
public SQLRewriteResult rewrite(final QueryContext queryContext, final RouteContext routeContext, final ConnectionContext connectionContext) {
SQLRewriteContext sqlRewriteContext = createSQLRewriteContext(queryContext, routeContext, connectionContext);
SQLTranslatorRule rule = globalRuleMetaData.getSing... | @Test
void assertRewriteForRouteSQLRewriteResult() {
ShardingSphereDatabase database = new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "H2"), mockResourceMetaData(),
mock(RuleMetaData.class), Collections.singletonMap("test", mock(ShardingS... |
@Override
public boolean complete() {
if (snapshotInProgress) {
return false;
}
while (emitFromTraverser(pendingTraverser)) {
try {
Message t = consumer.receiveNoWait();
if (t == null) {
pendingTraverser = eventTimeM... | @Test
public void when_projectionToNull_then_filteredOut() throws Exception {
String queueName = randomString();
logger.info("using queue: " + queueName);
String message1 = sendMessage(queueName, true);
String message2 = sendMessage(queueName, true);
initializeProcessor(queu... |
void addGetModelForKieBaseMethod(StringBuilder sb) {
sb.append(
" public java.util.List<Model> getModelsForKieBase(String kieBaseName) {\n");
if (!modelMethod.getKieBaseNames().isEmpty()) {
sb.append( " switch (kieBaseName) {\n");
for (String kBase : mod... | @Test
public void addGetModelForKieBaseMethodEmptyModelsByKBaseValuesTest() {
KieBaseModel kieBaseModel = getKieBaseModel("ModelTest");
Map<String, KieBaseModel> kBaseModels = new HashMap<>();
kBaseModels.put("default-kie", kieBaseModel);
Map<String, List<String>> modelsByKBase = new... |
@Override
protected String generatePoetStringTypes() {
StringBuilder symbolBuilder = new StringBuilder();
if (getMethodReturnType().equals(theContract)) {
symbolBuilder.append(" %L = %T.");
} else {
symbolBuilder.append("val %L = %L.");
}
symbolBuilder... | @Test
public void testGenerateJavaPoetStringTypesWhenReturnTypeIsNotContract() {
List<Method> listOfFilteredMethods = MethodFilter.extractValidMethods(greeterContractClass);
Method newGreeting =
listOfFilteredMethods.stream()
.filter(m -> m.getName().equals("... |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void givenTableMultipleColumns_whenLoad_thenReturnGenericRecord() {
var spec = new ObjectSpec(mapName,
col("id", INT),
col("name", STRING),
col("age", INT),
col("address", STRING));
objectProvider.createObject(spec);
... |
public Date parseString(String dateString) throws ParseException {
if (dateString == null || dateString.isEmpty()) {
return null;
}
Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString);
Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString)... | @Test
public void testFormatManySecondFractions() throws Exception
{
// Setup fixture
final String testValue = "2015-03-19T22:54:15.841473+00:00"; // Thu, 19 Mar 2015 22:54:15.841473 GMT
// Execute system under test
final Date result = xmppDateTimeFormat.parseString(testValue);
... |
InputStream getInternal(@Nullable JobID jobId, BlobKey blobKey) throws IOException {
if (this.socket.isClosed()) {
throw new IllegalStateException(
"BLOB Client is not connected. "
+ "Client has been shut down or encountered an error before.");
... | @Test
void testSocketTimeout() throws IOException {
Configuration clientConfig = getBlobClientConfig();
int oldSoTimeout = clientConfig.get(BlobServerOptions.SO_TIMEOUT);
clientConfig.set(BlobServerOptions.SO_TIMEOUT, 50);
try (final TestBlobServer testBlobServer =
... |
public void clean(final Date now) {
List<String> files = this.findFiles();
List<String> expiredFiles = this.filterFiles(files, this.createExpiredFileFilter(now));
for (String f : expiredFiles) {
this.delete(new File(f));
}
if (this.totalSizeCap != CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP && thi... | @Test
public void keepsRecentFilesAndOlderFilesWithinTotalSizeCap() {
setupSizeCapTest();
remover.clean(EXPIRY);
for (File f : recentFiles) {
verify(fileProvider, never()).deleteFile(f);
}
for (File f : Arrays.asList(expiredFiles).subList(0, MAX_HISTORY - NUM_FILES_TO_KEEP)) {
verify(... |
@Override
public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException {
if (needUsingInternalAddr()) {
remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true));
}
this.selfAddress = remoteInstan... | @Test
public void registerRemoteUsingInternal() throws NacosException {
nacosConfig.setInternalComHost(internalAddress.getHost());
nacosConfig.setInternalComPort(internalAddress.getPort());
registerRemote(internalAddress);
} |
boolean isWriteEnclosureForValueMetaInterface( ValueMetaInterface v ) {
return ( isWriteEnclosed( v ) )
|| isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( v.getName().getBytes() );
} | @Test
public void testWriteEnclosedForValueMetaInterfaceWithEnclosureForcedAndEnclosureFixDisabled() {
TextFileOutputData data = new TextFileOutputData();
data.binaryEnclosure = new byte[]{101};
data.binarySeparator = new byte[]{101};
data.writer = new ByteArrayOutputStream();
TextFileOutputMeta m... |
static AuthorizationResult getDefaultResult(Map<String, ?> configs) {
Object configValue = configs.get(ALLOW_EVERYONE_IF_NO_ACL_IS_FOUND_CONFIG);
if (configValue == null) return DENIED;
return Boolean.parseBoolean(configValue.toString().trim()) ? ALLOWED : DENIED;
} | @Test
public void testGetDefaultResult() {
assertEquals(DENIED, getDefaultResult(Collections.emptyMap()));
assertEquals(ALLOWED, getDefaultResult(Collections.singletonMap(
ALLOW_EVERYONE_IF_NO_ACL_IS_FOUND_CONFIG, "true")));
assertEquals(DENIED, getDefaultResult(Collections.singl... |
public static void init(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier,
MessageStoreConfig storeConfig, MessageStoreFetcher fetcher,
FlatFileStore flatFileStore, MessageStore next) {
TieredStoreMetricsManager.attributesBuilderSupplier = attributesBuilderSupplier;
ap... | @Test
public void init() {
MessageStoreConfig storeConfig = new MessageStoreConfig();
storeConfig.setTieredBackendServiceProvider(PosixFileSegment.class.getName());
TieredMessageStore messageStore = Mockito.mock(TieredMessageStore.class);
Mockito.when(messageStore.getStoreConfig()).t... |
public static Long jsToInteger( Object value, Class<?> clazz ) {
if ( Number.class.isAssignableFrom( clazz ) ) {
return ( (Number) value ).longValue();
} else {
String classType = clazz.getName();
if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
return ( new Long( (String) val... | @Test
public void jsToInteger_NativeJavaObject_Double() throws Exception {
Scriptable value = getDoubleValue();
assertEquals( LONG_ONE, JavaScriptUtils.jsToInteger( value, NativeJavaObject.class ) );
} |
public void printLine(String line) {
context.console().printLine(line);
} | @Test
public void shouldDelegatePrintLineToConsole() {
String line = "some line";
consoleLogger.printLine(line);
verify(mockedConsole).printLine(line);
} |
public long getDefaultValue() {
return defaultValue;
} | @Test
public void getDefaultValue_ReturnsDefaultValue() {
assertEquals(50, longRangeAttribute.getDefaultValue());
} |
public static Connection OpenConnection( String serveur, int port, String username, String password,
boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space, String proxyhost,
int proxyport, String proxyusername, String proxypassword ) throws KettleException {
Connection ... | @Test
public void testOpenConnectionTimeOut() throws Exception {
when( connection.authenticateWithPassword( username, password ) ).thenReturn( true );
assertNotNull( SSHData.OpenConnection( server, port, username, password, false, null,
null, 100, null, null, proxyPort, proxyUsername, proxyPassword ) );... |
public void free() {
try {
POSIX.munmap(baseAddress, mmappedLength);
} catch (IOException e) {
LOG.warn(this + ": failed to munmap", e);
}
LOG.trace(this + ": freed");
} | @Test(timeout=60000)
public void testStartupShutdown() throws Exception {
File path = new File(TEST_BASE, "testStartupShutdown");
path.mkdirs();
SharedFileDescriptorFactory factory =
SharedFileDescriptorFactory.create("shm_",
new String[] { path.getAbsolutePath() } );
FileInputStre... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertDouble() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.DOUBLE_TYPE).build();
BasicTypeDefine typeDefine = PostgresTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getNam... |
@GetMapping(value = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH, produces = "application/json; charset=UTF-8")
public ResponseEntity<String> metricNamespaceService(@PathVariable("namespaceId") String namespaceId,
@PathVariable("service") String service) throws NacosException {
ArrayNode arra... | @Test
public void testMetricNamespaceService() throws Exception {
when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn(testInstanceList);
String prometheusNamespaceServicePath = ApiConstants.PROMETHEUS_CONTROLLER_SERVICE_PATH.replace("{namespaceId}"... |
@Override
public Set<NodeHealth> readAll() {
long clusterTime = hzMember.getClusterTime();
long timeout = clusterTime - TIMEOUT_30_SECONDS;
Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap();
Set<UUID> hzMemberUUIDs = hzMember.getMemberUuids();
Set<NodeHealth> existingNodeHealths... | @Test
public void readAll_logs_message_for_each_non_existing_member_ignored_if_TRACE() {
logging.setLevel(Level.TRACE);
Map<String, TimestampedNodeHealth> map = new HashMap<>();
String memberUuid1 = randomAlphanumeric(44);
String memberUuid2 = randomAlphanumeric(44);
map.put(memberUuid1, new Times... |
public static String truncateContent(String content) {
if (content == null) {
return "";
} else if (content.length() <= SHOW_CONTENT_SIZE) {
return content;
} else {
return content.substring(0, SHOW_CONTENT_SIZE) + "...";
}
} | @Test
void testTruncateContentNull() {
String actual = ContentUtils.truncateContent(null);
assertEquals("", actual);
} |
@Override
Class<?> getReturnType() {
return null;
} | @Test
public void test_getReturnType() {
Class<?> returnType = NullGetter.NULL_GETTER.getReturnType();
assertNull(returnType);
} |
public static String baToHexString(byte[] ba) {
StringBuilder sb = new StringBuilder(ba.length * 2);
for (byte b : ba) {
int j = b & 0xff;
if (j < 16) {
sb.append('0'); // $NON-NLS-1$ add zero padding
}
sb.append(Integer.toHexString(j));
... | @Test
public void testbaToHexString() {
assertEquals("", JOrphanUtils.baToHexString(new byte[]{}));
assertEquals("00", JOrphanUtils.baToHexString(new byte[]{0}));
assertEquals("0f107f8081ff", JOrphanUtils.baToHexString(new byte[]{15, 16, 127, -128, -127, -1}));
} |
public Map<String, String> requestPenReset(PenRequest request) throws PenRequestException, SharedServiceClientException, SoapValidationException {
final List<PenRequestStatus> result = repository.findByBsnAndDocTypeAndSequenceNo(request.getBsn(), request.getDocType(), request.getSequenceNo());
checkIfTo... | @Test
public void penRequestWithConfigurationsErrorThrowsDWS3Exception() throws PenRequestException, SharedServiceClientException, SoapValidationException {
Mockito.when(ssMock.getSSConfigInt(speedRequest)).thenThrow(new SharedServiceClientException("DWS3"));
mockStatusList.add(status);
Mock... |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testArrayOfPrimitiveTypes() throws Exception {
Schema schema =
Schema.of(
Schema.Field.of("f0", FieldType.array(FieldType.DATETIME)),
Schema.Field.of("f1", FieldType.array(FieldType.DATETIME)),
Schema.Field.of("f2", FieldType.array(FieldType.FLOAT)),
... |
@Override
public DenseMatrix matrixMultiply(Matrix other) {
if (dim2 == other.getDimension1Size()) {
if (other instanceof DenseMatrix) {
DenseMatrix otherDense = (DenseMatrix) other;
double[][] output = new double[dim1][otherDense.dim2];
for (int ... | @Test
public void matrixMultiplyTest() {
//4x4 matrices
DenseMatrix a = generateA();
DenseMatrix b = generateB();
DenseMatrix c = generateC();
//4x7 matrix
DenseMatrix d = generateD();
//7x3 matrix
DenseMatrix e = generateE();
//3x4 matrix
... |
int numRemoteSources(EdgeDef edge) {
Set<Address> edgeSources = sources.get(edge.edgeId());
return edgeSources.contains(localAddress) ? edgeSources.size() - 1 : edgeSources.size();
} | @Test
public void when_traversingDAGAndCheckNumberOfConnections() {
VertexDef vertex_1 = createMockVertex(1);
VertexDef vertex_2 = createMockVertex(2);
List<VertexDef> vertices = Arrays.asList(vertex_1, vertex_2);
EdgeDef edge_1_2 = createEdge(vertex_1, vertex_2, null);
DagN... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testRunWithFiles() throws IOException {
// Test that the function DataflowRunner.stageFiles works as expected.
final String cloudDataflowDataset = "somedataset";
// Create some temporary files.
File temp1 = File.createTempFile("DataflowRunnerTest-", ".txt");
temp1.deleteOnExit()... |
@Override
public void createTable(Table table) {
validateTableType(table);
// first assert the table name is unique
if (tables.containsKey(table.getName())) {
throw new IllegalArgumentException("Duplicate table name: " + table.getName());
}
// invoke the provider's create
providers.get... | @Test(expected = IllegalArgumentException.class)
public void testCreateTable_duplicatedName() throws Exception {
Table table = mockTable("person");
store.createTable(table);
store.createTable(table);
} |
@Override
public Progress getProgress() {
// If current tracking range is no longer growable, get progress as a normal range.
if (range.getTo() != Long.MAX_VALUE || range.getTo() == range.getFrom()) {
return super.getProgress();
}
// Convert to BigDecimal in computation to prevent overflow, whi... | @Test
public void testProgressBeforeStart() throws Exception {
SimpleEstimator simpleEstimator = new SimpleEstimator();
GrowableOffsetRangeTracker tracker = new GrowableOffsetRangeTracker(10L, simpleEstimator);
simpleEstimator.setEstimateRangeEnd(20);
Progress currentProcess = tracker.getProgress();
... |
@Override
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) {
ServerHttpResponse response = exchange.getResponse();
long calculatedMaxAgeInSeconds = calculateMaxAgeInSeconds(exchange.getRequest(), cachedResponse,
configuredTimeToLive);
rewriteCacheControlMaxAge(response.getHeaders... | @Test
void maxAgeIsDecreasedByTimePassed_whenFilterIsAppliedAfterSecondsLater() {
Duration timeToLive = Duration.ofSeconds(30);
CachedResponse inputCachedResponse = CachedResponse.create(HttpStatus.OK).timestamp(clock.instant()).build();
SetMaxAgeHeaderAfterCacheExchangeMutator toTest = new SetMaxAgeHeaderAfter... |
public Configuration getConf() {
return conf;
} | @Test
public void testConfiguration() throws Exception {
Configuration conf = new Configuration(false);
conf.set("a", "A");
MyKeyProvider kp = new MyKeyProvider(conf);
Assert.assertEquals("A", kp.getConf().get("a"));
} |
public void alterResource(AlterResourceStmt stmt) throws DdlException {
this.writeLock();
try {
// check if the target resource exists .
String name = stmt.getResourceName();
Resource resource = this.getResource(name);
if (resource == null) {
... | @Test(expected = DdlException.class)
public void testAlterResourcePropertyNotExist(@Injectable EditLog editLog, @Mocked GlobalStateMgr globalStateMgr)
throws UserException {
ResourceMgr mgr = new ResourceMgr();
// add hive resource
name = "hive0";
type = "hive";
... |
@Override
public byte readByte(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0;
}
validateTypeCompatibility(fd, BYTE);
return super.readByte(fieldName);
} | @Test
public void testReadByte() throws Exception {
byte aByte = reader.readByte("byte");
assertEquals(1, aByte);
assertEquals(0, reader.readByte("NO SUCH FIELD"));
} |
public static KieSession loadKieSession(ModelLocalUriId modelLocalUriId, EfestoRuntimeContext context) {
logger.debug("loadKieSession {} {}", modelLocalUriId, context);
Optional<GeneratedExecutableResource> generatedExecutableResourceOpt =
GeneratedResourceUtils.getGeneratedExecutableRes... | @Disabled("DROOLS-7090 : In this test, there is no RuntimeService for drl so this cannot find IndexFile.drl_json")
@Test
void loadKieSession() {
EfestoRuntimeContext context = EfestoRuntimeContextUtils.buildWithParentClassLoader(Thread.currentThread().getContextClassLoader());
ModelLocalUriId lo... |
@Override
public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext)
{
if (addressSelectionContext.isPresent()) {
return addressSelectionContext
.map(HostAndPort::fromString)
.map(SimpleAddress::new);
}
List<... | @Test
public void testAddressSelectionNoContext()
{
InMemoryNodeManager internalNodeManager = new InMemoryNodeManager();
RandomCatalogServerAddressSelector selector = new RandomCatalogServerAddressSelector(internalNodeManager, hostAndPorts -> Optional.of(hostAndPorts.get(0)));
internalN... |
public ScanResults run(ScanTarget scanTarget) throws ExecutionException, InterruptedException {
return runAsync(scanTarget).get();
} | @Test
public void run_whenServiceFingerprinterSucceeded_fillsReconnaissanceReportWithFingerprintResult()
throws ExecutionException, InterruptedException {
Injector injector =
Guice.createInjector(
new FakeUtcClockModule(),
new FakePluginExecutionModule(),
new Fake... |
public abstract boolean compare(A actual, E expected); | @Test
public void testFormattingDiffsUsing_compare() {
// The compare behaviour should be the same as the wrapped correspondence.
assertThat(LENGTHS_WITH_DIFF.compare("foo", 3)).isTrue();
assertThat(LENGTHS_WITH_DIFF.compare("foot", 4)).isTrue();
assertThat(LENGTHS_WITH_DIFF.compare("foo", 4)).isFalse... |
@Override
public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) {
return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer);
} | @Test
void testUpdate2() {
List<ModifyRequest> modifyRequests = new ArrayList<>();
ModifyRequest modifyRequest1 = new ModifyRequest();
String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;";
modifyRequest1.setSql(sql);
Object[] args = new Object[] {1};
m... |
static KiePMMLDerivedField getKiePMMLDerivedField(final DerivedField derivedField,
final List<Field<?>> fields) {
DataType dataType = derivedField.getDataType() != null ? derivedField.getDataType() : getDataType(fields,derivedField.getName());
OP_TYP... | @Test
void getKiePMMLDerivedField() {
final String fieldName = "fieldName";
final DerivedField toConvert = getDerivedField(fieldName);
KiePMMLDerivedField retrieved = KiePMMLDerivedFieldInstanceFactory.getKiePMMLDerivedField(toConvert,
... |
@VisibleForTesting
ExportResult<MusicContainerResource> exportPlaylistItems(
TokensAndUrlAuthData authData,
IdOnlyContainerResource playlistData,
Optional<PaginationData> paginationData, UUID jobId)
throws IOException, InvalidTokenException, PermissionDeniedException, ParseException {
Stri... | @Test
public void exportPlaylistItemFirstSet()
throws IOException, InvalidTokenException, PermissionDeniedException, ParseException {
GooglePlaylistItem playlistItem = setUpSinglePlaylistItem("t1_isrc", "r1_icpn");
when(playlistItemExportResponse.getPlaylistItems())
.thenReturn(new GooglePlaylis... |
static void processResources(KieCompilerService kieCompilerService, EfestoResource toProcess, EfestoCompilationContext context) {
List<EfestoCompilationOutput> efestoCompilationOutputList = kieCompilerService.processResource(toProcess, context);
for (EfestoCompilationOutput compilationOutput : efestoCom... | @Test
void processResourcesWithRedirect() {
KieCompilerService kieCompilerServiceMock = mock(MockKieCompilerServiceF.class);
EfestoResource toProcess = new MockEfestoInputF();
EfestoCompilationContext context =
EfestoCompilationContextUtils.buildWithParentClassLoader(Thread.c... |
@Override
@Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入
public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
// 1.1 参数校验
if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY);
}
... | @Test
public void testImportUserList_02() {
// 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围
... |
public Schema addToSchema(Schema schema) {
validate(schema);
schema.addProp(LOGICAL_TYPE_PROP, name);
schema.setLogicalType(this);
return schema;
} | @Test
void bytesDecimalToFromJson() {
Schema schema = Schema.create(Schema.Type.BYTES);
LogicalTypes.decimal(9, 2).addToSchema(schema);
Schema parsed = new Schema.Parser().parse(schema.toString(true));
assertEquals(schema, parsed, "Constructed and parsed schemas should match");
} |
public String getValue() {
return value;
} | @Test
public void shouldHandleDoubleValueAsAString() throws Exception {
final ConfigurationValue configurationValue = new ConfigurationValue(3.1428571429D);
assertThat(configurationValue.getValue(), is("3.1428571429"));
} |
public synchronized Value get(String key) throws IOException {
checkNotClosed();
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
for (File file : entry.cleanFiles) {
// A file must have been deleted manually!
... | @Test public void aggressiveClearingHandlesRead() throws Exception {
deleteDirectory(cacheDir);
assertThat(cache.get("a")).isNull();
} |
public List<CreateIdStatus<K>> getElements()
{
return _collection;
} | @Test(dataProvider = "provideKeys")
public <K> void testCreate(K[] keys)
{
ProtocolVersion version = AllProtocolVersions.BASELINE_PROTOCOL_VERSION;
List<CreateIdStatus<K>> elements = new ArrayList<>();
elements.add(new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), keys[0], null, version));
e... |
public static String replaceAll(CharSequence content, String regex, String replacementTemplate) {
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
return replaceAll(content, pattern, replacementTemplate);
} | @Test
public void issuesI5TQDRTest(){
final Pattern patternIp = Pattern.compile("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})\\.((2(5[0-5]|[0-4]\\d))"
+ "|[0-1]?\\d{1,2})\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})");
final String s = ReUtil.replaceAll("1.2.3.4", patternIp, "$1.**.... |
public synchronized void put(Integer e) {
LOGGER.info("putting");
sourceList.add(e);
LOGGER.info("notifying");
notify();
} | @Test
void testPut() {
var g = new GuardedQueue();
g.put(12);
assertEquals(Integer.valueOf(12), g.get());
} |
public static String elasticsearchMessage(String indexName, String messageId) {
checkArgument("indexName", indexName);
checkArgument("messageId", messageId);
return String.join(":", ES_MESSAGE, indexName, messageId);
} | @Test
public void elasticsearchMessage() {
assertThat(EventOriginContext.elasticsearchMessage("graylog_0", "b5e53442-12bb-4374-90ed-c325c0d979ce"))
.isEqualTo("urn:graylog:message:es:graylog_0:b5e53442-12bb-4374-90ed-c325c0d979ce");
assertThatCode(() -> EventOriginContext.elasticsea... |
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod handlerMethod) {
preHandle(handlerMethod, request);
} else {
LOGGER.debug("Handler is not a HandlerMethod, skipping deprecated check.");
}
re... | @Test
public void preHandle_whenNotHandlerMethod_shouldLogDebugMessage() {
DeprecatedHandler handler = new DeprecatedHandler(userSession);
boolean result = handler.preHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), "Not handler");
assertThat(result).isTrue();
assertThat(logTe... |
@VisibleForTesting
protected static PrivateKey loadPrivateKey(File file, String password) throws IOException, GeneralSecurityException {
try (final InputStream is = Files.newInputStream(file.toPath())) {
final byte[] keyBytes = ByteStreams.toByteArray(is);
final String keyString = ne... | @Test
public void testLoadPrivateKey() throws Exception {
if (exceptionClass != null) {
expectedException.expect(exceptionClass);
expectedException.expectMessage(exceptionMessage);
}
final File keyFile = resourceToFile(keyFileName);
final PrivateKey privateKe... |
public void setSelectLength( int[] selectLength ) {
if ( selectLength.length > selectFields.length ) {
resizeSelectFields( selectLength.length );
}
for ( int i = 0; i < selectFields.length; i++ ) {
if ( i < selectLength.length ) {
selectFields[i].setLength( selectLength[i] );
} els... | @Test
public void setSelectLength() {
selectValuesMeta.setSelectLength( new int[] { 1, 2 } );
assertArrayEquals( new int[] { 1, 2 }, selectValuesMeta.getSelectLength() );
} |
State getState() {
return state;
} | @Test
public void verify_failed_restart_resulting_in_hard_stop_cycle() {
assertThat(underTest.getState()).isEqualTo(INIT);
verifyMoveTo(STARTING);
verifyMoveTo(OPERATIONAL);
verifyMoveTo(RESTARTING);
verifyMoveTo(HARD_STOPPING);
verifyMoveTo(FINALIZE_STOPPING);
verifyMoveTo(STOPPED);
} |
@Override
public Map<String, String> evaluate(FunctionArgs args, EvaluationContext context) {
final String value = valueParam.required(args, context);
if (Strings.isNullOrEmpty(value)) {
return Collections.emptyMap();
}
final CharMatcher kvPairsMatcher = splitParam.option... | @Test
void testDefaultSettingsTakeFirst() {
final Map<String, Expression> arguments = Collections.singletonMap("value", valueExpression);
Map<String, String> result = classUnderTest.evaluate(new FunctionArgs(classUnderTest, arguments), evaluationContext);
Map<String, String> expectedResult... |
@Override
public int hashCode() {
return Objects.hash(
threadName,
threadState,
activeTasks,
standbyTasks,
mainConsumerClientId,
restoreConsumerClientId,
producerClientIds,
adminClientId);
} | @Test
public void shouldNotBeEqualIfDifferInConsumerClientId() {
final ThreadMetadata differRestoreConsumerClientId = new ThreadMetadataImpl(
THREAD_NAME,
THREAD_STATE,
MAIN_CONSUMER_CLIENT_ID,
"different",
PRODUCER_CLIENT_IDS,
ADMIN_CL... |
@Override
public boolean match(Message msg, StreamRule rule) {
Double msgVal = getDouble(msg.getField(rule.getField()));
if (msgVal == null) {
return false;
}
Double ruleVal = getDouble(rule.getValue());
if (ruleVal == null) {
return false;
}
... | @Test
public void testSuccessfullInvertedMatchWithEqualValues() {
StreamRule rule = getSampleRule();
rule.setValue("-9001");
rule.setInverted(true);
Message msg = getSampleMessage();
msg.addField("something", "-9001");
StreamRuleMatcher matcher = getMatcher(rule);
... |
@Operation(summary = "start an application for an app coming from a request station", tags = { SwaggerConfig.RS_ACTIVATE_WITH_APP }, operationId = "request_station_session",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "... | @Test
void validateIfCorrectProcessesAreCalledRequestStationRequestSession() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
RsStartAppApplicationRequest request = new RsStartAppApplicationRequest();
activationContro... |
public Project getProject(String gitlabUrl, String pat, Long gitlabProjectId) {
String url = format("%s/projects/%s", gitlabUrl, gitlabProjectId);
LOG.debug("get project : [{}]", url);
Request request = new Request.Builder()
.addHeader(PRIVATE_TOKEN, pat)
.get()
.url(url)
.build();
... | @Test
public void get_project_details() throws InterruptedException {
MockResponse projectResponse = new MockResponse()
.setResponseCode(200)
.setBody("""
{\
"id": 1234,\
"name": "SonarQube example 2",\
"name_with_namespace": "SonarSource / SonarQube / SonarQube e... |
@Override
public void streamRequest(final StreamRequest request, final Callback<StreamResponse> callback)
{
streamRequest(request, new RequestContext(), callback);
} | @Test
public void testStreamWithFailout() throws URISyntaxException, InterruptedException {
setupRedirectStrategy(true);
sendAndVerifyStreamRequest();
ArgumentCaptor<StreamRequest> requestArgumentCaptor = ArgumentCaptor.forClass(StreamRequest.class);
verify(_d2Client, times(1)).streamRequest(request... |
@Override
public String selectForUpdateSkipLocked() {
return supportsSelectForUpdateSkipLocked ? " FOR UPDATE SKIP LOCKED" : "";
} | @Test
void mySQL8DoesNotSupportSelectForUpdateSkipLocked() {
assertThat(new MySqlDialect("MySQL", "8.0.0").selectForUpdateSkipLocked()).isEmpty();
} |
@Override
public Object parse(final String property, final Object value) {
if (property.equalsIgnoreCase(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT)) {
validator.validate(property, value);
return value;
}
final ConfigItem configItem = resolver.resolve(property, true)
.orElseTh... | @Test
public void shouldCallResolverForOtherProperties() {
// When:
parser.parse(KsqlConfig.KSQL_SERVICE_ID_CONFIG, "100");
// Then:
verify(resolver).resolve(KsqlConfig.KSQL_SERVICE_ID_CONFIG, true);
} |
@Override
public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) {
return getSqlRecordIteratorBatch(value, descending, null);
} | @Test
public void getSqlRecordIteratorBatchLeftIncludedRightExcludedDescending() {
var expectedKeyOrder = List.of(6, 3, 0);
var result = store.getSqlRecordIteratorBatch(0, true, 1, false, true);
assertResult(expectedKeyOrder, result);
} |
public static boolean validateAssuranceLevel(int assuranceLevel) {
return numberMap.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), assuranceLevel))
.findFirst()
.map(Map.Entry::getKey)
.isPresent();
} | @Test
void unknownAssuranceLevel() {
boolean result = LevelOfAssurance.validateAssuranceLevel(40);
assertFalse(result);
} |
public static String toAbsolute(String baseURL, String relativeURL) {
String relURL = relativeURL;
// Relative to protocol
if (relURL.startsWith("//")) {
return StringUtils.substringBefore(baseURL, "//") + "//"
+ StringUtils.substringAfter(relURL, "//");
}... | @Test
public void testToAbsoluteRelativeToFullPageURL() {
s = "?name=john";
t = "https://www.example.com/a/b/c.html?name=john";
assertEquals(t, HttpURL.toAbsolute(absURL, s));
} |
@Override
public GlobalTransaction beginTransaction(TransactionInfo txInfo) throws TransactionalExecutor.ExecutionException {
GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
try {
triggerBeforeBegin(tx);
tx.begin(txInfo.getTimeOut(), txInfo.getName());
... | @Test
public void testBeginTransaction() {
MockedStatic<GlobalTransactionContext> enhancedServiceLoader = Mockito.mockStatic(GlobalTransactionContext.class);
enhancedServiceLoader.when(GlobalTransactionContext::getCurrentOrCreate).thenReturn(new MockGlobalTransaction());
MockedStatic<Transac... |
static void verifyFixInvalidValues(final List<KiePMMLMiningField> notTargetMiningFields,
final PMMLRequestData requestData) {
logger.debug("verifyInvalidValues {} {}", notTargetMiningFields, requestData);
final Collection<ParameterInfo> requestParams = requestData.... | @Test
void verifyFixInvalidValuesInvalidAsValueWithoutReplacement() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
KiePMMLMiningField miningField0 = KiePMMLMiningField.builder("FIELD-0", null)
.withDataType(DATA_TYPE.STRING)
.withIn... |
public static SqlType fromValue(final BigDecimal value) {
// SqlDecimal does not support negative scale:
final BigDecimal decimal = value.scale() < 0
? value.setScale(0, BigDecimal.ROUND_UNNECESSARY)
: value;
/* We can't use BigDecimal.precision() directly for all cases, since it defines
... | @Test
public void shouldGetSchemaFromDecimal10_5() {
// When:
final SqlType schema = DecimalUtil.fromValue(new BigDecimal("12345.12345"));
// Then:
assertThat(schema, is(SqlTypes.decimal(10, 5)));
} |
public Span nextSpan(Message message) {
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdProperties(processorExtractor, message, message);
Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler.
// When an upstream context was not present, lookup keys are unl... | @Test void nextSpan_shouldnt_tag_queue_when_incoming_context() throws JMSException {
setStringProperty(message, "b3", "0000000000000001-0000000000000002-1");
message.setJMSDestination(createDestination("foo", TYPE.QUEUE));
jmsTracing.nextSpan(message).start().finish();
assertThat(testSpanHandler.takeLo... |
private static void addSearchChain(SearchChainResolver.Builder builder,
FederationConfig.Target target,
FederationConfig.Target.SearchChain searchChain)
{
String id = target.id();
if (!id.equals(searchChain.searchChainId()... | @Test
void require_that_optional_search_chains_does_not_delay_federation() {
BlockingSearcher blockingSearcher = new BlockingSearcher();
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addOptionalSearchChain("chain2", b... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void jdk9() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/java9.txt")),
CrashReportAnalyzer.Rule.JDK_9);
} |
private AccessLog(String logFormat, Object... args) {
Objects.requireNonNull(logFormat, "logFormat");
this.logFormat = logFormat;
this.args = args;
} | @Test
void accessLogDefaultFormat() {
disposableServer = createServer()
.handle((req, resp) -> {
resp.withConnection(conn -> {
ChannelHandler handler = conn.channel().pipeline().get(NettyPipeline.AccessLogHandler);
resp.header(ACCESS_LOG_HANDLER, handler != null ? FOUND : NOT_FOUND);
});
... |
@Override
public Collection<MepEntry> getAllMeps(MdId mdName, MaIdShort maName)
throws CfmConfigException {
//Will throw IllegalArgumentException if ma does not exist
cfmMdService.getMaintenanceAssociation(mdName, maName);
Collection<Mep> mepStoreCollection = mepStore.getAllMeps... | @Test
public void testGetAllMeps() throws CfmConfigException {
expect(mdService.getMaintenanceAssociation(MDNAME1, MANAME1))
.andReturn(Optional.ofNullable(ma1))
.anyTimes();
replay(mdService);
expect(deviceService.getDevice(DEVICE_ID1)).andReturn(device1).a... |
static void populateOutputFields(final PMML4Result toUpdate,
final ProcessingDTO processingDTO) {
logger.debug("populateOutputFields {} {}", toUpdate, processingDTO);
for (KiePMMLOutputField outputField : processingDTO.getOutputFields()) {
Object variable... | @Test
void populateTransformedOutputField1() {
KiePMMLOutputField outputField = KiePMMLOutputField.builder(OUTPUT_NAME, Collections.emptyList())
.withResultFeature(RESULT_FEATURE.TRANSFORMED_VALUE)
.build();
KiePMMLTestingModel kiePMMLModel = testingModelBuilder(outpu... |
public static TimestampExtractionPolicy create(
final KsqlConfig ksqlConfig,
final LogicalSchema schema,
final Optional<TimestampColumn> timestampColumn
) {
if (!timestampColumn.isPresent()) {
return new MetadataTimestampExtractionPolicy(getDefaultTimestampExtractor(ksqlConfig));
}
... | @Test
public void shouldCreateTimestampPolicyWhenTimestampFieldIsOfTypeTimestamp() {
// Given:
final String timestamp = "timestamp";
final LogicalSchema schema = schemaBuilder2
.valueColumn(ColumnName.of(timestamp.toUpperCase()), SqlTypes.TIMESTAMP)
.build();
// When:
final Timest... |
static Optional<Catalog> loadCatalog(Configuration conf, String catalogName) {
String catalogType = getCatalogType(conf, catalogName);
if (NO_CATALOG_TYPE.equalsIgnoreCase(catalogType)) {
return Optional.empty();
} else {
String name = catalogName == null ? ICEBERG_DEFAULT_CATALOG_NAME : catalog... | @Test
public void testDefaultCatalogProperties() {
String catalogProperty = "io.manifest.cache-enabled";
// Set global property
final String defaultCatalogProperty = InputFormatConfig.CATALOG_DEFAULT_CONFIG_PREFIX + catalogProperty;
conf.setBoolean(defaultCatalogProperty, true);
HiveCatalog defaul... |
@Override
public E putIfAbsent(String key, E value) {
return computeIfAbsent(key, k -> value);
} | @Test
public void putIfAbsent_cacheHit_noCacheUpdate() {
Function<String, Integer> mappingFunctionMock = Mockito.mock(Function.class);
doReturn(36).when(mutableEntryMock).getValue();
entryProcessorMock = new CacheRegistryStore.AtomicComputeProcessor<>();
entryProcessorArgMock = mappi... |
public long removePublication(final long registrationId)
{
final long correlationId = toDriverCommandBuffer.nextCorrelationId();
final int index = toDriverCommandBuffer.tryClaim(REMOVE_PUBLICATION, RemoveMessageFlyweight.length());
if (index < 0)
{
throw new AeronExceptio... | @Test
void threadSendsRemoveChannelMessage()
{
conductor.removePublication(CORRELATION_ID);
assertReadsOneMessage(
(msgTypeId, buffer, index, length) ->
{
final RemoveMessageFlyweight message = new RemoveMessageFlyweight();
message.wrap(buf... |
@Override
public boolean rejoinNeededOrPending() {
if (!subscriptions.hasAutoAssignedPartitions())
return false;
// we need to rejoin if we performed the assignment and metadata has changed;
// also for those owned-but-no-longer-existed partitions we should drop them as lost
... | @Test
public void testRebalanceInProgressOnSyncGroup() {
subscriptions.subscribe(singleton(topic1), Optional.of(rebalanceListener));
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
// join initiall... |
public FileConfig getFile() {
return file;
} | @Test
public void testFileConfig() {
ShenyuConfig.FileConfig fileConfig = config.getFile();
fileConfig.setMaxSize(10);
fileConfig.setEnabled(true);
Boolean enabled = fileConfig.getEnabled();
Integer maxSize = fileConfig.getMaxSize();
notEmptyElements(maxSize, enable... |
@Override
public Cursor<byte[]> scan(RedisClusterNode node, ScanOptions options) {
return new ScanCursor<byte[]>(0, options) {
private RedisClient client = getEntry(node);
@Override
protected ScanIteration<byte[]> doScan(long cursorId, ScanOptions options) {... | @Test
public void testScan() {
testInCluster(connection -> {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
map.put(RandomString.make(32).getBytes(), RandomString.make(32).getBytes(StandardCharsets.UTF_8));
}
conne... |
public OffsetRange[] getNextOffsetRanges(Option<String> lastCheckpointStr, long sourceLimit, HoodieIngestionMetrics metrics) {
// Come up with final set of OffsetRanges to read (account for new partitions, limit number of events)
long maxEventsToReadFromKafka = getLongWithAltKeys(props, KafkaSourceConfig.MAX_EV... | @Test
public void testGetNextOffsetRangesFromMultiplePartitions() {
HoodieTestDataGenerator dataGenerator = new HoodieTestDataGenerator();
testUtils.createTopic(testTopicName, 2);
testUtils.sendMessages(testTopicName, Helpers.jsonifyRecords(dataGenerator.generateInserts("000", 1000)));
KafkaOffsetGen ... |
static UnixResolverOptions parseEtcResolverOptions() throws IOException {
return parseEtcResolverOptions(new File(ETC_RESOLV_CONF_FILE));
} | @Test
public void timeoutOptionIsParsedIfPresent(@TempDir Path tempDir) throws IOException {
File f = buildFile(tempDir, "search localdomain\n" +
"nameserver 127.0.0.11\n" +
"options timeout:0\n");
assertEquals(0, parseEtcResolverOptions(f).timeout());
f = buildFile(... |
public Optional<Long> getTokenTimeout(
final Optional<String> token,
final KsqlConfig ksqlConfig,
final Optional<KsqlAuthTokenProvider> authTokenProvider
) {
final long maxTimeout =
ksqlConfig.getLong(KsqlConfig.KSQL_WEBSOCKET_CONNECTION_MAX_TIMEOUT_MS);
if (maxTimeout > 0) {
i... | @Test
public void shouldReturnMaxTimeout() {
// Given:
when(authTokenProvider.getLifetimeMs(TOKEN)).thenReturn(50000000L);
// Then:
assertThat(authenticationUtil.getTokenTimeout(Optional.of(TOKEN), ksqlConfig, Optional.of(authTokenProvider)), equalTo(Optional.of(60000L)));
} |
public void writeShortMethodDescriptor(MethodReference methodReference) throws IOException {
writeSimpleName(methodReference.getName());
writer.write('(');
for (CharSequence paramType: methodReference.getParameterTypes()) {
writeType(paramType);
}
writer.write(')');
... | @Test
public void testWriteShortMethodDescriptor() throws IOException {
DexFormattedWriter writer = new DexFormattedWriter(output);
writer.writeShortMethodDescriptor(getMethodReference());
Assert.assertEquals("methodName(Lparam1;Lparam2;)Lreturn/type;", output.toString());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.