focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Udf(schema = "ARRAY<STRUCT<K STRING, V BIGINT>>")
public List<Struct> entriesBigInt(
@UdfParameter(description = "The map to create entries from") final Map<String, Long> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return e... | @Test
public void shouldComputeBigIntEntries() {
final Map<String, Long> map = createMap(Long::valueOf);
shouldComputeEntries(map, () -> entriesUdf.entriesBigInt(map, false));
} |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = MergeRollupTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
if (!validate(tableConfig, taskType)) {
continue;
... | @Test
public void testPartitionedTable() {
Map<String, Map<String, String>> taskConfigsMap = new HashMap<>();
Map<String, String> tableTaskConfigs = new HashMap<>();
tableTaskConfigs.put("daily.mergeType", "concat");
tableTaskConfigs.put("daily.bufferTimePeriod", "2d");
tableTaskConfigs.put("daily... |
@Override
public void submit(VplsOperation vplsOperation) {
if (isLeader) {
// Only leader can execute operation
addVplsOperation(vplsOperation);
}
} | @Test
public void testDoNothingOperation() {
VplsData vplsData = VplsData.of(VPLS1);
vplsData.addInterfaces(ImmutableSet.of(V100H1, V100H2));
VplsOperation vplsOperation = VplsOperation.of(vplsData,
VplsOperation.Operation.ADD);
... |
@Override
public State waitUntilFinish() {
return State.DONE;
} | @Test
public void testWaitUntilFinishReturnsDone() {
FlinkRunnerResult result = new FlinkRunnerResult(Collections.emptyMap(), 100);
assertThat(result.waitUntilFinish(), is(PipelineResult.State.DONE));
assertThat(result.waitUntilFinish(Duration.millis(100)), is(PipelineResult.State.DONE));
} |
HasRuleEngineProfile getRuleEngineProfileForEntityOrElseNull(TenantId tenantId, EntityId entityId, TbMsg tbMsg) {
if (entityId.getEntityType().equals(EntityType.DEVICE)) {
if (TbMsgType.ENTITY_DELETED.equals(tbMsg.getInternalType())) {
try {
Device deletedDevice =... | @Test
public void testGetRuleEngineProfileForUpdatedAndDeletedDevice() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());
TenantId tenantId = new TenantId(UUID.randomUUID());
DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.randomUUID());
Device device = new Device(dev... |
public static GaussianProcessRegression<double[]> fit(double[][] x, double[] y, Properties params) {
MercerKernel<double[]> kernel = MercerKernel.of(params.getProperty("smile.gaussian_process.kernel", "linear"));
double noise = Double.parseDouble(params.getProperty("smile.gaussian_process.noise", "1E-10... | @Test
public void testOutOfBoundsException() throws Exception {
double[][] X = {
{4.543, 3.135, 0.86},
{5.159, 5.043, 1.53},
{5.366, 5.438, 1.57},
{5.759, 7.496, 1.81},
{4.663, 3.807, 0.99},
{5.697, 7.601, ... |
public static <T> RestResponse<T> fail() {
return new RestResponse<T>(-1);
} | @Test
public void testFail() {
Assert.assertFalse(RestResponse.fail().isSuccess());
Assert.assertEquals("error", RestResponse.fail("error").getMsg());
Assert.assertEquals("error", RestResponse.fail(500, "error").getMsg());
} |
public void validate(Map<String, NewDocumentType> documentDefinitions,
Set<NewDocumentType> globallyDistributedDocuments) {
verifyReferredDocumentsArePresent(documentDefinitions);
verifyReferredDocumentsAreGlobal(documentDefinitions, globallyDistributedDocuments);
} | @Test
void validation_succeeds_if_referenced_document_is_global() {
NewDocumentType parent = createDocumentType("parent");
Fixture fixture = new Fixture()
.addGlobalDocument(parent)
.addNonGlobalDocument(createDocumentType("child", parent));
validate(fixture);... |
@Override
public Mono<Boolean> confirmPassword(String username, String rawPassword) {
return getUser(username)
.filter(user -> {
if (!StringUtils.hasText(user.getSpec().getPassword())) {
// If the password is not set, return true directly.
... | @Test
void confirmPasswordWhenPasswordNotSet() {
var user = new User();
user.setSpec(new User.UserSpec());
when(client.get(User.class, "fake-user")).thenReturn(Mono.just(user));
userService.confirmPassword("fake-user", "fake-password")
.as(StepVerifier::create)
... |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void testTimeZoneInPacificTime() {
// Given:
final Timestamp timestamp = new Timestamp(1534353043000L);
// When:
final String pacificTime = udf.formatTimestamp(timestamp,
"yyyy-MM-dd HH:mm:ss zz", "America/Los_Angeles");
// Then:
assertThat(pacificTime,
either(is... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReport12MonthsFor59Days23Hours59Minutes30Seconds() throws Exception {
assertEquals(TimeConverter.ABOUT_X_MONTHS_AGO.argument(12), timeConverter
.getConvertedTime(365 * TimeConverter.DAY_IN_SECONDS - 31));
} |
public static void checkArgument(final boolean condition, final String errorMessage) {
if (!condition) {
throw new IllegalArgumentException(errorMessage);
}
} | @Test
void assertCheckArgumentFailed() {
assertThrows(IllegalArgumentException.class, () -> PluginPreconditions.checkArgument(false, "Port `-3306` of MySQL Service must be a positive number."));
} |
@Override
public void onComplete(final Request request) {
final RequestInfo requestInfo = getRequestInfo(request);
final List<Tag> tags = new ArrayList<>(5);
tags.add(Tag.of(PATH_TAG, requestInfo.path()));
tags.add(Tag.of(METHOD_TAG, requestInfo.method()));
tags.add(Tag.of(STATUS_CODE_TAG, Strin... | @Test
@SuppressWarnings("unchecked")
void testRequests() {
final String path = "/test";
final String method = "GET";
final int statusCode = 200;
final HttpURI httpUri = mock(HttpURI.class);
when(httpUri.getPath()).thenReturn(path);
final Request request = mock(Request.class);
when(requ... |
@Udf
public String concatWS(
@UdfParameter(description = "Separator string and values to join") final String... inputs) {
if (inputs == null || inputs.length < 2) {
throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments.");
}
final String separator = inputs[0... | @Test
public void shouldFailIfOnlySeparatorBytesInput() {
// When:
final KsqlException e = assertThrows(KsqlFunctionException.class, () -> udf.concatWS(ByteBuffer.wrap(new byte[] {3})));
// Then:
assertThat(e.getMessage(), containsString("expects at least two input arguments"));
} |
public int[] mappings() {
int[] cleansed = new int[mapping.length];
for (int i = 0; i < mapping.length; i++) {
cleansed[i] = unmask(mapping[i]);
}
return cleansed;
} | @Test
public void testMappings() {
instance.setMapping(0, 2 | VariableMapper.REMAP_FLAG, 1);
instance.setMapping(1, VariableMapper.REMAP_FLAG | VariableMapper.DOUBLE_SLOT_FLAG, 2);
assertEquals(2, instance.map(0));
assertEquals(0, instance.map(1));
} |
public static Map<String, Object> replaceKeyCharacter(Map<String, Object> map, char oldChar, char newChar) {
final Map<String, Object> result = new HashMap<>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
final String key = entry.getKey().replace(oldChar, newChar);
... | @Test
public void replaceKeyCharacterHandlesEmptyMap() {
assertThat(MapUtils.replaceKeyCharacter(Collections.emptyMap(), '.', '_')).isEmpty();
} |
@SuppressWarnings("unchecked")
public static <T> T convert(Class<T> klass, String value) {
if (Strings.isNullOrEmpty(value)) {
throw new IllegalArgumentException("Value must not be empty.");
}
if (Objects.isNull(converters.get(klass))) {
throw new IllegalArgumentExce... | @Test(expected = IllegalArgumentException.class)
public void testEmptyValue() {
PasswordParamConverter.convert(Double.class, "");
} |
public static <K, InputT> GroupIntoBatches<K, InputT> ofSize(long batchSize) {
Preconditions.checkState(batchSize < Long.MAX_VALUE);
return new GroupIntoBatches<K, InputT>(BatchingParams.createDefault()).withSize(batchSize);
} | @Test
@Category({
ValidatesRunner.class,
NeedsRunner.class,
UsesTimersInParDo.class,
UsesTestStream.class,
UsesStatefulParDo.class,
UsesOnWindowExpiration.class
})
public void testInStreamingMode() {
int timestampInterval = 1;
Instant startInstant = new Instant(0L);
TestStream.... |
void checkUrlPattern(String url, String message, Object... messageArguments) {
try {
HttpUrl okUrl = HttpUrl.parse(url);
if (okUrl == null) {
throw new IllegalArgumentException(String.format(message, messageArguments));
}
InetAddress address = InetAddress.getByName(okUrl.host());
... | @Test
@UseDataProvider("loopbackUrls")
public void checkUrlPatternSuccessfulForLoopbackAddressWhenSonarValidateWebhooksPropertyDisabled(String url) {
when(configuration.getBoolean("sonar.validateWebhooks")).thenReturn(of(false));
assertThatCode(() -> underTest.checkUrlPattern(url, "msg")).doesNotThrowAnyEx... |
@Override
public List<SnowflakeIdentifier> listDatabases() {
List<SnowflakeIdentifier> databases;
try {
databases =
connectionPool.run(
conn ->
queryHarness.query(
conn, "SHOW DATABASES IN ACCOUNT", DATABASE_RESULT_SET_HANDLER));
} catc... | @SuppressWarnings("unchecked")
@Test
public void testListDatabasesInterruptedException() throws SQLException, InterruptedException {
Exception injectedException = new InterruptedException("Fake interrupted exception");
when(mockClientPool.run(any(ClientPool.Action.class))).thenThrow(injectedException);
... |
@Override
public void resetLocal() {
this.min = Long.MAX_VALUE;
} | @Test
void testResetLocal() {
LongMinimum min = new LongMinimum();
long value = 9876543210L;
min.add(value);
assertThat(min.getLocalValue().longValue()).isEqualTo(value);
min.resetLocal();
assertThat(min.getLocalValue().longValue()).isEqualTo(Long.MAX_VALUE);
} |
@VisibleForTesting
static boolean isRichConsole(ConsoleOutput consoleOutput, HttpTraceLevel httpTraceLevel) {
if (httpTraceLevel != HttpTraceLevel.off) {
return false;
}
switch (consoleOutput) {
case plain:
return false;
case auto:
// Enables progress footer when ANSI is... | @Test
public void testIsRightConsole_autoWindowsTrue() {
System.setProperty("os.name", "windows");
assertThat(CliLogger.isRichConsole(ConsoleOutput.auto, HttpTraceLevel.off)).isTrue();
} |
public void startThreads() throws KettleException {
// Now prepare to start all the threads...
//
nrOfFinishedSteps = 0;
nrOfActiveSteps = 0;
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.TransformationStartThreads.id, this );
fireTransStartedListeners();
for ( int i... | @Test
public void testTransStartListenersConcurrentModification() throws Exception {
CountDownLatch start = new CountDownLatch( 1 );
TransFinishListenerAdder add = new TransFinishListenerAdder( trans, start );
TransStartListenerFirer starter = new TransStartListenerFirer( trans, start );
startThreads(... |
public void analyze(ConnectContext context) {
dbName = AnalyzerUtils.getOrDefaultDatabase(dbName, context);
FeNameFormat.checkLabel(labelName);
} | @Test(expected = SemanticException.class)
public void testNoLabel() throws SemanticException {
new Expectations() {
{
analyzer.getDefaultDb();
minTimes = 0;
result = "testDb";
}
};
LabelName label = new LabelName("", ""... |
@Override
public Optional<ComputationConfig> fetchConfig(String computationId) {
Preconditions.checkArgument(
!computationId.isEmpty(),
"computationId is empty. Cannot fetch computation config without a computationId.");
GetConfigResponse response =
applianceComputationConfigFetcher.f... | @Test
public void testGetComputationConfig() throws IOException {
List<Windmill.GetConfigResponse.NameMapEntry> nameMapEntries =
ImmutableList.of(
Windmill.GetConfigResponse.NameMapEntry.newBuilder()
.setUserName("userName1")
.setSystemName("systemName1")
... |
@SneakyThrows
public static String generatePolicy(Set<CredentialContext.Privilege> privileges, List<String> locations) {
JsonNode policyRoot = loadYaml(POLICY_STATEMENT);
ArrayNode policyStatement = (ArrayNode) policyRoot.findPath("Statement");
JsonNode operationsStatement = loadYaml(OPERATION_STATEMENT);... | @Test
public void testPolicyWithStorageProfileLocations() {
String updatePolicy =
AwsPolicyGenerator.generatePolicy(
Set.of(SELECT, UPDATE),
List.of(
"s3://my-bucket1/path1/table1", "s3://profile-bucket2/", "s3://profile-bucket3"));
assertThat(updatePolicy)
... |
public static boolean isContentType(String contentType, Message message) {
if (contentType == null) {
return message.getContentType() == null;
} else {
return contentType.equals(message.getContentType());
}
} | @Test
public void testIsContentTypeWithNullStringValueAndNonNullMessageContentType() {
Message message = Proton.message();
message.setContentType("test");
assertFalse(AmqpMessageSupport.isContentType(null, message));
} |
public Map<String, MetaProperties> logDirProps() {
return logDirProps;
} | @Test
public void testCopierGenerateValidDirectoryId() {
MetaPropertiesMockRandom random = new MetaPropertiesMockRandom();
MetaPropertiesEnsemble.Copier copier = new MetaPropertiesEnsemble.Copier(EMPTY);
copier.setRandom(random);
copier.logDirProps().put("/tmp/dir1",
new ... |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_FLOAT_basic() {
final MutableData data = new MutableData(new byte[4]);
data.setValue(1.0f, Data.FORMAT_FLOAT, 0);
assertArrayEquals(new byte[] { 1, 0, 0, 0 }, data.getValue());
} |
@Override
public Map<String, StepTransition> translate(WorkflowInstance workflowInstance) {
WorkflowInstance instance = objectMapper.convertValue(workflowInstance, WorkflowInstance.class);
if (instance.getRunConfig() != null) {
if (instance.getRunConfig().getPolicy() == RunPolicy.RESTART_FROM_INCOMPLET... | @Test
public void testTranslateIncludingAllSteps() {
Map<String, StepTransition> dag = translator.translate(instance);
Assert.assertEquals(
new HashSet<>(Arrays.asList("job1", "job.2", "job3", "job4")), dag.keySet());
} |
@Override
public OAuth2AccessTokenDO checkAccessToken(String accessToken) {
OAuth2AccessTokenDO accessTokenDO = getAccessToken(accessToken);
if (accessTokenDO == null) {
throw exception0(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "访问令牌不存在");
}
if (DateUtils.isExpire... | @Test
public void testCheckAccessToken_null() {
// 调研,并断言
assertServiceException(() -> oauth2TokenService.checkAccessToken(randomString()),
new ErrorCode(401, "访问令牌不存在"));
} |
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {LARGEINT, BIGINT}, returnType = LARGEINT)
public static ConstantOperator bitShiftRightLogicalLargeInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createLargeInt(
bitShiftRightLogicalForInt128(first.ge... | @Test
public void bitShiftRightLogicalLargeInt() {
assertEquals("12",
ScalarOperatorFunctions.bitShiftRightLogicalLargeInt(O_LI_100, O_BI_3).getLargeInt().toString());
assertEquals("800",
ScalarOperatorFunctions.bitShiftRightLogicalLargeInt(O_LI_100, O_BI_NEG_3).getLa... |
public ScheduledExecutorServiceBuilder scheduledExecutorService(String nameFormat) {
return scheduledExecutorService(nameFormat, false);
} | @Test
void scheduledExecutorServiceBuildsUserThreadsByDefault() {
final ScheduledExecutorService executorService = environment.scheduledExecutorService("user-%d").build();
assertThat(executorService.submit(() -> Thread.currentThread().isDaemon()))
.succeedsWithin(1, TimeUnit.SECONDS, as... |
@Override
public String getProperty(String name) {
Queue<Driver> queue = new LinkedList<>();
queue.add(this);
while (!queue.isEmpty()) {
Driver driver = queue.remove();
String property = driver.properties().get(name);
if (property != null) {
... | @Test
public void testGetProperty() throws Exception {
DefaultDriver root = new DefaultDriver(ROOT, Lists.newArrayList(), MFR, HW, SW,
ImmutableMap.of(), ImmutableMap.of());
DefaultDriver child = new DefaultDriver(CHILD, Lists.newArrayList(root), MFR, HW, SW,
Immutab... |
@Override
public DescribeTopicsResult describeTopics(final TopicCollection topics, DescribeTopicsOptions options) {
if (topics instanceof TopicIdCollection)
return DescribeTopicsResult.ofTopicIds(handleDescribeTopicsByIds(((TopicIdCollection) topics).topicIds(), options));
else if (topic... | @Test
public void testDescribeTopicsByIds() throws ExecutionException, InterruptedException {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
// Valid ID
Uuid topicId = Uuid.randomUuid();
St... |
public void createPipe(CreatePipeStmt stmt) throws DdlException {
try {
lock.writeLock().lock();
Pair<Long, String> dbIdAndName = resolvePipeNameUnlock(stmt.getPipeName());
boolean existed = nameToId.containsKey(dbIdAndName);
if (existed) {
if (!st... | @Test
public void showPipes() throws Exception {
PipeManager pm = ctx.getGlobalStateMgr().getPipeManager();
String createSql =
"create pipe show_1 as insert into tbl1 select * from files('path'='fake://pipe', 'format'='parquet')";
CreatePipeStmt createStmt = (CreatePipeStmt)... |
public static Class<?> name2class(String name) throws ClassNotFoundException {
return name2class(ClassUtils.getClassLoader(), name);
} | @Test
void testName2Class() throws Exception {
assertEquals(boolean.class, ReflectUtils.name2class("boolean"));
assertEquals(boolean[].class, ReflectUtils.name2class("boolean[]"));
assertEquals(int[][].class, ReflectUtils.name2class(ReflectUtils.getName(int[][].class)));
assertEquals... |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseIE11OnWindowsServer2008R2Test() {
final String uaStr = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
final UserAgent ua = UserAgentUtil.parse(uaStr);
assertEquals("MSIE11", ua.getBrowser().toString());
assertEquals("11.0", ua.getVersion());
assertEquals("Tride... |
static String resolveLocalRepoPath(String localRepoPath) {
// todo decouple home folder resolution
// find homedir
String home = System.getenv("ZEPPELIN_HOME");
if (home == null) {
home = System.getProperty("zeppelin.home");
}
if (home == null) {
home = "..";
}
return Paths.... | @Test
void should_not_change_absolute_path() {
String absolutePath
= Paths.get("first", "second").toAbsolutePath().toString();
String resolvedPath = Booter.resolveLocalRepoPath(absolutePath);
assertEquals(absolutePath, resolvedPath);
} |
@Override
public void requestPermission(ApplicationId appId, Permission permission) {
states.computeIf(appId, securityInfo -> (securityInfo == null || securityInfo.getState() != POLICY_VIOLATED),
(id, securityInfo) -> new SecurityInfo(securityInfo.getPermissions(), POLICY_VIOLATED));
... | @Test
public void testRequestPermission() {
states.compute(appId, (id, securityInfo) -> new SecurityInfo(securityInfo.getPermissions(), POLICY_VIOLATED));
assertEquals(POLICY_VIOLATED, states.get(appId).getState());
Permission testPermissionB = new Permission("testClassB", "testNameB");
... |
public DateTimeStamp minus(double offsetInDecimalSeconds) {
return add(-offsetInDecimalSeconds);
} | @Test
void minus() {
DateTimeStamp a = new DateTimeStamp(.586);
double a_ts = a.getTimeStamp();
ZonedDateTime a_dt = a.getDateTime();
DateTimeStamp b = new DateTimeStamp(.586 - .587);
assertEquals(b.getTimeStamp(), a.minus(.587).getTimeStamp(), .001);
assertEquals(a_t... |
@Override
public List<URI> getGlue() {
return configurationParameters
.get(GLUE_PROPERTY_NAME, s -> Arrays.asList(s.split(",")))
.orElse(Collections.singletonList(CLASSPATH_SCHEME_PREFIX))
.stream()
.map(String::trim)
.map(GlueP... | @Test
void getGlue() {
ConfigurationParameters config = new MapConfigurationParameters(
Constants.GLUE_PROPERTY_NAME,
"com.example.app, com.example.glue");
assertThat(new CucumberEngineOptions(config).getGlue(),
contains(
URI.create("classpath:/co... |
public <K> KTableHolder<K> build(
final KTableHolder<K> table,
final TableSuppress<K> step,
final RuntimeBuildContext buildContext,
final ExecutionKeyFactory<K> executionKeyFactory
) {
return build(
table,
step,
buildContext,
executionKeyFactory,
Phy... | @Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldSuppressSourceTable() {
// When:
final KTableHolder<Struct> result = builder.build(
tableHolder,
tableSuppress,
buildContext,
executionKeyFactory,
physicalSchemaFactory,
new MaterializedFacto... |
public static HiveConf create(Configuration conf) {
HiveConf hiveConf = new HiveConf(conf, HiveConf.class);
// to make sure Hive configuration properties in conf not be overridden
hiveConf.addResource(conf);
return hiveConf;
} | @Test
public void testCreateHiveConf() {
HiveConf hiveConf = createHiveConf();
assertThat(hiveConf.getBoolVar(HiveConf.ConfVars.METASTORE_USE_THRIFT_SASL)).isTrue();
// will override configurations from `hiveConf` with hive default values which default value
// is null or empty stri... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldResolveInMergePipelineConfigs() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("2.1-${COUNT}-#{foo}-bar-#{bar}");
HgMaterialConfig materialConfig = MaterialConfigsMother.hgMaterialCo... |
@SuppressWarnings("unchecked")
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
final String windowedInnerClassSerdeConfig = (String) configs.get(StreamsConfig.WINDOWED_INNER_CLASS_SERDE);
Serde<T> windowInnerClassSerde = null;
if (windowedInnerClassSe... | @Test
public void shouldThrowConfigExceptionWhenInvalidWindowedInnerClassSerialiserSupplied() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
assertThrows(ConfigException.class, () -> timeWindowedSerializer.configure(props, false));
} |
public String getMethod() {
return method;
} | @Test
public void testGetMethod() {
shenyuRequestLog.setMethod("test");
Assertions.assertEquals(shenyuRequestLog.getMethod(), "test");
} |
public static WriteStreams writeStreams() {
return new AutoValue_RedisIO_WriteStreams.Builder()
.setConnectionConfiguration(RedisConnectionConfiguration.create())
.setMaxLen(0L)
.setApproximateTrim(true)
.build();
} | @Test
public void testWriteStreamsWithTruncation() {
/* test data is 10 keys (stream IDs), each with two entries, each entry having one k/v pair of data */
List<String> redisKeys =
IntStream.range(0, 10).boxed().map(idx -> UUID.randomUUID().toString()).collect(toList());
Map<String, String> fooVa... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
doHttpFilter((HttpServletRequest) req, (HttpServletResponse) resp, chain);
} | @Test
public void ifRequestUriIsNull_returnBadRequest() throws ServletException, IOException {
HttpServletRequest request = newRequest("GET", "/");
when(request.getRequestURI()).thenReturn(null);
underTest.doFilter(request, response, chain);
verify(response).setStatus(HttpServletResponse.SC_BAD_REQUE... |
@Override
public V get(HollowMap<K, V> map, int ordinal, Object key) {
if(getSchema().getHashKey() != null) {
for(int i=0;i<ordinals.length;i+=2) {
if(ordinals[i] != -1 && map.equalsKey(ordinals[i], key))
return map.instantiateValue(ordinals[i+1]);
... | @Test
public void testGetOnEmptyMap() throws Exception {
addRecord();
addRecord(10, 20);
roundTripSnapshot();
HollowMapCachedDelegate<Integer, Integer> delegate = new HollowMapCachedDelegate<Integer, Integer>((HollowMapTypeReadState)readStateEngine.getTypeState("TestMap"), 0);
... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<AssertSchema> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
return AssertExecutor.execute(
statement.getMaskedStat... | @Test
public void shouldFailToAssertNotExistSchemaBySubjectAndId() {
// Given
final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("abc"), Optional.of(500), Optional.empty(), false);
final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement
.of(KsqlParser.... |
@Override
protected void processOptions(LinkedList<String> args)
throws IOException {
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE,
OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN,
OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE,
OPTION_MTIME, OPTION_SIZE, OPTION_A... | @Test
public void processPathDirOrderDefault() throws IOException {
TestFile testfile01 = new TestFile("testDirectory", "testFile01");
TestFile testfile02 = new TestFile("testDirectory", "testFile02");
TestFile testfile03 = new TestFile("testDirectory", "testFile03");
TestFile testfile04 = new TestFil... |
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks,
final Map<TaskId, Set<TopicPartition>> standbyTasks) {
log.info("Handle new assignment with:\n" +
"\tNew active tasks: {}\n" +
"\tNew standby tasks: {}\n" +... | @Test
public void shouldRecycleActiveTaskInStateUpdater() {
final StreamTask activeTaskToRecycle = statefulTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RESTORING)
.withInputPartitions(taskId03Partitions).build();
final StandbyTask recycledStandbyTask = standbyTa... |
@Override
public void send(Object message) throws RemotingException {
send(message, false);
} | @Test
void sendTest01() throws RemotingException {
boolean sent = true;
String message = "this is a test message";
header.send(message, sent);
List<Object> objects = channel.getSentObjects();
Assertions.assertEquals(objects.get(0), "this is a test message");
} |
public List<ConnectorMetadataUpdateHandle> getMetadataUpdateResults(List<ConnectorMetadataUpdateHandle> metadataUpdateRequests, QueryId queryId)
{
ImmutableList.Builder<ConnectorMetadataUpdateHandle> metadataUpdateResults = ImmutableList.builder();
for (ConnectorMetadataUpdateHandle connectorMetada... | @Test
public void testHiveFileRenamer()
{
HiveFileRenamer hiveFileRenamer = new HiveFileRenamer();
List<ConnectorMetadataUpdateHandle> requests = ImmutableList.of(TEST_HIVE_METADATA_UPDATE_REQUEST);
List<ConnectorMetadataUpdateHandle> results = hiveFileRenamer.getMetadataUpdateResults(re... |
@Override
public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp,
final String srcUser) {
ConfigInfoStateWrapper configInfo4BetaState = this.findConfigInfo4BetaState(configInfo.getDataId(),
configInfo.getGroup(... | @Test
void testInsertOrUpdateBetaOfAdd() {
String dataId = "betaDataId113";
String group = "group113";
String tenant = "tenant113";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper.setDa... |
@Override
public void close() throws Exception {
committer.stopAsync().awaitTerminated(1, TimeUnit.MINUTES);
} | @Test
public void close() throws Exception {
committer.close();
verify(fakeCommitter).stopAsync();
verify(fakeCommitter).awaitTerminated(1, TimeUnit.MINUTES);
} |
public static Schema schemaFromPojoClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedPOJO() {
Schema schema =
POJOUtils.schemaFromPojoClass(
new TypeDescriptor<NestedPOJO>() {}, JavaFieldTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_POJO_SCHEMA, schema);
} |
public long iterateAtLeastFrom(int index, Iterator<E> iterator) {
return storage.iterateAtLeastFrom(index, iterator);
} | @Test
public void testIterateAtLeastFrom() {
SparseIntArray.Iterator<Integer> iterator = new SparseIntArray.Iterator<>();
// test empty array
verifyIterateAtLeastFrom(0, iterator);
// try dense
for (int i = 0; i < ARRAY_STORAGE_32_MAX_SPARSE_SIZE / 2; ++i) {
set... |
public static FusedPipeline fuse(Pipeline p) {
return new GreedyPipelineFuser(p).fusedPipeline;
} | @Test
public void flattenWithHeterogeneousInputsSingleEnvOutputPartiallyMaterialized() {
Components components =
Components.newBuilder()
.putCoders("coder", Coder.newBuilder().build())
.putCoders("windowCoder", Coder.newBuilder().build())
.putWindowingStrategies(
... |
@Override
protected void doStart() throws Exception {
super.doStart();
LOG.debug("Creating connection to Azure ServiceBus");
client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(),
this::processMessage, this::processError);
... | @Test
void synchronizationDeadLettersMessageWithoutOptionsWhenExceptionNotPresent() throws Exception {
try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) {
when(configuration.getServiceBusReceiveMode()).thenReturn(ServiceBusReceiveMode.PEEK_LOCK);
when(co... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testPartialFetchWithPausedPartitions() {
// this test sends creates a completed fetch with 3 records and a max poll of 2 records to assert
// that a fetch that must be returned over at least 2 polls can be cached successfully when its partition is
// paused, then returned s... |
public URLNormalizer removeWWW() {
String host = toURL().getHost();
String newHost = StringUtils.removeStartIgnoreCase(host, "www.");
url = StringUtils.replaceOnce(url, host, newHost);
return this;
} | @Test
public void testRemoveWWW() {
s = "http://www.example.com/foo.html";
t = "http://example.com/foo.html";
assertEquals(t, n(s).removeWWW().toString());
s = "http://wwwexample.com/foo.html";
t = "http://wwwexample.com/foo.html";
assertEquals(t, n(s).removeWWW().toS... |
public static <E> E findStaticFieldValue(Class clazz, String fieldName) {
try {
Field field = clazz.getField(fieldName);
return (E) field.get(null);
} catch (Exception ignore) {
return null;
}
} | @Test
public void test_whenClassExist_butFieldDoesNot() {
Integer value = findStaticFieldValue(ClassWithStaticField.class, "nonexisting");
assertNull(value);
} |
public static IntArrayList constant(int size, int value) {
IntArrayList result = new IntArrayList(size);
Arrays.fill(result.buffer, value);
result.elementsCount = size;
return result;
} | @Test
public void testConstant() {
IntArrayList list = ArrayUtil.constant(10, 3);
assertEquals(10, list.size());
assertEquals(3, list.get(5));
assertEquals(3, list.get(9));
assertEquals(10, list.buffer.length);
} |
public Optional<ProjectAlmSettingDto> findProjectBindingByUuid(String uuid) {
try (DbSession session = dbClient.openSession(false)) {
return dbClient.projectAlmSettingDao().selectByUuid(session, uuid);
}
} | @Test
void findProjectBindingByUuid_whenNoResult_returnsOptionalEmpty() {
when(dbClient.projectAlmSettingDao().selectByUuid(dbSession, UUID)).thenReturn(Optional.empty());
assertThat(underTest.findProjectBindingByUuid(UUID)).isEmpty();
} |
@Override
public GlobalRollbackRequestProto convert2Proto(GlobalRollbackRequest globalRollbackRequest) {
final short typeCode = globalRollbackRequest.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNumber(... | @Test
public void convert2Proto() {
GlobalRollbackRequest globalRollbackRequest = new GlobalRollbackRequest();
globalRollbackRequest.setExtraData("extraData");
globalRollbackRequest.setXid("xid");
GlobalRollbackRequestConvertor convertor = new GlobalRollbackRequestConvertor();
... |
public static <T> Stream<T> stream(Enumeration<T> e) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(
new Iterator<T>() {
public T next() {
return e.nextElement();
}... | @Test
public void test_stream_from_enumeration() {
Enumeration<Integer> someEnumeration = Collections.enumeration(Arrays.asList(1, 2, 3));
assertThat(EnumerationUtil.stream(someEnumeration).collect(Collectors.toList())).containsOnlyOnce(1, 2, 3);
} |
public AclInfo getAcl(String addr, String subject, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
GetAclRequestHeader requestHeader = new GetAclRequestHeader(subject);
RemotingCommand request = RemotingComma... | @Test
public void assertGetAcl() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
setResponseBody(createAclInfo());
AclInfo actual = mqClientAPI.getAcl(defaultBrokerAddr, "", defaultTimeout);
assertNotNull(actual);
assertEquals("subject", ... |
public static int validateValidHeaderValue(CharSequence value) {
int length = value.length();
if (length == 0) {
return -1;
}
if (value instanceof AsciiString) {
return verifyValidHeaderValueAsciiString((AsciiString) value);
}
return verifyValidHea... | @Test
void headerValuesCannotEndWithNewlinesCharSequence() {
assertEquals(1, validateValidHeaderValue("a\n"));
assertEquals(1, validateValidHeaderValue("a\r"));
} |
@Override
@MethodNotAvailable
public boolean putIfAbsent(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testPutIfAbsent() {
adapter.putIfAbsent(23, "value");
} |
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
if (dst instanceof HeapChannelBuffer) {
getBytes(index, ((HeapChannelBuffer) dst).array, dstIndex, length);
} else {
dst.setBytes(dstIndex, array, index, length);
}
} | @Test
void testEqualsAndHashcode() {
HeapChannelBuffer b1 = new HeapChannelBuffer("hello-world".getBytes());
HeapChannelBuffer b2 = new HeapChannelBuffer("hello-world".getBytes());
MatcherAssert.assertThat(b1.equals(b2), is(true));
MatcherAssert.assertThat(b1.hashCode(), is(b2.hashC... |
public static List<File> recursiveListLocalDir(File dir) {
File[] files = dir.listFiles();
// File#listFiles can return null when the path is invalid
if (files == null) {
return Collections.emptyList();
}
List<File> result = new ArrayList<>(files.length);
for (File f : files) {
if (f... | @Test
public void recursiveList() throws Exception {
File tmpDirFile = Files.createTempDir();
tmpDirFile.deleteOnExit();
Set<File> allFiles = new HashSet<>();
// Create 10 files at randomly deep level in the directory
for (int i = 0; i < 10; i++) {
createFileOrDir(tmpDirFile, i, new Random(... |
public Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> newChannelInitializers() {
Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> channelInitializers = new HashMap<>();
Set<InetSocketAddress> addresses = new HashSet<>();
for (Map.Entry<String, Proxy... | @Test
public void testNewChannelInitializersSuccess() {
ChannelInitializer<SocketChannel> i1 = mock(ChannelInitializer.class);
ChannelInitializer<SocketChannel> i2 = mock(ChannelInitializer.class);
Map<InetSocketAddress, ChannelInitializer<SocketChannel>> p1Initializers = new HashMap<>();
... |
@Override
public void upload(UploadTask uploadTask) throws IOException {
Throwable error = getErrorSafe();
if (error != null) {
LOG.debug("don't persist {} changesets, already failed", uploadTask.changeSets.size());
uploadTask.fail(error);
return;
}
... | @Test
void testErrorHandling() throws Exception {
TestingStateChangeUploader probe = new TestingStateChangeUploader();
DirectScheduledExecutorService scheduler = new DirectScheduledExecutorService();
ChangelogStorageMetricGroup metrics = createUnregisteredChangelogStorageMetricGroup();
... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("warnedClasses", serializeCheckUtils.getWarnedClasses());
return JsonUtils.toJson(result);
} els... | @Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class);
SerializeWarnedClasses serializeWarnedClasses = new SerializeWarnedClasses(frameworkModel);
CommandCont... |
public boolean canRunAppAM(Resource amResource) {
if (Math.abs(maxAMShare - -1.0f) < 0.0001) {
return true;
}
Resource maxAMResource = computeMaxAMResource();
getMetrics().setMaxAMShare(maxAMResource);
Resource ifRunAMResource = Resources.add(amResourceUsage, amResource);
return Resources... | @Test
public void testCanRunAppAMReturnsFalse() {
conf.set(YarnConfiguration.RESOURCE_TYPES, CUSTOM_RESOURCE);
ResourceUtils.resetResourceTypes(conf);
resourceManager = new MockRM(conf);
resourceManager.start();
scheduler = (FairScheduler) resourceManager.getResourceScheduler();
Resource max... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateSingleStatWhenNullValues() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
ColumnStatisticsData data1 = new ColStatsBuilder<>(long.class).numNulls(1).numDVs(2).build();
List<ColStatsObjWithSourceInfo> statsList =
Collections.sing... |
public DoubleArrayAsIterable usingExactEquality() {
return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_containsAtLeast_primitiveDoubleArray_failure() {
expectFailureWhenTestingThat(array(1.1, 2.2, 3.3))
.usingExactEquality()
.containsAtLeast(array(2.2, 99.99));
assertFailureKeys(
"value of",
"missing (1)",
"---",
"expected to ... |
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
ConfigServer[] configServers = getConfigServers();
int[] zookeeperIds = getConfigServerZookeeperIds();
if (configServers.length != zookeeperIds.length) {
throw new IllegalArgumentException(String.format("Nu... | @Test
void zookeeperConfig_negative_zk_id() {
assertThrows(IllegalArgumentException.class, () -> {
TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(1, 2, -1));
getConfig(ZookeeperServerConfig.class, testOptions);
});
} |
public static Ip6Address valueOf(byte[] value) {
return new Ip6Address(value);
} | @Test
public void testAddressToOctetsIPv6() {
Ip6Address ipAddress;
byte[] value;
value = new byte[] {0x11, 0x11, 0x22, 0x22,
0x33, 0x33, 0x44, 0x44,
0x55, 0x55, 0x66, 0x66,
0x77, 0x77,
... |
@Override
public CompletableFuture<ConsumerGroupHeartbeatResponseData> consumerGroupHeartbeat(
RequestContext context,
ConsumerGroupHeartbeatRequestData request
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(new ConsumerGroupHeartbeatResponseData()
... | @Test
public void testConsumerGroupHeartbeat() throws ExecutionException, InterruptedException, TimeoutException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
... |
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
FutureCallback<Response<T>> callback = new FutureCallback<>();
sendRequest(request, requestContext, callback);
return new ResponseFutureImpl<>(callback);
} | @SuppressWarnings("deprecation")
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
public void testRestLiResponseExceptionCallback(SendRequestOption option,
TimeoutOption timeoutOption,
... |
@Override
public void setAttemptCount(JobVertexID jobVertexId, int subtaskIndex, int attemptNumber) {
Preconditions.checkArgument(subtaskIndex >= 0);
Preconditions.checkArgument(attemptNumber >= 0);
final List<Integer> attemptCounts =
vertexSubtaskToAttemptCounts.computeIfAb... | @Test
void testSetAttemptCount() {
final DefaultVertexAttemptNumberStore vertexAttemptNumberStore =
new DefaultVertexAttemptNumberStore();
final JobVertexID jobVertexId = new JobVertexID();
final int subtaskIndex = 4;
final int attemptCount = 2;
vertexAttemp... |
public Integer doCall() throws Exception {
String projectName = getProjectName();
String workingDir = RUN_PLATFORM_DIR + "/" + projectName;
printer().println("Exporting application ...");
// Cache export output in String for later usage in case of error
Printer runPrinter = pr... | @Test
public void shouldGenerateKubernetesManifest() throws Exception {
KubernetesRun command = createCommand();
command.filePaths = new String[] { "classpath:route.yaml" };
int exit = command.doCall();
Assertions.assertEquals(0, exit);
List<HasMetadata> resources = kuberne... |
public TimestampOffset entry(int n) {
return maybeLock(lock, () -> {
if (n >= entries())
throw new IllegalArgumentException("Attempt to fetch the " + n + "th entry from time index "
+ file().getAbsolutePath() + " which has size " + entries());
return p... | @Test
public void testEntry() {
appendEntries(maxEntries - 1);
assertEquals(new TimestampOffset(10L, 55L), idx.entry(0));
assertEquals(new TimestampOffset(20L, 65L), idx.entry(1));
assertEquals(new TimestampOffset(30L, 75L), idx.entry(2));
assertEquals(new TimestampOffset(40L... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeRoundingOdd() {
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.35)), BigDecimal.valueOf(10));
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.35), BigDecimal.ONE),
BigDecimal.val... |
public static <T> Predicate<T> instantiatePredicateClass(Class<? extends Predicate<T>> clazz) {
try {
Constructor<? extends Predicate<T>> c = clazz.getConstructor();
if (c != null) {
return c.newInstance();
} else {
throw new InstantiationExcep... | @Test
public void shouldInstantiatePredicateClass() {
assertThat(ClassUtils.instantiatePredicateClass(PublicPredicate.class)).isNotNull();
} |
public PackageDefinition findPackageDefinitionWith(String packageId) {
for (PackageRepository packageRepository : this) {
for (PackageDefinition packageDefinition : packageRepository.getPackages()) {
if (packageDefinition.getId().equals(packageId)) {
return packag... | @Test
void shouldGetPackageDefinitionForGivenPackageId() throws Exception {
PackageRepository repo1 = PackageRepositoryMother.create("repo-id1", "repo1", "plugin-id", "1.0", null);
PackageDefinition packageDefinitionOne = PackageDefinitionMother.create("pid1", repo1);
PackageDefinition packa... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldRequestStatuses() {
// Given:
CommandStatuses commandStatuses = new CommandStatuses(new HashMap<>());
server.setResponseObject(commandStatuses);
// When:
KsqlTarget target = ksqlClient.target(serverUri);
RestResponse<CommandStatuses> response = target.getStatuses();
... |
@Override
public TransformResultMetadata getResultMetadata() {
return new TransformResultMetadata(_lookupColumnFieldSpec.getDataType(),
_lookupColumnFieldSpec.isSingleValueField(), false);
} | @Test
public void resultDataTypeTest()
throws Exception {
HashMap<String, FieldSpec.DataType> testCases = new HashMap<String, FieldSpec.DataType>() {{
put("teamName", FieldSpec.DataType.STRING);
put("teamInteger", FieldSpec.DataType.INT);
put("teamFloat", FieldSpec.DataType.FLOAT);
p... |
@Override
public Region updateRegion(RegionId regionId, String name, Region.Type type,
List<Set<NodeId>> masterNodeIds) {
checkNotNull(regionId, REGION_ID_NULL);
checkNotNull(name, NAME_NULL);
checkNotNull(type, REGION_TYPE_NULL);
return store.updateRe... | @Test(expected = ItemNotFoundException.class)
public void missingUpdate() {
service.updateRegion(RID1, "R1", METRO, MASTERS);
} |
@Bean("shiroSecurityManager")
public DefaultWebSecurityManager securityManager(@Lazy @Qualifier("shiroRealm") final AuthorizingRealm shiroRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm);
return securityManager;
} | @Test
public void testSecurityManager() {
AuthorizingRealm realm = mock(AuthorizingRealm.class);
DefaultWebSecurityManager securityManager = shiroConfiguration.securityManager(realm);
Object[] realms = securityManager.getRealms().toArray();
assertEquals(1, realms.length);
ass... |
@Override
public Optional<QueryId> chooseQueryToKill(List<QueryMemoryInfo> runningQueries, List<MemoryInfo> nodes)
{
Map<QueryId, Long> memoryReservationOnBlockedNodes = new HashMap<>();
for (MemoryInfo node : nodes) {
MemoryPoolInfo generalPool = node.getPools().get(GENERAL_POOL);
... | @Test
public void testGeneralPoolNotBlocked()
{
int reservePool = 10;
int generalPool = 12;
Map<String, Map<String, Long>> queries = ImmutableMap.<String, Map<String, Long>>builder()
.put("q_1", ImmutableMap.of("n1", 0L, "n2", 6L, "n3", 0L, "n4", 0L, "n5", 0L))
... |
public static Result<Void> success() {
return new Result<Void>()
.setCode(Result.SUCCESS_CODE);
} | @Test
public void testSuccess() {
Object o = new Object();
Assert.isTrue(o.equals(Results.success(o).getData()));
Assert.isTrue(Result.SUCCESS_CODE.equals(Results.success().getCode()));
} |
@VisibleForTesting
void notifyTokenExpiration() {
try {
// Avoid notification multiple times in case of data center edition
if (!lockManager.tryLock(LOCK_NAME, LOCK_DURATION)) {
return;
}
notificationSender.sendNotifications();
} catch (RuntimeException e) {
LOG.error("Er... | @Test
public void log_error_if_exception_in_sending_notification() {
when(lockManager.tryLock(anyString(), anyInt())).thenReturn(true);
doThrow(new IllegalStateException()).when(notificationSender).sendNotifications();
underTest.notifyTokenExpiration();
assertThat(logTester.getLogs(LoggerLevel.ERROR))... |
@Override
public void removeMember(String memberId) {
ConsumerGroupMember oldMember = members.remove(memberId);
maybeUpdateSubscribedTopicNamesAndGroupSubscriptionType(oldMember, null);
maybeUpdateServerAssignors(oldMember, null);
maybeRemovePartitionEpoch(oldMember);
removeS... | @Test
public void testRemoveMember() {
ConsumerGroup consumerGroup = createConsumerGroup("foo");
ConsumerGroupMember member = consumerGroup.getOrMaybeCreateMember("member", true);
consumerGroup.updateMember(member);
assertTrue(consumerGroup.hasMember("member"));
consumerGro... |
static Builder builder() {
return new AutoValue_PubsubRowToMessage.Builder();
} | @Test
public void testSetTargetTimestampAttributeName() {
Instant mockTimestamp = Instant.now();
String mockTimestampString = mockTimestamp.toString();
byte[] bytes = new byte[] {1, 2, 3, 4};
Field payloadBytesField = Field.of(DEFAULT_PAYLOAD_KEY_NAME, FieldType.BYTES);
Schema withPayloadBytesSc... |
public Object extract(Object target, String attributeName, Object metadata) {
return extract(target, attributeName, metadata, true);
} | @Test
public void when_extractExtractor_then_correctValue() {
// GIVEN
AttributeConfig config
= new AttributeConfig("gimmePower", "com.hazelcast.query.impl.getters.ExtractorsTest$PowerExtractor");
Extractors extractors = createExtractors(config);
// WHEN
Obje... |
@Override
public WatchKey register(final Watchable folder,
final WatchEvent.Kind<?>[] events,
final WatchEvent.Modifier... modifiers)
throws IOException {
if(log.isInfoEnabled()) {
log.info(String.format("Register file %s for even... | @Test
public void testRegister() throws Exception {
final RegisterWatchService fs = new FSEventWatchService();
final Watchable folder = Paths.get(
File.createTempFile(UUID.randomUUID().toString(), "t").getParent());
final WatchKey key = fs.register(folder, new WatchEvent.Kind[]{E... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.