focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public CanaryScope buildCanaryScope(CanaryScope scope) {
WavefrontCanaryScope wavefrontCanaryScope = new WavefrontCanaryScope();
wavefrontCanaryScope.setScope(scope.getScope());
wavefrontCanaryScope.setLocation(scope.getLocation());
wavefrontCanaryScope.setStart(scope.getStart());
wavefr... | @Test
public void testBuildCanaryScope_WithDayGranularity() {
CanaryScope canaryScope =
new CanaryScope(
"scope",
"location",
Instant.now(),
Instant.now(),
WavefrontCanaryScopeFactory.DAY,
null);
CanaryScope generatedCanaryScope =... |
public void retain(IndexSet indexSet, IndexLifetimeConfig config, RetentionExecutor.RetentionAction action, String actionName) {
final Map<String, Set<String>> deflectorIndices = indexSet.getAllIndexAliases();
// Account for DST and time zones in determining age
final DateTime now = clock.nowUT... | @Test
public void timeBasedMissingClosingDate() {
when(indices.indexClosingDate("test_1")).thenReturn(Optional.empty());
when(indices.indexCreationDate("test_1")).thenReturn(Optional.of(NOW.minusDays(17)));
underTest.retain(indexSet, getIndexLifetimeConfig(14, 16), action, "action");
... |
public static SmartFilterTestExecutionResultDTO execSmartFilterTest(SmartFilterTestExecutionDTO execData) {
Predicate<TopicMessageDTO> predicate;
try {
predicate = MessageFilters.celScriptFilter(execData.getFilterCode());
} catch (Exception e) {
log.info("Smart filter '{}' compilation error", ex... | @Test
void execSmartFilterTestCompilesToNonBooleanExpression() {
var result = execSmartFilterTest(
new SmartFilterTestExecutionDTO()
.filterCode("1/0")
);
assertThat(result.getResult()).isNull();
assertThat(result.getError()).containsIgnoringCase("Compilation error");
} |
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
// tagging like maxweight:conditional=no/none @ destination/delivery/forestry/service
String condValue = way.getTag("maxweight:conditional", "");
if (!condValue.isEmpty()) {
Str... | @Test
public void testConditionalTags() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
ReaderWay readerWay = new ReaderWay(1);
readerWay.setTag("highway", "primary");
readerWay.setTag("hgv:conditional", "no @ (weight > 7.5)");
parser.handleWayTags(edgeId, edgeIntA... |
public JwtBuilder jwtBuilder() {
return new JwtBuilder();
} | @Test
void testParseWith64Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
assertTrue(token.startsWith(NacosSignatur... |
@Override
public CompletableFuture<JobID> submitJob(@Nonnull JobGraph jobGraph) {
CompletableFuture<java.nio.file.Path> jobGraphFileFuture =
CompletableFuture.supplyAsync(
() -> {
try {
final java.nio.file.Pa... | @Test
@Timeout(value = 120_000, unit = TimeUnit.MILLISECONDS)
void testJobSubmissionWithoutUserArtifact() throws Exception {
try (final TestRestServerEndpoint restServerEndpoint =
createRestServerEndpoint(new TestJobSubmitHandler())) {
try (RestClusterClient<?> restClusterCli... |
public boolean[][] getAdjacencyMatrix() {
return adjacencyMatrix;
} | @Test
public void testPriorityQueueWithMinimalNewEdges() {
Graph<BayesVariable> graph = new BayesNetwork();
GraphNode x0 = addNode(graph);
GraphNode x1 = addNode(graph);
GraphNode x2 = addNode(graph);
GraphNode x3 = addNode(graph);
GraphNode x4 = addNode(graph);
... |
public static DisruptContext delay(long delay)
{
if (delay < 0)
{
throw new IllegalArgumentException("Delay cannot be smaller than 0");
}
return new DelayDisruptContext(delay);
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testLatencyIllegal()
{
final long latency = -4200;
DisruptContexts.delay(latency);
} |
@VisibleForTesting
public static List<SchemaChangeEventType> resolveSchemaEvolutionTag(String tag) {
List<SchemaChangeEventType> types =
new ArrayList<>(Arrays.asList(SchemaChangeEventTypeFamily.ofTag(tag)));
if (types.isEmpty()) {
// It's a specified tag
Sche... | @Test
public void testResolveSchemaEvolutionTag() {
assertThat(ChangeEventUtils.resolveSchemaEvolutionTag("all"))
.isEqualTo(
Arrays.asList(
ADD_COLUMN,
ALTER_COLUMN_TYPE,
... |
public static <T> GoConfigClassLoader<T> classParser(Element e, Class<T> aClass, ConfigCache configCache, GoCipher goCipher, final ConfigElementImplementationRegistry registry, ConfigReferenceElements configReferenceElements) {
return new GoConfigClassLoader<>(e, aClass, configCache, goCipher, registry, configR... | @Test
public void shouldErrorOutWhenAttributeAwareConfigTagHasAttributeWithBlankValue() {
final Element element = new Element("example");
final GoConfigClassLoader<ConfigWithAttributeAwareConfigTagAnnotation> loader = GoConfigClassLoader.classParser(element, ConfigWithAttributeAwareConfigTagAnnotat... |
@Override
public void init(Properties config) throws ServletException {
super.init(config);
nonBrowserUserAgents = config.getProperty(
NON_BROWSER_USER_AGENTS, NON_BROWSER_USER_AGENTS_DEFAULT)
.split("\\W*,\\W*");
for (int i = 0; i < nonBrowserUserAgents.length; i++) {
non... | @Test(timeout=60000)
public void testNonDefaultNonBrowserUserAgentAsNonBrowser() throws Exception {
if (handler != null) {
handler.destroy();
handler = null;
}
handler = getNewAuthenticationHandler();
Properties props = getDefaultProperties();
props.setProperty("alt-kerberos.non-browse... |
public String checkAuthenticationStatus(AdSession adSession, SamlSession samlSession, String artifact) throws BvdException, SamlSessionException, UnsupportedEncodingException, AdException {
AdAuthenticationStatus status = AdAuthenticationStatus.valueOfLabel(adSession.getAuthenticationStatus());
if (sta... | @Test
public void checkAuthenticationStatusFailedTest() {
AdSession adSession = new AdSession();
adSession.setAuthenticationStatus(AdAuthenticationStatus.STATUS_FAILED.label);
SamlSession samlSession1 = new SamlSession(1L);
String artifact = "artifact";
Exception result = ... |
public boolean isAllLogsToConsoleEnabled(Props props) {
return props.valueAsBoolean(LOG_CONSOLE.getKey(), false);
} | @Test
public void log_to_console_setting_disabled() {
Properties properties = new Properties();
properties.setProperty("sonar.log.console", "false");
assertThat(underTest.isAllLogsToConsoleEnabled(new Props(properties))).isFalse();
} |
@Override
public void isEquivalentAccordingToCompareTo(@Nullable BigDecimal expected) {
compareValues(expected);
} | @Test
public void isEquivalentAccordingToCompareTo() {
// make sure this still works
assertThat(TEN).isEquivalentAccordingToCompareTo(TEN);
} |
@Override
public AppResponse process(Flow flow, ActivateAppRequest body) {
String decodedPin = ChallengeService.decodeMaskedPin(appSession.getIv(), appAuthenticator.getSymmetricKey(), body.getMaskedPincode());
if ((decodedPin == null || !Pattern.compile("\\d{5}").matcher(decodedPin).matches())) {
... | @Test
void processNoDecodedPin(){
mockedActivateAppRequest.setMaskedPincode("1234");
when(mockedFlow.setFailedStateAndReturnNOK(any(AppSession.class))).thenReturn(new NokResponse());
AppResponse appResponse = pincodeSet.process(mockedFlow, mockedActivateAppRequest);
assertTrue(appR... |
@Override
protected Num calculate(int index) {
if (index == 0) {
return indicator.getValue(0);
}
Num value = zero();
int loopLength = (index - barCount < 0) ? index + 1 : barCount;
int actualIndex = index;
for (int i = loopLength; i > 0; i--) {
... | @Test
public void calculate() {
MockBarSeries series = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d, 6d);
Indicator<Num> close = new ClosePriceIndicator(series);
Indicator<Num> wmaIndicator = new WMAIndicator(close, 3);
assertNumEquals(1, wmaIndicator.getValue(0));
asse... |
public static InetSocketAddress replaceUnresolvedNumericIp(InetSocketAddress inetSocketAddress) {
requireNonNull(inetSocketAddress, "inetSocketAddress");
if (!inetSocketAddress.isUnresolved()) {
return inetSocketAddress;
}
InetSocketAddress inetAddressForIpString = createForIpString(
inetSocketAddress.ge... | @Test
void replaceUnresolvedNumericIpBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> AddressUtils.replaceUnresolvedNumericIp(null))
.withMessage("inetSocketAddress");
} |
public static KeyValueBytesStoreSupplier persistentTimestampedKeyValueStore(final String name) {
Objects.requireNonNull(name, "name cannot be null");
return new RocksDBKeyValueBytesStoreSupplier(name, true);
} | @Test
public void shouldCreateRocksDbTimestampedStore() {
assertThat(Stores.persistentTimestampedKeyValueStore("store").get(), instanceOf(RocksDBTimestampedStore.class));
} |
protected Dependency getMainAndroidDependency(Dependency dependency1, Dependency dependency2) {
if (!dependency1.isVirtual()
&& !dependency2.isVirtual()
&& Ecosystem.JAVA.equals(dependency1.getEcosystem())
&& Ecosystem.JAVA.equals(dependency2.getEcosystem())) {
... | @Test
public void testGetMainAndroidDependency() throws Exception {
ArchiveAnalyzer aa = null;
try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION, getSettings())) {
Dependency dependency1 = new Dependency(BaseTest.getResourceAsFile(this, "aar-1.0.0.aar"));
depend... |
@Override
public byte[] putIfAbsent(final Bytes key,
final byte[] valueAndTimestamp) {
final byte[] previous = wrapped().putIfAbsent(key, valueAndTimestamp);
if (previous == null) {
// then it was absent
log(key, rawValue(valueAndTimestamp), valu... | @Test
public void shouldWriteToInnerOnPutIfAbsentNoPreviousValue() {
store.putIfAbsent(hi, rawThere);
assertThat(root.get(hi), equalTo(rawThere));
} |
@Override
public int rpcPortOffset() {
return Integer.parseInt(System.getProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY,
String.valueOf(Constants.SDK_GRPC_PORT_DEFAULT_OFFSET)));
} | @Test
void testRpcPortOffsetDefault() {
grpcSdkClient = new GrpcSdkClient("test");
assertEquals(1000, grpcSdkClient.rpcPortOffset());
} |
@Override
public Set<Path> getPaths(ElementId src, ElementId dst) {
return super.getPaths(src, dst, (LinkWeigher) null);
} | @Test(expected = NullPointerException.class)
public void testGetPathsWithNullSrc() {
VirtualNetwork vnet = setupEmptyVnet();
PathService pathService = manager.get(vnet.id(), PathService.class);
pathService.getPaths(null, DID3);
} |
public boolean isSystemTopic(String topic) {
return isSystemTopic(TopicName.get(topic));
} | @Test
public void testIsSystemTopic() {
BrokerService brokerService = pulsar.getBrokerService();
assertFalse(brokerService.isSystemTopic(TopicName.get("test")));
assertFalse(brokerService.isSystemTopic(TopicName.get("public/default/test")));
assertFalse(brokerService.isSystemTopic(To... |
@Override
public void start() {
executorService.scheduleAtFixedRate(this::checks, getInitialDelay(),
getEnqueueDelay(), SECONDS);
} | @Test
public void doNothingIfExceptionIsThrown() {
when(lockManager.tryLock(any(), anyInt())).thenThrow(new IllegalArgumentException("Oops"));
underTest.start();
executorService.runCommand();
verifyNoInteractions(dbClient);
} |
@CanIgnoreReturnValue
public <K1 extends K, V1 extends V> Caffeine<K1, V1> expireAfter(
Expiry<? super K1, ? super V1> expiry) {
requireNonNull(expiry);
requireState(this.expiry == null, "Expiry was already set to %s", this.expiry);
requireState(this.expireAfterAccessNanos == UNSET_INT,
"Exp... | @Test
public void expireAfter() {
var builder = Caffeine.newBuilder().expireAfter(expiry);
assertThat(builder.expiry).isSameInstanceAs(expiry);
assertThat(builder.build()).isNotNull();
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldNotAddSchemaIdsIfNotPresentAlready() {
// Given:
givenKeyAndValueInferenceSupported();
// When:
final ConfiguredStatement<CreateStream> result = injector.inject(csStatement);
// Then:
assertFalse(result.getStatement().getProperties().getKeySchemaId().isPresent());
... |
public static Object eval(String expression, Map<String, Object> context) {
return eval(expression, context, ListUtil.empty());
} | @Test
public void jexlScriptTest(){
final ExpressionEngine engine = new JexlEngine();
final String exps2="if(a>0){return 100;}";
final Map<String,Object> map2=new HashMap<>();
map2.put("a", 1);
final Object eval1 = engine.eval(exps2, map2, null);
assertEquals(100, eval1);
} |
public static <T> RetryOperator<T> of(Retry retry) {
return new RetryOperator<>(retry);
} | @Test
public void doNotRetryFromPredicateUsingMono() {
RetryConfig config = RetryConfig.custom()
.retryOnException(t -> t instanceof IOException)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
give... |
@Override
public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) {
Mono<T> toReturn = toRun.transform(new SentinelReactorTransformer<>(
new EntryConfig(resourceName, entryType)));
if (fallback != null) {
toReturn = toReturn.onErrorResume(fallback);
}
return toReturn;
} | @Test
public void testCreateWithNullRule() {
String id = "testCreateReactiveCbWithNullRule";
ReactiveSentinelCircuitBreaker cb = new ReactiveSentinelCircuitBreaker(id,
Collections.singletonList(null));
assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block())
.isEqualTo("foobar");
assertThat(... |
public static LogExceptionBehaviourInterface getExceptionStrategy( LogTableCoreInterface table ) {
return getExceptionStrategy( table, null );
} | @Test public void testGetExceptionStrategyWithoutException() {
LogExceptionBehaviourInterface exceptionStrategy = DatabaseLogExceptionFactory.getExceptionStrategy( logTable );
String strategyName = exceptionStrategy.getClass().getName();
assertEquals( SUPPRESSABLE, strategyName );
} |
@Override
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为 permission 如果变更,涉及到新老两个 permission。直接清理,简单有效
public void updateMenu(MenuSaveVO updateReqVO) {
// 校验更新的菜单是否存在
if (menuMapper.selectById(updateReqVO.getId()) == null) {
... | @Test
public void testUpdateMenu_success() {
// mock 数据(构造父子菜单)
MenuDO sonMenuDO = createParentAndSonMenu();
Long sonId = sonMenuDO.getId();
// 准备参数
MenuSaveVO reqVO = randomPojo(MenuSaveVO.class, o -> {
o.setId(sonId);
o.setName("testSonName"); // 修改名... |
public Value parseWithOffsetInJsonPointer(String json, String offsetInJsonPointer) {
return this.delegate.parseWithOffsetInJsonPointer(json, offsetInJsonPointer);
} | @Test
public void testParseWithPointer1() throws Exception {
final JsonParser parser = new JsonParser();
final Value msgpackValue = parser.parseWithOffsetInJsonPointer("{\"a\": {\"b\": 1}}", "/a/b");
assertEquals(1, msgpackValue.asIntegerValue().asInt());
} |
public String getNode(String key, String group) {
return zkClient.getConfig(key, group);
} | @Test
public void testGetNode() {
String result = zooKeeperBufferedClient.getNode(PARENT_PATH, null);
Assert.assertEquals(NODE_CONTENT, result);
} |
public static DLPReidentifyText.Builder newBuilder() {
return new AutoValue_DLPReidentifyText.Builder();
} | @Test
public void throwsExceptionWhenDelimiterIsNullAndHeadersAreSet() {
PCollectionView<List<String>> header =
testPipeline.apply(Create.of("header")).apply(View.asList());
assertThrows(
"Column delimiter should be set if headers are present.",
IllegalArgumentException.class,
... |
@Override
public void invoke(IN value, Context context) throws Exception {
bufferLock.lock();
try {
// TODO this implementation is not very effective,
// optimize this with MemorySegment if needed
ByteArrayOutputStream baos = new ByteArrayOutputStream();
... | @Test
void testDuplicatedToken() throws Exception {
functionWrapper.openFunction();
for (int i = 0; i < 6; i++) {
functionWrapper.invoke(i);
}
String version = initializeVersion();
CollectCoordinationResponse response;
response = functionWrapper.sendReque... |
private HttpResponse getTenant(RestApi.RequestContext context) {
TenantName name = TenantName.from(context.pathParameters().getStringOrThrow("tenant"));
if ( ! tenantRepository.checkThatTenantExists(name))
throw new RestApiException.NotFound("Tenant '" + name + "' was not found.");
... | @Test
public void testTenantCreateWithAllPossibleCharactersInName() throws Exception {
TenantName tenantName = TenantName.from("aB-9999_foo");
assertNull(tenantRepository.getTenant(tenantName));
assertResponse(PUT, "/application/v2/tenant/aB-9999_foo",
"{\"message\":\"... |
public RequestAndSize parseRequest(ByteBuffer buffer) {
if (isUnsupportedApiVersionsRequest()) {
// Unsupported ApiVersion requests are treated as v0 requests and are not parsed
ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest(new ApiVersionsRequestData(), (short) 0, header... | @Test
public void testInvalidRequestForImplicitHashCollection() throws UnknownHostException {
short version = (short) 5; // choose a version with fixed length encoding, for simplicity
ByteBuffer corruptBuffer = produceRequest(version);
// corrupt the length of the topics array
corrup... |
@Override
public Publisher<Exchange> to(String uri, Object data) {
String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> {
try {
String uuid = context.getUuidGenerator().generateUuid();
context.addRoutes(new RouteBuilder() {
... | @Test
public void testToWithExchange() throws Exception {
context.start();
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Flux.just(1, 2, 3)
.flatMap(e -> crs.to("bean:hello", e))
.map... |
public boolean hasViewPermissionDefined() {
return !viewConfig.equals(new ViewConfig());
} | @Test
public void shouldReturnFalseIfViewPermissionNotDefined() {
Authorization authorization = new Authorization(new ViewConfig());
assertThat(authorization.hasViewPermissionDefined(), is(false));
} |
@Override
public void open() throws Exception {
executableStage = ExecutableStage.fromPayload(payload);
hasSdfProcessFn = hasSDF(executableStage);
initializeUserState(executableStage, getKeyedStateBackend(), pipelineOptions);
// TODO: Wire this into the distributed cache and make it pluggable.
// ... | @Test
public void expectedInputsAreSent() throws Exception {
TupleTag<Integer> mainOutput = new TupleTag<>("main-output");
DoFnOperator.MultiOutputOutputManagerFactory<Integer> outputManagerFactory =
new DoFnOperator.MultiOutputOutputManagerFactory(
mainOutput,
VoidCoder.of(),
... |
@Override
public boolean writeRefOrNull(MemoryBuffer buffer, Object obj) {
if (obj == null) {
buffer.writeByte(Fury.NULL_FLAG);
return true;
} else {
buffer.writeByte(Fury.NOT_NULL_VALUE_FLAG);
return false;
}
} | @Test
public void testWriteRefOrNull() {
NoRefResolver referenceResolver = new NoRefResolver();
MemoryBuffer buffer = MemoryBuffer.newHeapBuffer(32);
assertTrue(referenceResolver.writeRefOrNull(buffer, null));
assertFalse(referenceResolver.writeRefOrNull(buffer, new Object()));
Object o = new Obje... |
public static AppConfigurationEntry keytabEntry(String keytab, String principal) {
checkNotNull(keytab, "keytab");
checkNotNull(principal, "principal");
Map<String, String> keytabKerberosOptions = new HashMap<>();
if (IBM_JAVA) {
keytabKerberosOptions.put("useKeytab", prep... | @Test
public void testKeytabEntry() {
String keytab = "user.keytab";
String principal = "user";
AppConfigurationEntry entry = KerberosUtils.keytabEntry(keytab, principal);
assertNotNull(entry);
} |
public static JdbcUrlUtil.UrlInfo parse(String url) {
String serverName = "";
Integer port = DEFAULT_PORT;
String dbInstance = null;
int hostIndex = url.indexOf("://");
if (hostIndex <= 0) {
return null;
}
Map<String, String> props = Collections.empty... | @Test
public void testParse() {
String url =
"jdbc:sqlserver://localhost:1433;databaseName=myDB;encrypt=true;trustServerCertificate=false;loginTimeout=30;";
JdbcUrlUtil.UrlInfo urlInfo = SqlServerURLParser.parse(url);
assertEquals("localhost", urlInfo.getHost());
asse... |
public static List<String> getPossibleMountPoints(String path) throws InvalidPathException {
String basePath = cleanPath(path);
List<String> paths = new ArrayList<>();
if ((basePath != null) && !basePath.equals(AlluxioURI.SEPARATOR)) {
paths.add(basePath);
String parent = getParent(path);
... | @Test
public void getPossibleMountPointsNoException() throws InvalidPathException {
ArrayList<String> paths = new ArrayList<>();
assertEquals(paths, PathUtils.getPossibleMountPoints("/"));
assertEquals(paths, PathUtils.getPossibleMountPoints("//"));
paths.add("/a");
assertEquals(paths, PathUtils.... |
public static RecordDataSchema.Field copyField(RecordDataSchema.Field originalField, DataSchema fieldSchemaToReplace)
{
RecordDataSchema.Field newField = new RecordDataSchema.Field(fieldSchemaToReplace);
if (originalField.getAliases() != null)
{
newField.setAliases(originalField.getAliases(), new St... | @Test
public void testCopyField() throws Exception
{
RecordDataSchema fooSchema = (RecordDataSchema) TestUtil.dataSchemaFromString(fooSchemaText);
RecordDataSchema.Field field = fooSchema.getField("intField");
// Use old field to do the exact copy
RecordDataSchema.Field newField = CopySchemaUtil.cop... |
@Override
public boolean isRedundant(final Object other) {
if (other instanceof PatternInspector) {
if (pattern.getObjectType()
.getType()
.equals(((PatternInspector) other).getPattern()
.getObjectType()
... | @Test
void testRedundancy01() throws Exception {
assertThat(a.isRedundant(b)).isTrue();
assertThat(b.isRedundant(a)).isTrue();
} |
@Override
public Ring<T> createRing(Map<T, Integer> pointsMap) {
return _ringFactory.createRing(pointsMap);
} | @Test(groups = { "small", "back-end" })
public void testPointsCleanUp()
throws URISyntaxException
{
Map<String, Integer> pointsMp = buildPointsMap(6);
PointBasedConsistentHashRingFactory<String> ringFactory = new PointBasedConsistentHashRingFactory<>(new DegraderLoadBalancerStrategyConfig(1L));
... |
public static FrameworkModel defaultModel() {
FrameworkModel instance = defaultInstance;
if (instance == null) {
synchronized (globalLock) {
resetDefaultFrameworkModel();
if (defaultInstance == null) {
defaultInstance = new FrameworkModel()... | @Test
void testDefaultModel() {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
Assertions.assertTrue(FrameworkModel.getAllInstances().contains(frameworkModel));
String desc = frameworkModel.getDesc();
Assertions.assertEquals(desc, "Dubbo Framework[" + frameworkModel.g... |
@Override
public void initialize(Configuration configuration, Properties tableProperties, Properties partitionProperties)
throws SerDeException {
super.initialize(configuration, tableProperties, partitionProperties);
jsonSerde.initialize(configuration, tableProperties, partitionProperties, false);
... | @Test
public void testUpperCaseKey() throws Exception {
Configuration conf = new Configuration();
Properties props = new Properties();
props.put(serdeConstants.LIST_COLUMNS, "empid,name");
props.put(serdeConstants.LIST_COLUMN_TYPES, "int,string");
JsonSerDe rjsd = new JsonSerDe();
rjsd.initia... |
public static DLPReidentifyText.Builder newBuilder() {
return new AutoValue_DLPReidentifyText.Builder();
} | @Test
public void throwsExceptionWhenBatchSizeIsTooLarge() {
assertThrows(
String.format(
"Batch size is too large! It should be smaller or equal than %d.",
DLPDeidentifyText.DLP_PAYLOAD_LIMIT_BYTES),
IllegalArgumentException.class,
() ->
DLPReidentifyTe... |
public void validate(OptionRule rule) {
List<RequiredOption> requiredOptions = rule.getRequiredOptions();
for (RequiredOption requiredOption : requiredOptions) {
validate(requiredOption);
for (Option<?> option : requiredOption.getOptions()) {
if (SingleChoiceOpti... | @Test
public void testSimpleConditionalRequiredOptionsWithDefaultValue() {
OptionRule rule =
OptionRule.builder()
.optional(TEST_MODE)
.conditional(TEST_MODE, OptionTest.TestMode.TIMESTAMP, TEST_TIMESTAMP)
.build();
... |
public static SortDir sortDir(String s) {
return !DESC.equals(s) ? SortDir.ASC : SortDir.DESC;
} | @Test
public void sortDirNull() {
assertEquals("null sort dir", SortDir.ASC, TableModel.sortDir(null));
} |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueIntFailWrongValue() {
expectFailureWhenTestingThat(fact("foo", "the foo")).factValue("foo", 0).isEqualTo("the bar");
assertFailureValue("value of", "failure.factValue(foo, 0)");
} |
Mono<ServerResponse> createReply(ServerRequest request) {
String commentName = request.pathVariable("name");
return request.bodyToMono(ReplyRequest.class)
.flatMap(replyRequest -> {
Reply reply = replyRequest.toReply();
reply.getSpec().setIpAddress(IpAddressUt... | @Test
void createReply() {
when(replyService.create(any(), any())).thenReturn(Mono.empty());
final ReplyRequest replyRequest = new ReplyRequest();
replyRequest.setRaw("raw");
replyRequest.setContent("content");
replyRequest.setAllowNotification(true);
when(rateLimit... |
@Override
public HttpResponse get() throws InterruptedException, ExecutionException {
try {
final Object result = process(0, null);
if (result instanceof Throwable) {
throw new ExecutionException((Throwable) result);
}
return (HttpResponse) res... | @Test(expected = ExecutionException.class)
public void errGetTimeoutThrowable() throws ExecutionException, InterruptedException, TimeoutException {
get(new Exception("wrong"), false);
} |
static String calculateBillingProjectId(Optional<String> configParentProjectId, Optional<Credentials> credentials)
{
if (configParentProjectId.isPresent()) {
return configParentProjectId.get();
}
// All other credentials types (User, AppEngine, GCE, CloudShell, etc.) take it fro... | @Test
public void testBothConfigurationAndCredentials()
throws Exception
{
String projectId = BigQueryConnectorModule.calculateBillingProjectId(Optional.of("pid"), credentials());
assertThat(projectId).isEqualTo("pid");
} |
public static <InputT, OutputT> Growth<InputT, OutputT, OutputT> growthOf(
Growth.PollFn<InputT, OutputT> pollFn, Requirements requirements) {
return new AutoValue_Watch_Growth.Builder<InputT, OutputT, OutputT>()
.setTerminationPerInput(Growth.never())
.setPollFn(Contextful.of(pollFn, requirem... | @Test
@Category({NeedsRunner.class, UsesUnboundedSplittableParDo.class})
public void testSinglePollMultipleInputs() {
PCollection<KV<String, String>> res =
p.apply(Create.of("a", "b"))
.apply(
Watch.growthOf(
new PollFn<String, String>() {
... |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testAllActionsMushedTogether() {
String result = KnowledgeHelperFixerTest.fixer.fix( "insert(myObject ); update(ourObject);\t retract(herObject);" );
assertEqualsIgnoreWhitespace( "drools.insert(myObject ); drools.update(ourObject);\t drools.retract(herObject);",
... |
public List<String> mergePartitions(
MergingStrategy mergingStrategy,
List<String> sourcePartitions,
List<String> derivedPartitions) {
if (!derivedPartitions.isEmpty()
&& !sourcePartitions.isEmpty()
&& mergingStrategy != MergingStrategy.EXCLUD... | @Test
void mergeIncludingPartitionsFailsOnDuplicate() {
List<String> sourcePartitions = Arrays.asList("col3", "col4");
List<String> derivedPartitions = Arrays.asList("col1", "col2");
assertThatThrownBy(
() ->
util.mergePartitions(
... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchEthTypeTest() {
Criterion criterion = Criteria.matchEthType((short) 0x8844);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@Override
public int hashCode() {
int result = lowBoundary != null ? lowBoundary.hashCode() : 0;
result = 31 * result + (highBoundary != null ? highBoundary.hashCode() : 0);
result = 31 * result + (lowEndPoint != null ? lowEndPoint.hashCode() : 0);
result = 31 * result + (highEndPoin... | @Test
void hashCodeTest() {
final RangeImpl rangeImpl = new RangeImpl(Range.RangeBoundary.OPEN, 10, 15, Range.RangeBoundary.OPEN);
assertThat(rangeImpl.hashCode()).isEqualTo(rangeImpl.hashCode());
RangeImpl rangeImpl2 = new RangeImpl(Range.RangeBoundary.OPEN, 10, 15, Range.RangeBoundary.OPE... |
@Override
public V load(K key) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void load() {
cacheStore.load("somekey");
} |
@Override
public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
Map<Consumer, List<Range>> result = new LinkedHashMap<>();
rwLock.readLock().lock();
try {
int start = 0;
for (Map.Entry<Integer, List<Consumer>> entry: hashRing.entrySet()) {
for... | @Test
public void shouldRemoveConsumersFromConsumerKeyHashRanges() {
ConsistentHashingStickyKeyConsumerSelector selector = new ConsistentHashingStickyKeyConsumerSelector(12);
List<Consumer> consumers = IntStream.range(1, 100).mapToObj(i -> "consumer" + i)
.map(consumerName -> {
... |
@Override
public synchronized boolean tryReturnRecordAt(
boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) {
if (lastGroupStart == null && !isAtSplitPoint) {
throw new IllegalStateException(
String.format("The first group [at %s] must be at a split point", groupStart.toString()))... | @Test
public void testTryReturnRecordBeforeStart() throws Exception {
GroupingShuffleRangeTracker tracker =
new GroupingShuffleRangeTracker(ofBytes(3, 0, 0), ofBytes(5, 0, 0));
expected.expect(IllegalStateException.class);
tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3));
} |
@Override
protected void set(String key, String value) {
props.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
} | @Test
public void set_throws_NPE_if_key_is_null() {
MapSettings underTest = new MapSettings();
expectKeyNullNPE(() -> underTest.set(null, randomAlphanumeric(3)));
} |
@Override
public List<Integer> embed(String s, Context context) {
var start = System.nanoTime();
var tokens = tokenizer.embed(s, context);
runtime.sampleSequenceLength(tokens.size(), context);
runtime.sampleEmbeddingLatency((System.nanoTime() - start)/1_000_000d, context);
re... | @Test
public void testEmbedderWithNormalization() {
String input = "This is a test";
var context = new Embedder.Context("schema.indexing");
Tensor result = normalizedEmbedder.embed(input, context, TensorType.fromSpec(("tensor<float>(x[8])")));
assertEquals(1.0, result.multiply(result... |
public Optional<Topic> getTopicReference(String topic) {
CompletableFuture<Optional<Topic>> future = topics.get(topic);
if (future != null && future.isDone() && !future.isCompletedExceptionally()) {
return future.join();
} else {
return Optional.empty();
}
} | @Test
public void testStatsOfStorageSizeWithSubscription() throws Exception {
final String topicName = "persistent://prop/ns-abc/no-subscription";
Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
PersistentTopic topicRef = (PersistentTopic) pulsar.getBrokerSe... |
public void merge(SequenceSet sequenceSet) {
Sequence node = sequenceSet.getHead();
while (node != null) {
add(node);
node = node.getNext();
}
} | @Test
public void testMerge() {
SequenceSet set = new SequenceSet();
set.add(new Sequence(0, 100));
SequenceSet set2 = new SequenceSet();
set.add(new Sequence(50, 150));
set.merge(set2);
assertEquals(151, set.rangeSize());
assertEquals(1, set.size());
} |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_density_xxhdpi() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("xxhdpi", config);
assertThat(config.density).isEqualTo(DENSITY_XXHIGH);
} |
@Override
public Tuple apply(Tuple x) {
int[] bag = new int[featureIndex.size()];
for (String column : columns) {
for (String word : tokenizer.apply(x.getString(column))) {
Integer index = featureIndex.get(word);
if (index != null) {
i... | @Test
public void testFeature() throws IOException {
System.out.println("feature");
String[][] text = smile.util.Paths.getTestDataLines("text/movie.txt")
.map(String::trim)
.filter(line -> !line.isEmpty())
.map(line -> line.split("\\s+", 2))
... |
public MediaType detect(InputStream input, Metadata metadata) {
// Look for a type hint in the input metadata
String hint = metadata.get(Metadata.CONTENT_TYPE);
if (hint != null) {
MediaType type = MediaType.parse(hint);
if (type != null) {
return type;
... | @Test
public void testDetect() {
assertDetect(MediaType.TEXT_PLAIN, "text/plain");
assertDetect(MediaType.TEXT_PLAIN, "TEXT/PLAIN");
assertDetect(MediaType.TEXT_PLAIN, " text/\tplain\n");
assertDetect(TEXT_PLAIN_A_EQ_B, "text/plain; a=b");
assertDetect(TEXT_PLAIN_A_EQ_B, "\tt... |
@Transactional
public MeetingConfirmResponse create(String uuid, long attendeeId, MeetingConfirmRequest request) {
LocalDateTime startDateTime = request.toStartDateTime();
LocalDateTime endDateTime = request.toEndDateTime();
Meeting meeting = meetingRepository.findByUuid(uuid)
... | @DisplayName("약속에 포함되지 않은 시간의 일정을 확정 시 예외가 발생한다.")
@Test
void confirmScheduleThrowsExceptionWhen_InvalidTime() {
MeetingConfirmRequest request = new MeetingConfirmRequest(
today.getDate(),
Timeslot.TIME_2200.startTime(),
today.getDate(),
Ti... |
public AbstractFile getLastFile(final long logIndex, final int waitToWroteSize, final boolean createIfNecessary) {
AbstractFile lastFile = null;
while (true) {
int fileCount = 0;
this.readLock.lock();
try {
if (!this.files.isEmpty()) {
... | @Test
public void writeDataToSecondFile() {
writeDataToFirstFile();
// Try get last file again , this file is a new blank file (from allocator)
final AbstractFile lastFile = this.fileManager.getLastFile(10, 10, true);
assertEquals(lastFile.getFileFromOffset(), this.indexFileSize);
... |
public static <T> Builder<T> builder() {
return new Builder<>();
} | @Test
void testBuilder() {
String pluginName = null;
String functionName = "concat";
String description = "concatenate two strings";
List<InputVariable> parameters = Collections
.singletonList(new InputVariable("string1",
"java.lang.String", "first string ... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseReverseDateRangeDayOnly() throws ParseException {
// This is reverse since Su=7 and Mo=1
// Note: If we use Locale.Germany or Locale.UK for calendar creation
// then cal.set(DAY_OF_WEEK, 7) results in a "time in millis" after Saturday leading to reverse=false
... |
@Override
public RegisteredClient getClientConfiguration(ServerConfiguration issuer) {
RegisteredClient client = staticClientService.getClientConfiguration(issuer);
if (client != null) {
return client;
} else {
return dynamicClientService.getClientConfiguration(issuer);
}
} | @Test
public void getClientConfiguration_useStatic() {
Mockito.when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient);
RegisteredClient result = hybridService.getClientConfiguration(mockServerConfig);
Mockito.verify(mockStaticService).getClientConfiguration(mockServerConfig);
... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleAliasQualifiedSelectStar() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT T.* FROM TEST1 T;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getSelect(),
is(new Select(ImmutableList.of(... |
@Udf(description = "Returns the natural logarithm (base e) of an INT value.")
public Double ln(
@UdfParameter(
value = "value",
description = "the value get the natual logarithm of."
) final Integer value
) {
return ln(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandlePositive() {
assertThat(udf.ln(1), is(0.0));
assertThat(udf.ln(1L), is(0.0));
assertThat(udf.ln(1.0), is(0.0));
} |
private void removeStaticMember(ConsumerGroupMember oldMember) {
if (oldMember.instanceId() != null) {
staticMembers.remove(oldMember.instanceId());
}
} | @Test
public void testRemoveStaticMember() {
ConsumerGroup consumerGroup = createConsumerGroup("foo");
ConsumerGroupMember member = new ConsumerGroupMember.Builder("member")
.setSubscribedTopicNames(Arrays.asList("foo", "bar"))
.setInstanceId("instance")
.build()... |
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
int paddingCount = 4 - (cookieValue.length() % 4);
if (paddingCount < 4) {
char[] padding = new char[paddingCount];
Arrays.fill(padding, '=');
cookieValue += new String(padding);
... | @Test
void decodeCookieTest() {
var cookieValue = "YWRtaW46MTcxODk2NDE3NDgwODpTSEE"
+ "tMjU2OmNkOTM0ZTAyZWQ4NGJmMzc1ZTA4MmE1OWU4YTA3NTNiMzA3ODg1MjZmYzA3Yjgy"
+ "YzVmY2Y3YmJiYzdjYzRkNWU";
// 123 % 4 = 3, so we need to add 1 '=' to make it a multiple of 4 for
// spring-... |
public static String[][] assignExecutors(
List<? extends ScanTaskGroup<?>> taskGroups, List<String> executorLocations) {
Map<Integer, JavaHash<StructLike>> partitionHashes = Maps.newHashMap();
String[][] locations = new String[taskGroups.size()][];
for (int index = 0; index < taskGroups.size(); index... | @TestTemplate
public void testFileScanTaskWithUnpartitionedDeletes() {
List<ScanTask> tasks1 =
ImmutableList.of(
new MockFileScanTask(
mockDataFile(Row.of()),
mockDeleteFiles(2, Row.of()),
SCHEMA,
PartitionSpec.unpartitioned()),
... |
public boolean isLeaseExpired() {
return lockExpiryTime > 0L && Clock.currentTimeMillis() > lockExpiryTime;
} | @Test
public void testIsLeaseExpired() throws Exception {
LockGuard stateLock = LockGuard.NOT_LOCKED;
assertFalse(stateLock.isLeaseExpired());
Address endpoint = newAddress();
stateLock = new LockGuard(endpoint, TXN, TimeUnit.HOURS.toMillis(1));
assertFalse(stateLock.isLease... |
public static String getName(Class<?> c) {
if (c.isArray()) {
StringBuilder sb = new StringBuilder();
do {
sb.append("[]");
c = c.getComponentType();
} while (c.isArray());
return c.getName() + sb.toString();
}
retu... | @Test
void testGetName() {
// getName
assertEquals("boolean", ReflectUtils.getName(boolean.class));
assertEquals("int[][][]", ReflectUtils.getName(int[][][].class));
assertEquals("java.lang.Object[][]", ReflectUtils.getName(Object[][].class));
} |
@Override
public String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
JMeterVariables vars = getVariables();
String stringToSplit = ((CompoundVariable) values[0]).execute();
String varNamePrefix = ((CompoundVariable) values[1]).ex... | @Test
public void shouldSplitWithoutAnyArguments() throws Exception {
String src = "a,b,c";
SplitFunction split;
split = splitParams(src, "VAR1", null);
assertEquals(src, split.execute());
assertEquals(src, vars.get("VAR1"));
assertEquals("3", vars.get("VAR1_n"));
... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processHighlightings(lineBuilder);
} catch (RangeOffsetConverterException e) {
readError = new ReadError(HIGHLIGHTING, lineBuilder.getLine());
LOG.debug(format("In... | @Test
public void not_fail_and_stop_processing_when_range_offset_converter_throw_RangeOffsetConverterException() {
TextRange textRange1 = newTextRange(LINE_1, LINE_1);
doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH);
Highligh... |
@Nonnull
@Override
public Result addChunk(ByteBuf buffer) {
final byte[] readable = new byte[buffer.readableBytes()];
buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes());
final GELFMessage msg = new GELFMessage(readable);
final ByteBuf aggregatedBuffer;
... | @Test
public void duplicateChunk() {
final byte[] messageId1 = generateMessageId(1);
final byte[] messageId2 = generateMessageId(2);
final ByteBuf chunk1 = createChunk(messageId1, (byte) 0, (byte) 2, new byte[16]);
final ByteBuf chunk2 = createChunk(messageId1, (byte) 0, (byte) 2, ne... |
@VisibleForTesting
static Key extractKey(String cacheKeys, Configuration conf) {
// generate key elements in a certain order, so that the Key instances are comparable
List<Object> elements = Lists.newArrayList();
elements.add(conf.get(HiveConf.ConfVars.METASTORE_URIS.varname, ""));
elements.add(conf.g... | @Test
public void testCacheKey() throws Exception {
UserGroupInformation current = UserGroupInformation.getCurrentUser();
UserGroupInformation foo1 = UserGroupInformation.createProxyUser("foo", current);
UserGroupInformation foo2 = UserGroupInformation.createProxyUser("foo", current);
UserGroupInforma... |
@Override
public String getPrefix() {
return String.format("%s.%s", DAVProtocol.class.getPackage().getName(), StringUtils.upperCase(this.getType().name()));
} | @Test
public void testPrefix() {
assertEquals("ch.cyberduck.core.dav.DAV", new DAVProtocol().getPrefix());
} |
@SuppressWarnings("unchecked")
public static String encode(Type parameter) {
if (parameter instanceof NumericType) {
return encodeNumeric(((NumericType) parameter));
} else if (parameter instanceof Address) {
return encodeAddress((Address) parameter);
} else if (param... | @Test
public void testPrimitiveShort() {
assertEquals(
encode(new Short((short) 0)),
("0000000000000000000000000000000000000000000000000000000000000000"));
assertEquals(
encode(new Short(java.lang.Short.MIN_VALUE)),
("fffffffffffffffff... |
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
Throwable throwable = ctx.getThrowable();
if (throwable != null) {
if (!BlockException.isBlockException(throwable)) {
// Trace exception for each entry an... | @Test
public void testRun() throws Exception {
SentinelZuulErrorFilter sentinelZuulErrorFilter = new SentinelZuulErrorFilter();
Object result = sentinelZuulErrorFilter.run();
Assert.assertNull(result);
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatSimpleCaseExpression() {
final SimpleCaseExpression expression = new SimpleCaseExpression(
new StringLiteral("operand"),
Collections.singletonList(
new WhenClause(new StringLiteral("foo"),
new LongLiteral(1))),
Optional.empty());
... |
static @Nullable <V> V getWhenSuccessful(@Nullable CompletableFuture<V> future) {
try {
return (future == null) ? null : future.join();
} catch (CancellationException | CompletionException e) {
return null;
}
} | @Test(dataProvider = "successful")
public void getWhenSuccessful_success(CompletableFuture<Integer> future) {
assertThat(Async.getWhenSuccessful(future)).isEqualTo(1);
} |
@PublicAPI(usage = ACCESS)
public static <T> DescribedPredicate<T> describe(String description, Predicate<? super T> predicate) {
return new DescribePredicate<>(description, predicate).forSubtype();
} | @Test
public void describe_works() {
Predicate<Integer> isEven = input -> input % 2 == 0;
assertThat(describe("is even", isEven))
.accepts(8)
.hasDescription("is even")
.accepts(4)
.rejects(5);
} |
@Override
public void applyToAllPartitions(ApplyPartitionFunction<OUT> applyPartitionFunction)
throws Exception {
if (isKeyed) {
for (Object key : keySet) {
partitionedContext
.getStateManager()
.executeInKeyContext(
... | @Test
void testApplyToAllPartitions() throws Exception {
AtomicInteger counter = new AtomicInteger(0);
List<Integer> collectedData = new ArrayList<>();
TestingTimestampCollector<Integer> collector =
TestingTimestampCollector.<Integer>builder()
.setCol... |
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors(
ReconnaissanceReport reconnaissanceReport) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> isVulnDetector(entry.getKey()))
.map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc... | @Test
public void getVulnDetectors_whenSoftwareFilterHasMatchingService_returnsMatchedService() {
NetworkService wordPressService =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80))
.setTransportProtocol(TransportProtocol.TCP)
... |
public Resource getIncrementAllocation() {
Long memory = null;
Integer vCores = null;
Map<String, Long> others = new HashMap<>();
ResourceInformation[] resourceTypes = ResourceUtils.getResourceTypesArray();
for (int i=0; i < resourceTypes.length; ++i) {
String name = resourceTypes[i].getName()... | @Test
public void testAllocationIncrementVCoreWithUnit() throws Exception {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RESOURCE_TYPES + "." +
ResourceInformation.VCORES.getName() +
FairSchedulerConfiguration.INCREMENT_ALLOCATION, "1k");
FairSchedulerConfiguration ... |
public static String replaceFirst(String source, String search, String replace) {
int start = source.indexOf(search);
int len = search.length();
if (start == -1) {
return source;
}
if (start == 0) {
return replace + source.substring(len);
}
... | @Test
public void testReplace5() {
assertEquals("abcdef", JOrphanUtils.replaceFirst("abcdef", "alt=\"\" ", ""));
} |
@Override
public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) {
switch(type) {
case directory:
if(log.isDebugEnabled()) {
log.debug(String.format("Compare local attributes %s with remote %s using %s", local,... | @Test
public void testCompareFile() {
final DefaultComparisonService c = new DefaultComparisonService(new TestProtocol());
assertEquals(Comparison.equal, c.compare(Path.Type.file, new PathAttributes().withETag("1"), new PathAttributes().withETag("1")));
assertEquals(Comparison.unknown, c.com... |
public abstract TraceContext shallowCopy(TraceContext context); | @Test void shallowCopy() {
TraceContext context = TraceContext.newBuilder().traceId(1).spanId(2).debug(true)
.addExtra(1L).build();
assertThat(InternalPropagation.instance.shallowCopy(context))
.isNotSameAs(context)
.usingRecursiveComparison()
.isEqualTo(context);
} |
public static NameNodeConnector getNameNodeConnector(Configuration conf)
throws InterruptedException {
final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
final Path externalSPSPathId = HdfsServerConstants.MOVER_ID_PATH;
String serverName = ExternalStoragePolicySatisfier.class.getSim... | @Test(timeout = 300000)
public void testInfiniteStartWhenAnotherSPSRunning()
throws Exception {
try {
// Create cluster and create mover path when get NameNodeConnector.
createCluster(true);
// Disable system exit for assert.
ExitUtil.disableSystemExit();
// Get NameNodeConn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.