focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void close() throws IOException {
ZipInputStream zis = (ZipInputStream) delegate;
if ( zis == null ) {
throw new IOException( INVALID_INPUT_MSG );
}
zis.close();
} | @Test
public void testClose() throws IOException {
createZIPInputStream().close();
} |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_DATE_DESC() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DATE_NEW_OLD);
List<FeedItem> itemList = getTestList();
assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting
permutor.reorder(itemList);
assert... |
@Override
public String telnet(Channel channel, String message) {
String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY);
if ((StringUtils.isEmpty(service)) && (StringUtils.isEmpty(message))) {
return "Please input service name, eg: \r\ntrace XxxService\r\ntrace ... | @Test
void testTraceTelnetAddTracer() throws Exception {
String method = "sayHello";
String message = "org.apache.dubbo.qos.legacy.service.DemoService sayHello 1";
Class<?> type = DemoService.class;
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(Dub... |
@Override
public boolean isDone() {
if (delegate.isDone()) {
try {
ensureResultSet(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (ExecutionException | CancellationException | TimeoutException ignored) {
ignore(ignored);
}
return true;... | @Test
public void completeDelegate_bothDone_outerAskedFirst() {
delegateFuture.run();
assertTrue(outerFuture.isDone());
assertTrue(delegateFuture.isDone());
} |
public StatisticRange addAndCollapseDistinctValues(StatisticRange other)
{
double overlapPercentOfThis = this.overlapPercentWith(other);
double overlapPercentOfOther = other.overlapPercentWith(this);
double overlapDistinctValuesThis = overlapPercentOfThis * distinctValues;
double ove... | @Test
public void testAddAndCollapseDistinctValues()
{
assertEquals(unboundedRange(NaN).addAndCollapseDistinctValues(unboundedRange(NaN)), unboundedRange(NaN));
assertEquals(unboundedRange(NaN).addAndCollapseDistinctValues(unboundedRange(1)), unboundedRange(NaN));
assertEquals(unboundedR... |
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) {
if(input.getOptionValues(action.name()).length == 2) {
switch(action) {
case download:
return new DownloadTransferItemFinder().find(input, action... | @Test
public void testDeferUploadNameFromLocal() throws Exception {
final CommandLineParser parser = new PosixParser();
final String temp = System.getProperty("java.io.tmpdir");
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "ftps://test.cyb... |
static Object normalizeResult(Object result) {
logger.trace("normalizeResult {}", result);
// this is to normalize types returned by external functions
if (result != null && result.getClass().isArray()) {
List<Object> objs = new ArrayList<>();
for (int i = 0; i < Array.ge... | @Test
void normalizeResult() {
List<Object> originalResult = List.of(3, "4", 56);
Object result = originalResult.toArray();
Object retrieved = BaseFEELFunctionHelper.normalizeResult(result);
assertNotNull(retrieved);
assertInstanceOf(List.class, retrieved);
List<Objec... |
@Override
public List<String> listDbNames() {
ImmutableList.Builder<String> builder = ImmutableList.builder();
try {
if (StringUtils.isNullOrEmpty(catalogOwner)) {
SecurityManager sm = odps.projects().get().getSecurityManager();
String result = sm.runQuery... | @Test
public void testListDbNames() {
List<String> expectedDbNames = Collections.singletonList("project");
List<String> dbNames = odpsMetadata.listDbNames();
Assert.assertEquals(dbNames, expectedDbNames);
} |
@Override
public void start(final String dataSourceName, final String sql, final List<Object> params, final ConnectionProperties connectionProps, final boolean isTrunkThread) {
for (SQLExecutionHook each : sqlExecutionHooks) {
each.start(dataSourceName, sql, params, connectionProps, isTrunkThrea... | @Test
void assertStart() {
spiSQLExecutionHook.start("ds", "SELECT 1", Collections.emptyList(), null, true);
assertTrue(SQLExecutionHookFixture.containsAction("start"));
} |
@Override
public List<RoleDO> getRoleList() {
return roleMapper.selectList();
} | @Test
public void testGetRoleList() {
// mock 数据
RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
roleMapper.insert(dbRole01);
RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
... |
public static Map<String, String> parseMap(String str) {
if (str != null) {
StringTokenizer tok = new StringTokenizer(str, ", \t\n\r");
HashMap<String, String> map = new HashMap<>();
while (tok.hasMoreTokens()) {
String record = tok.nextToken();
... | @Test
public void testParseMapEmptyString() {
Map<String, String> m = parseMap(null);
assertThat(m, aMapWithSize(0));
} |
@Override
@CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#updateReqVO.id")
public void updateMailAccount(MailAccountSaveReqVO updateReqVO) {
// 校验是否存在
validateMailAccountExists(updateReqVO.getId());
// 更新
MailAccountDO updateObj = BeanUtils.toBean(updateReqVO, MailAc... | @Test
public void testUpdateMailAccount_success() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
MailAccountSaveReqVO reqVO = randomPojo(MailAccountSaveReqVO.class, o -> {
... |
public List<String> splitSql(String text) {
List<String> queries = new ArrayList<>();
StringBuilder query = new StringBuilder();
char character;
boolean multiLineComment = false;
boolean singleLineComment = false;
boolean singleQuoteString = false;
boolean doubleQuoteString = false;
fo... | @Test
void testInvalidSql() {
SqlSplitter sqlSplitter = new SqlSplitter();
List<String> sqls = sqlSplitter.splitSql("select a from table_1 where a=' and b=1");
assertEquals(1, sqls.size());
assertEquals("select a from table_1 where a=' and b=1", sqls.get(0));
sqls = sqlSplitter.splitSql("--commen... |
@Override
public String toString() {
StringBuilder bld = new StringBuilder();
bld.append("ListenerInfo(");
String prefix = "";
for (Endpoint endpoint : listeners.values()) {
bld.append(prefix).append(endpoint);
prefix = ", ";
}
bld.append(")");... | @Test
public void testToString() {
ListenerInfo listenerInfo = ListenerInfo.create(Arrays.asList(EXTERNAL, SASL_PLAINTEXT));
assertEquals("ListenerInfo(Endpoint(listenerName='EXTERNAL', securityProtocol=SASL_SSL, host='example.com', port=9092), " +
"Endpoint(listenerName='SASL_PLAINTEXT'... |
public String getEcosystem(DefCveItem cve) {
final List<Reference> references = Optional.ofNullable(cve)
.map(DefCveItem::getCve)
.map(CveItem::getReferences)
.orElse(null);
if (Objects.nonNull(references)) {
for (Reference r : references) {
... | @Test
public void testGetEcosystemMustHandleNullCveReferences() {
// Given
UrlEcosystemMapper mapper = new UrlEcosystemMapper();
CveItem cveItem = new CveItem();
DefCveItem defCveItem = new DefCveItem(cveItem);
// When
String output = mapper.getEcosystem(defCveItem)... |
public Optional<String> reasonAllControllersZkMigrationNotReady(
MetadataVersion metadataVersion,
Map<Integer, ControllerRegistration> controllers
) {
if (!metadataVersion.isMigrationSupported()) {
return Optional.of("The metadata.version too low at " + metadataVersion);
... | @Test
public void testZkMigrationNotReadyIfControllerNotReady() {
assertEquals(Optional.of("Controller 0 has not enabled zookeeper.metadata.migration.enable"),
QUORUM_FEATURES.reasonAllControllersZkMigrationNotReady(
MetadataVersion.IBP_3_7_IV0, Collections.singletonMap(0,
... |
@Override
public Collection<? extends PrimitiveTypeEncoding<UTF8Buffer>> getAllEncodings() {
return Arrays.asList(smallBufferEncoding, largeBufferEncoding);
} | @Test
public void testGetAllEncodings() {
assertEquals(2, utf8BufferEncoding.getAllEncodings().size());
} |
public Set<VplsConfig> vplss() {
Set<VplsConfig> vplss = Sets.newHashSet();
JsonNode vplsNode = object.get(VPLS);
if (vplsNode == null) {
return vplss;
}
vplsNode.forEach(jsonNode -> {
String name = jsonNode.get(NAME).asText();
Set<String> if... | @Test
public void vplss() {
assertEquals("Cannot load VPLS configuration or unexpected configuration" +
"loaded", vplss, vplsAppConfig.vplss());
} |
public Model parse(File file) throws PomParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
if (ex instanceof PomParseException) {
throw (PomParseException) ex;
}
LOGGER.deb... | @Test
public void testParse_InputStream() throws Exception {
InputStream inputStream = BaseTest.getResourceAsStream(this, "pom/plexus-utils-3.0.24.pom");
PomParser instance = new PomParser();
String expectedArtifactId = "plexus-utils";
Model result = instance.parse(inputStream);
... |
@Override
public Expression getExpression(String tableName, Alias tableAlias) {
// 只有有登陆用户的情况下,才进行数据权限的处理
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
if (loginUser == null) {
return null;
}
// 只有管理员类型的用户,才进行数据权限的处理
if (ObjectUtil.notEqual(... | @Test // 无数据权限时
public void testGetExpression_noDeptDataPermission() {
try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock
= mockStatic(SecurityFrameworkUtils.class)) {
// 准备参数
String tableName = "t_user";
Alias tableAlias = new Alias... |
@Override
public List<KsqlPartitionLocation> locate(
final List<KsqlKey> keys,
final RoutingOptions routingOptions,
final RoutingFilterFactory routingFilterFactory,
final boolean isRangeScan
) {
if (isRangeScan && keys.isEmpty()) {
throw new IllegalStateException("Query is range sc... | @Test
public void shouldReturnOneStandByWhenActiveAndOtherStandByDown() {
// Given:
getActiveAndStandbyMetadata();
when(livenessFilter.filter(eq(ACTIVE_HOST)))
.thenReturn(Host.exclude(ACTIVE_HOST, "liveness"));
when(livenessFilter.filter(eq(STANDBY_HOST1)))
.thenReturn(Host.exclude(ST... |
@Udf(description = "Converts an INT value in radians to a value in degrees")
public Double degrees(
@UdfParameter(
value = "value",
description = "The value in radians to convert to degrees."
) final Integer value
) {
return degrees(value == null ? null : ... | @Test
public void shouldHandleZero() {
assertThat(udf.degrees(0), closeTo(0.0, 0.000000000000001));
assertThat(udf.degrees(0L), closeTo(0.0, 0.000000000000001));
assertThat(udf.degrees(0.0), closeTo(0.0, 0.000000000000001));
} |
public static String checkIPs(String... ips) {
if (ips == null || ips.length == 0) {
return CHECK_OK;
}
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
if (InternetAddressUtil.isIP(ip))... | @Test
void testCheckIPs() {
assertEquals("ok", InternetAddressUtil.checkIPs("127.0.0.1"));
assertEquals("ok", InternetAddressUtil.checkIPs());
assertEquals("ok", InternetAddressUtil.checkIPs());
assertEquals("ok", InternetAddressUtil.checkIPs(null));
assertEquals("il... |
@Override
@Deprecated
public String toString() {
if ( StringUtils.isBlank( message ) ) {
return subject;
} else if ( StringUtils.isBlank( subject ) ) {
return getMessage();
}
return String.format( "%s - %s", subject, getMessage() );
} | @Test
public void testToString() throws Exception {
LogMessage msg = new LogMessage( "Log message",
"Channel 01",
LogLevel.DEBUG );
msg.setSubject( "Simple" );
assertEquals( "Simple - Log message", msg.toString( ) );
} |
@Override
public boolean isFull() {
return entries() >= maxEntries() - 1;
} | @Test
public void testIsFull() {
assertFalse(idx.isFull());
appendEntries(maxEntries - 1);
assertTrue(idx.isFull());
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @SuppressWarnings("unchecked")
@Test
public void shouldEvaluateLambda() {
// Given:
final Expression lambda1 = new LambdaFunctionCall(
ImmutableList.of("X"),
new ArithmeticBinaryExpression(
Operator.ADD,
new IntegerLiteral(1),
new LambdaVariable("X")
... |
@Override
String simpleTypeName() {
return name;
} | @Test
public void testSimpleTypeName() {
ContinuousResourceId id1 = Resources.continuous(D1, P1, Bandwidth.class).resource(BW1.bps()).id();
assertThat(id1.simpleTypeName(), is("Bandwidth"));
} |
@Override
public String getSessionId() {
return sessionID;
} | @Test
public void testGetConfigRequest() {
log.info("Starting get-config async");
assertNotNull("Incorrect sessionId", session1.getSessionId());
try {
assertTrue("NETCONF get-config running command failed. ",
GET_REPLY_PATTERN.matcher(session1.getConfig(RUNNIN... |
@Override
public double p(double x) {
if (x <= 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
return Math.exp((0.5 * nu1 - 1.0) * Math.log(x) - 0.5 * (nu1 + nu2) * Math.log(nu2 + nu1 * x) + fac);
} | @Test
public void testP() {
System.out.println("p");
FDistribution instance = new FDistribution(10, 20);
instance.rand();
assertEquals(2.90264e-06, instance.p(0.01), 1E-10);
assertEquals(0.01504682, instance.p(0.1), 1E-7);
assertEquals(0.1198157, instance.p(0.2), 1E-7... |
@Override
public Set<String> keySet() {
if (this.prefix.isEmpty()) {
return this.backingConfig.keySet();
}
final HashSet<String> set = new HashSet<>();
int prefixLen = this.prefix.length();
for (String key : this.backingConfig.keySet()) {
if (key.sta... | @Test
void testDelegationConfigurationWithPrefix() {
String prefix = "pref-";
String expectedKey = "key";
/*
* Key matches the prefix
*/
Configuration backingConf = new Configuration();
backingConf.setValueInternal(prefix + expectedKey, "value", false);
... |
@Override
public String getColumnLabel() {
ProjectionIdentifierExtractEngine extractEngine = new ProjectionIdentifierExtractEngine(databaseType);
return getAlias().isPresent() && !DerivedColumn.isDerivedColumnName(getAlias().get().getValueWithQuoteCharacters())
? extractEngine.getIde... | @Test
void assertGetColumnLabelWithoutAlias() {
assertThat(new AggregationProjection(AggregationType.COUNT, "COUNT( A.\"DIRECTION\" )", null,
TypedSPILoader.getService(DatabaseType.class, "MySQL")).getColumnLabel(), is("COUNT( A.\"DIRECTION\" )"));
assertThat(new AggregationProjectio... |
@Override
public Future<RestResponse> restRequest(RestRequest request)
{
return restRequest(request, new RequestContext());
} | @Test(dataProvider = "isD2Async")
public void testStatsConsumerUpdateAndRemove(boolean isD2Async) throws Exception
{
AtomicReference<ServiceProperties> serviceProperties = new AtomicReference<>();
TestBackupRequestsStrategyStatsConsumer statsConsumer = new TestBackupRequestsStrategyStatsConsumer();
serv... |
protected void setMethod() {
boolean activateBody = RestMeta.isActiveBody( wMethod.getText() );
boolean activateParams = RestMeta.isActiveParameters( wMethod.getText() );
wlBody.setEnabled( activateBody );
wBody.setEnabled( activateBody );
wApplicationType.setEnabled( activateBody );
wlParamet... | @Test
public void testSetMethod_POST() {
doReturn( RestMeta.HTTP_METHOD_POST ).when( method ).getText();
dialog.setMethod();
verify( bodyl, times( 1 ) ).setEnabled( true );
verify( body, times( 1 ) ).setEnabled( true );
verify( type, times( 1 ) ).setEnabled( true );
verify( paramsl, times( ... |
public static <T> Deduplicate.Values<T> values() {
return new Deduplicate.Values<>(DEFAULT_TIME_DOMAIN, DEFAULT_DURATION);
} | @Test
@Category({NeedsRunner.class, UsesTestStream.class})
public void testInDifferentWindows() {
Instant base = new Instant(0);
TestStream<String> values =
TestStream.create(StringUtf8Coder.of())
.advanceWatermarkTo(base)
.addElements(
TimestampedValue.of("k1... |
@VisibleForTesting
static CPUResource getDefaultCpus(final Configuration configuration) {
int fallback = configuration.get(YarnConfigOptions.VCORES);
double cpuCoresDouble =
TaskExecutorProcessUtils.getCpuCoresWithFallback(configuration, fallback)
.getValue()
... | @Test
void testGetCpuCoresCommonOption() {
final Configuration configuration = new Configuration();
configuration.set(TaskManagerOptions.CPU_CORES, 1.0);
configuration.set(YarnConfigOptions.VCORES, 2);
configuration.set(TaskManagerOptions.NUM_TASK_SLOTS, 3);
assertThat(YarnWo... |
@Override
public boolean isAllowable(URL url, Invocation invocation) {
int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1);
long interval = url.getMethodParameter(
RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_... | @Test
void testIsNotAllowable() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParam... |
@Override
public Integer call() throws Exception {
super.call();
try(DefaultHttpClient client = client()) {
MutableHttpRequest<Object> request = HttpRequest
.GET(apiUri("/templates/export/by-query") + (namespace != null ? "?namespace=" + namespace : ""))
... | @Test
void run() throws IOException {
URL directory = TemplateExportCommandTest.class.getClassLoader().getResource("templates");
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.run(Map.of(... |
public static <T> Set<T> set(T... elements) {
if (elements == null) {
throw new IllegalArgumentException("Expected an array of elements (or empty array) but received a null.");
} else {
return new LinkedHashSet<>(Arrays.asList(elements));
}
} | @Test
void testSet() {
Set<Object> set = new HashSet<>();
set.add(null);
assertEquals(set, CollectionUtils.set(null, null, null));
assertEquals(new LinkedHashSet(Arrays.asList("", "a", "b")), CollectionUtils.set("", "a", "b"));
assertEquals(new HashSet(), CollectionUtils.set(... |
public static UnixMountInfo parseMountInfo(String line) {
// Example mount lines:
// ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb)
// map -hosts on /net (autofs, nosuid, automounted, nobrowse)
UnixMountInfo.Builder builder = new UnixMountInfo.Builder();
// First get and remove the mount t... | @Test
public void parseMountInfoWithoutType() throws Exception {
// OS X mount info.
UnixMountInfo info = ShellUtils.parseMountInfo("devfs on /dev (devfs, local, nobrowse)");
assertEquals(Optional.of("devfs"), info.getDeviceSpec());
assertEquals(Optional.of("/dev"), info.getMountPoint());
assertFa... |
@Override
public void encode(final ChannelHandlerContext context, final DatabasePacket message, final ByteBuf out) {
boolean isIdentifierPacket = message instanceof PostgreSQLIdentifierPacket;
if (isIdentifierPacket) {
prepareMessageHeader(out, ((PostgreSQLIdentifierPacket) message).getI... | @Test
void assertEncodeOccursException() {
PostgreSQLPacket packet = mock(PostgreSQLPacket.class);
RuntimeException ex = mock(RuntimeException.class);
when(ex.getMessage()).thenReturn("Error");
doThrow(ex).when(packet).write(any(PostgreSQLPacketPayload.class));
when(byteBuf.r... |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) {
final OutputStream putStream = session.getClient().putAsOutputStream(file.getAbsolute());
return new VoidStatusOutputStream(putStream);
} | @Test
public void testWrite() throws Exception {
final MantaWriteFeature feature = new MantaWriteFeature(session);
final Path container = new MantaDirectoryFeature(session).mkdir(randomDirectory(), new TransferStatus());
final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);
... |
@JsonIgnore
public long initiateAndGetByPrevMaxIterationId(ForeachStepOverview prev, long toReset) {
if (prev == null || prev.details == null) {
return 0;
}
long maxIterationId =
prev.details.flatten(e -> true).values().stream()
.flatMap(Collection::stream)
.reduce(0... | @Test
public void testInitiateAndGetByPrevMaxIterationId() throws Exception {
ForeachStepOverview prev =
loadObject(
"fixtures/instances/sample-foreach-step-overview-with-failed.json",
ForeachStepOverview.class);
ForeachStepOverview overview = new ForeachStepOverview();
ass... |
ControllerResult<ApiError> incrementalAlterConfig(
ConfigResource configResource,
Map<String, Entry<OpType, String>> keyToOps,
boolean newlyCreatedResource
) {
List<ApiMessageAndVersion> outputRecords =
BoundedList.newArrayBacked(MAX_RECORDS_PER_USER_OP);
ApiE... | @Test
public void testIncrementalAlterConfig() {
ConfigurationControlManager manager = new ConfigurationControlManager.Builder().
setKafkaConfigSchema(SCHEMA).
build();
Map<String, Entry<AlterConfigOp.OpType, String>> keyToOps = toMap(entry("abc", entry(APPEND, "123")));
... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(3.5), numOf(2.2)));
assertFalse(criterion.betterThan(numOf(1.5), numOf(2.7)));
} |
public XAConnection xaConnection(XAConnection xaConnection) {
return TracingXAConnection.create(xaConnection, this);
} | @Test void xaConnection_doesntDoubleWrap() {
XAConnection wrapped = jmsTracing.xaConnection(mock(XAConnection.class));
assertThat(jmsTracing.xaConnection(wrapped))
.isSameAs(wrapped);
} |
public long next() {
long part = parts[index++];
if (index == parts.length) {
index = 0;
}
return part;
} | @Test
public void check() {
RandomizedRateTracker tracker = new RandomizedRateTracker(1000, 5);
long p1 = tracker.next();
long p2 = tracker.next();
long p3 = tracker.next();
long p4 = tracker.next();
long p5 = tracker.next();
//total is divided up properly
... |
@Override
public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception {
this.config = config;
this.sourceContext = sourceContext;
this.intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(sourceContext.getTenant(),
sourceContext.getNamespac... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp =
"Bad config passed to TestBatchSource")
public void testWithoutRightSourceConfig() throws Exception {
config.remove("foo");
config.put("something", "else");
batchSourceExecutor.open(config, context);
} |
@Override
public String toString() {
return joinForDisplay(resourceNames());
} | @Test
public void shouldHaveNiceConvenienceConstructorThatDoesSomeNiftyParsing() {
ResourceConfigs actual = new ResourceConfigs("mou, fou");
assertThat(actual.toString(), is("fou | mou"));
} |
public Map<String, String> connectorBaseConfig(SourceAndTarget sourceAndTarget, Class<?> connectorClass) {
Map<String, String> props = new HashMap<>();
props.putAll(rawProperties);
props.keySet().retainAll(allConfigNames());
props.putAll(stringsWithPrefix(CONFIG_PROVIDERS_CONFI... | @Test
public void testClusterConfigProperties() {
MirrorMakerConfig mirrorConfig = new MirrorMakerConfig(makeProps(
"clusters", "a, b",
"a.bootstrap.servers", "servers-one",
"b.bootstrap.servers", "servers-two",
"security.protocol", "SSL",
"replica... |
@Override
public void clear() {
map.clear();
} | @Test
public void testClear() {
map.put(23, "foobar");
adapter.clear();
assertEquals(0, map.size());
} |
@NonNull
public Client authenticate(@NonNull Request request) {
// https://datatracker.ietf.org/doc/html/rfc7521#section-4.2
try {
if (!CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT.equals(request.clientAssertionType())) {
throw new AuthenticationException(
"unsupported client_assertion_ty... | @Test
void authenticate_badSubject_noMatch() throws JOSEException {
var key = generateKey();
var jwkSource = new StaticJwkSource<>(key);
var claims =
new JWTClaimsSet.Builder()
.audience(RP_ISSUER.toString())
.subject(CLIENT_ID)
.issuer(CLIENT_ID)
... |
@Override
public Map<Long, T> loadAll(Collection<Long> keys) {
long startNanos = Timer.nanos();
try {
return delegate.loadAll(keys);
} finally {
loadAllProbe.recordValue(Timer.nanosElapsed(startNanos));
}
} | @Test
public void loadAll() {
Collection<Long> keys = Arrays.asList(1L, 2L);
Map<Long, String> values = new HashMap<>();
values.put(1L, "value1");
values.put(2L, "value2");
when(delegate.loadAll(keys)).thenReturn(values);
Map<Long, String> result = queueStore.loadAl... |
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
TemporalAccessor parsed = FEEL_TIME.parse(val);
i... | @Test
void invokeStringParamTimeWrongFormat() {
FunctionTestUtil.assertResultError(timeFunction.invoke("10-15:06"), InvalidParametersEvent.class);
} |
public static VersionedBytesStoreSupplier persistentVersionedKeyValueStore(final String name,
final Duration historyRetention) {
Objects.requireNonNull(name, "name cannot be null");
final String hrMsgPrefix = prepareMillisChe... | @Test
public void shouldCreateRocksDbVersionedStore() {
final KeyValueStore<Bytes, byte[]> store = Stores.persistentVersionedKeyValueStore("store", ofMillis(1)).get();
assertThat(store, instanceOf(VersionedBytesStore.class));
assertThat(store.persistent(), equalTo(true));
} |
public ConnectionContext getConnection(UserGroupInformation ugi,
String nnAddress, Class<?> protocol, String nsId) throws IOException {
// Check if the manager is shutdown
if (!this.running) {
LOG.error(
"Cannot get a connection to {} because the manager isn't running",
nnAddress... | @Test
public void testGetConnection() throws Exception {
Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools();
final int totalConns = 10;
int activeConns = 5;
ConnectionPool pool = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1,
0, 10, 0.5f, ClientProtocol.class, null)... |
@ExceptionHandler(TokenAlreadyInvalidatedException.class)
protected ResponseEntity<Object> handleTokenAlreadyInvalidatedException(final TokenAlreadyInvalidatedException ex) {
CustomError customError = CustomError.builder()
.httpStatus(HttpStatus.BAD_REQUEST)
.header(CustomErr... | @Test
void givenTokenAlreadyInvalidatedException_whenHandleTokenAlreadyInvalidatedException_thenRespondWithBadRequest() {
// Given
TokenAlreadyInvalidatedException ex = new TokenAlreadyInvalidatedException();
CustomError expectedError = CustomError.builder()
.httpStatus(Htt... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("sds.listing.chunksize"));
} | @Test
public void testListAlphanumeric() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Typ... |
public ConfigPayloadBuilder build(Element configE) {
parseConfigName(configE);
ConfigPayloadBuilder payloadBuilder = new ConfigPayloadBuilder(configDefinition);
for (Element child : XML.getChildren(configE)) {
parseElement(child, payloadBuilder, null);
}
return paylo... | @Test
void require_that_item_is_reserved_in_root() {
assertThrows(IllegalArgumentException.class, () -> {
Element configRoot = getDocument(
"<config name=\"test.arraytypes\" version=\"1\">" +
" <item>13</item>" +
"</c... |
@Override
public Optional<Decision> onBufferConsumed(BufferIndexAndChannel consumedBuffer) {
return Optional.of(Decision.NO_ACTION);
} | @Test
void testOnBufferConsumed() {
BufferIndexAndChannel bufferIndexAndChannel = new BufferIndexAndChannel(0, 0);
Optional<Decision> bufferConsumedDecision =
spillStrategy.onBufferConsumed(bufferIndexAndChannel);
assertThat(bufferConsumedDecision).hasValue(Decision.NO_ACTION... |
public void update(final Collection<InspectedType> updates) {
final ArrayList<UUIDKey> originalItems = new ArrayList<>(map.keySet());
for (final InspectedType updatable : updates) {
final InspectorType inspector = map.get(updatable.getUuidKey());
if (inspector != null) {
... | @Test
void reAddNew() throws Exception {
final ArrayList<Item> updates = new ArrayList<>();
updates.add(new Item());
list.update(updates);
assertThat(list).hasSize(1);
updates.add(new Item());
list.update(updates);
assertThat(list).hasSize(2);
... |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
public Node deserializeObject(JsonReader reader) {
Log.info("Deserializing JSON to Node.");
JsonObject jsonObject = reader.readObject();
return deserializeObject(jsonObject);
} | @Test
void testJavaDocComment() {
CompilationUnit cu = parse("public class X{ " + " /**\n"
+ " * Woke text.\n"
+ " * @param a blub\n"
+ " * @return true \n"
+ " */"
+ " public boolean test(int a) { return... |
Object getFromSignal(String signalName, String paramName) {
try {
return executor
.submit(() -> fromSignal(signalName, paramName))
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(
e,
"getFromSignal throws ... | @Test
public void testInvalidGetFromSignal() {
SignalInitiator initiator = Mockito.mock(SignalInitiator.class);
when(instanceWrapper.getInitiator()).thenReturn(initiator);
when(initiator.getType()).thenReturn(Initiator.Type.TIME);
AssertHelper.assertThrows(
"Cannot get a param from non signal... |
@Override
public List<AdminUserDO> getUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return userMapper.selectBatchIds(ids);
} | @Test
public void testGetUserList() {
// mock 数据
AdminUserDO user = randomAdminUserDO();
userMapper.insert(user);
// 测试 id 不匹配
userMapper.insert(randomAdminUserDO());
// 准备参数
Collection<Long> ids = singleton(user.getId());
// 调用
List<AdminUser... |
public static LookupResult single(final CharSequence singleValue) {
return multi(singleValue, Collections.singletonMap(SINGLE_VALUE_KEY, singleValue));
} | @Test
public void serializeSingleNumber() {
final LookupResult lookupResult = LookupResult.single(42);
final JsonNode node = objectMapper.convertValue(lookupResult, JsonNode.class);
assertThat(node.isNull()).isFalse();
assertThat(node.path("single_value").asInt()).isEqualTo(42);
... |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testOnTimerWithWindow() throws Exception {
final String timerId = "my-timer-id";
final IntervalWindow testWindow = new IntervalWindow(new Instant(0), new Instant(15));
when(mockArgumentProvider.window()).thenReturn(testWindow);
class SimpleTimerDoFn extends DoFn<String, String> {
... |
@Override
public <T extends MigrationStep> MigrationStepRegistry add(long migrationNumber, String description, Class<T> stepClass) {
validate(migrationNumber);
requireNonNull(description, "description can't be null");
checkArgument(!description.isEmpty(), "description can't be empty");
requireNonNull(... | @Test
public void add_fails_with_NPE_is_migrationstep_class_is_null() {
assertThatThrownBy(() -> {
underTest.add(12, "sdsd", null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("MigrationStep class can't be null");
} |
public static boolean isAnyBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isBlank(cs)) {
return true;
}
}
return false;
} | @Test
void isAnyBlank() {
assertTrue(StringUtils.isAnyBlank(null));
assertTrue(StringUtils.isAnyBlank(null, "foo"));
assertTrue(StringUtils.isAnyBlank(null, null));
assertTrue(StringUtils.isAnyBlank("", "bar"));
assertTrue(StringUtils.isAnyBlank("bob", ""));
assertTru... |
@Override
public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException {
final TransferStatus status = super.prepare(file, local, parent, progress);
if(file.isFile()) {
final Write.Append append... | @Test
public void testPrepareAppend() throws Exception {
final Host host = new Host(new TestProtocol());
final ResumeFilter f = new ResumeFilter(new DisabledUploadSymlinkResolver(), new NullSession(host) {
@Override
public AttributedList<Path> list(final Path file, final List... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testPerElementProcessingTimeCounters() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
options
.as(DataflowPipelineDebugOptions.class)
.setExperiments(
Lists.newArrayList(DataflowElementExecutionTracker.TIME_PER_ELEMENT_EXPERIMENT));
... |
@Override
public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema schema) {
List<String> requiredFieldMethods = new ArrayList<>();
JsonNode properties = schema.getContent().get("properties");
for (Iterator<JsonNode> iterator = node.elements(... | @Test
public void shouldUpdateJavaDoc() throws JClassAlreadyExistsException {
JDefinedClass jclass = new JCodeModel()._class(TARGET_CLASS_NAME);
jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "fooBar");
jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "foo");
... |
@SneakyThrows
public static Integer getAreaId(String ip) {
return Integer.parseInt(SEARCHER.search(ip.trim()));
} | @Test
public void testGetAreaId_string() {
// 120.202.4.0|120.202.4.255|420600
Integer areaId = IPUtils.getAreaId("120.202.4.50");
assertEquals(420600, areaId);
} |
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
if (knownConsumerGroups == null) {
// If knownConsumerGroup is null, it means the initial loading has not finished.
// An exception should be thrown to trigger the retry behavior in the framework.
log.... | @Test
public void testConsumerGroupInitializeTimeout() {
MirrorCheckpointConfig config = new MirrorCheckpointConfig(makeProps());
MirrorCheckpointConnector connector = new MirrorCheckpointConnector(null, config);
assertThrows(
RetriableException.class,
() -> ... |
public AthenzDomain getParent() {
return new AthenzDomain(name.substring(0, lastDot()));
} | @Test
void parent_domain_is_without_name_suffix() {
assertEquals(new AthenzDomain("home.john"), new AthenzDomain("home.john.myapp").getParent());
} |
public static <T> PCollections<T> pCollections() {
return new PCollections<>();
} | @Test
@Category({ValidatesRunner.class, FlattenWithHeterogeneousCoders.class})
public void testFlattenMultipleCoders() throws CannotProvideCoderException {
PCollection<Long> bigEndianLongs =
p.apply(
"BigEndianLongs",
Create.of(0L, 1L, 2L, 3L, null, 4L, 5L, null, 6L, 7L, 8L, null... |
@Override
public CloseableIterator<ScannerReport.SyntaxHighlightingRule> readComponentSyntaxHighlighting(int fileRef) {
ensureInitialized();
return delegate.readComponentSyntaxHighlighting(fileRef);
} | @Test
public void verify_readComponentSyntaxHighlighting() {
writer.writeComponentSyntaxHighlighting(COMPONENT_REF, of(SYNTAX_HIGHLIGHTING_1, SYNTAX_HIGHLIGHTING_2));
CloseableIterator<ScannerReport.SyntaxHighlightingRule> res = underTest.readComponentSyntaxHighlighting(COMPONENT_REF);
assertThat(res).to... |
public Meter(MetricName rateMetricName, MetricName totalMetricName) {
this(TimeUnit.SECONDS, new WindowedSum(), rateMetricName, totalMetricName);
} | @Test
public void testMeter() {
Map<String, String> emptyTags = Collections.emptyMap();
MetricName rateMetricName = new MetricName("rate", "test", "", emptyTags);
MetricName totalMetricName = new MetricName("total", "test", "", emptyTags);
Meter meter = new Meter(rateMetricName, tota... |
@Override
public Set<KubevirtPort> ports(String networkId) {
checkArgument(!Strings.isNullOrEmpty(networkId), ERR_NULL_PORT_NET_ID);
return ImmutableSet.copyOf(kubevirtPortStore.ports().stream()
.filter(p -> p.networkId().equals(networkId))
.collect(Collectors.toSet()... | @Test
public void testGetPortsByNetworkId() {
createBasicPorts();
assertEquals("Number of port did not match", 1, target.ports(NETWORK_ID).size());
assertEquals("Number of port did not match", 0, target.ports(UNKNOWN_ID).size());
} |
public String convert(Object o) {
StringBuilder buf = new StringBuilder();
Converter<Object> p = headTokenConverter;
while (p != null) {
buf.append(p.convert(o));
p = p.getNext();
}
return buf.toString();
} | @Test
public void dateWithTimeZone() {
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(utc);
cal.set(2003, 4, 20, 10, 55);
FileNamePattern fnp = new FileNamePattern("foo%d{yyyy-MM-dd'T'HH:mm, Australia/Perth}", context);
// Perth is 8 hours ahead of UTC
assertE... |
JFieldRef getOrAddNotFoundVar(JDefinedClass jclass) {
jclass.field(PROTECTED | STATIC | FINAL, Object.class, NOT_FOUND_VALUE_FIELD,
_new(jclass.owner()._ref(Object.class)));
return jclass.staticRef(NOT_FOUND_VALUE_FIELD);
} | @Test
public void shouldAddNotFoundField() {
JFieldRef var = rule.getOrAddNotFoundVar(type);
assertThat(var, notNullValue());
} |
@Override
protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) {
return "";
} | @Test
public void testBuildHandle() {
List<URIRegisterDTO> list = new ArrayList<>();
list.add(URIRegisterDTO.builder().build());
assertEquals(StringUtils.EMPTY,
shenyuClientRegisterMotanService.buildHandle(list, SelectorDO.builder().build()));
} |
public static PipelineMetricRegistry create(MetricRegistry metricRegistry,
String pipelinesPrefix,
String rulesPrefix) {
return new PipelineMetricRegistry(metricRegistry, pipelinesPrefix, rulesPrefix);
} | @Test
void validation() {
final var metricRegistry = new MetricRegistry();
assertThatThrownBy(() -> PipelineMetricRegistry.create(null, "PIPELINE", "RULE"))
.isInstanceOf(NullPointerException.class);
assertThatThrownBy(() -> PipelineMetricRegistry.create(metricRegistry, nul... |
@Override
public void flush() throws IOException {
mLocalOutputStream.flush();
} | @Test
@PrepareForTest(OSSOutputStream.class)
public void testFlush() throws Exception {
PowerMockito.whenNew(BufferedOutputStream.class)
.withArguments(any(DigestOutputStream.class)).thenReturn(mLocalOutputStream);
OSSOutputStream stream = new OSSOutputStream("testBucketName", "testKey", mOssCli... |
@Override
public CompletableFuture<ConsumerRunningInfo> getConsumerRunningInfo(String address,
GetConsumerRunningInfoRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<ConsumerRunningInfo> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createR... | @Test
public void assertGetConsumerRunningInfoWithSuccess() throws Exception {
ConsumerRunningInfo responseBody = new ConsumerRunningInfo();
setResponseSuccess(RemotingSerializable.encode(responseBody));
GetConsumerRunningInfoRequestHeader requestHeader = mock(GetConsumerRunningInfoRequestHe... |
@Override
public int hashCode() {
return name.hashCode();
} | @Test
public void hashcode() {
assertEquals(t1.hashCode(), t2.hashCode());
assertNotEquals(t1.hashCode(), t3.hashCode());
assertNotEquals(t1.hashCode(), t4.hashCode());
} |
@Override
public boolean overlap(final Window other) throws IllegalArgumentException {
if (getClass() != other.getClass()) {
throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type "
+ other.getClass() + ".");
}
final Ti... | @Test
public void cannotCompareTimeWindowWithDifferentWindowType() {
assertThrows(IllegalArgumentException.class, () -> window.overlap(sessionWindow));
} |
public int readWPShort() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
if ((ch1 | ch2) < 0) {
throw new EOFException();
}
return (ch2 << 8) + ch1;
} | @Test
public void testReadShort() throws Exception {
try (WPInputStream wpInputStream = emptyWPStream()) {
wpInputStream.readWPShort();
fail("should have thrown EOF");
} catch (EOFException e) {
//swallow
}
} |
private WorkAttempt doWork() {
AgentIdentifier agentIdentifier = agentIdentifier();
LOG.debug("[Agent Loop] {} is checking for work from Go", agentIdentifier);
try {
getAgentRuntimeInfo().idle();
Work work = client.getWork(getAgentRuntimeInfo());
LOG.debug("[A... | @Test
void shouldRetrieveCookieIfNotPresent() {
agentController = createAgentController();
agentController.init();
when(loopServer.getCookie(eq(agentController.getAgentRuntimeInfo()))).thenReturn("cookie");
when(sslInfrastructureService.isRegistered()).thenReturn(true);
when... |
public static TriRpcStatus fromCode(int code) {
return fromCode(Code.fromCode(code));
} | @Test
void fromCode() {
Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(2).code);
try {
TriRpcStatus.fromCode(1000);
fail();
} catch (Throwable t) {
// pass
}
} |
public double pairingThreshold() {
/*
* We use 7000 because this equals 7 seconds (in milliseconds). Radar hits are normally
* updated every 13 seconds or less. Thus, we know any two aircraft will have radar hits
* within 6.5 seconds of each other. 6500 is rounded up to 7000 because..... | @Test
public void testDerivedPairThresholdReflectsTimeCoef() {
double TOLERANCE = 0.0001;
PairingConfig noTimeProps = new PairingConfig(timeWindow, 10, 0, 1.0);
assertEquals(
noTimeProps.pairingThreshold(),
10.0 * Spherical.feetPerNM(),
TOLERANCE
... |
public static boolean isLocalHost(String host) {
return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase(LOCALHOST_KEY));
} | @Test
void testIsLocalHost() {
assertTrue(NetUtils.isLocalHost("localhost"));
assertTrue(NetUtils.isLocalHost("127.1.2.3"));
assertFalse(NetUtils.isLocalHost("128.1.2.3"));
} |
@Nonnull
public static String fillRight(int len, @Nonnull String pattern, @Nullable String string) {
StringBuilder sb = new StringBuilder(string == null ? "" : string);
while (sb.length() < len)
sb.append(pattern);
return sb.toString();
} | @Test
void testFillRight() {
assertEquals("baaa", StringUtil.fillRight(4, "a", "b"));
assertEquals("aaaa", StringUtil.fillRight(4, "a", null));
} |
public String getManagedInstanceProviderName() {
if (managedInstanceService.isInstanceExternallyManaged()) {
return managedInstanceService.getProviderName();
}
return null;
} | @Test
public void getManagedInstanceProvider_whenInstanceNotManaged_shouldReturnNull() {
mockIdentityProviders(List.of());
mockManagedInstance(false);
assertThat(commonSystemInformation.getManagedInstanceProviderName())
.isNull();
} |
@Override
public TableStatistics getTableStatistics(
ConnectorSession session,
SchemaTableName table,
Map<String, ColumnHandle> columns,
Map<String, Type> columnTypes,
List<HivePartition> partitions)
{
if (!isStatisticsEnabled(session)) {
... | @Test
public void testGetTableStatisticsSampling()
{
MetastoreHiveStatisticsProvider statisticsProvider = new MetastoreHiveStatisticsProvider((session, table, hivePartitions) -> {
assertEquals(table, TABLE);
assertEquals(hivePartitions.size(), 1);
return ImmutableMap.... |
@Override
public TopicAssignment place(
PlacementSpec placement,
ClusterDescriber cluster
) throws InvalidReplicationFactorException {
RackList rackList = new RackList(random, cluster.usableBrokers());
throwInvalidReplicationFactorIfNonPositive(placement.numReplicas());
t... | @Test
public void testNotEnoughBrokers() {
MockRandom random = new MockRandom();
StripedReplicaPlacer placer = new StripedReplicaPlacer(random);
assertEquals("The target replication factor of 3 cannot be reached because only " +
"2 broker(s) are registered.",
assertTh... |
public static ImmutableList<String> glob(final String glob) {
Path path = getGlobPath(glob);
int globIndex = getGlobIndex(path);
if (globIndex < 0) {
return of(glob);
}
return doGlob(path, searchPath(path, globIndex));
} | @Test
public void should_glob_direct_files() {
ImmutableList<String> files = Globs.glob("src/test/resources/details/foo.json");
assertThat(files.contains("src/test/resources/details/foo.json"), is(true));
} |
@Override
public boolean needToLoad(FilterInvoker invoker) {
AbstractInterfaceConfig<?, ?> config = invoker.getConfig();
String enabled = config.getParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED);
if (StringUtils.isNotBlank(enabled)) {
return Boolean.parseBoolean(enabled)... | @Test
public void testNeedToLoadProvider() {
SentinelSofaRpcProviderFilter providerFilter = new SentinelSofaRpcProviderFilter();
ProviderConfig providerConfig = new ProviderConfig();
providerConfig.setInterfaceId(Serializer.class.getName());
providerConfig.setId("AAA");
Filte... |
@Override
public int getClassId() {
throw new UnsupportedOperationException(getClass().getName() + " is only used locally!");
} | @Test(expected = UnsupportedOperationException.class)
public void testGetId() {
operation.getClassId();
} |
public static void shutdownThreadPool(ExecutorService executor) {
shutdownThreadPool(executor, null);
} | @Test
void testShutdownThreadPoolWithInterruptedException() throws InterruptedException {
ExecutorService executor = mock(ExecutorService.class);
when(executor.awaitTermination(100, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException());
ThreadUtils.shutdownThreadPool(executor);
... |
@Override
public Set<NetworkPolicy> networkPolicies() {
return ImmutableSet.copyOf(k8sNetworkPolicyStore.networkPolicies());
} | @Test
public void testGetNetworkPolicies() {
createBasicNetworkPolicies();
assertEquals("Number of network policies did not match", 1, target.networkPolicies().size());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.