focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Range<T> rangeContaining(long key, long value) {
BitSet rangeBitSet = rangeBitSetMap.get(key);
if (rangeBitSet != null) {
if (!rangeBitSet.get(getSafeEntry(value))) {
// if position is not part of any range then return null
return null;
... | @Test
public void testRangeContaining() {
OpenLongPairRangeSet<LongPair> set = new OpenLongPairRangeSet<>(consumer);
set.add(Range.closed(new LongPair(0, 98), new LongPair(0, 99)));
set.add(Range.closed(new LongPair(0, 100), new LongPair(1, 5)));
com.google.common.collect.RangeSet<Lo... |
public static InputConsumableDecider.Factory loadInputConsumableDeciderFactory(
HybridPartitionDataConsumeConstraint hybridPartitionDataConsumeConstraint) {
switch (hybridPartitionDataConsumeConstraint) {
case ALL_PRODUCERS_FINISHED:
return AllFinishedInputConsumableDecid... | @Test
void testLoadInputConsumableDeciderFactory() {
assertAndLoadInputConsumableDecider(
UNFINISHED_PRODUCERS, DefaultInputConsumableDecider.Factory.INSTANCE);
assertAndLoadInputConsumableDecider(
ONLY_FINISHED_PRODUCERS, PartialFinishedInputConsumableDecider.Factory... |
long trySend(long now) {
long pollDelayMs = maxPollTimeoutMs;
// send any requests that can be sent now
for (Node node : unsent.nodes()) {
Iterator<ClientRequest> iterator = unsent.requestIterator(node);
if (iterator.hasNext())
pollDelayMs = Math.min(poll... | @Test
public void testTrySend() {
final AtomicBoolean isReady = new AtomicBoolean();
final AtomicInteger checkCount = new AtomicInteger();
client = new MockClient(time, metadata) {
@Override
public boolean ready(Node node, long now) {
checkCount.increm... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final DefaultPacketRequest other = (DefaultPacketRequest) obj;
return Objects.equals(this.selecto... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(packetRequest1, sameAsacketRequest1)
.addEqualityGroup(packetRequest2)
.addEqualityGroup(packetRequest3)
.addEqualityGroup(packetRequest4)
.testEquals();
... |
@Override
public void unsubscribeService(Service service, Subscriber subscriber, String clientId) {
throw new UnsupportedOperationException("No persistent subscribers");
} | @Test
void testUnsubscribeService() {
assertThrows(UnsupportedOperationException.class, () -> {
persistentClientOperationServiceImpl.unsubscribeService(service, subscriber, clientId);
});
} |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowStatement) {
return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s... | @Test
void assertCreateWithDMLStatement() {
DeleteStatementContext sqlStatementContext = new DeleteStatementContext(new PostgreSQLDeleteStatement(), DefaultDatabase.LOGIC_NAME);
assertThat(new PostgreSQLAdminExecutorCreator().create(sqlStatementContext, "delete from t where id = 1", "", Collections.... |
@Override
public WorkerIdentity get() {
// Look at configurations first
if (mConf.isSetByUser(PropertyKey.WORKER_IDENTITY_UUID)) {
String uuidStr = mConf.getString(PropertyKey.WORKER_IDENTITY_UUID);
final WorkerIdentity workerIdentity = WorkerIdentity.ParserV1.INSTANCE.fromUUID(uuidStr);
LOG... | @Test
public void autoGenerateIfIdFilePathNotSetAndFileNotExists() throws Exception {
AlluxioProperties props = new AlluxioProperties();
props.put(PropertyKey.WORKER_IDENTITY_UUID_FILE_PATH, mUuidFilePath.toString(), Source.DEFAULT);
// put the identity in a file in the same directory but with a different... |
public static Resource getResource(File workingDir, String path) {
if (path.startsWith(Resource.CLASSPATH_COLON)) {
path = removePrefix(path);
File file = classPathToFile(path);
if (file != null) {
return new FileResource(file, true, path);
}
... | @Test
void testResolveRelativeClassPathFile() {
Resource temp = ResourceUtils.getResource(new File(""), "classpath:com/intuit/karate/resource/dir1/dir1.log");
Resource resource = temp.resolve("../dir2/dir2.log");
assertTrue(resource.isFile());
assertTrue(resource.isClassPath());
... |
public PropertyPanel addProp(String key, String label, String value) {
properties.add(new Prop(key, label, value));
return this;
} | @Test
public void intValues() {
basic();
pp.addProp(KEY_A, KEY_A, 200)
.addProp(KEY_B, KEY_B, 2000)
.addProp(KEY_C, KEY_C, 1234567);
validateProp(KEY_A, "200");
validateProp(KEY_B, "2,000");
validateProp(KEY_C, "1,234,567");
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final ReadOnlySessionStore<GenericKey, GenericRow> store = sta... | @Test
public void shouldReturnValueIfSessionEndsAtUpperBoundIfUpperBoundClosed() {
// Given:
final Range<Instant> endBounds = Range.closed(
LOWER_INSTANT,
UPPER_INSTANT
);
final Instant wstart = UPPER_INSTANT.minusMillis(1);
givenSingleSession(wstart, UPPER_INSTANT);
// When:... |
public void createView(View view, boolean replace, boolean ifNotExists) {
if (ifNotExists) {
relationsStorage.putIfAbsent(view.name(), view);
} else if (replace) {
relationsStorage.put(view.name(), view);
} else if (!relationsStorage.putIfAbsent(view.name(), view)) {
... | @Test
public void when_createsDuplicateViewsIfReplaceAndIfNotExists_then_succeeds() {
// given
View view = view();
// when
catalog.createView(view, true, true);
// then
verify(relationsStorage).putIfAbsent(eq(view.name()), isA(View.class));
} |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_DATE_ASC_NulPubDatel() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DATE_OLD_NEW);
List<FeedItem> itemList = getTestList();
itemList.get(2) // itemId 2
.setPubDate(null);
assertTrue(checkIdOrder(itemLis... |
@Override
synchronized public boolean cd(String directory) {
if (StrUtil.isBlank(directory)) {
// 当前目录
return true;
}
try {
return client.changeWorkingDirectory(directory);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | @Test
@Disabled
public void cdTest() {
final Ftp ftp = new Ftp("looly.centos");
ftp.cd("/file/aaa");
Console.log(ftp.pwd());
IoUtil.close(ftp);
} |
@Override
protected void write(final MySQLPacketPayload payload) {
payload.writeInt1(STATUS);
payload.writeInt4(statementId);
// TODO Column Definition Block should be added in future when the meta data of the columns is cached.
payload.writeInt2(columnCount);
payload.writeIn... | @Test
void assertWrite() {
MySQLComStmtPrepareOKPacket actual = new MySQLComStmtPrepareOKPacket(1, 0, 1, 0);
actual.write(payload);
verify(payload).writeInt1(0x00);
verify(payload, times(2)).writeInt2(0);
verify(payload).writeInt2(1);
verify(payload).writeInt4(1);
... |
public final void isLessThan(int other) {
asDouble.isLessThan(other);
} | @Test
public void isLessThan_int() {
expectFailureWhenTestingThat(2.0f).isLessThan(2);
assertThat(2.0f).isLessThan(3);
assertThat(0x1.0p30f).isLessThan((1 << 30) + 1);
} |
public abstract boolean compare(A actual, E expected); | @Test
public void testTransforming_both_compare_nullTransformedValue() {
assertThat(HYPHENS_MATCH_COLONS.compare("mailing-list", "abcdefg-hij")).isFalse();
assertThat(HYPHENS_MATCH_COLONS.compare("forum", "abcde:fghij")).isFalse();
assertThat(HYPHENS_MATCH_COLONS.compare("forum", "abcde-fghij")).isTrue();... |
public static LinkExtractorParser getParser(String parserClassName)
throws LinkExtractorParseException {
// Is there a cached parser?
LinkExtractorParser parser = PARSERS.get(parserClassName);
if (parser != null) {
LOG.debug("Fetched {}", parserClassName);
re... | @Test
public void testNotReusableCache() throws Exception {
assertNotSame(BaseParser.getParser(NotReusableParser.class.getCanonicalName()), BaseParser.getParser(NotReusableParser.class.getCanonicalName()));
} |
public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException {
return new InputStream() {
private int mPosition = 0;
private int mMark = 0;
private final int mLimit = Math.min(limit, is.available());
@Override
... | @Test
void testLimitedInputStream() throws Exception {
InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt");
assertThat(10, is(is.available()));
is = StreamUtils.limitedInputStream(is, 2);
assertThat(2, is(is.available()));
assertThat(is.markSup... |
public static InetSocketAddress parseAddress(String address, int defaultPort) {
return parseAddress(address, defaultPort, false);
} | @Test
void parseAddressBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> AddressUtils.parseAddress(null, 0))
.withMessage("address");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> AddressUtils.parseAddress("address", -1))
.withMessa... |
public static void initRequestFromEntity(HttpRequestBase requestBase, Map<String, String> body, String charset)
throws Exception {
if (body == null || body.isEmpty()) {
return;
}
List<NameValuePair> params = new ArrayList<>(body.size());
for (Map.Entry<String, Str... | @Test
void testInitRequestFromEntity5() throws Exception {
HttpDelete httpDelete = new HttpDelete("");
HttpUtils.initRequestFromEntity(httpDelete, Collections.singletonMap("k", "v"), "UTF-8");
// nothing change
assertEquals(new HttpDelete("").getMethod(), httpDelete... |
@Delete(uri = "/{executionId}")
@ExecuteOn(TaskExecutors.IO)
@Operation(tags = {"Executions"}, summary = "Delete an execution")
@ApiResponse(responseCode = "204", description = "On success")
public HttpResponse<Void> delete(
@Parameter(description = "The execution id") @PathVariable String execu... | @Test
void delete() {
Execution result = triggerInputsFlowExecution(true);
var response = client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/executions/" + result.getId()));
assertThat(response.getStatus(), is(HttpStatus.NO_CONTENT));
var notFound = assertThrows(HttpClientRes... |
@Override
public <R> R run(Action<R, C, E> action) throws E, InterruptedException {
return run(action, retryByDefault);
} | @Test
public void testNoRetryingNonRetryableException() {
try (MockClientPoolImpl mockClientPool =
new MockClientPoolImpl(2, RetryableException.class, true, 3)) {
assertThatThrownBy(() -> mockClientPool.run(MockClient::failWithNonRetryable, true))
.isInstanceOf(NonRetryableException.class)... |
public static VersionRange parse(String rangeString) {
validateRangeString(rangeString);
Inclusiveness minVersionInclusiveness =
rangeString.startsWith("[") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE;
Inclusiveness maxVersionInclusiveness =
rangeString.endsWith("]") ? Inclusiveness... | @Test
public void parse_withEmptyRangeString_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> VersionRange.parse(""));
assertThat(exception).hasMessageThat().isEqualTo("Range string cannot be empty.");
} |
@Override
public void abortLm(MdId mdName, MaIdShort maName, MepId mepId)
throws CfmConfigException {
throw new UnsupportedOperationException("Not yet implemented");
} | @Test
public void testAbortAllLmOnMep() throws CfmConfigException {
//TODO: Implement underlying method
try {
soamManager.abortLm(MDNAME1, MANAME1, MEPID1);
fail("Expecting UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
} |
public static File openFile(String path, String fileName) {
return openFile(path, fileName, false);
} | @Test
void testOpenFileWithPath() {
File file = DiskUtils.openFile(testFile.getParent(), testFile.getName(), false);
assertNotNull(file);
assertEquals(testFile.getPath(), file.getPath());
assertEquals(testFile.getName(), file.getName());
} |
static ImmutableList<PushImageStep> makeListForManifestList(
BuildContext buildContext,
ProgressEventDispatcher.Factory progressEventDispatcherFactory,
RegistryClient registryClient,
ManifestTemplate manifestList,
boolean manifestListAlreadyExists)
throws IOException {
Set<String... | @Test
public void testMakeListForManifestList_manifestListAlreadyExists() throws IOException {
System.setProperty(JibSystemProperties.SKIP_EXISTING_IMAGES, "true");
List<PushImageStep> pushImageStepList =
PushImageStep.makeListForManifestList(
buildContext, progressDispatcherFactory, regi... |
Map<Path, Set<Integer>> changedLines() {
return tracker.changedLines();
} | @Test
public void count_multiple_added_lines() throws IOException {
String example = "Index: sample1\n"
+ "===================================================================\n"
+ "--- a/sample1\n"
+ "+++ b/sample1\n"
+ "@@ -1 +1,3 @@\n"
+ " same line\n"
+ "+added line 1\n"
... |
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException {
YamlJDBCConfiguration rootConfig = YamlEngine.unmarshal(yamlFile, YamlJDBCConfiguration.class);
return createDataSource(new YamlDataSourceConfigurationSwapper().swapToDataSources(rootConfig.getDataSources()... | @Test
void assertCreateDataSourceWithBytes() throws SQLException, IOException {
assertDataSource(YamlShardingSphereDataSourceFactory.createDataSource(readFile(getYamlFileUrl()).getBytes()));
} |
public List<Expr> getPartitionExprs(Map<ColumnId, Column> idToColumn) {
List<Expr> result = new ArrayList<>(partitionExprs.size());
for (ColumnIdExpr columnIdExpr : partitionExprs) {
result.add(columnIdExpr.convertToColumnNameExpr(idToColumn));
}
return result;
} | @Test
public void testExpressionRangePartitionInfoSerialized_FunctionExpr() throws Exception {
ConnectContext ctx = starRocksAssert.getCtx();
String createSQL = "CREATE TABLE table_hitcount (\n" +
"databaseName varchar(200) NULL COMMENT \"\",\n" +
"tableName varchar(2... |
@Override
public KubevirtNode removeNode(String hostname) {
checkArgument(!Strings.isNullOrEmpty(hostname), ERR_NULL_HOSTNAME);
KubevirtNode node = nodeStore.removeNode(hostname);
log.info(String.format(MSG_NODE, hostname, MSG_REMOVED));
return node;
} | @Test(expected = IllegalArgumentException.class)
public void testRemoveNullNode() {
target.removeNode(null);
} |
public SubsetItem getClientsSubset(String serviceName,
int minClusterSubsetSize,
int partitionId,
Map<URI, Double> possibleUris,
long version,
SimpleLoadBalancerState state)
{
SubsettingStrategy<URI> subsettingStrategy = _subsettingStrategyFactory.get(serviceName, minClusterSubsetSiz... | @Test
public void testMultiThreadCase() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(THREAD_NUM * 3);
Mockito.when(_subsettingMetadataProvider.getSubsettingMetadata(_state))
.thenReturn(new DeterministicSubsettingMetadata(0, 5, 0));
for (int i = 0; i < THREAD_NUM... |
public static void convertFromLegacyTableConfig(TableConfig tableConfig) {
// It is possible that indexing as well as ingestion configs exist, in which case we always honor ingestion config.
IngestionConfig ingestionConfig = tableConfig.getIngestionConfig();
BatchIngestionConfig batchIngestionConfig =
... | @Test
public void testConvertFromLegacyTableConfig() {
String expectedPushFrequency = "HOURLY";
String expectedPushType = "APPEND";
Map<String, String> expectedStreamConfigsMap = getTestStreamConfigs();
TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(TABLE_NAME)
... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchError() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
assertFalse(fetcher.hasCompletedFetches());
client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NOT_LEADER_O... |
public static void sleep(long timeMs) {
accept(SLEEP, timeMs);
} | @Test
public void testSleep() {
final long start = System.currentTimeMillis();
CommonUtils.sleep(SLEEP_TIME);
final long end = System.currentTimeMillis();
// There is an error, and the error value is 20 ms before and after
assertTrue((end - start < SLEEP_TIME + DIFF) || (end... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldInjectForCtStatement() {
// Given:
givenKeyAndValueInferenceSupported();
// When:
final ConfiguredStatement<CreateTable> result = injector.inject(ctStatement);
// Then:
assertThat(result.getStatement().getElements(),
is(combineElements(INFERRED_KSQL_KEY_SCHEMA... |
public static Namespace of(String... levels) {
Preconditions.checkArgument(null != levels, "Cannot create Namespace from null array");
if (levels.length == 0) {
return empty();
}
for (String level : levels) {
Preconditions.checkNotNull(level, "Cannot create a namespace with a null level");
... | @Test
public void testWithNullInLevel() {
assertThatThrownBy(() -> Namespace.of("a", null, "b"))
.isInstanceOf(NullPointerException.class)
.hasMessage("Cannot create a namespace with a null level");
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseNestedArray() {
SchemaAndValue schemaAndValue = Values.parseString("[[]]");
assertEquals(Type.ARRAY, schemaAndValue.schema().type());
assertEquals(Type.ARRAY, schemaAndValue.schema().valueSchema().type());
} |
public static List<WeightedHostAddress> prioritize(WeightedHostAddress[] records) {
final List<WeightedHostAddress> result = new LinkedList<>();
// sort by priority (ascending)
SortedMap<Integer, Set<WeightedHostAddress>> byPriority = new TreeMap<>();
for(final WeightedHostAddress recor... | @Test
public void testOneHostZeroWeight() throws Exception {
// setup
final DNSUtil.WeightedHostAddress host = new DNSUtil.WeightedHostAddress("host", 5222, false, 1, 0);
// do magic
final List<DNSUtil.WeightedHostAddress> result = DNSUtil.prioritize(new DNSUtil.WeightedHostAddress[... |
static String getPoolNameFromPodName(String clusterName, String podName) {
return podName.substring(clusterName.length() + 1, podName.lastIndexOf("-"));
} | @Test
public void testPoolNameFromPodName() {
assertThat(ReconcilerUtils.getPoolNameFromPodName("my-cluster", "my-cluster-brokers-2"), is("brokers"));
assertThat(ReconcilerUtils.getPoolNameFromPodName("my-cluster", "my-cluster-new-brokers-2"), is("new-brokers"));
assertThat(ReconcilerUtils.g... |
@Override
public Connection connect(String url, Properties info) throws SQLException {
// calciteConnection is initialized with an empty Beam schema,
// we need to populate it with pipeline options, load table providers, etc
return JdbcConnection.initialize((CalciteConnection) super.connect(url, info));
... | @Test
public void testSelectsFromExistingComplexTable() throws Exception {
TestTableProvider tableProvider = new TestTableProvider();
Connection connection = JdbcDriver.connect(tableProvider, PipelineOptionsFactory.create());
connection
.createStatement()
.executeUpdate(
"CREA... |
@Override
public void write(DataOutput out) throws IOException {
super.write(out);
writeToOutput(out);
} | @Test
public void testWrite() throws IOException {
// create a mock for DataOutput that will be used in the write method
// this way we can capture and verify if correct arguments were passed
DataOutput out = mock(DataOutput.class);
// register expected method calls for void functions
// so that ... |
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("BUILDKITE_COMMIT");
return new CiConfigurationImpl(revision, getName());
} | @Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("BUILDKITE", "true");
setEnvVariable("BUILDKITE_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
} |
@Override
public String toEncrypted(final Session<?> session, final String directoryId, final String filename, final EnumSet<Path.Type> type) throws BackgroundException {
final String ciphertextName = cryptomator.getFileNameCryptor().encryptFilename(BaseEncoding.base64Url(),
filename, directoryI... | @Test(expected = NotfoundException.class)
public void testToEncryptedInvalidArgument() throws Exception {
final Path home = new Path("/vault", EnumSet.of(Path.Type.directory));
final CryptoVault vault = new CryptoVault(home);
final CryptoDirectory provider = new CryptoDirectoryV7Provider(hom... |
public static void createNewFile(String filePath) throws IOException {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
if (!file.getParentFile().exists()) {
createParentFile(file);
}
file.createNewFile();
} | @Test
public void createNewFile() throws IOException {
// create new file
FileUtils.createNewFile("/tmp/test.txt");
Assertions.assertEquals("", FileUtils.readFileToStr(Paths.get("/tmp/test.txt")));
// delete exist file and create new file
FileUtils.writeStringToFile("/tmp/te... |
public static String getTaskManagerShellCommand(
org.apache.flink.configuration.Configuration flinkConfig,
ContaineredTaskManagerParameters tmParams,
String configDirectory,
String logDirectory,
boolean hasLogback,
boolean hasLog4j,
boo... | @Test
void testGetTaskManagerShellCommand() {
final Configuration cfg = new Configuration();
final TaskExecutorProcessSpec taskExecutorProcessSpec =
new TaskExecutorProcessSpec(
new CPUResource(1.0),
new MemorySize(0), // frameworkHeapS... |
@Override
public CompletableFuture<Collection<TaskManagerLocation>> getPreferredLocations(
final ExecutionVertexID executionVertexId,
final Set<ExecutionVertexID> producersToIgnore) {
checkNotNull(executionVertexId);
checkNotNull(producersToIgnore);
final Collection... | @Test
void testInputLocationsChoosesInputOfFewerLocations() {
final TestingInputsLocationsRetriever.Builder locationRetrieverBuilder =
new TestingInputsLocationsRetriever.Builder();
final ExecutionVertexID consumerId = new ExecutionVertexID(new JobVertexID(), 0);
int parall... |
public static int checkPositive(int i, String name) {
if (i <= INT_ZERO) {
throw new IllegalArgumentException(name + " : " + i + " (expected: > 0)");
}
return i;
} | @Test
public void testCheckPositiveFloatString() {
Exception actualEx = null;
try {
ObjectUtil.checkPositive(POS_ONE_FLOAT, NUM_POS_NAME);
} catch (Exception e) {
actualEx = e;
}
assertNull(actualEx, TEST_RESULT_NULLEX_NOK);
actualEx = null;
... |
public static Class findClassByName(String className) {
try {
return Class.forName(className);
} catch (Exception e) {
throw new NacosRuntimeException(SERVER_ERROR, "this class name not found");
}
} | @Test
void testFindClassByName2() {
assertThrows(NacosRuntimeException.class, () -> {
ClassUtils.findClassByName("not.exist.Class");
});
} |
@Override
public void putAll(Map<String, ?> vars) {
throw new UnsupportedOperationException();
} | @Test
public void testPutAllJMeterVariables() {
assertThrowsUnsupportedOperation(
() -> unmodifiables.putAll(vars));
} |
public Optional<UpdateCenter> getUpdateCenter() {
return getUpdateCenter(false);
} | @Test
public void cache_data() throws Exception {
when(reader.readString(new URI(URL_DEFAULT_VALUE), StandardCharsets.UTF_8)).thenReturn("sonar.versions=2.2,2.3");
underTest.getUpdateCenter();
underTest.getUpdateCenter();
verify(reader, times(1)).readString(new URI(URL_DEFAULT_VALUE), StandardCharse... |
@Nullable
String updateMessage(final String message)
{
final String[] messageWords = WHITESPACE_REGEXP.split(message);
boolean editedMessage = false;
for (int i = 0; i < messageWords.length; i++)
{
// Remove tags except for <lt> and <gt>
final String trigger = Text.removeFormattingTags(messageWords[i])... | @Test
public void testEmojiUpdateMessage()
{
String PARTY_POPPER = "<img=" + Emoji.getEmoji("@@@").ordinal() + '>';
String OPEN_MOUTH = "<img=" + Emoji.getEmoji(":O").ordinal() + '>';
assertNull(emojiPlugin.updateMessage("@@@@@"));
assertEquals(PARTY_POPPER, emojiPlugin.updateMessage("@@@"));
assertEquals(P... |
public List<Favorite> search(String userId, String appId, Pageable page) {
boolean isUserIdEmpty = Strings.isNullOrEmpty(userId);
boolean isAppIdEmpty = Strings.isNullOrEmpty(appId);
if (isAppIdEmpty && isUserIdEmpty) {
throw new BadRequestException("user id and app id can't be empty at the same time... | @Test(expected = BadRequestException.class)
@Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testSearchWithErrorParams() {
favoriteService.search(null, nu... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_of_a_single_line() {
duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 1), new TextBlock(2, 2));
setNewLines(FILE_1);
underTest.execute(new TestComputationStepContext());
assertRawMeasureValue(FI... |
public String getMetricsName() {
return metricsName;
} | @Test
public void testGetMetricsName() {
assertThat(endpoint.getMetricsName(), is(METRICS_NAME));
} |
public static DateTime parseRFC2822(CharSequence source) {
if (source == null) {
return null;
}
// issue#I9C2D4
if(StrUtil.contains(source, ',')){
if(StrUtil.contains(source, "星期")){
return parse(source, FastDateFormat.getInstance(DatePattern.HTTP_DATETIME_PATTERN, Locale.CHINA));
}
return pars... | @Test
public void parseRFC2822Test() {
final String dateStr = "Wed Sep 16 11:26:23 CST 2009";
final SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.US);
// Asia/Shanghai是以地区命名的地区标准时,在中国叫CST,因此如果解析CST时不使用"Asia/Shanghai"而使用"GMT+08:00",会导致相差一个小时
sdf.setTimeZone(TimeZone.getTi... |
static Set<String> findVariables(List<Statement> statements, EncodedValueLookup lookup) {
List<List<Statement>> groups = CustomModelParser.splitIntoGroup(statements);
Set<String> variables = new LinkedHashSet<>();
for (List<Statement> group : groups) findVariablesForGroup(variables, group, looku... | @Test
public void runVariables() {
DecimalEncodedValue prio1 = new DecimalEncodedValueImpl("my_priority", 5, 1, false);
IntEncodedValueImpl prio2 = new IntEncodedValueImpl("my_priority2", 5, -5, false, false);
EncodedValueLookup lookup = new EncodingManager.Builder().add(prio1).add(prio2).bu... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testFetchWithUnknownServerError() {
buildDependencies();
assignAndSeek(topicAPartition0);
// Try to data and validate that we get an empty Fetch back.
CompletedFetch completedFetch = completedFetchBuilder
.error(Errors.UNKNOWN_SERVER_ERROR)
... |
public QueryObjectBundle rewriteQuery(@Language("SQL") String query, QueryConfiguration queryConfiguration, ClusterType clusterType)
{
return rewriteQuery(query, queryConfiguration, clusterType, false);
} | @Test
public void testRewriteDate()
{
QueryBundle queryBundle = getQueryRewriter().rewriteQuery("SELECT date '2020-01-01', date(now()) today", CONFIGURATION, CONTROL);
assertCreateTableAs(queryBundle.getQuery(), "SELECT\n" +
" CAST(date '2020-01-01' AS timestamp)\n" +
... |
public String geomap() {
return get(GEOMAP, null);
} | @Test
public void setGeomap() {
loadLayout(L1);
assertEquals("map not brighton", UK_BRIGHTON, cfg.geomap());
cfg.geomap(NEW_MAP);
assertEquals("not new map", NEW_MAP, cfg.geomap());
cfg.geomap(null);
assertNull("geomap not cleared", cfg.geomap());
} |
@Operation(summary = "verifyResourceName", description = "VERIFY_RESOURCE_NAME_NOTES")
@Parameters({
@Parameter(name = "type", description = "RESOURCE_TYPE", required = true, schema = @Schema(implementation = ResourceType.class)),
@Parameter(name = "fullName", description = "RESOURCE_FULL_NA... | @Test
public void testVerifyResourceName() throws Exception {
Result mockResult = new Result<>();
mockResult.setCode(Status.TENANT_NOT_EXIST.getCode());
Mockito.when(resourcesService.verifyResourceName(Mockito.anyString(), Mockito.any(), Mockito.any()))
.thenReturn(mockResult... |
@Override
public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) {
for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) {
Map<String, ?> sourceOffset = offsetEntry.getValue();
if (sourceOffset == null)... | @Test
public void testAlterOffsetsMultiplePartitions() {
MirrorCheckpointConnector connector = new MirrorCheckpointConnector();
Map<String, ?> partition1 = sourcePartition("consumer-app-3", "t1", 0);
Map<String, ?> partition2 = sourcePartition("consumer-app-4", "t1", 1);
Map<Map<St... |
public static InternalRequestSignature fromHeaders(Crypto crypto, byte[] requestBody, HttpHeaders headers) {
if (headers == null) {
return null;
}
String signatureAlgorithm = headers.getHeaderString(SIGNATURE_ALGORITHM_HEADER);
String encodedSignature = headers.getHeaderStri... | @Test
public void fromHeadersShouldThrowExceptionOnInvalidBase64Signature() {
assertThrows(BadRequestException.class, () -> InternalRequestSignature.fromHeaders(crypto, REQUEST_BODY,
internalRequestHeaders("not valid base 64", SIGNATURE_ALGORITHM)));
} |
public void createUsersWithListInput(List<User> body) throws RestClientException {
createUsersWithListInputWithHttpInfo(body);
} | @Test
public void createUsersWithListInputTest() {
List<User> body = null;
api.createUsersWithListInput(body);
// TODO: test validations
} |
@ProcessElement
public void processElement(OutputReceiver<InitialPipelineState> receiver) throws IOException {
LOG.info(daoFactory.getStreamTableDebugString());
LOG.info(daoFactory.getMetadataTableDebugString());
LOG.info("ChangeStreamName: " + daoFactory.getChangeStreamName());
boolean resume = fals... | @Test
public void testInitializeStopWithoutDNP() throws IOException {
// DNP row doesn't exist, so we don't need to stop the pipeline. But some random data row with
// the same prefix exists. We want to make sure we clean it up even in "STOP" option.
dataClient.mutateRow(
RowMutation.create(
... |
public static String getVersion() {
return VERSION;
} | @Test
public void testFromDefaultVersion() {
String version = VersionUtils.getVersion();
assertNotNull(version);
} |
@Override
public GenericRow apply(final GenericRow left, final GenericRow right) {
final GenericRow row = new GenericRow(leftCount + rightCount + additionalCount);
if (left != null) {
row.appendAll(left.values());
} else {
fillWithNulls(row, leftCount);
}
if (right != null) {
... | @Test
public void shouldJoinValueLeftEmpty() {
final KsqlValueJoiner joiner = new KsqlValueJoiner(leftSchema.value().size(),
rightSchema.value().size(), 0
);
final GenericRow joined = joiner.apply(null, rightRow);
final List<Object> expected = Arrays.asList(null, null, 20L, "baz");
assert... |
@Override
public RelDataType deriveAvgAggType(RelDataTypeFactory typeFactory, RelDataType argumentType) {
switch (argumentType.getSqlTypeName()) {
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case DECIMAL:
return typeFact... | @Test
public void deriveAvgAggTypeTest() {
assertEquals(type(VARCHAR), HazelcastTypeSystem.INSTANCE.deriveAvgAggType(TYPE_FACTORY, type(VARCHAR)));
assertEquals(type(BOOLEAN), HazelcastTypeSystem.INSTANCE.deriveAvgAggType(TYPE_FACTORY, type(BOOLEAN)));
assertEquals(type(DECIMAL), HazelcastTy... |
@Override
public void start() {
if (!PluginConfigManager.getPluginConfig(DiscoveryPluginConfig.class).isEnableRegistry()) {
return;
}
final LbConfig lbConfig = PluginConfigManager.getPluginConfig(LbConfig.class);
maxSize = lbConfig.getMaxRetryConfigCache();
defaul... | @Test
public void start() {
retryService.start();
final Optional<Object> defaultRetry = ReflectUtils.getFieldValue(retryService, "defaultRetry");
Assert.assertTrue(defaultRetry.isPresent());
} |
public static Builder withSchema(Schema schema) {
return new Builder(schema);
} | @Test
public void testByteBufferEquality() {
byte[] a0 = new byte[] {1, 2, 3, 4};
byte[] b0 = new byte[] {1, 2, 3, 4};
Schema schema = Schema.of(Schema.Field.of("bytes", Schema.FieldType.BYTES));
Row a = Row.withSchema(schema).addValue(ByteBuffer.wrap(a0)).build();
Row b = Row.withSchema(schema)... |
public static String clusterPath(String basePath)
{
return String.format("%s/%s", normalizeBasePath(basePath), CLUSTER_PATH);
} | @Test (dataProvider = "clusterPaths")
public void testZKFSUtilClusterPath(String basePath, String clusterPath)
{
Assert.assertEquals(ZKFSUtil.clusterPath(basePath), clusterPath);
} |
@Override
public void run() {
try {
// We kill containers until the kernel reports the OOM situation resolved
// Note: If the kernel has a delay this may kill more than necessary
while (true) {
String status = cgroups.getCGroupParam(
CGroupsHandler.CGroupController.MEMORY,
... | @Test
public void testOneGuaranteedContainerOverLimitUponOOM() throws Exception {
ConcurrentHashMap<ContainerId, Container> containers =
new ConcurrentHashMap<>();
Container c1 = createContainer(1, true, 2L, true);
containers.put(c1.getContainerId(), c1);
Container c2 = createContainer(2, true... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final long beginTimeMills = this.brokerController.getMessageStore().now();
request.addExtFieldIfNotExist(BORN_TIME, String.valueOf(System.currentTimeMil... | @Test
public void testProcessRequest_TopicNotExist() throws RemotingCommandException {
when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig());
brokerController.getTopicConfigManager().getTopicConfigTable().remove(topic);
final RemotingCommand request = createPopMsgCo... |
@Override
public void unSubscribe(final AppAuthData appAuthData) {
SignAuthDataCache.getInstance().removeAuthData(appAuthData);
} | @Test
void unSubscribe() {
AppAuthData appAuthData = new AppAuthData();
appAuthData.setAppKey("D9FD95F496C9495DB5604222A13C3D08");
appAuthData.setAppSecret("02D25048AA1E466F8920E68B08E668DE");
appAuthData.setEnabled(true);
signAuthDataSubscriber.onSubscribe(appAuthData);
... |
@Description("Returns a \"simplified\" version of the given geometry")
@ScalarFunction("simplify_geometry")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice simplifyGeometry(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(DOUBLE) double distanceTolerance)
{
if (isNaN(distanceTolerance)) {
... | @Test
public void testSimplifyGeometry()
{
// Eliminate unnecessary points on the same line.
assertFunction("ST_AsText(simplify_geometry(ST_GeometryFromText('POLYGON ((1 0, 2 1, 3 1, 3 1, 4 1, 1 0))'), 1.5))", VARCHAR, "POLYGON ((1 0, 2 1, 4 1, 1 0))");
// Use distanceTolerance to contr... |
@Override
public AppResponse process(Flow flow, AppRequest request) {
appSession = new AppSession();
appSession.setState(State.INITIALIZED.name());
appSession.setActivationMethod(ActivationMethod.APP);
appSession.setFlow(ActivateAppWithOtherAppFlow.NAME);
appSession.setAction... | @Test
void processTest(){
AppResponse appResponse = startActivationWithOtherApp.process(mockedFlow, null);
verify(digidClientMock, times(1)).remoteLog("1365", ImmutableMap.of("", ""));
assertTrue(appResponse instanceof AppSessionResponse);
assertEquals(startActivationWithOtherApp.ge... |
public static Map<String, Object> map(String metricName, Metric metric) {
final Map<String, Object> metricMap = Maps.newHashMap();
metricMap.put("full_name", metricName);
metricMap.put("name", metricName.substring(metricName.lastIndexOf(".") + 1));
if (metric instanceof Timer) {
... | @Test
public void mapSupportsHdrHistogram() {
final HdrHistogram histogram = new HdrHistogram(1000L, 0);
histogram.update(23);
final Map<String, Object> map = MetricUtils.map("metric", histogram);
assertThat(map)
.containsEntry("type", "histogram")
.e... |
private Watch.Listener watch(final BiConsumer<String, String> updateHandler,
final Consumer<String> deleteHandler) {
return Watch.listener(response -> {
for (WatchEvent event : response.getEvents()) {
String path = event.getKeyValue().getKey().toStrin... | @Test
public void watchTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
BiConsumer<String, String> updateHandler = mock(BiConsumer.class);
Consumer<String> deleteHandler = mock(Consumer.class);
final Method watch = EtcdClient.class.getDeclaredMethod("w... |
@Override
public Flux<RawMetric> retrieve(KafkaCluster c, Node node) {
log.debug("Retrieving metrics from prometheus exporter: {}:{}", node.host(), c.getMetricsConfig().getPort());
MetricsConfig metricsConfig = c.getMetricsConfig();
var webClient = new WebClientConfigurator()
.configureBufferSize... | @Test
void callsMetricsEndpointAndConvertsResponceToRawMetric() {
var url = mockWebServer.url("/metrics");
mockWebServer.enqueue(prepareResponse());
MetricsConfig metricsConfig = prepareMetricsConfig(url.port(), null, null);
StepVerifier.create(retriever.retrieve(WebClient.create(), url.host(), metr... |
public static HintValueContext extractHint(final String sql) {
if (!containsSQLHint(sql)) {
return new HintValueContext();
}
HintValueContext result = new HintValueContext();
int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
String hintKeyValueText = sql.su... | @Test
void assertSQLHintDisableAuditNames() {
HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: DISABLE_AUDIT_NAMES=sharding_audit1 sharding_audit2 */");
assertThat(actual.getDisableAuditNames().size(), is(2));
assertTrue(actual.getDisableAuditNames().containsAll(Ar... |
@Override
public String toString() {
return "ControllerRegistration(id=" + id +
", incarnationId=" + incarnationId +
", zkMigrationReady=" + zkMigrationReady +
", listeners=[" +
listeners.keySet().stream().sorted().
map(... | @Test
public void testToString() {
assertEquals("ControllerRegistration(id=1, " +
"incarnationId=ubT_wuD6R3uopZ_lV76dQg, " +
"zkMigrationReady=true, " +
"listeners=[" +
"Endpoint(listenerName='PLAINTEXT', securityProtocol=PLAINTEXT, host='localhost', port=9108... |
protected void initializePipeline() {
// Set up rules for packet-out forwarding. We support only IPv4 routing.
final long cpuPort = capabilities.cpuPort().get();
flowRuleService.applyFlowRules(
ingressVlanRule(cpuPort, false, DEFAULT_VLAN),
fwdClassifierRule(cpuPo... | @Test
public void testInitializePipeline() {
final Capture<FlowRule> capturedCpuIgVlanRule = newCapture(CaptureType.ALL);
final Capture<FlowRule> capturedCpuFwdClsRule = newCapture(CaptureType.ALL);
// ingress_port_vlan table for cpu port
final TrafficSelector cpuIgVlanSelector = De... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldRunUnSetStatements() {
// Given:
final PreparedStatement<SetProperty> setProp = PreparedStatement.of("SET",
new SetProperty(Optional.empty(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"));
final PreparedStatement<UnsetProperty> unsetProp = PreparedStatement.of("UNS... |
public static <T> Bounded<T> from(BoundedSource<T> source) {
return new Bounded<>(null, source);
} | @Test
@Category({
NeedsRunner.class,
UsesUnboundedPCollections.class,
UsesUnboundedSplittableParDo.class
})
public void testUnboundedSdfWrapperCacheStartedReaders() {
long numElements = 1000L;
PCollection<Long> input =
pipeline.apply(Read.from(new ExpectCacheUnboundedSource(numElements... |
@ApiOperation(value = "Get Asset Profile names (getAssetProfileNames)",
notes = "Returns a set of unique asset profile names owned by the tenant."
+ TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "... | @Test
public void testGetAssetProfileNames() throws Exception {
var pageLink = new PageLink(Integer.MAX_VALUE);
var assetProfileInfos = doGetTypedWithPageLink("/api/assetProfileInfos?",
new TypeReference<PageData<AssetProfileInfo>>() {
}, pageLink);
Assert.ass... |
@Override
public void serialize(Asn1OutputStream out, String value) {
out.write(BCD.encode(value));
} | @Test
public void shouldSerialize() {
assertArrayEquals(
new byte[] { 0x01, 0x12 },
serialize(new BcdAsStringConverter(), String.class, "0112")
);
} |
@Around(CLIENT_INTERFACE_REMOVE_CONFIG_RPC)
Object removeConfigAroundRpc(ProceedingJoinPoint pjp, ConfigRemoveRequest request, RequestMeta meta)
throws Throwable {
final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.REMOVE_BY_RPC;
final List<ConfigChangeP... | @Test
void testRemoveConfigAroundRpcException() throws Throwable {
Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE);
ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class);
ConfigRemoveRequest request = ... |
public static Source flattenBaseSpecs(Source source) {
if (source.getBaseSpecs() == null) {
return source;
}
Map<String, Object> params = new HashMap<>();
for (Map<String, Object> baseSpec : source.getBaseSpecs()) {
params.putAll(baseSpec);
}
params.putAll(source.getSpec());
Sou... | @Test
public void testFlattenBaseSpecs() throws Exception {
// G = grandparent, P = parent, C = child.
CloudObject grandparent = CloudObject.forClassName("text");
addString(grandparent, "G", "g_g");
addString(grandparent, "GP", "gp_g");
addString(grandparent, "GC", "gc_g");
addString(grandpare... |
public static boolean overlapsOrdered(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) {
assert left.isDescending() == right.isDescending() : "Cannot compare pointer with different directions";
assert left.lastEntryKeyData == null && right.lastEntryKeyData == null : "Can m... | @Test
void overlapsOrderedSingleton() {
assertTrue(overlapsOrdered(pointer(singleton(5)), pointer(singleton(5)),
OrderedIndexStore.SPECIAL_AWARE_COMPARATOR), "singleton value should overlap with itself");
assertFalse(overlapsOrdered(pointer(singleton(5)), pointer(singleton(6)),
... |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = true,但是不通过
public void testApproveOrDeny_autoApproveNo() {
// 准备参数
String responseType = "code";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = randomString();
String state = randomStr... |
@Override
public double mean() {
return nu2 / (nu2 - 2.0);
} | @Test
public void testMean() {
System.out.println("mean");
FDistribution instance = new FDistribution(10, 20);
instance.rand();
assertEquals(10.0/9, instance.mean(), 1E-7);
} |
public static boolean isServiceRegistered() {
return INSTANCE != null;
} | @Test
public void isServiceRegisteredTest() {
assertFalse(OmemoService.isServiceRegistered());
} |
@Override
public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
// 校验旧密码密码
validateOldPassword(id, reqVO.getOldPassword());
// 执行更新
AdminUserDO updateObj = new AdminUserDO().setId(id);
updateObj.setPassword(encodePassword(reqVO.getNewPassword())); //... | @Test
public void testUpdateUserPassword_success() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO(o -> o.setPassword("encode:tudou"));
userMapper.insert(dbUser);
// 准备参数
Long userId = dbUser.getId();
UserProfileUpdatePasswordReqVO reqVO = randomPojo(UserProfileUp... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_FileKey() throws Exception {
Path path = getPath("secret.key");
String input = Paths.get("").toUri().relativize(path.toUri()).getPath();
String output = resolve("${readFile:" + input + "}");
assertThat(output, equalTo(FILE.lookup(input)));
assertThat... |
public PluginWrapper(PluginManager parent, File archive, Manifest manifest, URL baseResourceURL,
ClassLoader classLoader, File disableFile,
List<Dependency> dependencies, List<Dependency> optionalDependencies) {
this.parent = parent;
this.manifest = manifest;
this.shortNa... | @Test
public void jenkinsCoreTooOld() {
PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded();
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains(ex, "Failed to load: Fake (fake 42)", "Jenkins (3.0) or higher req... |
@Override
public List<String> listDbNames() {
return hmsOps.getAllDatabaseNames();
} | @Test
public void testListDbNames() {
List<String> databaseNames = hiveMetadata.listDbNames();
Assert.assertEquals(Lists.newArrayList("db1", "db2"), databaseNames);
CachingHiveMetastore queryLevelCache = CachingHiveMetastore.createQueryLevelInstance(cachingHiveMetastore, 100);
Assert... |
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
} | @Test
void handleFlowableTaskAlreadyClaimedExceptionWithoutSendFullErrorException() throws Exception {
testController.exceptionSupplier = () -> new FlowableTaskAlreadyClaimedException("task-2", "tester");
handlerAdvice.setSendFullErrorException(false);
String body = mockMvc.perform(get("/")... |
@Override
public void executeUpdate(final UnregisterStorageUnitStatement sqlStatement, final ContextManager contextManager) {
if (!sqlStatement.isIfExists()) {
checkExisted(sqlStatement.getStorageUnitNames());
}
checkInUsed(sqlStatement);
try {
contextManager.... | @Test
void assertExecuteUpdateWithStorageUnitInUsedWithIfExists() {
ShardingSphereRule rule = mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS);
DataSourceMapperRuleAttribute ruleAttribute = mock(DataSourceMapperRuleAttribute.class);
when(ruleAttribute.getDataSourceMapper()).thenReturn(Coll... |
@Override
public ExecuteContext after(ExecuteContext context) {
Object logStartupInfo = context.getMemberFieldValue("logStartupInfo");
if ((logStartupInfo instanceof Boolean) && (Boolean) logStartupInfo && INIT.compareAndSet(false, true)) {
final FlowControlInitServiceImpl service = Plug... | @Test
public void testStart() throws Exception {
final SpringApplicationInterceptor springApplicationInterceptor = new SpringApplicationInterceptor();
springApplicationInterceptor.after(buildContext());
Assert.assertTrue(executed.get());
} |
public List<TradeHistoryResponse> findTradeHistories(final Long memberId, final boolean isSeller) {
if (isSeller) {
return findHistories(memberId, tradeHistory.sellerId::eq);
}
return findHistories(memberId, tradeHistory.buyerId::eq);
} | @Test
void 구매자의_구매_내역을_조회한다() {
// when
List<TradeHistoryResponse> result = tradeHistoryQueryRepository.findTradeHistories(buyer.getId(), false);
// then
assertSoftly(softly -> {
softly.assertThat(result).hasSize(1);
softly.assertThat(result.get(0).buyerName(... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeInsertIntoCorrectly() {
final String output = anon.anonymize(
"INSERT INTO my_stream SELECT user_id, browser_cookie, ip_address\n"
+ "FROM another_stream\n"
+ "WHERE user_id = 4214\n"
+ "AND browser_cookie = 'aefde34ec'\n"
+ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.