focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Deprecated
private static String compatibleTypeDeclare(String declare) {
switch (declare.trim().toUpperCase()) {
case "LONG":
return "BIGINT";
case "SHORT":
return "SMALLINT";
case "BYTE":
return "TINYINT";
defa... | @Test
public void testCompatibleTypeDeclare() {
SeaTunnelDataType<?> longType =
SeaTunnelDataTypeConvertorUtil.deserializeSeaTunnelDataType("c_long", "long");
Assertions.assertEquals(BasicType.LONG_TYPE, longType);
SeaTunnelDataType<?> shortType =
SeaTunnelDa... |
@Override
public ObjectNode encode(LispSegmentAddress address, CodecContext context) {
checkNotNull(address, "LispSegmentAddress cannot be null");
final ObjectNode result = context.mapper().createObjectNode()
.put(INSTANCE_ID, address.getInstanceId());
if (address.getAddres... | @Test
public void testLispSegmentAddressEncode() {
LispSegmentAddress address = new LispSegmentAddress.Builder()
.withInstanceId(INSTANCE_ID)
.withAddress(MappingAddresses.ipv4MappingAddress(IPV4_PREFIX))
.build();
ObjectNode addressJson = segmentAddre... |
@Nullable
public static EpoxyModel<?> getModelFromPayload(List<Object> payloads, long modelId) {
if (payloads.isEmpty()) {
return null;
}
for (Object payload : payloads) {
DiffPayload diffPayload = (DiffPayload) payload;
if (diffPayload.singleModel != null) {
if (diffPayload.si... | @Test
public void getMultipleModelsFromMultipleDiffPayloads() {
TestModel model1Payload1 = new TestModel(1);
TestModel model2Payload1 = new TestModel(2);
DiffPayload diffPayload1 = diffPayloadWithModels(model1Payload1, model2Payload1);
TestModel model1Payload2 = new TestModel(3);
TestModel model2... |
public IterableSubject asList() {
return checkNoNeedToDisplayBothValues("asList()").that(Shorts.asList(checkNotNull(actual)));
} | @Test
public void asListWithoutCastingFails() {
expectFailureWhenTestingThat(array(1, 1, 0)).asList().containsAtLeast(1, 0);
assertFailureKeys(
"value of",
"missing (2)",
"though it did contain (3)",
"---",
"expected to contain at least",
"but was");
} |
@Override
public Object getValue( Node node ) throws KettleException {
switch ( storageType ) {
case STORAGE_TYPE_NORMAL:
String valueString = XMLHandler.getNodeValue( node );
if ( Utils.isEmpty( valueString ) ) {
return null;
}
// Handle Content -- only when not ... | @Test
public void testGetValueFromNode() throws Exception {
ValueMetaBase valueMetaBase = null;
Node xmlNode = null;
valueMetaBase = new ValueMetaBase( "test", ValueMetaInterface.TYPE_STRING );
xmlNode = XMLHandler.loadXMLString( "<value-data>String val</value-data>" ).getFirstChild();
assertEqu... |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData,
PhotosContainerResource data)
throws Exception {
if (data == null) {
return ImportResult.OK;
}
AppleMediaInterface mediaInterface = f... | @Test
public void importPhotosMultipleBatches() throws Exception {
// set up
final int photoCount = ApplePhotosConstants.maxNewMediaRequests + 1;
final List<PhotoModel> photos = createTestPhotos(photoCount);
final Map<String, Integer> dataIdToStatus =
photos.stream()
.collect(
... |
@Override
public List<String> getChildrenKeys(final String key) {
try {
List<String> result = client.getChildren().forPath(key);
result.sort(Comparator.reverseOrder());
return result;
// CHECKSTYLE:OFF
} catch (final Exception ex) {
// CHEC... | @Test
void assertGetChildrenKeys() throws Exception {
List<String> keys = Arrays.asList("/test/children/keys/1", "/test/children/keys/2");
when(getChildrenBuilder.forPath("/test/children/keys")).thenReturn(keys);
List<String> childrenKeys = REPOSITORY.getChildrenKeys("/test/children/keys");
... |
public static CommitTransactionRequest fromJson(String json) {
return JsonUtil.parse(json, CommitTransactionRequestParser::fromJson);
} | @Test
public void invalidTableIdentifier() {
assertThatThrownBy(
() ->
CommitTransactionRequestParser.fromJson(
"{\"table-changes\":[{\"ns1.table1\" : \"ns1.table1\"}]}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid table chang... |
@VisibleForTesting
void processIncludeView( Object[] outputRow ) {
// Views
if ( meta.isIncludeView() ) {
try {
String[] viewNames = data.db.getViews( data.realSchemaName, meta.isAddSchemaInOut() );
String[] viewNamesWithoutSchema = data.db.getViews( data.realSchemaName, false );
... | @Test
public void processIncludeViewIncludesSchemaTest() throws KettleException {
prepareIncludeViewTest( true );
getTableNamesSpy.processIncludeView( new Object[] { "", "", "", "" } );
//Regardless of include schema is true or false calls to isSystemTable should be done
//with the table name without ... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void shouldThrowMaxRetriesExceptionAfterRetriesExhaustedWhenConfigured() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3)
.failAfte... |
public static int getValueMetaLen() {
return VALUE_DATA_OFFSET;
} | @Test
void testValueSpacePutAndGet() {
for (int i = 0; i < 100; i++) {
int valueLen = ThreadLocalRandom.current().nextInt(100) + 1;
ValueSpace valueSpace = createValueSpace(valueLen);
int valueMetaLen = SkipListUtils.getValueMetaLen();
int totalValueSpaceLen =... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setChatMenuButton() {
BaseResponse response = bot.execute(new SetChatMenuButton().chatId(chatId)
.menuButton(new MenuButtonWebApp("webapp", new WebAppInfo("https://core.telegram.org"))));
assertTrue(response.isOk());
response = bot.execute(new SetChatMenuBu... |
public boolean fence(HAServiceTarget fromSvc) {
return fence(fromSvc, null);
} | @Test
public void testShortNameSshWithUser() throws BadFencingConfigurationException {
NodeFencer fencer = setupFencer("sshfence(user)");
assertFalse(fencer.fence(MOCK_TARGET));
} |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
final String param = exchange.getAttribute(Constants.PARAM_TRANSFORM);
ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);... | @Test
@SuppressWarnings("all")
public void testDoExecute() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
ServerWebExchange exchange = getServerWebExchange();
exchange.getAttributes().put(Constants.PARAM_TRANSFORM, "{message:1}");
exchange.getAttributes().p... |
@Override
public short readShort(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0;
}
switch (fd.getType()) {
case SHORT:
return super.readShort(fieldName);
case ... | @Test
public void testReadShort() throws Exception {
int aByte = reader.readShort("byte");
int aShort = reader.readShort("short");
assertEquals(1, aByte);
assertEquals(3, aShort);
assertEquals(0, reader.readShort("NO SUCH FIELD"));
} |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public Long createTenant(TenantSaveReqVO createReqVO) {
// 校验租户名称是否重复
validTenantNameDuplicate(createReqVO.getName(), null);
// 校验租户域名是否重复
validTenantWebsiteDuplicate(createReqVO.getWebsite(), null);
/... | @Test
public void testCreateTenant() {
// mock 套餐 100L
TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L));
when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage);
// mock 角色 200L
when(roleService.createRole(argThat... |
public List<DirectEncryptedPseudonymType> provideDep(ProvideDEPsRequest request) throws BsnkException {
try {
return ((BSNKDEPPort) this.bindingProvider).bsnkProvideDEPs(request).getDirectEncryptedPseudonyms();
} catch (SOAPFaultException ex) {
if (ex.getCause().getMessage().equa... | @Test
public void testValidResponseSuccess() {
setupWireMock();
try {
assertEquals(1, client.provideDep(request).size());
} catch (BsnkException ex) {
fail(ex.getMessage());
}
} |
public static void delete(final File file, final boolean ignoreFailures)
{
if (file.exists())
{
if (file.isDirectory())
{
final File[] files = file.listFiles();
if (null != files)
{
for (final File f : files)... | @Test
void deleteIgnoreFailuresNonExistingDirectory()
{
final File dir = tempDir.resolve("shadow-dir").toFile();
assertTrue(dir.mkdir());
assertTrue(dir.delete());
IoUtil.delete(dir, false);
assertFalse(dir.exists());
} |
public static InetSocketAddress getBindAddress(Configuration conf) {
return conf.getSocketAddr(
YarnConfiguration.PROXY_BIND_HOST,
YarnConfiguration.PROXY_ADDRESS,
YarnConfiguration.DEFAULT_PROXY_ADDRESS,
YarnConfiguration.DEFAULT_PROXY_PORT);
} | @Test
void testStart() {
webAppProxy.init(conf);
assertEquals(STATE.INITED, webAppProxy.getServiceState());
webAppProxy.start();
for (Service service : webAppProxy.getServices()) {
if (service instanceof WebAppProxy) {
assertEquals(proxyAddress, ((WebAppProxy) service).getBindAddress());... |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_enum() {
Row beamRow = BigQueryUtils.toBeamRow(ENUM_STRING_TYPE, BQ_ENUM_ROW);
assertEquals(ENUM_STRING_ROW, beamRow);
} |
static Collection<File> internalGetFileResources(String path, Pattern pattern) {
final File file = new File(path);
if (!file.isDirectory()) {
return Collections.emptySet();
}
return getFileResourcesFromDirectory(file, pattern);
} | @Test
public void internalGetResourcesNotExisting() {
String path = "." + File.separator + "target" + File.separator + "test-classes";
Pattern pattern = Pattern.compile(".*arg");
final Collection<File> retrieved = ResourceHelper.internalGetFileResources(path, pattern);
commonVerifyCo... |
public Response downloadDumpFile(String topologyId, String hostPort, String fileName, String user) throws IOException {
String[] hostPortSplit = hostPort.split(":");
String host = hostPortSplit[0];
String portStr = hostPortSplit[1];
Path rawFile = logRoot.resolve(topologyId).resolve(port... | @Test
public void testDownloadDumpFile() throws IOException {
try (TmpPath rootPath = new TmpPath()) {
LogviewerProfileHandler handler = createHandlerTraversalTests(rootPath.getFile().toPath());
Response topoAResponse = handler.downloadDumpFile("topoA", "localhost:1111", "worker.jf... |
public PointBuilder<T> time(Instant time) {
requireNonNull(time);
this.epochTime = time.toEpochMilli();
return this;
} | @Test
public void testTime() {
Instant time = Instant.EPOCH.plusSeconds(12);
Point<?> p1 = (new PointBuilder<>()).time(time)
.latLong(0.0, 0.0)
.build();
assertTrue(p1.time().equals(time));
} |
public List<StorageLocation> check(
final Configuration conf,
final Collection<StorageLocation> dataDirs)
throws InterruptedException, IOException {
final HashMap<StorageLocation, Boolean> goodLocations =
new LinkedHashMap<>();
final Set<StorageLocation> failedLocations = new HashSet<... | @Test(timeout=30000)
public void testBadConfiguration() throws Exception {
final List<StorageLocation> locations =
makeMockLocations(HEALTHY, HEALTHY, HEALTHY);
final Configuration conf = new HdfsConfiguration();
conf.setInt(DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, 3);
thrown.expect(HadoopI... |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> left,
final KTableHolder<K> right,
final StreamTableJoin<K> join,
final RuntimeBuildContext buildContext,
final JoinedFactory joinedFactory
) {
final Formats leftFormats = join.getInternalFormats();
final QueryConte... | @Test
public void shouldDoInnerJoin() {
// Given:
givenInnerJoin(L_KEY);
// When:
final KStreamHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
verify(leftKStream).join(
same(rightKTable),
eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.valu... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testUnknownSpdyWindowUpdateFrameFlags() throws Exception {
short type = 9;
byte flags = (byte) 0xFF; // undefined flags
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeFromUnsupportedKafkaVersion(VertxTestContext context) {
String oldKafkaVersion = "2.8.0";
String oldInterBrokerProtocolVersion = "2.8";
String oldLogMessageFormatVersion = "2.8";
String kafkaVersion = VERSIONS.defaultVersion().version();
Version... |
public static Collection<MetaDataLoaderMaterial> getMetaDataLoaderMaterials(final Collection<String> tableNames,
final GenericSchemaBuilderMaterial material, final boolean checkMetaDataEnable) {
Map<String, Collection<String>> dataS... | @Test
void assertGetSchemaMetaDataLoaderMaterialsWhenConfigCheckMetaDataEnable() {
ShardingSphereRule rule = mock(ShardingSphereRule.class);
DataNodeRuleAttribute ruleAttribute = mock(DataNodeRuleAttribute.class);
when(ruleAttribute.getDataNodesByTableName("t_order")).thenReturn(mockSharding... |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void format_sets_subject_with_project_name_and_branch_name_of_first_issue_in_set_when_change_from_Analysis() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newBranch("prj_" + i, "br_" + i), newRando... |
@Override
public void addPath(String word, int outputSymbol) {
MutableState state = getStartState();
if (state == null) {
throw new IllegalStateException("Start state cannot be null");
}
List<MutableArc> arcs = state.getArcs();
boolean isFound = false;
for (MutableArc arc : arcs) {
... | @Test
public void testRegexMatcherPrefix() {
MutableFST fst = new MutableFSTImpl();
fst.addPath("he", 127);
fst.addPath("hp", 136);
RoaringBitmapWriter<MutableRoaringBitmap> writer = RoaringBitmapWriter.bufferWriter().get();
RealTimeRegexpMatcher.regexMatch("h.*", fst, writer::add);
Assert.... |
@Override
public int compareTo(IndexKey o) {
if (_name.equals(o._name)) {
return _type.getId().compareTo(o._type.getId());
}
return _name.compareTo(o._name);
} | @Test
public void testCompareTo() {
List<IndexKey> iks = Arrays
.asList(new IndexKey("foo", StandardIndexes.inverted()), new IndexKey("bar", StandardIndexes.bloomFilter()),
new IndexKey("foo", StandardIndexes.forward()), new IndexKey("bar", StandardIndexes.dictionary()),
new IndexK... |
@Override
@CanIgnoreReturnValue
public FileChannel truncate(long size) throws IOException {
Util.checkNotNegative(size, "size");
checkOpen();
checkWritable();
synchronized (this) {
boolean completed = false;
try {
if (!beginBlocking()) {
return this; // AsynchronousClo... | @Test
public void testTruncateNegative() throws IOException {
FileChannel channel = channel(regularFile(0), READ, WRITE);
try {
channel.truncate(-1);
fail();
} catch (IllegalArgumentException expected) {
}
} |
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
if (ArrayUtils.isEmpty(args)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
String message = args[0];
... | @Test
void testChangeServiceNotExport() {
String result = change.execute(mockCommandContext, new String[] {"demo"});
assertEquals("No such service demo", result);
} |
@Override
public boolean hasOperatePermission(CaseInsensitiveString username, UserRoleMatcher userRoleMatcher, boolean everyoneIsAllowedToOperateIfNoAuthIsDefined) {
return this.getAuthorizationPart().hasOperatePermission(username, userRoleMatcher, everyoneIsAllowedToOperateIfNoAuthIsDefined);
} | @Test
public void shouldUseDefaultPermissionsForOperatePermissionIfAuthorizationIsNotDefined_When2ConfigParts() {
BasicPipelineConfigs filePart = new BasicPipelineConfigs();
filePart.setOrigin(new FileConfigOrigin());
assertThat(new MergePipelineConfigs(filePart, new BasicPipelineConfigs())... |
@Override
public void remove(String objectName) {
writeLock.lock();
try {
indexKeyObjectNamesMap.values().removeIf(objectName::equals);
} finally {
writeLock.unlock();
}
} | @Test
void remove() {
var spec =
PrimaryKeySpecUtils.primaryKeyIndexSpec(IndexEntryContainerTest.FakeExtension.class);
var descriptor = new IndexDescriptor(spec);
var entry = new IndexEntryImpl(descriptor);
entry.addEntry(List.of("slug-1"), "fake-name-1");
assertT... |
@Override
public Connection getConnection() {
return null;
} | @Test
void assertGetConnection() {
assertNull(metaData.getConnection());
} |
@Override
public Optional<Long> getTimeUntilBackupRequestNano()
{
_costLimiter.arrive();
synchronized (_lock)
{
if (_histogramReady)
{
return Optional.of(Math.max(_minBackupDelayNano, _histogram.getValueAtPercentile(_percentile)));
} else
{
return Optional.empty(... | @Test
public void testValuesOutOfRange()
{
BoundedCostBackupRequestsStrategy strategy = new BoundedCostBackupRequestsStrategy(5, 64, 1024, 128, 0);
BackupRequestsSimulator simulator = new BackupRequestsSimulator(new PoissonEventsArrival(200, TimeUnit.SECONDS),
new GaussianResponseTimeDistribution(B... |
@Override
public int hashCode() {
return Objects.hash(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift,
roundingMode, Arrays.hashCode(codes), codeSeparator, codePrefixed);
} | @Test
public void testHashCode() {
MonetaryFormat mf1 = new MonetaryFormat(true);
MonetaryFormat mf2 = new MonetaryFormat(true);
assertEquals(mf1.hashCode(), mf2.hashCode());
} |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowOnInsertHeaders() {
// Given:
givenSourceStreamWithSchema(SCHEMA_WITH_HEADERS, SerdeFeatures.of(), SerdeFeatures.of());
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
allColumnNames(SCHEMA_WITH_HEADERS),
ImmutableList.of(
new... |
@Override
public String pluginNamed() {
return PluginEnum.LOGGING_CLICK_HOUSE.getName();
} | @Test
public void testPluginNamed() {
Assertions.assertEquals(loggingClickHousePluginDataHandler.pluginNamed(), "loggingClickHouse");
} |
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException {
checkMaybeCompatible(source, target);
if (source.isOptional() && !target.isOptional()) {
if (target.defaultValue() != null) {
if (record != null) {
... | @Test
public void testNumericTypeProjection() {
Schema[] promotableSchemas = {Schema.INT8_SCHEMA, Schema.INT16_SCHEMA, Schema.INT32_SCHEMA, Schema.INT64_SCHEMA, Schema.FLOAT32_SCHEMA, Schema.FLOAT64_SCHEMA};
Schema[] promotableOptionalSchemas = {Schema.OPTIONAL_INT8_SCHEMA, Schema.OPTIONAL_INT16_SCH... |
public HostAndPort getHttpBindAddress() {
return httpBindAddress
.requireBracketsForIPv6()
.withDefaultPort(GRAYLOG_DEFAULT_PORT);
} | @Test
public void testHttpBindAddressWithDefaultPort() throws RepositoryException, ValidationException {
jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_bind_address", "example.com")))
.addConfigurationBean(configuration)
.process();
assertThat(c... |
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
Supplier<T> toRunDecorator = decorator.decorateSupplier(toRun);
try {
return toRunDecorator.get();
}
catch (CallAbortedException e) {
LOGGER.debug("PolarisCircuitBreaker CallAbortedException: {}", e.getMessage());
Polaris... | @Test
public void run() {
this.contextRunner.run(context -> {
PolarisCircuitBreakerFactory polarisCircuitBreakerFactory = context.getBean(PolarisCircuitBreakerFactory.class);
CircuitBreaker cb = polarisCircuitBreakerFactory.create(SERVICE_CIRCUIT_BREAKER);
PolarisCircuitBreakerConfigBuilder.PolarisCircuit... |
public void asyncAddData(T data, AddDataCallback callback, Object ctx){
if (!batchEnabled){
if (state == State.CLOSING || state == State.CLOSED){
callback.addFailed(BUFFERED_WRITER_CLOSED_EXCEPTION, ctx);
return;
}
ByteBuf byteBuf = dataSeriali... | @Test
public void testFailWhenAddData() throws Exception {
int batchedWriteMaxSize = 1024;
TxnLogBufferedWriter.DataSerializer dataSerializer =
new WrongDataSerializer(batchedWriteMaxSize, true, true, true);
int writeCount = 100;
var callbackWithCounter = createCallBa... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void getGameHighScores() {
GameHighScore[] scores = bot.execute(new GetGameHighScores(chatId, "AgAAAPrwAQCj_Q4D2s-51_8jsuU")).result();
GameHighScoreTest.check(scores);
scores = bot.execute(new GetGameHighScores(chatId, chatId, 8162)).result();
GameHighScoreTest.check(s... |
public void clear() {
for (Section s : sections) {
s.clear();
}
} | @Test
public void testClear() {
ConcurrentLongLongPairHashMap map = ConcurrentLongLongPairHashMap.newBuilder()
.expectedItems(2)
.concurrencyLevel(1)
.autoShrink(true)
.mapIdleFactor(0.25f)
.build();
assertEquals(map.cap... |
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
initCacheConfig();
final String pluginName = named();
PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName);
// early exit
if (Objects.isNull(plug... | @Test
public void executePluginIsNullTest() {
StepVerifier.create(testShenyuPlugin.execute(exchange, shenyuPluginChain)).expectSubscription().verifyComplete();
verify(shenyuPluginChain).execute(exchange);
} |
@POST
@Path("/{connector}/restart")
@Operation(summary = "Restart the specified connector")
public Response restartConnector(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @DefaultValue("false") @Que... | @Test
public void testRestartConnectorAndTasksLeaderRedirect() throws Throwable {
RestartRequest restartRequest = new RestartRequest(CONNECTOR_NAME, true, false);
final ArgumentCaptor<Callback<ConnectorStateInfo>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackNotLeaderExcept... |
void removeSubscription(final Subscription subscription)
{
clientLock.lock();
try
{
if (isTerminating || isClosed)
{
return;
}
if (!subscription.isClosed())
{
ensureNotReentrant();
s... | @Test
void shouldThrowAeronExceptionOnAttemptToRemoveWrongResourceUsingSubscriptionRegistrationId()
{
final long registrationId = 42;
conductor.resourceByRegIdMap.put(registrationId, "test resource");
final AeronException exception =
assertThrowsExactly(AeronException.class,... |
@Override
public Local create(final Path file) {
return this.create(new UUIDRandomStringService().random(), file);
} | @Test
public void testTemporaryPath() {
final Path file = new Path("/f1/f2/t.txt", EnumSet.of(Path.Type.file));
file.attributes().setDuplicate(true);
file.attributes().setVersionId("1");
final Local local = new DefaultTemporaryFileService().create(file);
assertEquals("t.txt",... |
public static TableIdentifier toIcebergTableIdentifier(SnowflakeIdentifier identifier) {
Preconditions.checkArgument(
identifier.type() == SnowflakeIdentifier.Type.TABLE,
"SnowflakeIdentifier must be type TABLE, got '%s'",
identifier);
return TableIdentifier.of(
identifier.databa... | @Test
public void testToIcebergTableIdentifierWrongType() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() ->
NamespaceHelpers.toIcebergTableIdentifier(
SnowflakeIdentifier.ofSchema("DB1", "SCHEMA1")))
.withMessageContainin... |
public <T> void update(T[][] observations, int iterations, ToIntFunction<T> ordinal) {
update(
Arrays.stream(observations)
.map(sequence -> Arrays.stream(sequence).mapToInt(ordinal).toArray())
.toArray(int[][]::new),
iterations);
... | @Test
public void testUpdate() {
System.out.println("update");
MathEx.setSeed(19650218); // to get repeatable results.
EmpiricalDistribution initial = new EmpiricalDistribution(pi);
EmpiricalDistribution[] transition = new EmpiricalDistribution[a.length];
for (int i = 0; i ... |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty()) {
return new GroupAssignment(Collections.emptyMap());
} else if (groupSpec.subscr... | @Test
public void testReassignmentWhenMultipleSubscriptionsRemovedAfterInitialAssignmentWithThreeMembersTwoTopics() {
Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>();
topicMetadata.put(topic1Uuid, new TopicMetadata(
topic1Uuid,
topic1Name,
3,
... |
public String getQuery() throws Exception {
return getQuery(weatherConfiguration.getLocation());
} | @Test
public void testSingleIdStationQuery() throws Exception {
WeatherConfiguration weatherConfiguration = new WeatherConfiguration();
weatherConfiguration.setIds("52");
weatherConfiguration.setMode(WeatherMode.JSON);
weatherConfiguration.setLanguage(WeatherLanguage.nl);
wea... |
@Override
public Response toResponse(Throwable e) {
if (log.isDebugEnabled()) {
log.debug("Uncaught exception in REST call: ", e);
} else if (log.isInfoEnabled()) {
log.info("Uncaught exception in REST call: {}", e.getMessage());
}
if (e instanceof NotFoundExc... | @Test
public void testToResponseInvalidTypeIdException() {
RestExceptionMapper mapper = new RestExceptionMapper();
JsonParser parser = null;
JavaType type = null;
Response resp = mapper.toResponse(InvalidTypeIdException.from(parser, "dummy msg", type, "dummy typeId"));
assert... |
public static ServiceConfiguration convertFrom(PulsarConfiguration conf, boolean ignoreNonExistMember)
throws RuntimeException {
try {
final ServiceConfiguration convertedConf = ServiceConfiguration.class
.getDeclaredConstructor().newInstance();
Field[] co... | @Test
public void testConfigurationConverting() {
MockConfiguration mockConfiguration = new MockConfiguration();
ServiceConfiguration serviceConfiguration = PulsarConfigurationLoader.convertFrom(mockConfiguration);
// check whether converting correctly
assertEquals(serviceConfigurat... |
private IcebergUUIDObjectInspector() {
super(TypeInfoFactory.stringTypeInfo);
} | @Test
public void testIcebergUUIDObjectInspector() {
IcebergUUIDObjectInspector oi = IcebergUUIDObjectInspector.get();
assertThat(oi.getCategory()).isEqualTo(ObjectInspector.Category.PRIMITIVE);
assertThat(oi.getPrimitiveCategory())
.isEqualTo(PrimitiveObjectInspector.PrimitiveCategory.STRING);
... |
public List<String> split(String in) {
final StringBuilder result = new StringBuilder();
final char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++) {
final char c = chars[i];
if (CHAR_OPERATORS.contains(String.valueOf(c))) {
if (i < char... | @Test
public void split3() {
List<String> tokens = parser.split("((a and b))");
assertEquals(Arrays.asList("(", "(", "a", "and", "b", ")", ")"), tokens);
} |
@SuppressWarnings("unchecked")
public static <T> T getObjectWithKey(String key, RequestContext requestContext, Class<T> clazz)
{
final Object object = requestContext.getLocalAttr(key);
return (clazz.isInstance(object)) ? (T) object : null;
} | @Test
public void testGetObjectWithKey()
{
_requestContext.putLocalAttr(KEY, VALUE);
Assert.assertEquals(RequestContextUtil.getObjectWithKey(KEY, _requestContext, String.class), VALUE);
} |
public String filterNamespaceName(String namespaceName) {
if (namespaceName.toLowerCase().endsWith(".properties")) {
int dotIndex = namespaceName.lastIndexOf(".");
return namespaceName.substring(0, dotIndex);
}
return namespaceName;
} | @Test
public void testFilterNamespaceNameWithMultiplePropertiesSuffix() throws Exception {
String someName = "a.properties.properties";
assertEquals("a.properties", namespaceUtil.filterNamespaceName(someName));
} |
public String filterNamespaceName(String namespaceName) {
if (namespaceName.toLowerCase().endsWith(".properties")) {
int dotIndex = namespaceName.lastIndexOf(".");
return namespaceName.substring(0, dotIndex);
}
return namespaceName;
} | @Test
public void testFilterNamespaceNameUnchanged() throws Exception {
String someName = "a.xml";
assertEquals(someName, namespaceUtil.filterNamespaceName(someName));
} |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void noDefault() throws IOException {
Flow flow = this.parse("flows/valids/parallel.yaml");
String s = mapper.writeValueAsString(flow);
assertThat(s, not(containsString("\"-c\"")));
assertThat(s, containsString("\"deleted\":false"));
} |
public DataSource<T> loadDataSource(Path csvPath, String responseName) throws IOException {
return loadDataSource(csvPath, Collections.singleton(responseName));
} | @Test
public void testLoadMultiOutput() throws IOException {
URL path = CSVLoaderTest.class.getResource("/org/tribuo/data/csv/test-multioutput.csv");
Set<String> responses = new HashSet<>(Arrays.asList("R1", "R2"));
CSVLoader<MockMultiOutput> loader = new CSVLoader<>(new MockMultiOutputFacto... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNameOnFlatTransformWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransform(flatTransformerSupplier, Named.as("flatTransform"), (String) ... |
@Override
public int hashCode() {
return name.hashCode();
} | @Test
public void test_hash() {
assertEquals(new Option<>("foo", String.class).hashCode(), new Option<>("foo", String.class).hashCode());
//hash is only based on name
assertEquals(new Option<>("foo", String.class).hashCode(), new Option<>("foo", Integer.class).hashCode());
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetLogsWithNumericBlockRange() throws Exception {
web3j.ethGetLogs(
new EthFilter(
DefaultBlockParameter.valueOf(Numeric.toBigInt("0xe8")),
DefaultBlockParameter.valueOf("latest"),
... |
private void performChecking(Context context, ResourceWrapper r) throws BlockException {
// If user has set a degrade rule for the resource, the default rule will not be activated
if (DegradeRuleManager.hasConfig(r.getName())) {
return;
}
List<CircuitBreaker> circuitBreakers... | @Test
public void testPerformChecking() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
DefaultCircuitBreakerSlot defaultCircuitBreakerSlot = mock(DefaultCircuitBreakerSlot.class);
Context context = mock(Context.class);
String resA = "resA";
Method p... |
public CruiseConfig deserializeConfig(String content) throws Exception {
String md5 = md5Hex(content);
Element element = parseInputStream(new ByteArrayInputStream(content.getBytes()));
LOGGER.debug("[Config Save] Updating config cache with new XML");
CruiseConfig configForEdit = classPa... | @Test
void shouldLoadTasksWithOnCancel() throws Exception {
CruiseConfig config = xmlLoader.deserializeConfig(TASKS_WITH_ON_CANCEL);
JobConfig job = config.jobConfigByName("pipeline1", "mingle", "cardlist", true);
Task task = job.tasks().findFirstByType(AntTask.class);
assertThat(ta... |
public static String getTmpSegmentNamePrefix(String segmentName) {
return segmentName + TMP;
} | @Test
public void testGenerateSegmentFilePrefix() {
String segmentName = "segment";
assertEquals(SegmentCompletionUtils.getTmpSegmentNamePrefix(segmentName), "segment.tmp.");
} |
private Mono<ServerResponse> listNotificationPreferences(ServerRequest request) {
var username = request.pathVariable("username");
return listReasonTypeNotifierMatrix(username)
.flatMap(matrix -> ServerResponse.ok().bodyValue(matrix));
} | @Test
void listNotificationPreferences() {
when(client.list(eq(ReasonType.class), eq(null), any())).thenReturn(Flux.empty());
when(client.list(eq(NotifierDescriptor.class), eq(null), any())).thenReturn(Flux.empty());
when(userNotificationPreferenceService.getByUser(any())).thenReturn(Mono.em... |
@VisibleForTesting
static int getIdForInsertionRequest(EditorInfo info) {
return info == null
? 0
: Arrays.hashCode(new int[] {info.fieldId, info.packageName.hashCode()});
} | @Test
public void testCallsRemoteInsertionWithCorrectArguments() {
simulateFinishInputFlow();
EditorInfo info = createEditorInfoTextWithSuggestionsForSetUp();
EditorInfoCompat.setContentMimeTypes(info, new String[] {"image/gif"});
simulateOnStartInputFlow(false, info);
Mockito.verify(mRemoteInser... |
@Override
public Class<? extends ModuleDefine> module() {
return AlarmModule.class;
} | @Test
public void module() {
assertEquals(AlarmModule.class, moduleProvider.module());
} |
boolean fillIssueInFileLocation(NewIssueLocation newIssueLocation, Location location) {
PhysicalLocation physicalLocation = location.getPhysicalLocation();
String fileUri = getFileUriOrThrow(location);
Optional<InputFile> file = findFile(fileUri);
if (file.isEmpty()) {
return false;
}
Inp... | @Test
public void fillIssueInFileLocation_ifNullArtifactLocation_throws() {
when(location.getPhysicalLocation().getArtifactLocation()).thenReturn(null);
assertThatIllegalArgumentException()
.isThrownBy(() -> locationMapper.fillIssueInFileLocation(newIssueLocation, location))
.withMessage(EXPECTED... |
List<MethodSpec> buildFunctions(AbiDefinition functionDefinition)
throws ClassNotFoundException {
return buildFunctions(functionDefinition, true);
} | @Test
public void testBuildFunctionTransactionAndCall() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
false,
Arrays.asList(new NamedType("param", "uint8")),
"functionName",
... |
@Override
public String processType() {
return TYPE;
} | @Test
void processType() {
assertEquals(DistroClientDataProcessor.TYPE, distroClientDataProcessor.processType());
} |
public static void deletePath(String path, BrokerDesc brokerDesc) throws UserException {
TNetworkAddress address = getAddress(brokerDesc);
try {
TBrokerDeletePathRequest tDeletePathRequest = new TBrokerDeletePathRequest(
TBrokerVersion.VERSION_ONE, path, brokerDesc.getPro... | @Test
public void testDeletePath(@Mocked TFileBrokerService.Client client, @Mocked GlobalStateMgr globalStateMgr,
@Injectable BrokerMgr brokerMgr) throws AnalysisException, TException {
// delete response
TBrokerOperationStatus status = new TBrokerOperationStatus();
... |
@Deprecated
public static Schema parse(File file) throws IOException {
return new Parser().parse(file);
} | @Test
void testParserNullValidate() {
new Schema.Parser((NameValidator) null).parse("{\"type\":\"record\",\"name\":\"\",\"fields\":[]}"); // Empty name
} |
@Override
public Object invokeReflectively(EvaluationContext ctx, Object[] params) {
// use reflection to call the appropriate invoke method
try {
boolean isNamedParams = params.length > 0 && params[0] instanceof NamedParameter;
if (!isCustomFunction()) {
Can... | @Test
void invokeReflectiveCustomFunction() {
List<FEELFunction.Param> parameters = List.of(new FEELFunction.Param("foo", BuiltInType.UNKNOWN),
new FEELFunction.Param("person's age", BuiltInType.UNKNOWN));
BaseNode left = new InfixOpNode(InfixOperat... |
public EnumSet<RepositoryFilePermission> processCheckboxes() {
return processCheckboxes( false );
} | @Test
public void testProcessCheckboxesManageCheckedEnableAppropriateTrue() {
when( readCheckbox.isChecked() ).thenReturn( false );
when( writeCheckbox.isChecked() ).thenReturn( false );
when( deleteCheckbox.isChecked() ).thenReturn( false );
when( manageCheckbox.isChecked() ).thenReturn( true );
... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
... | @Test
public void testGetFieldDefinition() {
assertEquals( "FOO TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, false, false ) );
... |
@Override
public void process() {
JMeterContext context = getThreadContext();
Sampler sam = context.getCurrentSampler();
SampleResult res = context.getPreviousResult();
HTTPSamplerBase sampler;
HTTPSampleResult result;
if (!(sam instanceof HTTPSamplerBase) || !(res in... | @Test
public void testSimpleParse2() throws Exception {
HTTPSamplerBase config = makeUrlConfig("/index\\.html");
HTTPSamplerBase context = makeContext("http://www.apache.org/subdir/previous.html");
String responseText = "<html><head><title>Test page</title></head><body>"
+ "<... |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsSignatureNotRequiredV0() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0);
Callback<Void> taskConfigCb = mock(Callback.class);
List<String> stages = expectRecordStages(taskConfigCb);
herder.putTaskConfigs(CONN1, TASK_CONFIGS... |
public void connect() throws ConnectException {
connect(s -> {}, t -> {}, () -> {});
} | @Test
public void testReconnectIfFirstConnectionFailed() throws Exception {
when(webSocketClient.connectBlocking()).thenReturn(false);
assertThrows(
ConnectException.class,
() -> {
service.connect();
});
service.connect();
... |
@Override
public Publisher<Exchange> toStream(String name, Object data) {
return doRequest(
name,
ReactiveStreamsHelper.convertToExchange(context, data));
} | @Test
public void testToStream() throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("reactive-streams:reactive").setBody().constant("123");
}
});
context.start();
Publisher<Exchange> publisher = crs.toStr... |
public static Set<Metric> mapFromDataProvider(TelemetryDataProvider<?> provider) {
switch (provider.getDimension()) {
case INSTALLATION -> {
return mapInstallationMetric(provider);
} case PROJECT -> {
return mapProjectMetric(provider);
} case USER -> {
return mapUserMetric(... | @Test
void mapFromDataProvider_whenAdhocInstallationProviderWithoutValue_shouldNotMapToMetric() {
TestTelemetryAdhocBean provider = new TestTelemetryAdhocBean(Dimension.INSTALLATION, false); // Force the value so that nothing is returned
Set<Metric> metrics = TelemetryMetricsMapper.mapFromDataProvider(provid... |
public static void validateApplicationConfig(ApplicationConfig config) {
if (config == null) {
return;
}
if (!config.isValid()) {
throw new IllegalStateException("No application config found or it's not a valid config! "
+ "Please add <dubbo:applicati... | @Test
void testValidateApplicationConfig() throws Exception {
try (MockedStatic<ConfigValidationUtils> mockedStatic = Mockito.mockStatic(ConfigValidationUtils.class); ) {
mockedStatic
.when(() -> ConfigValidationUtils.validateApplicationConfig(any()))
.the... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testReadCommittedLagMetric() {
buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
Metri... |
public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws ShenyuException {
ConsumerConfig<GenericService> reference = ApplicationConfigCache.getInstance().get(metaData.getPath());
if (Objects.isNull(reference) || StringUtils.isEmpty(referenc... | @Test
@SuppressWarnings("all")
public void testGenericInvoker() throws IllegalAccessException {
ConsumerConfig consumerConfig = mock(ConsumerConfig.class);
GenericService genericService = mock(GenericService.class);
when(consumerConfig.refer()).thenReturn(genericService);
when(co... |
public static void skipFully(InputStream in, long len) throws IOException {
long amt = len;
while (amt > 0) {
long ret = in.skip(amt);
if (ret == 0) {
// skip may return 0 even if we're not at EOF. Luckily, we can
// use the read() method to figure out if we're at the end.
... | @Test
public void testSkipFully() throws IOException {
byte inArray[] = new byte[] {0, 1, 2, 3, 4};
ByteArrayInputStream in = new ByteArrayInputStream(inArray);
try {
in.mark(inArray.length);
IOUtils.skipFully(in, 2);
IOUtils.skipFully(in, 2);
try {
IOUtils.skipFully(in, 2)... |
@WithSpan
@Override
public SearchResponse apply(SearchResponse searchResponse) {
final List<ResultMessageSummary> summaries = searchResponse.messages().stream()
.map(summary -> {
if (requireAllFields && !usedVariables.stream().allMatch(variable -> summary.message().co... | @Test
public void formatAllowEmptyValues() {
final DecoratorImpl decorator = getDecoratorConfig("${field_a}: ${field_b}", "message", false);
final FormatStringDecorator formatStringDecorator = new FormatStringDecorator(decorator, templateEngine, messageFactory);
final SearchResponse searchR... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>();
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
... | @Test
public void testDeleteContainer() throws Exception {
final Path container = new Path(new AsciiRandomStringService().random(), EnumSet.of(Path.Type.volume, Path.Type.directory));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
new S3DirectoryFeature(sessi... |
@Override
public void handleRequest(HttpServerExchange httpServerExchange) {
if (!httpServerExchange.getRequestMethod().equals(HttpString.tryFromString("GET"))) {
httpServerExchange.setStatusCode(HTTP_METHOD_NOT_ALLOWED);
httpServerExchange.getResponseSender().send("");
} else {
// For now i... | @Test
void methodNotAllowed() {
var sut = new HealthEndpoint();
// when
var httpServerExchange = mock(HttpServerExchange.class);
var sender = mock(Sender.class);
when(httpServerExchange.getResponseSender()).thenReturn(sender);
when(httpServerExchange.getRequestMethod()).thenReturn(HttpString... |
public static Map<String, Integer> indexByName(Types.StructType struct) {
IndexByName indexer = new IndexByName();
visit(struct, indexer);
return indexer.byName();
} | @Test
public void testValidateSchemaViaIndexByName() {
Types.NestedField nestedType =
Types.NestedField.required(
1,
"a",
Types.StructType.of(
required(2, "b", Types.StructType.of(required(3, "c", Types.BooleanType.get()))),
required(4, "... |
@Override
public Thread newThread(Runnable r) {
Thread t = newThread(FastThreadLocalRunnable.wrap(r), prefix + nextId.incrementAndGet());
try {
if (t.isDaemon() != daemon) {
t.setDaemon(daemon);
}
if (t.getPriority() != priority) {
... | @Test
@Timeout(value = 2000, unit = TimeUnit.MILLISECONDS)
public void testDescendantThreadGroups() throws InterruptedException {
final SecurityManager current = System.getSecurityManager();
boolean securityManagerSet = false;
try {
try {
// install security ... |
@Override
public Serde<GenericRow> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
final Optiona... | @Test
public void shouldConfigureLoggingSerde() {
// When:
factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
verify(loggingSerde).configure(ImmutableMap.of(), false);
} |
@Override
protected void encode(
ChannelHandlerContext ctx, AddressedEnvelope<M, InetSocketAddress> msg, List<Object> out) throws Exception {
assert out.isEmpty();
encoder.encode(ctx, msg.content(), out);
if (out.size() != 1) {
throw new EncoderException(
... | @Test
public void testEncode() {
testEncode(false);
} |
public static String finalSigningKeyStringWithDefaultInfo(String secret, String region) {
String signDate = LocalDateTime.now(UTC_0).format(V4_SIGN_DATE_FORMATTER);
return finalSigningKeyString(secret, signDate, region, RamConstants.SIGNATURE_V4_PRODUCE,
RamConstants.SIGNATURE_V4_METHOD)... | @Test
void testFinalSigningKeyStringWithDefaultInfo() {
assertNotNull(CalculateV4SigningKeyUtil.finalSigningKeyStringWithDefaultInfo("", "cn-hangzhou"));
} |
@Override
public Result reconcile(Request request) {
return client.fetch(ReverseProxy.class, request.name())
.map(reverseProxy -> {
if (isDeleted(reverseProxy)) {
cleanUpResourcesAndRemoveFinalizer(request.name());
return new Result(false, ... | @Test
void reconcileRemoval() {
// fix gh-2937
ReverseProxy reverseProxy = new ReverseProxy();
reverseProxy.setMetadata(new Metadata());
reverseProxy.getMetadata().setName("fake-reverse-proxy");
reverseProxy.getMetadata().setDeletionTimestamp(Instant.now());
reversePr... |
public void evaluate(List<AuthorizationContext> contexts) {
if (CollectionUtils.isEmpty(contexts)) {
return;
}
contexts.forEach(this.authorizationStrategy::evaluate);
} | @Test
public void evaluate8() {
if (MixAll.isMac()) {
return;
}
User user = User.of("test", "test");
this.authenticationMetadataManager.createUser(user).join();
Acl acl = AuthTestHelper.buildAcl("User:test", "Topic:test*", "Pub", "192.168.0.0/24", Decision.DENY);... |
public static ByteBuf wrappedBuffer(byte[] array) {
if (array.length == 0) {
return EMPTY_BUFFER;
}
return new UnpooledHeapByteBuf(ALLOC, array, array.length);
} | @Test
public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is wrapped in the ByteBuf.
final ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
final ByteBuf wrappedBuffer = wrappedBuffer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.