focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public boolean appliesTo(String pipelineName, String stageName) {
boolean pipelineMatches = this.pipelineName.equals(pipelineName) ||
this.pipelineName.equals(GoConstants.ANY_PIPELINE);
boolean stageMatches = this.stageName.equals(stageName) ||
this.stageName.equals(GoConstants.ANY_STAGE);
return pipelineMatches && stageMatches;
} | @Test
void anyPipelineAndAnyStageShouldAlwaysApply() {
NotificationFilter filter = new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Breaks, false);
assertThat(filter.appliesTo("cruise2", "dev")).isTrue();
} |
@Override
public final void filter(DiscFilterRequest request, ResponseHandler handler) {
filter(request)
.ifPresent(errorResponse -> writeResponse(request, errorResponse, handler));
} | @Test
void filter_renders_errors_as_json() throws IOException {
int statusCode = 403;
String message = "Forbidden";
DiscFilterRequest request = FilterTestUtils.newRequestBuilder().build();
SimpleSecurityRequestFilter filter =
new SimpleSecurityRequestFilter(new JsonSecurityRequestFilterBase.ErrorResponse(statusCode, message));
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
filter.filter(request, responseHandler);
Response response = responseHandler.getResponse();
assertNotNull(response);
assertEquals(statusCode, response.getStatus());
JsonNode jsonNode = Jackson.mapper().readTree(responseHandler.readAll());
assertEquals(message, jsonNode.get("message").asText());
assertEquals(statusCode, jsonNode.get("code").asInt());
} |
@Override
public String getSecurityLevel() {
return securityLevel;
} | @Test
public void testGetSecurityLevel() {
assertEquals(securityLevel, defaultSnmpv3Device.getSecurityLevel());
} |
public void run() {
runner = newJsonRunnerWithSetting(
globalSettings.stream()
.filter(byEnv(this.env))
.map(toRunnerSetting())
.collect(toList()), startArgs);
runner.run();
} | @Test
public void should_not_run_without_env() throws IOException {
stream = getResourceAsStream("settings/env-settings.json");
runner = new SettingRunner(stream, createStartArgs(12306, "bar"));
runner.run();
assertThrows(HttpResponseException.class, () -> {
helper.get(remoteUrl("/foo/foo"));
});
} |
@Override
public int getOrder() {
return PluginEnum.CONTEXT_PATH.getCode();
} | @Test
public void getOrderTest() {
assertEquals(PluginEnum.CONTEXT_PATH.getCode(), contextPathPlugin.getOrder());
} |
@VisibleForTesting
Collection<PluginClassLoaderDef> defineClassloaders(Map<String, ExplodedPlugin> pluginsByKey) {
Map<String, PluginClassLoaderDef> classloadersByBasePlugin = new HashMap<>();
for (ExplodedPlugin plugin : pluginsByKey.values()) {
PluginInfo info = plugin.getPluginInfo();
String baseKey = basePluginKey(info, pluginsByKey);
PluginClassLoaderDef def = classloadersByBasePlugin.get(baseKey);
if (def == null) {
def = new PluginClassLoaderDef(baseKey);
classloadersByBasePlugin.put(baseKey, def);
}
def.addFiles(singleton(plugin.getMain()));
def.addFiles(plugin.getLibs());
def.addMainClass(info.getKey(), info.getMainClass());
for (String defaultSharedResource : DEFAULT_SHARED_RESOURCES) {
def.getExportMask().include(String.format("%s/%s/api/", defaultSharedResource, info.getKey()));
}
// The plugins that extend other plugins can only add some files to classloader.
// They can't change metadata like ordering strategy or compatibility mode.
if (Strings.isNullOrEmpty(info.getBasePlugin())) {
if (info.isUseChildFirstClassLoader()) {
LoggerFactory.getLogger(getClass()).warn("Plugin {} [{}] uses a child first classloader which is deprecated", info.getName(),
info.getKey());
}
def.setSelfFirstStrategy(info.isUseChildFirstClassLoader());
Version minSonarPluginApiVersion = info.getMinimalSonarPluginApiVersion();
boolean compatibilityMode = minSonarPluginApiVersion != null && minSonarPluginApiVersion.compareToIgnoreQualifier(COMPATIBILITY_MODE_MAX_VERSION) < 0;
if (compatibilityMode) {
LoggerFactory.getLogger(getClass()).warn("API compatibility mode is no longer supported. In case of error, plugin {} [{}] " +
"should package its dependencies.",
info.getName(), info.getKey());
}
}
}
return classloadersByBasePlugin.values();
} | @Test
public void log_warning_if_plugin_is_built_with_api_5_2_or_lower() throws Exception {
File jarFile = temp.newFile();
PluginInfo info = new PluginInfo("foo")
.setJarFile(jarFile)
.setMainClass("org.foo.FooPlugin")
.setMinimalSonarPluginApiVersion(Version.create("4.5.2"));
Collection<PluginClassLoaderDef> defs = underTest.defineClassloaders(
ImmutableMap.of("foo", createExplodedPlugin(info)));
assertThat(defs).extracting(PluginClassLoaderDef::getBasePluginKey).containsExactly("foo");
List<String> warnings = logTester.logs(Level.WARN);
assertThat(warnings).contains("API compatibility mode is no longer supported. In case of error, plugin foo [foo] should package its dependencies.");
} |
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
this.config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesNodeConfiguration.class);
this.keys = config.getKeys();
} | @Test
void givenMsg_whenOnMsg_thenVerifyOutput_SendAttributesDeletedNotification_NoNotifyDevice() throws Exception {
config.setSendAttributesDeletedNotification(true);
nodeConfiguration = new TbNodeConfiguration(JacksonUtil.valueToTree(config));
node.init(ctx, nodeConfiguration);
onMsg_thenVerifyOutput(true, false, false);
} |
void createIfMissing(String key, SelTypes type) { // won't create array
if (symtab.containsKey(key)) {
return;
} else if (inputTab != null && inputTab.containsKey(key)) {
Object inputVal = inputTab.get(key);
SelType newVal = box(inputVal);
symtab.put(key, newVal);
} else {
symtab.put(key, type.newSelTypeObj());
}
} | @Test
public void createIfMissing() {
state.resetWithInput(params, null);
state.createIfMissing("foo", SelTypes.STRING);
SelType res = state.get("foo");
assertEquals("STRING: bar", res.type() + ": " + res);
state.createIfMissing("fuu", SelTypes.STRING);
res = state.get("fuu");
assertEquals("STRING: null", res.type() + ": " + res);
} |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void testWithLettersComingFromLog4j() {
// Letters: p = level and c = logger
pl.setPattern("%d %p [%t] %c{30} - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
// message
String regex = ClassicTestConstants.ISO_REGEX + " INFO " + MAIN_REGEX
+ " c.q.l.c.pattern.ConverterTest - Some message\\s*";
assertTrue(val.matches(regex));
} |
public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) {
if (is.markSupported()) {
return is;
}
return new InputStream() {
byte[] mMarkBuffer;
boolean mInMarked = false;
boolean mInReset = false;
boolean mDry = false;
private int mPosition = 0;
private int mCount = 0;
@Override
public int read() throws IOException {
if (!mInMarked) {
return is.read();
} else {
if (mPosition < mCount) {
byte b = mMarkBuffer[mPosition++];
return b & 0xFF;
}
if (!mInReset) {
if (mDry) {
return -1;
}
if (null == mMarkBuffer) {
mMarkBuffer = new byte[markBufferSize];
}
if (mPosition >= markBufferSize) {
throw new IOException("Mark buffer is full!");
}
int read = is.read();
if (-1 == read) {
mDry = true;
return -1;
}
mMarkBuffer[mPosition++] = (byte) read;
mCount++;
return read;
} else {
// mark buffer is used, exit mark status!
mInMarked = false;
mInReset = false;
mPosition = 0;
mCount = 0;
return is.read();
}
}
}
/**
* NOTE: the <code>readlimit</code> argument for this class
* has no meaning.
*/
@Override
public synchronized void mark(int readlimit) {
mInMarked = true;
mInReset = false;
// mark buffer is not empty
int count = mCount - mPosition;
if (count > 0) {
System.arraycopy(mMarkBuffer, mPosition, mMarkBuffer, 0, count);
mCount = count;
mPosition = 0;
}
}
@Override
public synchronized void reset() throws IOException {
if (!mInMarked) {
throw new IOException("should mark before reset!");
}
mInReset = true;
mPosition = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int available() throws IOException {
int available = is.available();
if (mInMarked && mInReset) {
available += mCount - mPosition;
}
return available;
}
@Override
public void close() throws IOException {
is.close();
}
};
} | @Test
void testMarkSupportedInputStream() throws Exception {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
assertEquals(10, is.available());
is = new PushbackInputStream(is);
assertEquals(10, is.available());
assertFalse(is.markSupported());
is = StreamUtils.markSupportedInputStream(is);
assertEquals(10, is.available());
is.mark(0);
assertEquals((int) '0', is.read());
assertEquals((int) '1', is.read());
is.reset();
assertEquals((int) '0', is.read());
assertEquals((int) '1', is.read());
assertEquals((int) '2', is.read());
is.mark(0);
assertEquals((int) '3', is.read());
assertEquals((int) '4', is.read());
assertEquals((int) '5', is.read());
is.reset();
assertEquals((int) '3', is.read());
assertEquals((int) '4', is.read());
is.mark(0);
assertEquals((int) '5', is.read());
assertEquals((int) '6', is.read());
is.reset();
assertEquals((int) '5', is.read());
assertEquals((int) '6', is.read());
assertEquals((int) '7', is.read());
assertEquals((int) '8', is.read());
assertEquals((int) '9', is.read());
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.mark(0);
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.reset();
assertEquals(-1, is.read());
assertEquals(-1, is.read());
is.close();
} |
public int go(String inputFileName, String outputFileName, String processor,
Flags flags, OfflineEditsVisitor visitor)
{
if (flags.getPrintToScreen()) {
System.out.println("input [" + inputFileName + "]");
System.out.println("output [" + outputFileName + "]");
}
boolean xmlInput = StringUtils.toLowerCase(inputFileName).endsWith(".xml");
if (xmlInput && StringUtils.equalsIgnoreCase("xml", processor)) {
System.err.println("XML format input file is not allowed"
+ " to be processed by XML processor.");
return -1;
} else if(!xmlInput && StringUtils.equalsIgnoreCase("binary", processor)) {
System.err.println("Binary format input file is not allowed"
+ " to be processed by Binary processor.");
return -1;
}
try {
if (visitor == null) {
visitor = OfflineEditsVisitorFactory.getEditsVisitor(
outputFileName, processor, flags.getPrintToScreen());
}
OfflineEditsLoader loader = OfflineEditsLoaderFactory.
createLoader(visitor, inputFileName, xmlInput, flags);
loader.loadEdits();
} catch(Exception e) {
System.err.println("Encountered exception. Exiting: " + e.getMessage());
e.printStackTrace(System.err);
return -1;
}
return 0;
} | @Test
public void testStatisticsStrWithNullOpCodeCount() throws IOException {
String editFilename = nnHelper.generateEdits();
String outFilename = editFilename + ".stats";
FileOutputStream fout = new FileOutputStream(outFilename);
StatisticsEditsVisitor visitor = new StatisticsEditsVisitor(fout);
OfflineEditsViewer oev = new OfflineEditsViewer();
String statisticsStr = null;
if (oev.go(editFilename, outFilename, "stats", new Flags(), visitor) == 0) {
statisticsStr = visitor.getStatisticsString();
}
Assert.assertNotNull(statisticsStr);
String str;
Long count;
Map<FSEditLogOpCodes, Long> opCodeCount = visitor.getStatistics();
for (FSEditLogOpCodes opCode : FSEditLogOpCodes.values()) {
count = opCodeCount.get(opCode);
// Verify the str when the opCode's count is null
if (count == null) {
str =
String.format(" %-30.30s (%3d): %d%n", opCode.toString(),
opCode.getOpCode(), Long.valueOf(0L));
assertTrue(statisticsStr.contains(str));
}
}
} |
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 from the environment
if (credentials.isPresent() && credentials.get() instanceof ServiceAccountCredentials) {
return ((ServiceAccountCredentials) credentials.get()).getProjectId();
}
return BigQueryOptions.getDefaultProjectId();
} | @Test
public void testConfigurationOnly()
throws Exception
{
String projectId = BigQueryConnectorModule.calculateBillingProjectId(Optional.of("pid"), Optional.empty());
assertThat(projectId).isEqualTo("pid");
} |
public static boolean isBoxedPrimitive(@Nullable String desc) {
return PRIMITIVE_BOXES.contains(desc);
} | @Test
void testIsPrimitiveBox() {
for (Type primitive : Types.PRIMITIVES) {
assertFalse(Types.isBoxedPrimitive(primitive.getDescriptor()), "Failed on: " + primitive);
}
for (String primitiveBox : Types.PRIMITIVE_BOXES) {
assertTrue(Types.isBoxedPrimitive(primitiveBox), "Failed on: " + primitiveBox);
}
assertFalse(Types.isBoxedPrimitive(null));
} |
public MijnDigidSessionStatus sessionStatus(String mijnDigiDSessionId) {
Optional<MijnDigidSession> optionalSession = mijnDigiDSessionRepository.findById(mijnDigiDSessionId);
if( optionalSession.isEmpty()) {
return MijnDigidSessionStatus.INVALID;
}
MijnDigidSession session = optionalSession.get();
if( session.isAuthenticated() ) {
return MijnDigidSessionStatus.VALID;
}
return MijnDigidSessionStatus.INVALID;
} | @Test
void testStatusUnauthenticatedExistingSession() {
MijnDigidSession session = new MijnDigidSession(1L);
session.setAuthenticated(false);
when(mijnDigiDSessionRepository.findById(eq(session.getId()))).thenReturn(Optional.of(session));
MijnDigidSessionStatus status = mijnDigiDSessionService.sessionStatus(session.getId());
verify(mijnDigiDSessionRepository, times(1)).findById(eq(session.getId()));
assertEquals(status, MijnDigidSessionStatus.INVALID);
} |
@Override
public String toString() {
return String.format("%s.orFinally(%s)", subTriggers.get(ACTUAL), subTriggers.get(UNTIL));
} | @Test
public void testToString() {
TriggerStateMachine trigger =
StubTriggerStateMachine.named("t1").orFinally(StubTriggerStateMachine.named("t2"));
assertEquals("t1.orFinally(t2)", trigger.toString());
} |
public Set<Long> calculateUsers(DelegateExecution execution, int level) {
Assert.isTrue(level > 0, "level 必须大于 0");
// 获得发起人
ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId());
Long startUserId = NumberUtils.parseLong(processInstance.getStartUserId());
// 获得对应 leve 的部门
DeptRespDTO dept = null;
for (int i = 0; i < level; i++) {
// 获得 level 对应的部门
if (dept == null) {
dept = getStartUserDept(startUserId);
if (dept == null) { // 找不到发起人的部门,所以无法使用该规则
return emptySet();
}
} else {
DeptRespDTO parentDept = deptApi.getDept(dept.getParentId());
if (parentDept == null) { // 找不到父级部门,所以只好结束寻找。原因是:例如说,级别比较高的人,所在部门层级比较少
break;
}
dept = parentDept;
}
}
return dept.getLeaderUserId() != null ? asSet(dept.getLeaderUserId()) : emptySet();
} | @Test
public void testCalculateUsers_existParentDept() {
// 准备参数
DelegateExecution execution = mockDelegateExecution(1L);
// mock 方法(startUser)
AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L));
when(adminUserApi.getUser(eq(1L))).thenReturn(startUser);
DeptRespDTO startUserDept = randomPojo(DeptRespDTO.class, o -> o.setId(10L).setParentId(100L)
.setLeaderUserId(20L));
when(deptApi.getDept(eq(10L))).thenReturn(startUserDept);
// mock 方法(父 dept)
DeptRespDTO parentDept = randomPojo(DeptRespDTO.class, o -> o.setId(100L).setParentId(1000L)
.setLeaderUserId(200L));
when(deptApi.getDept(eq(100L))).thenReturn(parentDept);
// 调用
Set<Long> result = expression.calculateUsers(execution, 2);
// 断言
assertEquals(asSet(200L), result);
} |
public String sprites() {
return get(SPRITES, null);
} | @Test(expected = InvalidFieldException.class)
public void cantSetSpritesIfGeoIsSet() {
cfg = cfgFromJson(tmpNode(GEOMAP));
cfg.sprites("sprites-name");
} |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchingFunctionException(arguments);
}
// if none were found (candidate isn't present) try again with implicit casting
candidate = findMatchingCandidate(arguments, true);
if (candidate.isPresent()) {
return candidate.get();
}
throw createNoMatchingFunctionException(arguments);
} | @Test
public void shouldChooseSpecificOverOnlyVarArgsReversedInsertionOrder() {
// Given:
givenFunctions(
function(OTHER, 0, STRING_VARARGS),
function(EXPECTED, -1, STRING, STRING, STRING, STRING)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(
SqlArgument.of(SqlTypes.STRING), SqlArgument.of(SqlTypes.STRING),
SqlArgument.of(SqlTypes.STRING), SqlArgument.of(SqlTypes.STRING)
));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
} |
public static <F extends Future<Void>> Mono<Void> deferFuture(Supplier<F> deferredFuture) {
return new DeferredFutureMono<>(deferredFuture);
} | @Test
void raceTestDeferredFutureMonoWithSuccess() {
for (int i = 0; i < 1000; i++) {
final TestSubscriber subscriber = new TestSubscriber();
final ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE;
final Promise<Void> promise = eventExecutor.newPromise();
final Supplier<Promise<Void>> promiseSupplier = () -> promise;
RaceTestUtils.race(() -> FutureMono.deferFuture(promiseSupplier)
.subscribe(subscriber),
subscriber::cancel,
() -> promise.setSuccess(null));
assertThat(resolveListeners(promise)).isNullOrEmpty();
assertThat(subscriber.operations).first()
.isEqualTo(TestSubscriber.Operation.ON_SUBSCRIBE);
}
} |
public static List<ProcessInformations> buildProcessInformations(InputStream in,
boolean windows, boolean macOrAix) {
final String charset;
if (windows) {
charset = "Cp1252";
} else {
charset = "UTF-8";
}
final Scanner sc = new Scanner(in, charset);
sc.useRadix(10);
sc.useLocale(Locale.US);
sc.nextLine();
if (windows) {
sc.nextLine();
sc.nextLine();
}
final List<ProcessInformations> processInfos = new ArrayList<>();
while (sc.hasNext()) {
final ProcessInformations processInfo = new ProcessInformations(sc, windows, macOrAix);
processInfos.add(processInfo);
}
return Collections.unmodifiableList(processInfos);
} | @Test
public void testExecuteAndReadPs() throws IOException {
final List<ProcessInformations> processes = ProcessInformations.buildProcessInformations();
assertNotNull("processes null", processes);
assertFalse("processes vide", processes.isEmpty());
final boolean windows = System.getProperty("os.name").toLowerCase(Locale.getDefault())
.contains("windows");
checkProcesses(processes, windows);
} |
@Override
public void close() throws Exception {
super.close();
collector = null;
triggerContext = null;
if (windowAggregator != null) {
windowAggregator.close();
}
} | @Test
public void testWindowCloseWithoutOpen() throws Exception {
if (!UTC_ZONE_ID.equals(shiftTimeZone)) {
return;
}
final int windowSize = 3;
LogicalType[] windowTypes = new LogicalType[] {new BigIntType()};
WindowOperator operator =
WindowOperatorBuilder.builder()
.withInputFields(inputFieldTypes)
.withShiftTimezone(shiftTimeZone)
.countWindow(windowSize)
.aggregate(
new GeneratedNamespaceTableAggsHandleFunction<>(
"MockClass", "", new Object[] {}),
accTypes,
aggResultTypes,
windowTypes)
.build();
// close() before open() called
operator.close();
} |
@Override
public boolean canPass(Node node, int acquireCount) {
return canPass(node, acquireCount, false);
} | @Test
public void testThrottlingControllerZeroThreshold() throws InterruptedException {
ThrottlingController paceController = new ThrottlingController(500, 0d);
Node node = mock(Node.class);
for (int i = 0; i < 2; i++) {
assertFalse(paceController.canPass(node, 1));
assertTrue(paceController.canPass(node, 0));
}
} |
@Override
@NonNull
public String getId() {
return ID;
} | @Test
public void shouldFailForBadCredentialIdOnCreate() throws IOException, UnirestException {
User user = login();
Map resp = createCredentials(user, MapsHelper.of("credentials",
new MapsHelper.Builder<String,Object>()
.put("privateKeySource", MapsHelper.of(
"privateKey", "abcabc1212",
"stapler-class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"))
.put("passphrase", "ssh2")
.put("scope", "USER")
.put("domain","blueocean-git-domain")
.put("description", "ssh2 desc")
.put("$class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey")
.put("username", "ssh2").build()
)
);
String credentialId = (String) resp.get("id");
Assert.assertNotNull(credentialId);
resp = new RequestBuilder(baseUrl)
.status(400)
.jwtToken(getJwtToken(j.jenkins,user.getId(), user.getId()))
.crumb( crumb )
.post("/organizations/" + getOrgName() + "/pipelines/")
.data(MapsHelper.of("name", "demo",
"$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
"scmConfig", MapsHelper.of("uri", "git@github.com:vivek/capability-annotation.git",
"credentialId", credentialId))).build(Map.class);
assertEquals(resp.get("code"), 400);
List<Map> errors = (List<Map>) resp.get("errors");
assertEquals(1, errors.size());
assertEquals(errors.get(0).toString(), "scmConfig.credentialId", errors.get(0).get("field"));
assertEquals(errors.get(0).toString(), "INVALID", errors.get(0).get("code"));
} |
@Override
public String named() {
return PluginEnum.WAF.getName();
} | @Test
public void testNamed() {
final String result = wafPluginUnderTest.named();
assertEquals(PluginEnum.WAF.getName(), result);
} |
public static KettleDatabaseBatchException createKettleDatabaseBatchException( String message, SQLException ex ) {
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException( message, ex );
if ( ex instanceof BatchUpdateException ) {
kdbe.setUpdateCounts( ( (BatchUpdateException) ex ).getUpdateCounts() );
} else {
// Null update count forces rollback of batch
kdbe.setUpdateCounts( null );
}
List<Exception> exceptions = new ArrayList<>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these
// drivers
// always return the same exception on getNextException() (and thus go
// into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( ( nextException != null ) && ( oldException != nextException ) ) {
exceptions.add( nextException );
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList( exceptions );
return kdbe;
} | @Test
public void testCreateKettleDatabaseBatchExceptionConstructsExceptionList() {
BatchUpdateException root = new BatchUpdateException();
SQLException next = new SQLException();
SQLException next2 = new SQLException();
root.setNextException( next );
next.setNextException( next2 );
List<Exception> exceptionList = Database.createKettleDatabaseBatchException( "", root ).getExceptionsList();
assertEquals( 2, exceptionList.size() );
assertEquals( next, exceptionList.get( 0 ) );
assertEquals( next2, exceptionList.get( 1 ) );
} |
@Override
public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final TimestampedSegment segment = super.getOrCreateSegmentIfLive(segmentId, context, streamTime);
cleanupExpiredSegments(streamTime);
return segment;
} | @Test
public void shouldCleanupSegmentsThatHaveExpired() {
final TimestampedSegment segment1 = segments.getOrCreateSegmentIfLive(0, context, -1L);
final TimestampedSegment segment2 = segments.getOrCreateSegmentIfLive(1, context, -1L);
final TimestampedSegment segment3 = segments.getOrCreateSegmentIfLive(7, context, SEGMENT_INTERVAL * 7L);
assertFalse(segment1.isOpen());
assertFalse(segment2.isOpen());
assertTrue(segment3.isOpen());
assertFalse(new File(context.stateDir(), "test/test.0").exists());
assertFalse(new File(context.stateDir(), "test/test." + SEGMENT_INTERVAL).exists());
assertTrue(new File(context.stateDir(), "test/test." + 7 * SEGMENT_INTERVAL).exists());
} |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
SQLStatement dalStatement = sqlStatementContext.getSqlStatement();
if (dalStatement instanceof MySQLShowDatabasesStatement) {
return new LocalDataMergedResult(Collections.singleton(new LocalDataQueryResultRow(databaseName)));
}
ShardingSphereSchema schema = getSchema(sqlStatementContext, database);
if (dalStatement instanceof MySQLShowTablesStatement) {
return new LogicTablesMergedResult(shardingRule, sqlStatementContext, schema, queryResults);
}
if (dalStatement instanceof MySQLShowTableStatusStatement) {
return new ShowTableStatusMergedResult(shardingRule, sqlStatementContext, schema, queryResults);
}
if (dalStatement instanceof MySQLShowIndexStatement) {
return new ShowIndexMergedResult(shardingRule, sqlStatementContext, schema, queryResults);
}
if (dalStatement instanceof MySQLShowCreateTableStatement) {
return new ShowCreateTableMergedResult(shardingRule, sqlStatementContext, schema, queryResults);
}
return new TransparentMergedResult(queryResults.get(0));
} | @Test
void assertMergeForShowIndexStatement() throws SQLException {
DALStatement dalStatement = new MySQLShowIndexStatement();
SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement);
ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(DefaultDatabase.LOGIC_NAME, mock(ShardingRule.class));
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getName()).thenReturn(DefaultDatabase.LOGIC_NAME);
assertThat(resultMerger.merge(queryResults, sqlStatementContext, database, mock(ConnectionContext.class)), instanceOf(ShowIndexMergedResult.class));
} |
public BrokerFileSystem getFileSystem(String path, Map<String, String> properties) {
WildcardURI pathUri = new WildcardURI(path);
String scheme = pathUri.getUri().getScheme();
if (Strings.isNullOrEmpty(scheme)) {
throw new BrokerException(TBrokerOperationStatusCode.INVALID_INPUT_FILE_PATH,
"invalid path. scheme is null");
}
BrokerFileSystem brokerFileSystem = null;
if (scheme.equals(HDFS_SCHEME) || scheme.equals(VIEWFS_SCHEME)) {
brokerFileSystem = getDistributedFileSystem(scheme, path, properties);
} else if (scheme.equals(S3A_SCHEME)) {
brokerFileSystem = getS3AFileSystem(path, properties);
} else if (scheme.equals(OSS_SCHEME)) {
brokerFileSystem = getOSSFileSystem(path, properties);
} else if (scheme.equals(COS_SCHEME)) {
brokerFileSystem = getCOSFileSystem(path, properties);
} else if (scheme.equals(KS3_SCHEME)) {
brokerFileSystem = getKS3FileSystem(path, properties);
} else if (scheme.equals(OBS_SCHEME)) {
brokerFileSystem = getOBSFileSystem(path, properties);
} else if (scheme.equals(TOS_SCHEME)) {
brokerFileSystem = getTOSFileSystem(path, properties);
} else {
// If all above match fails, then we will read the settings from hdfs-site.xml, core-site.xml of FE,
// and try to create a universal file system. The reason why we can do this is because hadoop/s3
// SDK is compatible with nearly all file/object storage system
brokerFileSystem = getUniversalFileSystem(path, properties);
}
return brokerFileSystem;
} | @Test
public void testGetFileSystemForMultipleNameServicesHA() throws IOException {
Map<String, String> properties = new HashMap<String, String>();
properties.put("username", "user");
properties.put("password", "passwd");
properties.put("fs.defaultFS", "hdfs://starrocks");
properties.put("dfs.nameservices", "DClusterNmg1,DClusterNmg2");
properties.put("dfs.ha.namenodes.DClusterNmg1", "nn11,nn12");
properties.put("dfs.namenode.rpc-address.DClusterNmg1.nn11", "127.0.0.1:8888");
properties.put("dfs.namenode.rpc-address.DClusterNmg1.nn12", "127.0.0.1:7777");
properties.put("dfs.client.failover.proxy.provider.DClusterNmg1",
"org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
properties.put("dfs.ha.namenodes.DClusterNmg2", "nn21,nn22");
properties.put("dfs.namenode.rpc-address.DClusterNmg2.nn21", "127.0.0.1:8020");
properties.put("dfs.namenode.rpc-address.DClusterNmg2.nn22", "127.0.0.1:8030");
properties.put("dfs.client.failover.proxy.provider.DClusterNmg2",
"org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
BrokerFileSystem fs = fileSystemManager.getFileSystem(testHdfsHost + "/user/user/dd_cdm/hive/dd_cdm/", properties);
assertNotNull(fs);
fs.getDFSFileSystem().close();
} |
@Override
public Object intercept(final Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
//Elegant access to object properties through MetaObject, here is access to the properties of statementHandler;
//MetaObject is an object provided by Mybatis for easy and elegant access to object properties,
// through which you can simplify the code, no need to try/catch various reflect exceptions,
// while it supports the operation of JavaBean, Collection, Map three types of object operations.
// MetaObject metaObject = MetaObject
// .forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
// new DefaultReflectorFactory());
//First intercept to RoutingStatementHandler, there is a StatementHandler type delegate variable,
// its implementation class is BaseStatementHandler, and then to the BaseStatementHandler member variable mappedStatement
// MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
// String id = mappedStatement.getId(); mapper method full path
// String sqlCommandType = mappedStatement.getSqlCommandType().toString(); sql method eg: insert update delete select
BoundSql boundSql = statementHandler.getBoundSql();
// get original sql file
// reflect modify sql file
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, boundSql.getSql().replace("`", "\"").toLowerCase());
return invocation.proceed();
} | @Test
public void interceptTest() {
final PostgreSQLPrepareInterceptor postgreSQLPrepareInterceptor = new PostgreSQLPrepareInterceptor();
final Invocation invocation = mock(Invocation.class);
final StatementHandler statementHandler = mock(StatementHandler.class);
when(invocation.getTarget()).thenReturn(statementHandler);
final BoundSql boundSql = mock(BoundSql.class);
when(statementHandler.getBoundSql()).thenReturn(boundSql);
when(boundSql.getSql()).thenReturn("select * from users where name = 1 limit 1");
Assertions.assertDoesNotThrow(() -> postgreSQLPrepareInterceptor.intercept(invocation));
} |
static Properties resolveProducerProperties(Map<String, String> options, Object keySchema, Object valueSchema) {
Properties properties = from(options);
withSerdeProducerProperties(true, options, keySchema, properties);
withSerdeProducerProperties(false, options, valueSchema, properties);
return properties;
} | @Test
public void when_producerProperties_preferredLocalParallelismPropertyIsDefined_then_itIsIgnored() {
assertThat(resolveProducerProperties(Map.of(OPTION_PREFERRED_LOCAL_PARALLELISM, "-1")))
.containsExactlyEntriesOf(Map.of(KEY_SERIALIZER, ByteArraySerializer.class.getCanonicalName()));
} |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testPartitionedMonths() throws Exception {
createPartitionedTable(spark, tableName, "months(ts)");
SparkScanBuilder builder = scanBuilder();
MonthsFunction.TimestampToMonthsFunction function =
new MonthsFunction.TimestampToMonthsFunction();
UserDefinedScalarFunc udf = toUDF(function, expressions(fieldRef("ts")));
Predicate predicate =
new Predicate(
">",
expressions(
udf, intLit(timestampStrToMonthOrdinal("2017-11-22T00:00:00.000000+00:00"))));
pushFilters(builder, predicate);
Batch scan = builder.build().toBatch();
assertThat(scan.planInputPartitions().length).isEqualTo(5);
// NOT GT
builder = scanBuilder();
predicate = new Not(predicate);
pushFilters(builder, predicate);
scan = builder.build().toBatch();
assertThat(scan.planInputPartitions().length).isEqualTo(5);
} |
public GrpcChannel acquireChannel(GrpcNetworkGroup networkGroup,
GrpcServerAddress serverAddress, AlluxioConfiguration conf, boolean alwaysEnableTLS) {
GrpcChannelKey channelKey = getChannelKey(networkGroup, serverAddress, conf);
CountingReference<ManagedChannel> channelRef =
mChannels.compute(channelKey, (key, ref) -> {
boolean shutdownExistingConnection = false;
int existingRefCount = 0;
if (ref != null) {
// Connection exists, wait for health check.
if (waitForConnectionReady(ref.get(), conf)) {
LOG.debug("Acquiring an existing connection. ConnectionKey: {}. Ref-count: {}", key,
ref.getRefCount());
return ref.reference();
} else {
// Health check failed.
shutdownExistingConnection = true;
}
}
// Existing connection should be shutdown.
if (shutdownExistingConnection) {
existingRefCount = ref.getRefCount();
LOG.debug("Shutting down an existing unhealthy connection. "
+ "ConnectionKey: {}. Ref-count: {}", key, existingRefCount);
// Shutdown the channel forcefully as it's already unhealthy.
shutdownManagedChannel(ref.get());
}
// Create a new managed channel.
LOG.debug("Creating a new managed channel. ConnectionKey: {}. Ref-count:{},"
+ " alwaysEnableTLS:{} config TLS:{}", key, existingRefCount, alwaysEnableTLS,
conf.getBoolean(alluxio.conf.PropertyKey.NETWORK_TLS_ENABLED));
ManagedChannel managedChannel = createManagedChannel(channelKey, conf, alwaysEnableTLS);
// Set map reference.
return new CountingReference<>(managedChannel, existingRefCount).reference();
});
return new GrpcChannel(channelKey, channelRef.get());
} | @Test
public void testDifferentKeys() throws Exception {
try (CloseableTestServer server1 = createServer();
CloseableTestServer server2 = createServer()) {
GrpcChannel conn1 = GrpcChannelPool.INSTANCE.acquireChannel(
GrpcNetworkGroup.RPC, server1.getConnectAddress(), sConf, false);
GrpcChannel conn2 = GrpcChannelPool.INSTANCE.acquireChannel(
GrpcNetworkGroup.RPC, server2.getConnectAddress(), sConf, false);
assertNotEquals(conn1, conn2);
}
} |
public StatMap<K> merge(K key, int value) {
if (key.getType() == Type.LONG) {
merge(key, (long) value);
return this;
}
int oldValue = getInt(key);
int newValue = key.merge(oldValue, value);
if (newValue == 0) {
_map.remove(key);
} else {
_map.put(key, newValue);
}
return this;
} | @Test(dataProvider = "allTypeStats", expectedExceptions = IllegalArgumentException.class)
public void dynamicTypeCheckWhenAddInt(MyStats stat) {
if (stat.getType() == StatMap.Type.INT) {
throw new SkipException("Skipping INT test");
}
if (stat.getType() == StatMap.Type.LONG) {
throw new SkipException("Skipping LONG test");
}
StatMap<MyStats> statMap = new StatMap<>(MyStats.class);
statMap.merge(stat, 1);
} |
public static Object deep(Object o) {
if (o == null) {
return null;
}
final Class<?> cls = o.getClass();
final Valuefier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return converter.convert(o);
}
return fallbackConvert(o, cls);
} | @Test
public void testRubyBignum() {
RubyBignum v = RubyBignum.newBignum(RubyUtil.RUBY, "-9223372036854776000");
Object result = Javafier.deep(v);
assertEquals(BigInteger.class, result.getClass());
assertEquals( "-9223372036854776000", result.toString());
} |
public CompletableFuture<Integer> getCount(final UUID identifier, final byte deviceId) {
final Timer.Sample sample = Timer.start();
return dynamoDbAsyncClient.query(QueryRequest.builder()
.tableName(tableName)
.consistentRead(false)
.keyConditionExpression("#uuid = :uuid AND begins_with (#sort, :sortprefix)")
.expressionAttributeNames(Map.of("#uuid", KEY_ACCOUNT_UUID, "#sort", KEY_DEVICE_ID_KEY_ID))
.expressionAttributeValues(Map.of(
":uuid", getPartitionKey(identifier),
":sortprefix", getSortKeyPrefix(deviceId)))
.projectionExpression(ATTR_REMAINING_KEYS)
.limit(1)
.build())
.thenApply(response -> {
if (response.count() > 0) {
final Map<String, AttributeValue> item = response.items().getFirst();
if (item.containsKey(ATTR_REMAINING_KEYS)) {
return Integer.parseInt(item.get(ATTR_REMAINING_KEYS).n());
} else {
// Some legacy keys sets may not have pre-counted keys; in that case, we'll tell the owners of those key
// sets that they have none remaining, prompting an upload of a fresh set that we'll pre-count. This has
// no effect on consumers of keys, which will still be able to take keys if any are actually present.
noKeyCountAvailableCounter.increment();
return 0;
}
} else {
return 0;
}
})
.whenComplete((keyCount, throwable) -> {
sample.stop(getKeyCountTimer);
if (throwable == null && keyCount != null) {
availableKeyCountDistributionSummary.record(keyCount);
}
});
} | @Test
void getCount() {
final SingleUsePreKeyStore<K> preKeyStore = getPreKeyStore();
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = 1;
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
final List<K> preKeys = generateRandomPreKeys();
preKeyStore.store(accountIdentifier, deviceId, preKeys).join();
assertEquals(KEY_COUNT, preKeyStore.getCount(accountIdentifier, deviceId).join());
for (int i = 0; i < KEY_COUNT; i++) {
preKeyStore.take(accountIdentifier, deviceId).join();
assertEquals(KEY_COUNT - (i + 1), preKeyStore.getCount(accountIdentifier, deviceId).join());
}
preKeyStore.store(accountIdentifier, deviceId, List.of(generatePreKey(KEY_COUNT + 1))).join();
clearKeyCountAttributes();
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
} |
public void fetchBytesValues(String column, int[] inDocIds, int length, byte[][] outValues) {
_columnValueReaderMap.get(column).readBytesValues(inDocIds, length, outValues);
} | @Test
public void testFetchBytesValues() {
testFetchBytesValues(BYTES_COLUMN);
testFetchBytesValues(NO_DICT_BYTES_COLUMN);
testFetchBytesValues(STRING_COLUMN);
testFetchBytesValues(NO_DICT_STRING_COLUMN);
} |
public static long betweenDay(Date beginDate, Date endDate, boolean isReset) {
if (isReset) {
beginDate = beginOfDay(beginDate);
endDate = beginOfDay(endDate);
}
return between(beginDate, endDate, DateUnit.DAY);
} | @Test
public void betweenDayTest() {
for (int i = 0; i < 1000; i++) {
final String datr = RandomUtil.randomInt(1900, 2099) + "-01-20";
final long betweenDay = DateUtil.betweenDay(
DateUtil.parseDate("1970-01-01"),
DateUtil.parseDate(datr), false);
assertEquals(Math.abs(LocalDate.parse(datr).toEpochDay()), betweenDay);
}
} |
protected int getMaxUnconfirmedReads(final TransferStatus status) {
final PreferencesReader preferences = new HostPreferences(session.getHost());
if(TransferStatus.UNKNOWN_LENGTH == status.getLength()) {
return preferences.getInteger("sftp.read.maxunconfirmed");
}
return Integer.min(((int) (status.getLength() / preferences.getInteger("connection.chunksize")) + 1),
preferences.getInteger("sftp.read.maxunconfirmed"));
} | @Test
public void testUnconfirmedReadsNumber() {
final SFTPReadFeature feature = new SFTPReadFeature(session);
assertEquals(33, feature.getMaxUnconfirmedReads(new TransferStatus().withLength(TransferStatus.MEGA * 1L)));
assertEquals(64, feature.getMaxUnconfirmedReads(new TransferStatus().withLength((long) (TransferStatus.GIGA * 1.3))));
} |
boolean valid(int nodeId, MetadataImage image) {
TopicImage topicImage = image.topics().getTopic(topicIdPartition.topicId());
if (topicImage == null) {
return false; // The topic has been deleted.
}
PartitionRegistration partition = topicImage.partitions().get(topicIdPartition.partitionId());
if (partition == null) {
return false; // The partition no longer exists.
}
// Check if this broker is still a replica.
return Replicas.contains(partition.replicas, nodeId);
} | @Test
public void testAssignmentForNonExistentTopicIsNotValid() {
assertFalse(new Assignment(
new TopicIdPartition(Uuid.fromString("uuOi4qGPSsuM0QwnYINvOw"), 0),
Uuid.fromString("rzRT8XZaSbKsP6j238zogg"),
0,
NoOpRunnable.INSTANCE).valid(0, TEST_IMAGE));
} |
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.OverTwoYears().getConvertedTime(duration);
} | @Test
public void testShouldReport23HoursFor23Hours59Minutes29Seconds() throws Exception {
assertEquals(TimeConverter.ABOUT_X_HOURS_AGO.argument(23), timeConverter
.getConvertedTime(24 * TimeConverter.HOUR_IN_SECONDS - 31));
} |
ConcurrentPublication addPublication(final String channel, final int streamId)
{
clientLock.lock();
try
{
ensureActive();
ensureNotReentrant();
final long registrationId = driverProxy.addPublication(channel, streamId);
stashedChannelByRegistrationId.put(registrationId, channel);
awaitResponse(registrationId);
return (ConcurrentPublication)resourceByRegIdMap.get(registrationId);
}
finally
{
clientLock.unlock();
}
} | @Test
void addPublicationShouldNotifyMediaDriver()
{
whenReceiveBroadcastOnMessage(
ControlProtocolEvents.ON_PUBLICATION_READY,
publicationReadyBuffer,
(buffer) -> publicationReady.length());
conductor.addPublication(CHANNEL, STREAM_ID_1);
verify(driverProxy).addPublication(CHANNEL, STREAM_ID_1);
} |
@Override
public URL getResource(String name) {
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resource '{}'", name);
for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) {
URL url = null;
switch (classLoadingSource) {
case APPLICATION:
url = super.getResource(name);
break;
case PLUGIN:
url = findResource(name);
break;
case DEPENDENCIES:
url = findResourceFromDependencies(name);
break;
}
if (url != null) {
log.trace("Found resource '{}' in {} classpath", name, classLoadingSource);
return url;
} else {
log.trace("Couldn't find resource '{}' in {}", name, classLoadingSource);
}
}
return null;
} | @Test
void parentLastGetResourceExistsOnlyInDependnecy() throws IOException, URISyntaxException {
URL resource = parentLastPluginClassLoader.getResource("META-INF/dependency-file");
assertFirstLine("dependency", resource);
} |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) ||
resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) {
checkVersion(resourceInfo.getResourceMethod().getAnnotationsByType(SupportedSearchVersion.class));
} else if (resourceInfo.getResourceClass().isAnnotationPresent(SupportedSearchVersion.class) ||
resourceInfo.getResourceClass().isAnnotationPresent(SupportedSearchVersions.class)) {
checkVersion(resourceInfo.getResourceClass().getAnnotationsByType(SupportedSearchVersion.class));
}
} | @Test
public void testFilterOnNeitherClassNorMethod() throws Exception {
final Method resourceMethod = TestResourceWithOutAnnotation.class.getMethod("methodWithoutAnnotation");
final Class resourceClass = TestResourceWithOutAnnotation.class;
when(resourceInfo.getResourceMethod()).thenReturn(resourceMethod);
when(resourceInfo.getResourceClass()).thenReturn(resourceClass);
filter.filter(requestContext);
verify(versionProvider, never()).get();
} |
@Nullable
@Override
public GenericRow decode(byte[] payload, GenericRow destination) {
try {
destination = (GenericRow) _decodeMethod.invoke(null, payload, destination);
} catch (Exception e) {
throw new RuntimeException(e);
}
return destination;
} | @Test(dataProvider = "defaultCases")
public void whenDefaultCases(String fieldName, Object protoValue, Object pinotVal)
throws Exception {
Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(fieldName);
ComplexTypes.TestMessage.Builder messageBuilder = ComplexTypes.TestMessage.newBuilder();
Assert.assertEquals(protoValue, fd.getDefaultValue());
messageBuilder.setField(fd, protoValue);
GenericRow row = new GenericRow();
ProtoBufCodeGenMessageDecoder messageDecoder = setupDecoder("complex_types.jar",
"org.apache.pinot.plugin.inputformat.protobuf.ComplexTypes$TestMessage", getAllSourceFieldsForComplexType());
messageDecoder.decode(messageBuilder.build().toByteArray(), row);
Assert.assertEquals(row.getValue(fd.getName()), pinotVal);
} |
public MapStoreConfig setClassName(@Nonnull String className) {
this.className = checkHasText(className, "Map store class name must contain text");
this.implementation = null;
return this;
} | @Test
public void setClassName() {
assertEquals("some.class", cfgNonNullClassName.getClassName());
assertEquals(new MapStoreConfig().setClassName("some.class"), cfgNonNullClassName);
} |
public static void preserve(FileSystem targetFS, Path path,
CopyListingFileStatus srcFileStatus,
EnumSet<FileAttribute> attributes,
boolean preserveRawXattrs) throws IOException {
// strip out those attributes we don't need any more
attributes.remove(FileAttribute.BLOCKSIZE);
attributes.remove(FileAttribute.CHECKSUMTYPE);
// If not preserving anything from FileStatus, don't bother fetching it.
FileStatus targetFileStatus = attributes.isEmpty() ? null :
targetFS.getFileStatus(path);
String group = targetFileStatus == null ? null :
targetFileStatus.getGroup();
String user = targetFileStatus == null ? null :
targetFileStatus.getOwner();
boolean chown = false;
if (attributes.contains(FileAttribute.ACL)) {
List<AclEntry> srcAcl = srcFileStatus.getAclEntries();
List<AclEntry> targetAcl = getAcl(targetFS, targetFileStatus);
if (!srcAcl.equals(targetAcl)) {
targetFS.removeAcl(path);
targetFS.setAcl(path, srcAcl);
}
// setAcl doesn't preserve sticky bit, so also call setPermission if needed.
if (srcFileStatus.getPermission().getStickyBit() !=
targetFileStatus.getPermission().getStickyBit()) {
targetFS.setPermission(path, srcFileStatus.getPermission());
}
} else if (attributes.contains(FileAttribute.PERMISSION) &&
!srcFileStatus.getPermission().equals(targetFileStatus.getPermission())) {
targetFS.setPermission(path, srcFileStatus.getPermission());
}
final boolean preserveXAttrs = attributes.contains(FileAttribute.XATTR);
if (preserveXAttrs || preserveRawXattrs) {
final String rawNS =
StringUtils.toLowerCase(XAttr.NameSpace.RAW.name());
Map<String, byte[]> srcXAttrs = srcFileStatus.getXAttrs();
Map<String, byte[]> targetXAttrs = getXAttrs(targetFS, path);
if (srcXAttrs != null && !srcXAttrs.equals(targetXAttrs)) {
for (Entry<String, byte[]> entry : srcXAttrs.entrySet()) {
String xattrName = entry.getKey();
if (xattrName.startsWith(rawNS) || preserveXAttrs) {
targetFS.setXAttr(path, xattrName, entry.getValue());
}
}
}
}
// The replication factor can only be preserved for replicated files.
// It is ignored when either the source or target file are erasure coded.
if (attributes.contains(FileAttribute.REPLICATION) &&
!targetFileStatus.isDirectory() &&
!targetFileStatus.isErasureCoded() &&
!srcFileStatus.isErasureCoded() &&
srcFileStatus.getReplication() != targetFileStatus.getReplication()) {
targetFS.setReplication(path, srcFileStatus.getReplication());
}
if (attributes.contains(FileAttribute.GROUP) &&
!group.equals(srcFileStatus.getGroup())) {
group = srcFileStatus.getGroup();
chown = true;
}
if (attributes.contains(FileAttribute.USER) &&
!user.equals(srcFileStatus.getOwner())) {
user = srcFileStatus.getOwner();
chown = true;
}
if (chown) {
targetFS.setOwner(path, user, group);
}
if (attributes.contains(FileAttribute.TIMES)) {
targetFS.setTimes(path,
srcFileStatus.getModificationTime(),
srcFileStatus.getAccessTime());
}
} | @Test
public void testPreserveUserOnDirectory() throws IOException {
FileSystem fs = FileSystem.get(config);
EnumSet<FileAttribute> attributes = EnumSet.of(FileAttribute.USER);
Path dst = new Path("/tmp/abc");
Path src = new Path("/tmp/src");
createDirectory(fs, src);
createDirectory(fs, dst);
fs.setPermission(src, fullPerm);
fs.setOwner(src, "somebody", "somebody-group");
fs.setPermission(dst, noPerm);
fs.setOwner(dst, "nobody", "nobody-group");
CopyListingFileStatus srcStatus = new CopyListingFileStatus(fs.getFileStatus(src));
DistCpUtils.preserve(fs, dst, srcStatus, attributes, false);
CopyListingFileStatus dstStatus = new CopyListingFileStatus(fs.getFileStatus(dst));
// FileStatus.equals only compares path field, must explicitly compare all fields
Assert.assertFalse(srcStatus.getPermission().equals(dstStatus.getPermission()));
Assert.assertTrue(srcStatus.getOwner().equals(dstStatus.getOwner()));
Assert.assertFalse(srcStatus.getGroup().equals(dstStatus.getGroup()));
} |
public static String getProperty(final String propertyName)
{
final String propertyValue = System.getProperty(propertyName);
return NULL_PROPERTY_VALUE.equals(propertyValue) ? null : propertyValue;
} | @Test
void shouldGetNormalProperty()
{
final String key = "org.agrona.test.case";
final String value = "wibble";
System.setProperty(key, value);
try
{
assertEquals(value, SystemUtil.getProperty(key));
}
finally
{
System.clearProperty(key);
}
} |
@Operation(summary = "queryResourceList", description = "QUERY_RESOURCE_LIST_NOTES")
@Parameters({
@Parameter(name = "type", description = "RESOURCE_TYPE", required = true, schema = @Schema(implementation = ResourceType.class)),
@Parameter(name = "fullName", description = "RESOURCE_FULLNAME", required = true, schema = @Schema(implementation = String.class))
})
@GetMapping(value = "/list")
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_RESOURCES_LIST_ERROR)
public Result<Object> queryResourceList(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@RequestParam(value = "type") ResourceType type,
@RequestParam(value = "fullName") String fullName) {
Map<String, Object> result = resourceService.queryResourceList(loginUser, type, fullName);
return returnDataList(result);
} | @Test
public void testQuerytResourceList() throws Exception {
Map<String, Object> mockResult = new HashMap<>();
mockResult.put(Constants.STATUS, Status.SUCCESS);
Mockito.when(resourcesService.queryResourceList(Mockito.any(), Mockito.any(), Mockito.anyString()))
.thenReturn(mockResult);
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("fullName", "dolphinscheduler/resourcePath");
paramsMap.add("type", ResourceType.FILE.name());
MvcResult mvcResult = mockMvc.perform(get("/resources/list")
.header(SESSION_ID, sessionId)
.params(paramsMap))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class);
Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());
logger.info(mvcResult.getResponse().getContentAsString());
} |
@Override
public Table getTable(long id, String name, List<Column> schema, String dbName, String catalogName,
Map<String, String> properties) throws DdlException {
Map<String, String> newProp = new HashMap<>(properties);
newProp.putIfAbsent(JDBCTable.JDBC_TABLENAME, "[" + dbName + "]" + "." + "[" + name + "]");
return new JDBCTable(id, name, schema, dbName, catalogName, newProp);
} | @Test
public void testGetTable() throws SQLException {
new Expectations() {
{
dataSource.getConnection();
result = connection;
minTimes = 0;
connection.getCatalog();
result = "t1";
minTimes = 0;
connection.getMetaData().getColumns("t1", "test", "tbl1", "%");
result = columnResult;
minTimes = 0;
}
};
try {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
Table table = jdbcMetadata.getTable("test", "tbl1");
Assert.assertTrue(table instanceof JDBCTable);
Assert.assertEquals("catalog.test.tbl1", table.getUUID());
Assert.assertEquals("tbl1", table.getName());
Assert.assertNull(properties.get(JDBCTable.JDBC_TABLENAME));
Assert.assertTrue(table.getColumn("a").getType().isVarchar());
Assert.assertTrue(table.getColumn("b").getType().isBigint());
Assert.assertTrue(table.getColumn("c").getType().isBoolean());
Assert.assertTrue(table.getColumn("d").getType().isChar());
Assert.assertTrue(table.getColumn("e").getType().isChar());
Assert.assertTrue(table.getColumn("f").getType().isDate());
Assert.assertTrue(table.getColumn("g").getType().isDecimalV3());
Assert.assertTrue(table.getColumn("h").getType().isDecimalV3());
Assert.assertTrue(table.getColumn("i").getType().isDecimalV3());
Assert.assertTrue(table.getColumn("j").getType().isDouble());
Assert.assertTrue(table.getColumn("k").getType().isInt());
Assert.assertTrue(table.getColumn("l").getType().isInt());
Assert.assertTrue(table.getColumn("m").getType().isVarchar());
Assert.assertTrue(table.getColumn("n").getType().isVarchar());
Assert.assertTrue(table.getColumn("o").getType().isVarchar());
Assert.assertTrue(table.getColumn("p").getType().isChar());
Assert.assertTrue(table.getColumn("q").getType().isDecimalV3());
Assert.assertTrue(table.getColumn("r").getType().isVarchar());
Assert.assertTrue(table.getColumn("s").getType().isFloat());
Assert.assertTrue(table.getColumn("t").getType().isSmallint());
Assert.assertTrue(table.getColumn("u").getType().isTime());
Assert.assertTrue(table.getColumn("v").getType().isDatetime());
Assert.assertTrue(table.getColumn("w").getType().isDatetime());
Assert.assertTrue(table.getColumn("x").getType().isDatetime());
Assert.assertTrue(table.getColumn("y").getType().isSmallint());
Assert.assertTrue(table.getColumn("z").getType().isVarchar());
Assert.assertTrue(table.getColumn("aa").getType().isBinaryType());
Assert.assertTrue(table.getColumn("bb").getType().isBinaryType());
Assert.assertTrue(table.getColumn("cc").getType().isBinaryType());
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
}
} |
@Override
public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding, ChannelPromise promise) {
try {
if (connection.goAwayReceived()) {
throw connectionError(PROTOCOL_ERROR, "Sending PUSH_PROMISE after GO_AWAY received.");
}
Http2Stream stream = requireStream(streamId);
// Reserve the promised stream.
connection.local().reservePushStream(promisedStreamId, stream);
promise = promise.unvoid();
ChannelFuture future = frameWriter.writePushPromise(ctx, streamId, promisedStreamId, headers, padding,
promise);
// Writing headers may fail during the encode state if they violate HPACK limits.
Throwable failureCause = future.cause();
if (failureCause == null) {
// This just sets internal stream state which is used elsewhere in the codec and doesn't
// necessarily mean the write will complete successfully.
stream.pushPromiseSent();
if (!future.isSuccess()) {
// Either the future is not done or failed in the meantime.
notifyLifecycleManagerOnError(future, ctx);
}
} else {
lifecycleManager.onError(ctx, true, failureCause);
}
return future;
} catch (Throwable t) {
lifecycleManager.onError(ctx, true, t);
promise.tryFailure(t);
return promise;
}
} | @Test
public void pushPromiseWriteAfterGoAwayReceivedShouldFail() throws Exception {
createStream(STREAM_ID, false);
goAwayReceived(0);
ChannelFuture future = encoder.writePushPromise(ctx, STREAM_ID, PUSH_STREAM_ID, EmptyHttp2Headers.INSTANCE, 0,
newPromise());
assertTrue(future.isDone());
assertFalse(future.isSuccess());
} |
@PutMapping
@Secured(action = ActionTypes.WRITE)
public String update(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
final String clusterName = WebUtils.required(request, CommonParams.CLUSTER_NAME);
final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
ClusterMetadata clusterMetadata = new ClusterMetadata();
clusterMetadata.setHealthyCheckPort(NumberUtils.toInt(WebUtils.required(request, "checkPort")));
clusterMetadata.setUseInstancePortForCheck(
ConvertUtils.toBoolean(WebUtils.required(request, "useInstancePort4Check")));
AbstractHealthChecker healthChecker = HealthCheckerFactory
.deserialize(WebUtils.required(request, "healthChecker"));
clusterMetadata.setHealthChecker(healthChecker);
clusterMetadata.setHealthyCheckType(healthChecker.getType());
clusterMetadata.setExtendData(
UtilsAndCommons.parseMetadata(WebUtils.optional(request, "metadata", StringUtils.EMPTY)));
judgeClusterOperator().updateClusterMetadata(namespaceId, serviceName, clusterName, clusterMetadata);
return "ok";
} | @Test
void testUpdate() throws Exception {
mockRequestParameter(CommonParams.NAMESPACE_ID, "test-namespace");
mockRequestParameter(CommonParams.CLUSTER_NAME, TEST_CLUSTER_NAME);
mockRequestParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME);
mockRequestParameter("checkPort", "1");
mockRequestParameter("useInstancePort4Check", "true");
mockRequestParameter("healthChecker", "{\"type\":\"HTTP\"}");
assertEquals("ok", clusterController.update(request));
verify(clusterOperatorV2).updateClusterMetadata(eq("test-namespace"), eq(TEST_SERVICE_NAME), eq(TEST_CLUSTER_NAME),
any(ClusterMetadata.class));
} |
public boolean equals(Object obj)
{
return this == obj; // this is correct because there are only two COSBoolean objects.
} | @Test
void testEquals()
{
COSBoolean test1 = COSBoolean.TRUE;
COSBoolean test2 = COSBoolean.TRUE;
COSBoolean test3 = COSBoolean.TRUE;
// Reflexive (x == x)
assertEquals(test1, test1);
// Symmetric is preserved ( x==y then y===x)
assertEquals(test2, test1);
assertEquals(test1, test2);
// Transitive (if x==y && y==z then x===z)
assertEquals(test1, test2);
assertEquals(test2, test3);
assertEquals(test1, test3);
assertNotEquals(COSBoolean.TRUE, COSBoolean.FALSE);
// same 'value' but different type
assertNotEquals(Boolean.TRUE, COSBoolean.TRUE);
assertNotEquals(Boolean.FALSE, COSBoolean.FALSE);
assertNotEquals(true, COSBoolean.TRUE);
assertNotEquals(true, COSBoolean.FALSE);
} |
public String webURL() {
return DEFAULT_WEB_URL;
} | @Test
public void default_webUrl() {
assertThat(underTest.webURL()).isEqualTo("https://bitbucket.org/");
} |
public boolean update(final String profileId, final IndexFieldTypeProfile updatedProfile) {
if (!ObjectId.isValid(profileId)) {
return false;
}
updatedProfile.customFieldMappings().forEach(mapping -> checkFieldTypeCanBeChanged(mapping.fieldName()));
final WriteResult<IndexFieldTypeProfile, ObjectId> writeResult = db.updateById(new ObjectId(profileId), updatedProfile);
return writeResult.getN() > 0;
} | @Test
public void testUpdate() {
final IndexFieldTypeProfile profile = new IndexFieldTypeProfile("123400000000000000000001", "profile", "profile", new CustomFieldMappings());
toTest.save(profile);
final IndexFieldTypeProfile updatedProfile = new IndexFieldTypeProfile(profile.id(), "Changed!", "Changed!",
new CustomFieldMappings(List.of(new CustomFieldMapping("field", "date"))));
toTest.update(profile.id(), updatedProfile);
assertEquals(updatedProfile, toTest.get(profile.id()).get());
} |
public static long readUint32BE(ByteBuffer buf) throws BufferUnderflowException {
return Integer.toUnsignedLong(buf.order(ByteOrder.BIG_ENDIAN).getInt());
} | @Test
public void testReadUInt32BE() {
assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2}, 0));
assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2, 3, 4}, 0));
assertEquals(772L, ByteUtils.readUint32BE(new byte[]{1, 2, 0, 0, 3, 4}, 2));
} |
public static String encodeForRegistry(String element) {
return IDN.toASCII(element);
} | @Test
public void testFormatIdempotent() throws Throwable {
assertConverted("xn--lzg", RegistryPathUtils.encodeForRegistry(EURO));
} |
@UdafFactory(description = "collect values of a field into a single Array")
public static <T> TableUdaf<T, List<T>, List<T>> createCollectListT() {
return new Collect<>();
} | @Test
public void shouldCollectTimes() {
final TableUdaf<Time, List<Time>, List<Time>> udaf = CollectListUdaf.createCollectListT();
final Time[] values = new Time[] {new Time(1), new Time(2)};
List<Time> runningList = udaf.initialize();
for (final Time i : values) {
runningList = udaf.aggregate(i, runningList);
}
assertThat(runningList, contains(new Time(1), new Time(2)));
} |
@Override
public TaskExecutor executor() {
return new JsonBasedTaskExecutor(pluginId, pluginRequestHelper, handlerMap);
} | @Test
public void shouldGetTaskExecutor() {
assertTrue(task.executor() instanceof JsonBasedTaskExecutor);
} |
public static <K, V> KvCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) {
return new KvCoder<>(keyCoder, valueCoder);
} | @Test
public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
CoderProperties.coderSerializable(
KvCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE));
} |
public static org.apache.avro.Schema toAvroSchema(
Schema beamSchema, @Nullable String name, @Nullable String namespace) {
final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name;
final String schemaNamespace = namespace == null ? "" : namespace;
String childNamespace =
!"".equals(schemaNamespace) ? schemaNamespace + "." + schemaName : schemaName;
List<org.apache.avro.Schema.Field> fields = Lists.newArrayList();
for (Field field : beamSchema.getFields()) {
org.apache.avro.Schema.Field recordField = toAvroField(field, childNamespace);
fields.add(recordField);
}
return org.apache.avro.Schema.createRecord(schemaName, null, schemaNamespace, false, fields);
} | @Test
public void testAvroSchemaFromBeamSchemaWithFieldCollisionCanBeParsed() {
// Two similar schemas, the only difference is the "street" field type in the nested record.
Schema contact =
new Schema.Builder()
.addField(Field.of("name", FieldType.STRING))
.addField(
Field.of(
"address",
FieldType.row(
new Schema.Builder()
.addField(Field.of("street", FieldType.STRING))
.addField(Field.of("city", FieldType.STRING))
.build())))
.build();
Schema contactMultiline =
new Schema.Builder()
.addField(Field.of("name", FieldType.STRING))
.addField(
Field.of(
"address",
FieldType.row(
new Schema.Builder()
.addField(Field.of("street", FieldType.array(FieldType.STRING)))
.addField(Field.of("city", FieldType.STRING))
.build())))
.build();
// Ensure that no collisions happen between two sibling fields with same-named child fields
// (with different schemas, between a parent field and a sub-record field with the same name,
// and artificially with the generated field name.
Schema beamSchema =
new Schema.Builder()
.addField(Field.of("home", FieldType.row(contact)))
.addField(Field.of("work", FieldType.row(contactMultiline)))
.addField(Field.of("address", FieldType.row(contact)))
.addField(Field.of("topLevelRecord", FieldType.row(contactMultiline)))
.build();
org.apache.avro.Schema convertedSchema = AvroUtils.toAvroSchema(beamSchema);
org.apache.avro.Schema validatedSchema =
new org.apache.avro.Schema.Parser().parse(convertedSchema.toString());
assertEquals(convertedSchema, validatedSchema);
} |
@Override
public O next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
O result = nextObject;
nextObject = null;
return result;
} | @Test
public void call_next_without_hasNext() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
assertThat(it.next()).isEqualTo(1);
assertThat(it.next()).isEqualTo(2);
try {
it.next();
fail();
} catch (NoSuchElementException expected) {
}
} |
public void ipCheck(EidSession session, String clientIp) {
if (session.getClientIpAddress() != null && !session.getClientIpAddress().isEmpty()) {
String[] clientIps = clientIp.split(", ");
byte[] data = clientIps[0].concat(sourceIpSalt).getBytes(StandardCharsets.UTF_8);
String anonimizedIp = Base64.toBase64String(DigestUtils.digest("SHA256").digest(data));
if (!anonimizedIp.equals(session.getClientIpAddress())) {
String logMessage = String.format(
"Security exception: Browser and Desktop client IP doesn't match: %s expected: %s",
anonimizedIp, session.getClientIpAddress());
if (sourceIpCheck) {
throw new ClientException(logMessage);
} else {
logger.warn(logMessage);
}
}
}
} | @Test
public void testIpCheckIncorrectIp() {
setIpCheck(true);
EidSession session = new EidSession();
// this ip is one = sign bigger
session.setClientIpAddress("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
ClientException thrown = assertThrows(ClientException.class, () -> target.ipCheck(session, "SSSSSSSSSSSSSS"));
assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", thrown.getMessage());
} |
public static Map<String, Object> merge(Map<String, Object> orig, Map<String, Object> update) {
final Map<String, Object> merged = new HashMap<>(orig);
update.forEach((k, v) -> {
if (orig.get(k) instanceof EncryptedValue origValue && v instanceof EncryptedValue newValue) {
merged.put(k, mergeEncryptedValues(origValue, newValue));
} else {
merged.put(k, v);
}
});
return merged;
} | @Test
void testMerge_keepValue() {
final Map<String, Object> orig = Map.of(
"unencrypted", "old unencrypted",
"encrypted", encryptedValueService.encrypt("old encrypted")
);
final Map<String, Object> update = Map.of(
"encrypted", EncryptedValue.createWithKeepValue()
);
assertThat(EncryptedInputConfigs.merge(orig, update)).isEqualTo(orig);
} |
public static List<URI> getPeerServerURIs(HelixManager helixManager, String tableNameWithType, String segmentName,
String downloadScheme) {
HelixAdmin helixAdmin = helixManager.getClusterManagmentTool();
String clusterName = helixManager.getClusterName();
List<URI> onlineServerURIs = new ArrayList<>();
try {
RetryPolicies.exponentialBackoffRetryPolicy(MAX_NUM_ATTEMPTS, INITIAL_DELAY_MS, DELAY_SCALE_FACTOR)
.attempt(() -> {
getOnlineServersFromExternalView(helixAdmin, clusterName, tableNameWithType, segmentName, downloadScheme,
onlineServerURIs);
return !onlineServerURIs.isEmpty();
});
} catch (AttemptsExceededException e) {
LOGGER.error("Failed to find ONLINE servers for segment: {} in table: {} after {} attempts", segmentName,
tableNameWithType, MAX_NUM_ATTEMPTS);
} catch (Exception e) {
LOGGER.error("Caught exception while getting peer server URIs for segment: {} in table: {}", segmentName,
tableNameWithType, e);
}
return onlineServerURIs;
} | @Test
public void testSegmentNotFound() {
assertTrue(PeerServerSegmentFinder.getPeerServerURIs(_helixManager, REALTIME_TABLE_NAME, SEGMENT_2,
CommonConstants.HTTP_PROTOCOL).isEmpty());
} |
@Override
public boolean isAutoTrackEnabled() {
return false;
} | @Test
public void isAutoTrackEnabled() {
List<SensorsDataAPI.AutoTrackEventType> typeList = new ArrayList<>();
typeList.add(SensorsDataAPI.AutoTrackEventType.APP_START);
typeList.add(SensorsDataAPI.AutoTrackEventType.APP_END);
mSensorsAPI.disableAutoTrack(typeList);
Assert.assertFalse(mSensorsAPI.isAutoTrackEnabled());
} |
void changePopInvisibleTimeAsync(String topic, String consumerGroup, String extraInfo, long invisibleTime, AckCallback callback)
throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
String[] extraInfoStrs = ExtraInfoUtil.split(extraInfo);
String brokerName = ExtraInfoUtil.getBrokerName(extraInfoStrs);
int queueId = ExtraInfoUtil.getQueueId(extraInfoStrs);
String desBrokerName = brokerName;
if (brokerName != null && brokerName.startsWith(MixAll.LOGICAL_QUEUE_MOCK_BROKER_PREFIX)) {
desBrokerName = this.mQClientFactory.getBrokerNameFromMessageQueue(this.defaultMQPushConsumer.queueWithNamespace(new MessageQueue(topic, brokerName, queueId)));
}
FindBrokerResult
findBrokerResult = this.mQClientFactory.findBrokerAddressInSubscribe(desBrokerName, MixAll.MASTER_ID, true);
if (null == findBrokerResult) {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(topic);
findBrokerResult = this.mQClientFactory.findBrokerAddressInSubscribe(desBrokerName, MixAll.MASTER_ID, true);
}
if (findBrokerResult != null) {
ChangeInvisibleTimeRequestHeader requestHeader = new ChangeInvisibleTimeRequestHeader();
requestHeader.setTopic(ExtraInfoUtil.getRealTopic(extraInfoStrs, topic, consumerGroup));
requestHeader.setQueueId(queueId);
requestHeader.setOffset(ExtraInfoUtil.getQueueOffset(extraInfoStrs));
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setExtraInfo(extraInfo);
requestHeader.setInvisibleTime(invisibleTime);
requestHeader.setBrokerName(brokerName);
//here the broker should be polished
this.mQClientFactory.getMQClientAPIImpl().changeInvisibleTimeAsync(brokerName, findBrokerResult.getBrokerAddr(), requestHeader, ASYNC_TIMEOUT, callback);
return;
}
throw new MQClientException("The broker[" + desBrokerName + "] not exist", null);
} | @Test
public void testChangePopInvisibleTimeAsync() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
AckCallback callback = mock(AckCallback.class);
String extraInfo = createMessageExt().getProperty(MessageConst.PROPERTY_POP_CK);
defaultMQPushConsumerImpl.changePopInvisibleTimeAsync(defaultTopic, defaultGroup, extraInfo, defaultTimeout, callback);
verify(mqClientAPIImpl).changeInvisibleTimeAsync(eq(defaultBroker),
eq(defaultBrokerAddr),
any(ChangeInvisibleTimeRequestHeader.class),
eq(defaultTimeout),
any(AckCallback.class));
} |
@Override
public List<ApplicationAttemptId> getAppsInQueue(String queueName) {
FSQueue queue = queueMgr.getQueue(queueName);
if (queue == null) {
return null;
}
List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>();
queue.collectSchedulerApplications(apps);
return apps;
} | @Test
public void testGetAppsInQueue() throws Exception {
scheduler.init(conf);
scheduler.start();
scheduler.reinitialize(conf, resourceManager.getRMContext());
ApplicationAttemptId appAttId1 =
createSchedulingRequest(1024, 1, "queue1.subqueue1", "user1");
ApplicationAttemptId appAttId2 =
createSchedulingRequest(1024, 1, "queue1.subqueue2", "user1");
ApplicationAttemptId appAttId3 =
createSchedulingRequest(1024, 1, "user1", "user1");
List<ApplicationAttemptId> apps =
scheduler.getAppsInQueue("queue1.subqueue1");
assertEquals(1, apps.size());
assertEquals(appAttId1, apps.get(0));
// with and without root prefix should work
apps = scheduler.getAppsInQueue("root.queue1.subqueue1");
assertEquals(1, apps.size());
assertEquals(appAttId1, apps.get(0));
apps = scheduler.getAppsInQueue("user1");
assertEquals(1, apps.size());
assertEquals(appAttId3, apps.get(0));
// with and without root prefix should work
apps = scheduler.getAppsInQueue("root.user1");
assertEquals(1, apps.size());
assertEquals(appAttId3, apps.get(0));
// apps in subqueues should be included
apps = scheduler.getAppsInQueue("queue1");
Assert.assertEquals(2, apps.size());
Set<ApplicationAttemptId> appAttIds = Sets.newHashSet(apps.get(0), apps.get(1));
assertTrue(appAttIds.contains(appAttId1));
assertTrue(appAttIds.contains(appAttId2));
} |
@Override
public int getLinkCount() {
checkPermission(LINK_READ);
return store.getLinkCount();
} | @Test
public void updateLink() {
addLink(DID1, P1, DID2, P2, DIRECT);
addLink(DID2, P2, DID1, P1, INDIRECT);
assertEquals("incorrect link count", 2, service.getLinkCount());
providerService.linkDetected(new DefaultLinkDescription(cp(DID2, P2), cp(DID1, P1), DIRECT));
validateEvents(LINK_UPDATED);
assertEquals("incorrect link count", 2, service.getLinkCount());
providerService.linkDetected(new DefaultLinkDescription(cp(DID2, P2), cp(DID1, P1), INDIRECT));
providerService.linkDetected(new DefaultLinkDescription(cp(DID2, P2), cp(DID1, P1), DIRECT));
assertEquals("no events expected", 0, listener.events.size());
} |
@Override
public Mono<SetProfileResponse> setProfile(final SetProfileRequest request) {
validateRequest(request);
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> Mono.zip(
Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)),
Mono.fromFuture(() -> profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
))
.doOnNext(accountAndMaybeProfile -> {
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> accountAndMaybeProfile.getT1().getNumber().startsWith(prefix));
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asRuntimeException();
}
}
})
.flatMap(accountAndMaybeProfile -> {
final Account account = accountAndMaybeProfile.getT1();
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
case AVATAR_CHANGE_UPDATE -> {
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
Optional.of(generateAvatarUploadForm(updateAvatarObjectName)));
}
};
final Mono<Void> profileSetMono = Mono.fromFuture(() -> profilesManager.setAsync(account.getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getPhoneNumberSharing().toByteArray(),
request.getCommitment().toByteArray())));
final List<Mono<?>> updates = new ArrayList<>(2);
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, account.getBadges()))
.orElseGet(account::getBadges);
updates.add(Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
})));
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
updates.add(Mono.fromFuture(() -> asyncS3client.deleteObject(DeleteObjectRequest.builder()
.bucket(bucket)
.key(avatarData.currentAvatar().get())
.build())));
}
return profileSetMono.thenMany(Flux.merge(updates)).then(Mono.just(avatarData));
})
.map(avatarData -> avatarData.uploadAttributes()
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
.orElse(SetProfileResponse.newBuilder().build())
);
} | @Test
void setProfile() throws InvalidInputException {
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
final byte[] validAboutEmoji = new byte[60];
final byte[] validAbout = new byte[540];
final byte[] validPaymentAddress = new byte[582];
final byte[] validPhoneNumberSharing = new byte[29];
final SetProfileRequest request = SetProfileRequest.newBuilder()
.setVersion(VERSION)
.setName(ByteString.copyFrom(VALID_NAME))
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
.setAbout(ByteString.copyFrom(validAbout))
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
.setPhoneNumberSharing(ByteString.copyFrom(validPhoneNumberSharing))
.setCommitment(ByteString.copyFrom(commitment))
.build();
authenticatedServiceStub().setProfile(request);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
verify(profilesManager).setAsync(eq(account.getUuid()), profileArgumentCaptor.capture());
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.commitment()).isEqualTo(commitment);
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(VERSION);
assertThat(profile.name()).isEqualTo(VALID_NAME);
assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji);
assertThat(profile.about()).isEqualTo(validAbout);
assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress);
assertThat(profile.phoneNumberSharing()).isEqualTo(validPhoneNumberSharing);
} |
public static UPrimitiveTypeTree create(TypeTag tag) {
return new AutoValue_UPrimitiveTypeTree(tag);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.INT), UPrimitiveTypeTree.INT)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.LONG), UPrimitiveTypeTree.LONG)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.DOUBLE), UPrimitiveTypeTree.DOUBLE)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.FLOAT), UPrimitiveTypeTree.FLOAT)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.CHAR), UPrimitiveTypeTree.CHAR)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.VOID), UPrimitiveTypeTree.VOID)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.BOT), UPrimitiveTypeTree.NULL)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.BOOLEAN), UPrimitiveTypeTree.BOOLEAN)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.BYTE), UPrimitiveTypeTree.BYTE)
.addEqualityGroup(UPrimitiveTypeTree.create(TypeTag.SHORT), UPrimitiveTypeTree.SHORT)
.testEquals();
} |
public Mono<CosmosContainerResponse> createContainer(
final String containerId, final String containerPartitionKeyPath, final ThroughputProperties throughputProperties,
final IndexingPolicy indexingPolicy) {
CosmosDbUtils.validateIfParameterIsNotEmpty(containerId, PARAM_CONTAINER_ID);
CosmosDbUtils.validateIfParameterIsNotEmpty(containerPartitionKeyPath, PARAM_CONTAINER_PARTITION_KEY_PATH);
// containerPartitionKeyPath it needs to start with /
final String enhancedContainerPartitionKeyPath;
if (!containerPartitionKeyPath.startsWith("/")) {
enhancedContainerPartitionKeyPath = "/" + containerPartitionKeyPath;
} else {
enhancedContainerPartitionKeyPath = containerPartitionKeyPath;
}
if (ObjectHelper.isNotEmpty(indexingPolicy)) {
CosmosContainerProperties cosmosProp
= new CosmosContainerProperties(containerId, enhancedContainerPartitionKeyPath);
cosmosProp.setIndexingPolicy(indexingPolicy);
return applyToDatabase(database -> database.createContainerIfNotExists(cosmosProp,
throughputProperties));
} else {
return applyToDatabase(database -> database.createContainerIfNotExists(containerId, containerPartitionKeyPath,
throughputProperties));
}
} | @Test
void testCreateContainer() {
final CosmosAsyncDatabase database = mock(CosmosAsyncDatabase.class);
final CosmosContainerResponse containerResponse = mock(CosmosContainerResponse.class);
when(containerResponse.getProperties()).thenReturn(new CosmosContainerProperties("test-container", "/path"));
when(database.createContainerIfNotExists(any(), any(), any())).thenReturn(Mono.just(containerResponse));
final CosmosDbDatabaseOperations databaseOperations = new CosmosDbDatabaseOperations(Mono.just(database));
// assert params
CosmosDbTestUtils
.assertIllegalArgumentException(() -> databaseOperations.createContainer(null, null, null, null));
CosmosDbTestUtils
.assertIllegalArgumentException(() -> databaseOperations.createContainer("", null, null, null));
CosmosDbTestUtils.assertIllegalArgumentException(() -> databaseOperations.createContainer("", "", null, null));
CosmosDbTestUtils
.assertIllegalArgumentException(() -> databaseOperations.createContainer("test", "", null, null));
CosmosDbTestUtils
.assertIllegalArgumentException(() -> databaseOperations.createContainer("", "test", null, null));
// assert key path
final CosmosContainerResponse returnedContainerResponseFirstCase
= databaseOperations.createContainer("test-container", "path", null, null).block();
final CosmosContainerResponse returnedContainerResponseSecondCase
= databaseOperations.createContainer("test-container", "/path", null, null).block();
assertNotNull(returnedContainerResponseFirstCase);
assertNotNull(returnedContainerResponseSecondCase);
assertEquals("test-container", returnedContainerResponseFirstCase.getProperties().getId());
assertEquals("test-container", returnedContainerResponseSecondCase.getProperties().getId());
assertEquals("/path", returnedContainerResponseFirstCase.getProperties().getPartitionKeyDefinition().getPaths().get(0));
assertEquals("/path",
returnedContainerResponseSecondCase.getProperties().getPartitionKeyDefinition().getPaths().get(0));
} |
@Override
public String[] split(String text) {
boundary.setText(text);
List<String> words = new ArrayList<>();
int start = boundary.first();
int end = boundary.next();
while (end != BreakIterator.DONE) {
String word = text.substring(start, end).trim();
if (!word.isEmpty()) {
words.add(word);
}
start = end;
end = boundary.next();
}
return words.toArray(new String[0]);
} | @Test
public void testSplitContraction() {
System.out.println("tokenize contraction");
String text = "Here are some examples of contractions: 'tis, "
+ "'twas, ain't, aren't, Can't, could've, couldn't, didn't, doesn't, "
+ "don't, hasn't, he'd, he'll, he's, how'd, how'll, how's, i'd, i'll, i'm, "
+ "i've, isn't, it's, might've, mightn't, must've, mustn't, Shan't, "
+ "she'd, she'll, she's, should've, shouldn't, that'll, that's, "
+ "there's, they'd, they'll, they're, they've, wasn't, we'd, we'll, "
+ "we're, weren't, what'd, what's, when'd, when'll, when's, "
+ "where'd, where'll, where's, who'd, who'll, who's, why'd, why'll, "
+ "why's, Won't, would've, wouldn't, you'd, you'll, you're, you've";
String[] expResult = {"Here", "are", "some", "examples", "of",
"contractions", ":", "'", "tis", ",", "'", "twas", ",", "ain't",
",", "aren't", ",", "Can't", ",", "could've",
",", "couldn't", ",", "didn't", ",", "doesn't", ",", "don't",
",", "hasn't", ",", "he'd", ",", "he'll", ",",
"he's", ",", "how'd", ",", "how'll", ",", "how's",
",", "i'd", ",", "i'll", ",", "i'm", ",", "i've", ",",
"isn't", ",", "it's", ",", "might've", ",", "mightn't",
",", "must've", ",", "mustn't", ",", "Shan't",
",", "she'd", ",", "she'll", ",", "she's", ",",
"should've", ",", "shouldn't", ",", "that'll", ",",
"that's", ",", "there's", ",", "they'd", ",", "they'll",
",", "they're", ",", "they've", ",", "wasn't", ",", "we'd",
",", "we'll", ",", "we're", ",", "weren't", ",",
"what'd", ",", "what's", ",", "when'd",
",", "when'll", ",", "when's", ",", "where'd", ",",
"where'll", ",", "where's", ",", "who'd", ",", "who'll",
",", "who's", ",", "why'd", ",", "why'll", ",",
"why's", ",", "Won't", ",", "would've", ",", "wouldn't",
",", "you'd", ",", "you'll", ",", "you're", ",",
"you've"};
BreakIteratorTokenizer instance = new BreakIteratorTokenizer();
String[] result = instance.split(text);
assertEquals(expResult.length, result.length);
for (int i = 0; i < result.length; i++) {
assertEquals(expResult[i], result[i]);
}
} |
public Stream<Hit> stream() {
if (nPostingLists == 0) {
return Stream.empty();
}
return StreamSupport.stream(new PredicateSpliterator(), false);
} | @Test
void requireThatSortingWorksForManyPostingLists() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 5, 2, 2},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(0, 0x000100ff),
entry(1, 0x000100ff)),
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(1, 0x000100ff),
entry(2, 0x000100ff)),
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(1, 0x000100ff),
entry(3, 0x000100ff)),
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(1, 0x000100ff),
entry(2, 0x000100ff)),
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(1, 0x000100ff),
entry(3, 0x000100ff)));
assertEquals(
List.of(new Hit(0), new Hit(1), new Hit(2), new Hit(3)).toString(),
search.stream().toList().toString());
} |
@Override
public boolean isAuthenticationRequired(SubjectConnectionReference conn) {
Subject subject = conn.getSubject();
if (subject.isAuthenticated()) {
//already authenticated:
return false;
}
//subject is not authenticated. Authentication is required by default for all accounts other than
//the anonymous user (if enabled) or the vm account (if enabled)
if (isAnonymousAccessAllowed()) {
if (isAnonymousAccount(subject)) {
return false;
}
}
if (!isVmConnectionAuthenticationRequired()) {
if (isSystemAccount(subject)) {
return false;
}
}
return true;
} | @Test
public void testIsAuthenticationRequiredWhenSystemConnectionAndSystemSubject() {
Subject subject = new SubjectAdapter() {
@Override
public PrincipalCollection getPrincipals() {
return new SimplePrincipalCollection("system", "iniRealm");
}
};
SubjectConnectionReference sc = new SubjectConnectionReference(new ConnectionContext(), new ConnectionInfo(),
new DefaultEnvironment(), subject);
assertFalse(policy.isAuthenticationRequired(sc));
} |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the TIMESTAMP value."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.")
public Timestamp parseTimestamp(
@UdfParameter(
description = "The string representation of a date.") final String formattedTimestamp,
@UdfParameter(
description = "The format pattern should be in the format expected by"
+ " java.time.format.DateTimeFormatter.") final String formatPattern) {
return parseTimestamp(formattedTimestamp, formatPattern, ZoneId.of("GMT").getId());
} | @Test
public void shouldParseTimestamp() throws ParseException {
// When:
final Object result = udf.parseTimestamp("2021-12-01 12:10:11.123",
"yyyy-MM-dd HH:mm:ss.SSS");
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
// Then:
final Timestamp expectedResult = Timestamp.from(sdf.parse("2021-12-01 12:10:11.123").toInstant());
assertThat(result, is(expectedResult));
} |
public static boolean isSubdirectoryOf(File parent, File subdirectory) throws IOException {
File parentFile = parent.getCanonicalFile();
File current = subdirectory.getCanonicalFile();
while (current != null) {
if (current.equals(parentFile)) {
return true;
}
current = current.getParentFile();
}
return false;
} | @Test
void shouldDetectSubfoldersWhenUsingRelativePaths() throws Exception {
File parent = new File("/a/b");
assertThat(isSubdirectoryOf(parent, new File(parent, "../../.."))).isFalse();
} |
public long getId(final WorkerNetAddress address) throws IOException {
return retryRPC(() -> {
GetWorkerIdPRequest request =
GetWorkerIdPRequest.newBuilder().setWorkerNetAddress(GrpcUtils.toProto(address)).build();
return mClient.getWorkerId(request).getWorkerId();
}, LOG, "GetId", "address=%s", address);
} | @Test
public void getId() throws Exception {
WorkerNetAddress testExistsAddress = new WorkerNetAddress();
WorkerNetAddress testNonExistsAddress = new WorkerNetAddress();
testNonExistsAddress.setHost("1.2.3.4");
long workerId = 1L;
Map<WorkerNetAddress, Long> workerIds = ImmutableMap.of(testExistsAddress, workerId);
createMockService(
new BlockMasterWorkerServiceGrpc.BlockMasterWorkerServiceImplBase() {
@Override
public void getWorkerId(GetWorkerIdPRequest request,
StreamObserver<GetWorkerIdPResponse> responseObserver) {
WorkerNetAddress address = GrpcUtils.fromProto(request.getWorkerNetAddress());
Long id = workerIds.get(address);
if (id == null) {
id = -1L;
}
responseObserver.onNext(GetWorkerIdPResponse.newBuilder().setWorkerId(id).build());
responseObserver.onCompleted();
}
});
BlockMasterClient client = new BlockMasterClient(
MasterClientContext.newBuilder(ClientContext.create(mConf)).build()
);
assertEquals(workerId, client.getId(testExistsAddress));
assertEquals(-1L, client.getId(testNonExistsAddress));
} |
public static Runnable catchingAndLoggingThrowables(Runnable runnable) {
return new CatchingAndLoggingRunnable(runnable);
} | @Test
public void shouldCatchAndLogException() {
Runnables.catchingAndLoggingThrowables(() -> {
throw new RuntimeException();
}).run();
} |
@Override
public void run() {
synchronized (this) {
serverPushClient.writeAndFlush('\r');
serverPushClient.writeAndFlush('\n');
}
serverPushClient.scheduleHeartbeat();
} | @Test
public void run_reSchedulesHeartBeat() {
underTest.run();
verify(serverPushClient, times(2)).writeAndFlush(anyChar());
verify(serverPushClient).scheduleHeartbeat();
} |
@Override
public void validate(final Analysis analysis) {
failPersistentQueryOnWindowedTable(analysis);
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis);
} | @Test
public void shouldNotThrowOnPersistentPushQueryOnUnwindowedTable() {
// Given:
givenPersistentQuery();
givenSourceTable();
givenUnwindowedSource();
// When/Then(don't throw):
validator.validate(analysis);
} |
public void addPermission(String role, String resource, String action) {
if (!roleSet.contains(role)) {
throw new IllegalArgumentException("role " + role + " not found!");
}
permissionPersistService.addPermission(role, resource, action);
} | @Test
void addPermission() {
try {
nacosRoleService.addPermission("role-admin", "", "rw");
} catch (Exception e) {
assertTrue(e.getMessage().contains("role role-admin not found!"));
}
} |
@SuppressWarnings("unchecked")
public E lookup(final int key)
{
@DoNotSub int size = this.size;
final int[] keys = this.keys;
final Object[] values = this.values;
for (@DoNotSub int i = 0; i < size; i++)
{
if (key == keys[i])
{
final E value = (E)values[i];
makeMostRecent(key, value, i);
return value;
}
}
final E value = factory.apply(key);
if (value != null)
{
if (capacity == size)
{
closer.accept((E)values[size - 1]);
}
else
{
size++;
this.size = size;
}
makeMostRecent(key, value, size - 1);
}
return value;
} | @Test
void shouldReconstructItemsAfterEviction()
{
cache.lookup(1);
final AutoCloseable second = cache.lookup(2);
cache.lookup(3);
cache.lookup(1);
verify(mockCloser).accept(second);
verifyOneConstructed(2);
} |
public static StackTraceElement[] extract(Throwable t, String fqnOfInvokingClass, final int maxDepth,
List<String> frameworkPackageList) {
if (t == null) {
return null;
}
StackTraceElement[] steArray = t.getStackTrace();
StackTraceElement[] callerDataArray;
int found = LINE_NA;
for (int i = 0; i < steArray.length; i++) {
if (isInFrameworkSpace(steArray[i].getClassName(), fqnOfInvokingClass, frameworkPackageList)) {
// the caller is assumed to be the next stack frame, hence the +1.
found = i + 1;
} else {
if (found != LINE_NA) {
break;
}
}
}
// we failed to extract caller data
if (found == LINE_NA) {
return EMPTY_CALLER_DATA_ARRAY;
}
int availableDepth = steArray.length - found;
int desiredDepth = maxDepth < (availableDepth) ? maxDepth : availableDepth;
callerDataArray = new StackTraceElement[desiredDepth];
for (int i = 0; i < desiredDepth; i++) {
callerDataArray[i] = steArray[found + i];
}
return callerDataArray;
} | @Test
public void testBasic() {
Throwable t = new Throwable();
StackTraceElement[] steArray = t.getStackTrace();
StackTraceElement[] cda = CallerData.extract(t, CallerDataTest.class.getName(), 100, null);
Arrays.stream(cda).forEach( ste -> System.out.println(ste));
assertNotNull(cda);
assertTrue(cda.length > 0);
assertEquals(steArray.length - 1, cda.length);
} |
@Override
public void resolve(ConcurrentJobModificationException e) {
final List<Job> concurrentUpdatedJobs = e.getConcurrentUpdatedJobs();
final List<ConcurrentJobModificationResolveResult> failedToResolve = concurrentUpdatedJobs
.stream()
.map(this::resolve)
.filter(ConcurrentJobModificationResolveResult::failed)
.collect(toList());
if (!failedToResolve.isEmpty()) {
throw new UnresolvableConcurrentJobModificationException(failedToResolve, e);
}
} | @Test
void concurrentStateChangeFromUnsupportedStateChangeIsNotAllowedAndThrowsException() {
final Job job1 = aJobInProgress().build();
final Job job2 = aJobInProgress().build();
when(storageProvider.getJobById(job1.getId())).thenReturn(aCopyOf(job1).build());
when(storageProvider.getJobById(job2.getId())).thenReturn(aCopyOf(job2).build());
assertThatThrownBy(() -> concurrentJobModificationResolver.resolve(new ConcurrentJobModificationException(asList(job1, job2))))
.isInstanceOf(ConcurrentJobModificationException.class)
.has(failedJob(job1))
.has(failedJob(job2));
} |
public synchronized void write(Mutation tableRecord) throws IllegalStateException {
write(ImmutableList.of(tableRecord));
} | @Test
public void testWriteMultipleRecordsShouldWorkWhenSpannerWriteSucceeds()
throws ExecutionException, InterruptedException {
// arrange
prepareTable();
when(spanner.getDatabaseClient(any()).write(any())).thenReturn(Timestamp.now());
ImmutableList<Mutation> testMutations =
ImmutableList.of(
Mutation.newInsertOrUpdateBuilder("SingerId")
.set("SingerId")
.to(1)
.set("FirstName")
.to("Marc")
.set("LastName")
.to("Richards")
.build(),
Mutation.newInsertOrUpdateBuilder("SingerId")
.set("SingerId")
.to(2)
.set("FirstName")
.to("Catalina")
.set("LastName")
.to("Smith")
.build());
// act
testManager.write(testMutations);
// assert
verify(spanner.getDatabaseClient(any())).write(writeMutationCaptor.capture());
Iterable<Mutation> actualWriteMutation = writeMutationCaptor.getValue();
assertThat(actualWriteMutation).containsExactlyElementsIn(testMutations);
} |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis);
} | @Test
public void shouldThrowOnGroupBy() {
// Given:
when(analysis.getGroupBy()).thenReturn(Optional.of(new GroupBy(
Optional.empty(),
ImmutableList.of(AN_EXPRESSION)
)));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> validator.validate(analysis)
);
// Then:
assertThat(e.getMessage(), containsString("Pull queries don't support GROUP BY clauses."));
} |
@Override
public PageResult<DictTypeDO> getDictTypePage(DictTypePageReqVO pageReqVO) {
return dictTypeMapper.selectPage(pageReqVO);
} | @Test
public void testGetDictTypePage() {
// mock 数据
DictTypeDO dbDictType = randomPojo(DictTypeDO.class, o -> { // 等会查询到
o.setName("yunai");
o.setType("芋艿");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setCreateTime(buildTime(2021, 1, 15));
});
dictTypeMapper.insert(dbDictType);
// 测试 name 不匹配
dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setName("tudou")));
// 测试 type 不匹配
dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setType("土豆")));
// 测试 status 不匹配
dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 createTime 不匹配
dictTypeMapper.insert(cloneIgnoreId(dbDictType, o -> o.setCreateTime(buildTime(2021, 1, 1))));
// 准备参数
DictTypePageReqVO reqVO = new DictTypePageReqVO();
reqVO.setName("nai");
reqVO.setType("艿");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime(buildBetweenTime(2021, 1, 10, 2021, 1, 20));
// 调用
PageResult<DictTypeDO> pageResult = dictTypeService.getDictTypePage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbDictType, pageResult.getList().get(0));
} |
@Deprecated
public long searchOffset(final String addr, final String topic, final int queueId, final long timestamp,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
requestHeader.setTimestamp(timestamp);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
SearchOffsetResponseHeader responseHeader =
(SearchOffsetResponseHeader) response.decodeCommandCustomHeader(SearchOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark(), addr);
} | @Test
public void testSearchOffset() throws Exception {
doAnswer((Answer<RemotingCommand>) mock -> {
RemotingCommand request = mock.getArgument(1);
final RemotingCommand response = RemotingCommand.createResponseCommand(SearchOffsetResponseHeader.class);
final SearchOffsetResponseHeader responseHeader = (SearchOffsetResponseHeader) response.readCustomHeader();
responseHeader.setOffset(100L);
response.makeCustomHeaderToNet();
response.setCode(ResponseCode.SUCCESS);
response.setOpaque(request.getOpaque());
return response;
}).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong());
long offset = mqClientAPI.searchOffset(brokerAddr, topic, 0, System.currentTimeMillis() - 1000, 10000);
assertThat(offset).isEqualTo(100L);
} |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoundException("This ClassLoader is closed");
}
if (config.shouldAcquire(name)) {
loadedClass =
PerfStatsCollector.getInstance()
.measure("load sandboxed class", () -> maybeInstrumentClass(name));
} else {
loadedClass = getParent().loadClass(name);
}
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
} | @Test
public void shouldDelegateToHandlerForConstructors() throws Exception {
Class<?> clazz = loadClass(AClassWithNoDefaultConstructor.class);
Constructor<?> ctor = clazz.getDeclaredConstructor(String.class);
assertThat(Modifier.isPublic(ctor.getModifiers())).isFalse();
ctor.setAccessible(true);
Object instance = ctor.newInstance("new one");
assertThat(transcript)
.containsExactly(
"methodInvoked: AClassWithNoDefaultConstructor.__constructor__(java.lang.String new"
+ " one)");
Field nameField = clazz.getDeclaredField("name");
nameField.setAccessible(true);
assertNull(nameField.get(instance));
} |
public ContainerBuildPlan toContainerBuildPlan() {
return containerBuildPlanBuilder.build();
} | @Test
public void testToContainerBuildPlan_default() throws InvalidImageReferenceException {
ImageConfiguration imageConfiguration =
ImageConfiguration.builder(ImageReference.parse("base/image")).build();
JibContainerBuilder containerBuilder =
new JibContainerBuilder(imageConfiguration, spyBuildContextBuilder);
ContainerBuildPlan buildPlan = containerBuilder.toContainerBuildPlan();
Assert.assertEquals("base/image", buildPlan.getBaseImage());
Assert.assertEquals(ImmutableSet.of(new Platform("amd64", "linux")), buildPlan.getPlatforms());
Assert.assertEquals(Instant.EPOCH, buildPlan.getCreationTime());
Assert.assertEquals(ImageFormat.Docker, buildPlan.getFormat());
Assert.assertEquals(Collections.emptyMap(), buildPlan.getEnvironment());
Assert.assertEquals(Collections.emptyMap(), buildPlan.getLabels());
Assert.assertEquals(Collections.emptySet(), buildPlan.getVolumes());
Assert.assertEquals(Collections.emptySet(), buildPlan.getExposedPorts());
Assert.assertNull(buildPlan.getUser());
Assert.assertNull(buildPlan.getWorkingDirectory());
Assert.assertNull(buildPlan.getEntrypoint());
Assert.assertNull(buildPlan.getCmd());
Assert.assertEquals(Collections.emptyList(), buildPlan.getLayers());
} |
@Override
public int hashCode() {
return hashCode;
} | @Test
void assertDifferentHashCode() {
assertThat(new Grantee("name", "").hashCode(), not(new Grantee("name", "127.0.0.1").hashCode()));
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
try {
return serializer.serialize(topic, jsonValue);
} catch (SerializationException e) {
throw new DataException("Converting Kafka Connect data to byte[] failed due to serialization error: ", e);
}
} | @Test
public void nullSchemaAndMapToJson() {
// This still needs to do conversion of data, null schema means "anything goes". Make sure we mix and match
// types to verify conversion still works.
Map<String, Object> input = new HashMap<>();
input.put("key1", 12);
input.put("key2", "string");
input.put("key3", true);
JsonNode converted = parse(converter.fromConnectData(TOPIC, null, input));
validateEnvelopeNullSchema(converted);
assertTrue(converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME).isNull());
assertEquals(JsonNodeFactory.instance.objectNode().put("key1", 12).put("key2", "string").put("key3", true),
converted.get(JsonSchema.ENVELOPE_PAYLOAD_FIELD_NAME));
} |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchMapValue() {
assertThrows(DataException.class,
() -> ConnectSchema.validateValue(MAP_INT_STRING_SCHEMA, Collections.singletonMap(1, 2)));
} |
public void setHeader(Header header) {
this.header = header;
} | @Test
void testSetHeader() {
HttpRestResult<String> result = new HttpRestResult<>();
result.setData("test data");
Header header = Header.newInstance();
result.setHeader(header);
assertEquals(header, result.getHeader());
assertEquals("test data", result.getData());
} |
public static <T, ComparatorT extends Comparator<T> & Serializable>
Combine.Globally<T, List<T>> of(int count, ComparatorT compareFn) {
return Combine.globally(new TopCombineFn<>(count, compareFn));
} | @Test
public void testTopEmptyWithIncompatibleWindows() {
p.enableAbandonedNodeEnforcement(false);
Window<String> windowingFn = Window.into(FixedWindows.of(Duration.standardDays(10L)));
PCollection<String> input = p.apply(Create.empty(StringUtf8Coder.of())).apply(windowingFn);
expectedEx.expect(IllegalStateException.class);
expectedEx.expectMessage("Top");
expectedEx.expectMessage("GlobalWindows");
expectedEx.expectMessage("withoutDefaults");
expectedEx.expectMessage("asSingletonView");
input.apply(Top.of(1, new OrderByLength()));
} |
public static Sensor getInvocationSensor(
final Metrics metrics,
final String sensorName,
final String groupName,
final String functionDescription
) {
final Sensor sensor = metrics.sensor(sensorName);
if (sensor.hasMetrics()) {
return sensor;
}
final BiFunction<String, String, MetricName> metricNamer = (suffix, descPattern) -> {
final String description = String.format(descPattern, functionDescription);
return metrics.metricName(sensorName + "-" + suffix, groupName, description);
};
sensor.add(
metricNamer.apply("avg", AVG_DESC),
new Avg()
);
sensor.add(
metricNamer.apply("max", MAX_DESC),
new Max()
);
sensor.add(
metricNamer.apply("count", COUNT_DESC),
new WindowedCount()
);
sensor.add(
metricNamer.apply("rate", RATE_DESC),
new Rate(TimeUnit.SECONDS, new WindowedCount())
);
return sensor;
} | @Test
public void shouldRegisterCountMetric() {
// Given:
when(metrics.metricName(SENSOR_NAME + "-count", GROUP_NAME, description(COUNT_DESC)))
.thenReturn(specificMetricName);
// When:
FunctionMetrics
.getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME);
// Then:
verify(sensor).add(eq(specificMetricName), isA(WindowedCount.class));
} |
public static <T> T[] addAll(final T[] array1, @SuppressWarnings("unchecked") final T... array2) {
if (array1 == null) {
return clone(array2);
} else if (array2 == null) {
return clone(array1);
}
final Class<?> type1 = array1.getClass().getComponentType();
@SuppressWarnings("unchecked")
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
try {
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
} catch (final ArrayStoreException ase) {
final Class<?> type2 = array2.getClass().getComponentType();
if (!type1.isAssignableFrom(type2)) {
throw new IllegalArgumentException("Cannot store " + type2.getName() + " in an array of "
+ type1.getName(), ase);
}
throw ase;
}
return joinedArray;
} | @Test
public void assertAddAll() {
String[] array = new String[]{"1"};
Assert.isTrue(ArrayUtil.addAll(array, null).length == 1);
Assert.isTrue(ArrayUtil.addAll(null, array).length == 1);
Assert.isTrue(ArrayUtil.addAll(array, new String[]{"1"}).length == 2);
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatNullLiteral() {
assertThat(ExpressionFormatter.formatExpression(new NullLiteral()), equalTo("null"));
} |
@Transactional
public Spending updateSpending(Long spendingId, SpendingReq request) {
Spending spending = spendingService.readSpending(spendingId).orElseThrow(() -> new SpendingErrorException(SpendingErrorCode.NOT_FOUND_SPENDING));
SpendingCustomCategory customCategory = (request.isCustomCategory())
? spendingCustomCategoryService.readSpendingCustomCategory(request.categoryId()).orElseThrow(() -> new SpendingErrorException(SpendingErrorCode.NOT_FOUND_CUSTOM_CATEGORY))
: null;
spending.update(request.amount(), request.icon(), request.spendAt().atStartOfDay(), request.accountName(), request.memo(), customCategory);
return spending;
} | @DisplayName("커스텀 카테고리를 사용한 지출 내역으로 수정할 시, 커스텀 카테고리를 포함하는 지출내역으로 Spending 객체가 수정 된다.")
@Test
void testUpdateSpendingWithCustomCategory() {
// given
Long spendingId = 1L;
given(spendingService.readSpending(spendingId)).willReturn(Optional.of(spending));
given(spendingCustomCategoryService.readSpendingCustomCategory(1L)).willReturn(Optional.of(customCategory));
// when - then
assertDoesNotThrow(() -> spendingUpdateService.updateSpending(spendingId, requestWithCustomCategory));
assertNotNull(spending.getSpendingCustomCategory());
} |
@Udf
public String uuid() {
return java.util.UUID.randomUUID().toString();
} | @Test
public void shouldHaveCorrectOutputFormat() {
// aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
final String anUuid = udf.uuid();
assertThat(anUuid.length(), is(36));
assertThat(anUuid.charAt(8), is('-'));
assertThat(anUuid.charAt(13), is('-'));
assertThat(anUuid.charAt(18), is('-'));
assertThat(anUuid.charAt(23), is('-'));
for (final char c : anUuid.toCharArray()) {
assertThat(c, isIn(Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', '-')));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.