focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public ApplicationBuilder environment(String environment) {
this.environment = environment;
return getThis();
} | @Test
void environment() {
ApplicationBuilder builder = new ApplicationBuilder();
Assertions.assertEquals("product", builder.build().getEnvironment());
builder.environment("develop");
Assertions.assertEquals("develop", builder.build().getEnvironment());
builder.environment("t... |
public int deleteById(ModelId id) {
final DBQuery.Query query = DBQuery.is(Identified.FIELD_META_ID, id);
final WriteResult<ContentPack, ObjectId> writeResult = dbCollection.remove(query);
return writeResult.getN();
} | @Test
@MongoDBFixtures("ContentPackPersistenceServiceTest.json")
public void deleteById() {
final int deletedContentPacks = contentPackPersistenceService.deleteById(ModelId.of("dcd74ede-6832-4ef7-9f69-deadbeef0000"));
final Set<ContentPack> contentPacks = contentPackPersistenceService.loadAll();... |
@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 shouldInjectValuesAndMaintainKeysAndHeadersForCs() {
// Given:
givenKeyAndValueInferenceSupported();
when(cs.getElements()).thenReturn(HEADER_AND_VALUE);
// When:
final ConfiguredStatement<CreateStream> result = injector.inject(csStatement);
// Then:
assertThat(result.g... |
@Override
public boolean add(FilteredBlock block) throws VerificationException, PrunedException {
boolean success = super.add(block);
if (success) {
trackFilteredTransactions(block.getTransactionCount());
}
return success;
} | @Test
public void receiveCoins() throws Exception {
Context.propagate(new Context(100, Coin.ZERO, false, true));
int height = 1;
// Quick check that we can actually receive coins.
Transaction tx1 = createFakeTx(TESTNET.network(),
COIN,
... |
public static <K, C, V, T> V computeIfAbsent(Map<K, V> target, K key, BiFunction<C, T, V> mappingFunction, C param1,
T param2) {
Objects.requireNonNull(target, "target");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(mappingFunction, ... | @Test
public void computeIfAbsentNotExistParam2Test() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try {
MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", null);
... |
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
... | @Test
public void decodeFailsWithEmptyShortMessage() throws Exception {
final String json = "{"
+ "\"version\": \"1.1\","
+ "\"host\": \"example.org\","
+ "\"short_message\": \"\""
+ "}";
final RawMessage rawMessage = new RawMessage(js... |
@Override
public int compare(T o1, T o2) {
if (!(o1 instanceof CharSequence) || !(o2 instanceof CharSequence)) {
throw new RuntimeException("Attempted use of AvroCharSequenceComparator on non-CharSequence objects: "
+ o1.getClass().getName() + " and " + o2.getClass().getName());
}
return c... | @Test
void compareString() {
assertEquals(0, mComparator.compare("", ""));
assertThat(mComparator.compare("", "a"), lessThan(0));
assertThat(mComparator.compare("a", ""), greaterThan(0));
assertEquals(0, mComparator.compare("a", "a"));
assertThat(mComparator.compare("a", "b"), lessThan(0));
a... |
@SuppressWarnings("removal") // Since JDK 22
public static void fullFence()
{
UnsafeAccess.UNSAFE.fullFence();
} | @Test
void fullFence()
{
MemoryAccess.fullFence();
} |
public static String bestMatch(Collection<String> supported, String header)
{
return bestMatch(supported.stream(), header);
} | @Test(dataProvider = "invalidHeaders", expectedExceptions = InvalidMimeTypeException.class)
public void testBestMatchForInvalidHeaders(List<String> supportedTypes, String header)
{
MIMEParse.bestMatch(supportedTypes, header);
} |
public static boolean compare(Object source, Object target) {
if (source == target) {
return true;
}
if (source == null || target == null) {
return false;
}
if (source.equals(target)) {
return true;
}
if (source instanceof Bo... | @Test
public void stringTest() {
Assert.assertTrue(CompareUtils.compare("20180101", DateFormatter.fromString("20180101")));
Assert.assertTrue(CompareUtils.compare(1, "1"));
Assert.assertTrue(CompareUtils.compare("1", 1));
Assert.assertTrue(CompareUtils.compare("1.0", 1.0D));
... |
@Override
public ClientPoolHandler addFirst(String name, ChannelHandler handler) {
super.addFirst(name, handler);
return this;
} | @Test
public void addFirst() {
ClientPoolHandler handler = new ClientPoolHandler();
Assert.assertTrue(handler.isEmpty());
handler.addFirst(null, new TestHandler());
Assert.assertFalse(handler.isEmpty());
} |
@Override
public int write(ByteBuffer src) throws IOException {
checkNotNull(src);
checkOpen();
checkWritable();
int written = 0; // will definitely either be assigned or an exception will be thrown
synchronized (this) {
boolean completed = false;
try {
if (!beginBlocking()) ... | @Test
public void testWriteNegative() throws IOException {
FileChannel channel = channel(regularFile(0), READ, WRITE);
try {
channel.write(buffer("111"), -1);
fail();
} catch (IllegalArgumentException expected) {
}
ByteBuffer[] bufs = {buffer("111"), buffer("111")};
try {
c... |
@Override
public MaterializedWindowedTable windowed() {
return new KsqlMaterializedWindowedTable(inner.windowed());
} | @Test
public void shouldPipeTransformsWindowed() {
// Given:
final MaterializedWindowedTable table = materialization.windowed();
givenNoopProject();
when(filter.apply(any(), any(), any())).thenReturn(Optional.of(transformed));
// When:
table.get(aKey, partition, windowStartBounds, windowEndBo... |
public void onPeriodicEmit() {
updateCombinedWatermark();
} | @Test
void noCombinedDeferredUpdateWhenWeHaveZeroOutputs() {
TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput();
WatermarkOutputMultiplexer multiplexer =
new WatermarkOutputMultiplexer(underlyingWatermarkOutput);
multiplexer.onPeriodicEmit();
... |
public int maxValue()
{
final int missingValue = this.missingValue;
int max = 0 == size ? missingValue : Integer.MIN_VALUE;
final int[] entries = this.entries;
@DoNotSub final int length = entries.length;
for (@DoNotSub int valueIndex = 1; valueIndex < length; valueIndex += ... | @Test
void shouldFindMaxValue()
{
addValues(map);
assertEquals(10, map.maxValue());
} |
@Override
public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
if(status.isExists()) {
... | @Test
public void testCopyRecursiveToRoot() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.T... |
public static Map<String, Object> compare(byte[] baselineImg, byte[] latestImg, Map<String, Object> options,
Map<String, Object> defaultOptions) throws MismatchException {
boolean allowScaling = toBool(defaultOptions.get("allowScaling"));
ImageComparison im... | @Test
void testFailureThresholdTriggered() {
ImageComparison.MismatchException exception = assertThrows(ImageComparison.MismatchException.class, () ->
ImageComparison.compare(B_3x3_IMG, BG_3x3_IMG, opts(), opts()));
double mismatchPercentage = (double)exception.data.get("mismatchPer... |
int calculatePartBufferSize(HazelcastProperties hazelcastProperties, long jarSize) {
int partBufferSize = hazelcastProperties.getInteger(JOB_UPLOAD_PART_SIZE);
// If jar size is smaller, then use it
if (jarSize < partBufferSize) {
partBufferSize = (int) jarSize;
}
re... | @Test
public void calculatePartBufferSize_when_JarIsSmall() {
SubmitJobPartCalculator submitJobPartCalculator = new SubmitJobPartCalculator();
Properties properties = new Properties();
HazelcastProperties hazelcastProperties = new HazelcastProperties(properties);
long jarSize = 2_0... |
@Override
public void setConf(Configuration conf) {
if (conf != null) {
conf = addSecurityConfiguration(conf);
}
super.setConf(conf);
} | @Test
public void testFailoverWithFencerConfigured() throws Exception {
Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
HdfsConfiguration conf = getHAConf();
conf.set(DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY, getFencerTrueCommand());
tool.setConf(conf);
assertEquals(0, ... |
static boolean fieldMatch(Object repoObj, Object filterObj) {
return filterObj == null || repoObj.equals(filterObj);
} | @Test
public void testFieldMatchWithNonEqualNonStringObjectsShouldReturnFalse() {
assertFalse(Utilities.fieldMatch(42, 43));
} |
@Override
public int run(String[] argv) {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-safemode".equals(cmd)) {
if (argv.length != 2) ... | @Test(timeout = 60000)
public void testDFSAdminUnreachableDatanode() throws Exception {
redirectStream();
final DFSAdmin dfsAdmin = new DFSAdmin(conf);
for (String command : new String[]{"-getDatanodeInfo",
"-evictWriters", "-getBalancerBandwidth"}) {
// Connecting to Xfer port instead of IP... |
public final T apply(Schema left, Schema right) {
return visit(this, Context.EMPTY, FieldType.row(left), FieldType.row(right));
} | @Test
public void testCountMissingFields() {
assertEquals(4, new CountMissingFields().apply(LEFT, RIGHT).intValue());
} |
public static SchemaFactory getSchemaFactory() throws SAXException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
setProperty(schemaFactory, XMLConstants.ACCESS_EXTERNAL_SCHEMA);
setProperty(schemaFactory, XMLConstants.ACCESS_EXTERNAL_DTD);
... | @Test
public void testGetSchemaFactory() throws Exception {
SchemaFactory schemaFactory = XmlUtil.getSchemaFactory();
assertNotNull(schemaFactory);
assertThrows(SAXException.class, () -> XmlUtil.setProperty(schemaFactory, "test://no-such-property"));
ignoreXxeFailureProp.setOrClearPr... |
List<Quote> getQuotes() {
return this.quotes;
} | @Test
void staticQuotesAreLoaded() {
assertThat(quotesProperties.getQuotes()).hasSize(2);
} |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ExportStorageNodesStatement sqlStatement, final ContextManager contextManager) {
checkSQLStatement(contextManager.getMetaDataContexts().getMetaData(), sqlStatement);
String exportedData = generateExportData(contextManager.getMetaData... | @Test
void assertExecute() {
when(database.getName()).thenReturn("normal_db");
Map<String, StorageUnit> storageUnits = createStorageUnits();
when(database.getResourceMetaData().getStorageUnits()).thenReturn(storageUnits);
when(database.getRuleMetaData().getConfigurations()).thenRetur... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_execute_bound_statement() {
// Given
String queries = "@prepare[users_insert]=INSERT INTO zeppelin.users" +
"(login,firstname,lastname,addresses,location)" +
"VALUES(:login,:fn,:ln,:addresses,:loc)\n" +
"@bind[users_insert]='jdoe','John','DOE'," +
"{street_num... |
@Override
public ManageSnapshots createTag(String name, long snapshotId) {
updateSnapshotReferencesOperation().createTag(name, snapshotId);
return this;
} | @TestTemplate
public void testCreateTag() {
table.newAppend().appendFile(FILE_A).commit();
long snapshotId = table.currentSnapshot().snapshotId();
// Test a basic case of creating a tag
table.manageSnapshots().createTag("tag1", snapshotId).commit();
SnapshotRef expectedTag = table.ops().refresh().... |
@Override
public List<RoleDO> getRoleListByStatus(Collection<Integer> statuses) {
return roleMapper.selectListByStatus(statuses);
} | @Test
public void testGetRoleListByStatus() {
// mock 数据
RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
roleMapper.insert(dbRole01);
RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));... |
void release() {
Arrays.stream(subpartitionCacheDataManagers)
.forEach(SubpartitionRemoteCacheManager::release);
} | @Test
void testRelease() {
TieredStoragePartitionId partitionId =
TieredStorageIdMappingUtils.convertId(new ResultPartitionID());
AtomicBoolean isReleased = new AtomicBoolean(false);
TestingPartitionFileWriter partitionFileWriter =
new TestingPartitionFileWrit... |
public static ParseResult parse(String text) {
Map<String, String> localProperties = new HashMap<>();
String intpText = "";
String scriptText = null;
Matcher matcher = REPL_PATTERN.matcher(text);
if (matcher.find()) {
String headingSpace = matcher.group(1);
intpText = matcher.group(2);
... | @Test
void testParagraphTextQuotedPropertyKeyAndValue() {
ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse(
"%spark.pyspark(\"po ol\"=\"value with \\\" inside\")");
assertEquals("spark.pyspark", parseResult.getIntpText());
assertEquals(1, parseResult.getLocalProperties()... |
protected List<HeaderValue> parseHeaderValue(String headerValue) {
return parseHeaderValue(headerValue, HEADER_VALUE_SEPARATOR, HEADER_QUALIFIER_SEPARATOR);
} | @Test
void headers_parseHeaderValue_validMultipleCookie() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(validCookieRequest, mockContext, null, config);
List<AwsHttpServletRequest.HeaderValue> values = request.parseHeaderValue(request.getHeader(HttpHeaders.COOKIE), ";", ",");
... |
@Override
public KsqlSecurityContext provide(final ApiSecurityContext apiSecurityContext) {
final Optional<KsqlPrincipal> principal = apiSecurityContext.getPrincipal();
final Optional<String> authHeader = apiSecurityContext.getAuthHeader();
final List<Entry<String, String>> requestHeaders = apiSecurityCo... | @Test
public void shouldCreateDefaultServiceContextIfUserPrincipalIsMissing() {
// Given:
when(securityExtension.getUserContextProvider()).thenReturn(Optional.of(userContextProvider));
when(apiSecurityContext.getPrincipal()).thenReturn(Optional.empty());
// When:
final KsqlSecurityContext ksqlSec... |
@Override
@SuccessResponse(statuses = { HttpStatus.S_204_NO_CONTENT })
@ServiceErrors(INVALID_PERMISSIONS)
@ParamError(code = INVALID_ID, parameterNames = { "albumEntryId" })
public UpdateResponse update(CompoundKey key, AlbumEntry entity)
{
long photoId = (Long) key.getPart("photoId");
long albumId =... | @Test(expectedExceptions = RestLiServiceException.class)
public void testBadUpdateAlbumId()
{
// album 100 doesn't exist
CompoundKey key = new CompoundKey().append("photoId", 1L).append("albumId", 100L);
AlbumEntry entry = new AlbumEntry().setAddTime(4);
_entryRes.update(key, entry);
} |
@Override
public String toString() {
return ioStatisticsToString(this);
} | @Test
public void testStringification2() throws Throwable {
String ss = snapshot.toString();
LOG.info("original {}", ss);
Assertions.assertThat(ss)
.describedAs("snapshot toString()")
.contains("c1=0")
.contains("g1=1");
} |
public static String getJobOffsetItemPath(final String jobId, final int shardingItem) {
return String.join("/", getJobOffsetPath(jobId), Integer.toString(shardingItem));
} | @Test
void assertGetJobOffsetItemPath() {
assertThat(PipelineMetaDataNode.getJobOffsetItemPath(jobId, 0), is(jobRootPath + "/offset/0"));
} |
@Override
public Future<?> submit(Runnable runnable) {
submitted.mark();
return delegate.submit(new InstrumentedRunnable(runnable));
} | @Test
@SuppressWarnings("unchecked")
public void reportsTasksInformationForForkJoinPool() throws Exception {
executor = Executors.newWorkStealingPool(4);
instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp");
submitted = registry.meter("fjp.submitted");... |
@Override
public MetadataNode child(String name) {
if (name.equals("name")) {
return new MetadataLeafNode(image.name());
} else if (name.equals("id")) {
return new MetadataLeafNode(image.id().toString());
} else {
int partitionId;
try {
... | @Test
public void testChildPartitionIdNull() {
MetadataNode child1 = NODE.child("1");
MetadataNode child2 = NODE.child("a");
assertNull(child1);
assertNull(child2);
} |
@GET
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get prekey count",
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use... | @Test
void putKeysStructurallyInvalidPQOneTimeKey() {
final ECKeyPair identityKeyPair = Curve.generateKeyPair();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final WeaklyTypedSignedPreKey wrongPreKey = WeaklyTypedSignedPreKey.fromSignedPreKey(KeysHelper.signedECPreKey(1... |
CompletableFuture<String> getOperationFuture() {
return operationFuture;
} | @Test
void testJobFailedAndSavepointOperationSucceeds() throws Exception {
try (MockStopWithSavepointContext ctx = new MockStopWithSavepointContext()) {
StateTrackingMockExecutionGraph mockExecutionGraph =
new StateTrackingMockExecutionGraph();
final CompletableFu... |
public String send() throws MailException {
try {
return doSend();
} catch (MessagingException e) {
if (e instanceof SendFailedException) {
// 当地址无效时,显示更加详细的无效地址信息
final Address[] invalidAddresses = ((SendFailedException) e).getInvalidAddresses();
final String msg = StrUtil.format("Invalid Address... | @Test
@Disabled
public void sendByAccountTest() {
MailAccount account = new MailAccount();
account.setHost("smtp.yeah.net");
account.setPort(465);
account.setSslEnable(true);
account.setFrom("hutool@yeah.net");
account.setUser("hutool");
account.setPass("q1w2e3");
JakartaMailUtil.send(account, "hutool... |
@Override
public KTable<K, V> reduce(final Reducer<V> reducer) {
return reduce(reducer, Materialized.with(keySerde, valueSerde));
} | @Test
public void shouldReduceAndMaterializeResults() {
groupedStream.reduce(
MockReducer.STRING_ADDER,
Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("reduce")
.withKeySerde(Serdes.String())
.withValueSerde(Serdes.String()));
t... |
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("position") BigDecimal position,
@ParameterName("newItem") Object newItem) {
if (list == null) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", CANNO... | @Test
void invokeMatchNull() {
FunctionTestUtil.assertResultError(listReplaceFunction.invoke(new ArrayList(), (AbstractCustomFEELFunction) null, ""), InvalidParametersEvent.class);
} |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testWhenRequiredOptionIsNeverSet() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"Missing required value for "
+ "[public abstract java.lang.String org.apache.beam."
+ "sdk.options.PipelineOptionsValidatorTest$Req... |
public RateLimitSet getUser() {
return user;
} | @Test
public void testUser() {
LimitConfig.RateLimitSet limitUser = limitConfig.getUser();
Assert.assertEquals(limitUser.getDirectMaps().size(), 3);
} |
@Override
public Long sendSingleMailToAdmin(String mail, Long userId,
String templateCode, Map<String, Object> templateParams) {
// 如果 mail 为空,则加载用户编号对应的邮箱
if (StrUtil.isEmpty(mail)) {
AdminUserDO user = adminUserService.getUser(userId);
... | @Test
public void testSendSingleMailToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// m... |
@Override
public boolean imbalanceDetected(LoadImbalance imbalance) {
long min = imbalance.minimumLoad;
long max = imbalance.maximumLoad;
if (min == Long.MIN_VALUE || max == Long.MAX_VALUE) {
return false;
}
long lowerBound = (long) (MIN_MAX_RATIO_MIGRATION_THRES... | @Test
public void testImbalanceDetected_shouldReturnFalseWhenNoKnownMaximum() {
imbalance.maximumLoad = Long.MAX_VALUE;
boolean imbalanceDetected = strategy.imbalanceDetected(imbalance);
assertFalse(imbalanceDetected);
} |
protected String readEncodingAndString(int max) throws IOException {
byte encoding = readByte();
return readEncodedString(encoding, max - 1);
} | @Test
public void testReadUtf16NullPrefix() throws IOException {
byte[] data = {
ID3Reader.ENCODING_UTF16_WITH_BOM,
(byte) 0xff, (byte) 0xfe, // BOM
0x00, 0x01, // Latin Capital Letter A with macron (Ā)
0, 0, // Null-terminated
};
CountingInput... |
@Override
public OutputFile newOutputFile(String path) {
return new OSSOutputFile(client(), new OSSURI(path), aliyunProperties, metrics);
} | @Test
public void testOutputFile() throws IOException {
String location = randomLocation();
int dataSize = 1024 * 10;
byte[] data = randomData(dataSize);
OutputFile out = fileIO().newOutputFile(location);
writeOSSData(out, data);
OSSURI uri = new OSSURI(location);
assertThat(ossClient().... |
SelType pop() {
SelType ret = stack[top];
stack[top--] = null;
return ret;
} | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void testInvalidPop() {
state.pop();
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateIsNotNullPredicate() {
// Given:
final Expression expression1 = new IsNotNullPredicate(
COL11
);
final Expression expression2 = new IsNotNullPredicate(
new NullLiteral()
);
// When:
InterpretedExpression interpreter1 = interpreter(expression... |
@Override
public void close() {
diskCacheManager.close();
} | @Test
void testRelease() {
AtomicBoolean isReleased = new AtomicBoolean(false);
TestingPartitionFileWriter partitionFileWriter =
new TestingPartitionFileWriter.Builder()
.setReleaseRunnable(() -> isReleased.set(true))
.build();
... |
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
rejectCount.incrementAndGet();
if (ApplicationContextHolder.getInstance() != null) {
try {
ThreadPoolCheckAlarm alarmHandler = ApplicationContextHolder.getBean(ThreadPoolCheckAla... | @Test
public void testInvoke() throws Throwable {
Object[] mockArgs = new Object[]{"arg1", "arg2"};
MockedStatic<ApplicationContextHolder> mockedStatic = Mockito.mockStatic(ApplicationContextHolder.class);
mockedStatic.when(ApplicationContextHolder::getInstance).thenReturn(applicationContext... |
@Override
public void stop() throws BundleException {
throw newException();
} | @Test
void require_that_stop_throws_exception() throws BundleException {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().stop();
});
} |
@Override
public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey,
SubscriberPermissionsOnProject subscriberPermissionsOnProject) {
verifyProjectKey(projectKey);
try (DbSession dbSession = dbClient.openSession(false)) {
Set<EmailSubscriberDto> emailSubscribe... | @Test
public void findSubscribedEmailRecipients_fails_with_NPE_if_projectKey_is_null() {
String dispatcherKey = randomAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
.hasMessa... |
@Override
public RexNode visit(CallExpression call) {
boolean isBatchMode = unwrapContext(relBuilder).isBatchMode();
for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) {
Optional<RexNode> converted = rule.convert(call, newFunctionContext());
if (conve... | @Test
void testTimestampLiteral() {
RexNode rex =
converter.visit(
valueLiteral(
LocalDateTime.parse("2012-12-12T12:12:12.12345"),
DataTypes.TIMESTAMP(3).notNull()));
assertThat(((RexLiteral) rex)... |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testHierarchicalLarge() {
int[][] qData = new int[][] {
// / A D G
// B C E F H I
{ 400, 200, 60, 140, 100, 70, 30, 100, 10, 90 }, // abs
{ 400, 400, 400, 400, 400, 400, 400, 400, 400, 400 }, ... |
public void setProperty(String name, String value) {
if (value == null) {
return;
}
name = Introspector.decapitalize(name);
PropertyDescriptor prop = getPropertyDescriptor(name);
if (prop == null) {
addWarn("No such property [" + name + "] in " + objClass.getName() + ".");
} else ... | @Test
public void charset() {
setter.setProperty("charset", "UTF-8");
assertEquals(Charset.forName("UTF-8"), house.getCharset());
house.setCharset(null);
setter.setProperty("charset", "UTF");
assertNull(house.getCharset());
StatusChecker checker = new StatusChecker(context);
checker.... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String shardingResultSuffix = getShardingResultSuffix(cutS... | @Test
void assertPreciseDoShardingWithIntShardingValue() {
ModShardingAlgorithm algorithm = (ModShardingAlgorithm) TypedSPILoader.getService(ShardingAlgorithm.class, "MOD", PropertiesBuilder.build(new Property("sharding-count", "16")));
assertThat(algorithm.doSharding(createAvailableTargetNames(), n... |
public Plan validateReservationDeleteRequest(
ReservationSystem reservationSystem, ReservationDeleteRequest request)
throws YarnException {
return validateReservation(reservationSystem, request.getReservationId(),
AuditConstants.DELETE_RESERVATION_REQUEST);
} | @Test
public void testDeleteReservationInvalidPlan() {
ReservationDeleteRequest request = new ReservationDeleteRequestPBImpl();
ReservationId reservationID =
ReservationSystemTestUtil.getNewReservationId();
request.setReservationId(reservationID);
when(rSystem.getPlan(PLAN_NAME)).thenReturn(nu... |
@Override
public void updatePort(Port osPort) {
checkNotNull(osPort, ERR_NULL_PORT);
checkArgument(!Strings.isNullOrEmpty(osPort.getId()), ERR_NULL_PORT_ID);
checkArgument(!Strings.isNullOrEmpty(osPort.getNetworkId()), ERR_NULL_PORT_NET_ID);
osNetworkStore.updatePort(osPort);
... | @Test(expected = IllegalArgumentException.class)
public void testUpdatePortWithNullId() {
final Port testPort = NeutronPort.builder()
.networkId(NETWORK_ID)
.build();
target.updatePort(testPort);
} |
@Override
public ScheduledExecutor getScheduledExecutor() {
return internalScheduledExecutor;
} | @Test
void testExecuteRunnable() throws Exception {
final OneShotLatch latch = new OneShotLatch();
pekkoRpcService.getScheduledExecutor().execute(latch::trigger);
latch.await(30L, TimeUnit.SECONDS);
} |
public static void checkValidProjectId(String idToCheck) {
if (idToCheck.length() < MIN_PROJECT_ID_LENGTH) {
throw new IllegalArgumentException("Project ID " + idToCheck + " cannot be empty.");
}
if (idToCheck.length() > MAX_PROJECT_ID_LENGTH) {
throw new IllegalArgumentException(
"Pro... | @Test
public void testCheckValidProjectIdWhenIdIsTooLong() {
assertThrows(
IllegalArgumentException.class,
() -> checkValidProjectId("really-really-really-really-long-project-id"));
} |
@Override
public String loopbackEthOnu(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();... | @Test
public void testValidLoopbackEthOnu() throws Exception {
String target;
String reply;
for (int i = ZERO; i < VALID_ETHPORT_LOOPBACK_TCS.length; i++) {
target = VALID_ETHPORT_LOOPBACK_TCS[i];
currentKey = i;
reply = voltConfig.loopbackEthOnu(target);... |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/{executionId}")
@Operation(tags = {"Executions"}, summary = "Get an execution")
public Execution get(
@Parameter(description = "The execution id") @PathVariable String executionId
) {
return executionRepository
.findById(tenantService... | @SuppressWarnings("unchecked")
@Test
void getDistinctNamespaceExecutables() {
List<String> result = client.toBlocking().retrieve(
GET("/api/v1/executions/namespaces"),
Argument.of(List.class, String.class)
);
assertThat(result.size(), greaterThanOrEqualTo(5));
... |
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
final Http2HeadersFrame headers = (Http2HeadersFrame) msg;
transportListener.onHeader(headers.headers(), headers.isEndStream());
}... | @Test
void testChannelRead0() throws Exception {
final Http2Headers headers = new DefaultHttp2Headers(true);
DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers, true);
handler.channelRead0(ctx, headersFrame);
Mockito.verify(transportListener, Mockito.times(1... |
public SchemaMapping fromParquet(MessageType parquetSchema) {
List<Type> fields = parquetSchema.getFields();
List<TypeMapping> mappings = fromParquet(fields);
List<Field> arrowFields = fields(mappings);
return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings);
} | @Test(expected = IllegalStateException.class)
public void testParquetInt32TimestampMicrosToArrow() {
converter.fromParquet(Types.buildMessage()
.addField(Types.optional(INT32)
.as(LogicalTypeAnnotation.timestampType(false, MICROS))
.named("a"))
.named("root"));
} |
public boolean fence(HAServiceTarget fromSvc) {
return fence(fromSvc, null);
} | @Test
public void testShortNameSsh() throws BadFencingConfigurationException {
NodeFencer fencer = setupFencer("sshfence");
assertFalse(fencer.fence(MOCK_TARGET));
} |
@SuppressWarnings({"checkstyle:ParameterNumber"})
public static Supplier<RequestManagers> supplier(final Time time,
final LogContext logContext,
final BackgroundEventHandler backgroundEventHandler,
... | @Test
public void testMemberStateListenerRegistered() {
final MemberStateListener listener = (memberEpoch, memberId) -> { };
final Properties properties = requiredConsumerConfig();
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "consumerGroup");
final ConsumerConfig config ... |
public Stream<Hit> stream() {
if (nPostingLists == 0) {
return Stream.empty();
}
return StreamSupport.stream(new PredicateSpliterator(), false);
} | @Test
void requireThatPostingListsAreSortedAfterAdvancing() {
PredicateSearch search = createPredicateSearch(
new byte[]{2, 1, 1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(0, 0x000100ff),
entry(3, 0x000100ff)),
... |
public double calculateAveragePercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) {
int skippedResourceTypes = 0;
double total = 0.0;
if (usedMemoryMb > totalMemoryMb) {
throwBecauseUsedIsNotSubsetOfTotal(used, totalMemoryMb, usedMemoryMb);
}... | @Test
public void testCalculateAvgWithResourceMissingFromTotal() {
Map<String, Double> allResourcesMap = new HashMap<>();
allResourcesMap.put(Constants.COMMON_CPU_RESOURCE_NAME, 2.0);
NormalizedResources resources = new NormalizedResources(normalize(allResourcesMap));
Map<String, Dou... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseStepParameterWith3Underscore() {
StringParameter bar =
StringParameter.builder().name("bar").expression("_step1___foo + '-1';").build();
paramEvaluator.parseStepParameter(
Collections.singletonMap("_step1", Collections.emptyMap()),
Collections.emptyMap(),
... |
public List<Stream> match(Message message) {
final Set<Stream> result = Sets.newHashSet();
final Set<String> blackList = Sets.newHashSet();
for (final Rule rule : rulesList) {
if (blackList.contains(rule.getStreamId())) {
continue;
}
final St... | @Test
public void issue1396() throws Exception {
final StreamMock stream = getStreamMock("GitHub issue #1396");
stream.setMatchingType(Stream.MatchingType.AND);
final StreamRuleMock rule1 = new StreamRuleMock(ImmutableMap.<String, Object>builder()
.put("_id", new ObjectId())... |
public static List<ZKAuthInfo> parseAuth(String authString) throws
BadAuthFormatException{
List<ZKAuthInfo> ret = Lists.newArrayList();
if (authString == null) {
return ret;
}
List<String> authComps = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults()
... | @Test
public void testEmptyAuth() {
List<ZKAuthInfo> result = ZKUtil.parseAuth("");
assertTrue(result.isEmpty());
} |
@Override
public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
checkState(authAppInstallationToken != null, "An auth app token is required in case repository permissions checking is necessary.");
String[] orgaAndRepoTokenified = devOpsProjectCreationContext.fullName().split("/");
String org... | @Test
void isScanAllowedUsingPermissionsFromDevopsPlatform_whenCollaboratorHasDirectAccess_returnsTrue() {
GsonRepositoryCollaborator collaborator1 = mockCollaborator("collaborator1", 1, "role1", "read", "admin");
GsonRepositoryCollaborator collaborator2 = mockCollaborator("collaborator2", 2, "role2", "read",... |
@Override
public void writeShort(final int v) throws IOException {
ensureAvailable(SHORT_SIZE_IN_BYTES);
Bits.writeShort(buffer, pos, (short) v, isBigEndian);
pos += SHORT_SIZE_IN_BYTES;
} | @Test
public void testWriteShortV() throws Exception {
short expected = 100;
out.writeShort(expected);
short actual = Bits.readShortB(out.buffer, 0);
assertEquals(expected, actual);
} |
@Override
public List<JreInfoRestResponse> getJresMetadata(@Nullable String os, @Nullable String arch) {
Predicate<JreInfoRestResponse> osFilter = isBlank(os) ? jre -> true : (jre -> OS.from(jre.os()) == OS.from(os));
Predicate<JreInfoRestResponse> archFilter = isBlank(arch) ? jre -> true : (jre -> Arch.from(... | @Test
void getJresMetadata_shouldFail_whenFilteredWithUnsupportedOsValue() {
String anyUnsupportedOS = "not-supported";
assertThatThrownBy(() -> jresHandler.getJresMetadata(anyUnsupportedOS, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("Unsupported OS: '" + anyUnsu... |
public static CoordinatorRecord newGroupMetadataRecord(
ClassicGroup group,
Map<String, byte[]> assignment,
MetadataVersion metadataVersion
) {
List<GroupMetadataValue.MemberMetadata> members = new ArrayList<>(group.allMembers().size());
group.allMembers().forEach(member -> {... | @Test
public void testNewGroupMetadataRecordThrowsWhenEmptyAssignment() {
Time time = new MockTime();
List<GroupMetadataValue.MemberMetadata> expectedMembers = new ArrayList<>();
expectedMembers.add(
new GroupMetadataValue.MemberMetadata()
.setMemberId("member-1"... |
static MetricRegistry getMetricRegistryFromCamelRegistry(Registry camelRegistry, String registryName) {
MetricRegistry registry = camelRegistry.lookupByNameAndType(registryName, MetricRegistry.class);
if (registry != null) {
return registry;
} else {
Set<MetricRegistry> r... | @Test
public void testGetMetricRegistryFromCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(metricRegistry);
MetricRegistry result = MetricsComponent.getMetricRegistryFromCamelRegistry(camelRegistry, "name");
assertThat(result, is(metricRegis... |
@Override
public Iterator<RawUnionValue> call(Iterator<WindowedValue<InputT>> inputs) throws Exception {
SparkPipelineOptions options = pipelineOptions.get().as(SparkPipelineOptions.class);
// Register standard file systems.
FileSystems.setDefaultPipelineOptions(options);
// Do not call processElemen... | @Test(expected = Exception.class)
public void sdkErrorsSurfaceOnClose() throws Exception {
SparkExecutableStageFunction<Integer, ?> function = getFunction(Collections.emptyMap());
doThrow(new Exception()).when(remoteBundle).close();
List<WindowedValue<Integer>> inputs = new ArrayList<>();
inputs.add(W... |
public static String getCharset(HttpURLConnection conn) {
if (conn == null) {
return null;
}
return getCharset(conn.getContentType());
} | @Test
public void getCharsetTest() {
String charsetName = ReUtil.get(HttpUtil.CHARSET_PATTERN, "Charset=UTF-8;fq=0.9", 1);
assertEquals("UTF-8", charsetName);
charsetName = ReUtil.get(HttpUtil.META_CHARSET_PATTERN, "<meta charset=utf-8", 1);
assertEquals("utf-8", charsetName);
charsetName = ReUtil.get(HttpU... |
private int getGroups(String[] usernames) throws IOException {
// Get groups users belongs to
ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol();
if (usernames.length == 0) {
usernames = new String[] { UserGroupInformation.getCurrentUser().getUserName() };
}
for ... | @Test
public void testGetGroups() throws Exception {
when(admin.getGroupsForUser(eq("admin"))).thenReturn(
new String[] {"group1", "group2"});
PrintStream origOut = System.out;
PrintStream out = mock(PrintStream.class);
System.setOut(out);
try {
String[] args = { "-getGroups", "admin... |
public boolean fence(HAServiceTarget fromSvc) {
return fence(fromSvc, null);
} | @Test
public void testWhitespaceAndCommentsInConfig()
throws BadFencingConfigurationException {
NodeFencer fencer = setupFencer(
"\n" +
" # the next one will always fail\n" +
" " + AlwaysFailFencer.class.getName() + "(foo) # <- fails\n" +
AlwaysSucceedFencer.class.getName() +... |
@Override
public String put(String key, String value) {
if (value == null) throw new IllegalArgumentException("Null value not allowed as an environment variable: " + key);
return super.put(key, value);
} | @Test
public void overrideOrderCalculatorInOrder() {
EnvVars env = new EnvVars();
EnvVars overrides = new EnvVars();
overrides.put("A", "NoReference");
overrides.put("B", "${A}");
overrides.put("C", "${B}");
overrides.put("D", "${E}");
overrides.put("E", "${C}... |
@Override
public CompletableFuture<Void> endTransactionOneway(ProxyContext ctx, String brokerName, EndTransactionRequestHeader requestHeader,
long timeoutMillis) {
CompletableFuture<Void> future = new CompletableFuture<>();
SimpleChannel channel = channelManager.createChannel(ctx);
C... | @Test
public void testEndTransaction() throws Exception {
EndTransactionRequestHeader requestHeader = new EndTransactionRequestHeader();
localMessageService.endTransactionOneway(proxyContext, null, requestHeader, 1000L);
Mockito.verify(endTransactionProcessorMock, Mockito.times(1)).processRe... |
public MutableRecordBatch nextBatch() {
int remaining = buffer.remaining();
Integer batchSize = nextBatchSize();
if (batchSize == null || remaining < batchSize)
return null;
byte magic = buffer.get(buffer.position() + MAGIC_OFFSET);
ByteBuffer batchSlice = buffer.s... | @Test
public void iteratorRaisesOnInvalidMagic() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, Compression.NONE, TimestampType.CREATE_TIME, 0L);
builder.append(15L, "a".getBytes(), "1".getBytes());
builder.append(20L, "b... |
@Override
public AppResponse process(Flow flow, CheckAuthenticationStatusRequest request){
switch(appSession.getState()) {
case "AUTHENTICATION_REQUIRED", "AWAITING_QR_SCAN":
return new CheckAuthenticationStatusResponse("PENDING", false);
case "RETRIEVED", "AWAITING_C... | @Test
void processRetrieved(){
appSession.setState("RETRIEVED");
AppResponse response = checkAuthenticationStatus.process(flow, request);
assertTrue(response instanceof CheckAuthenticationStatusResponse);
assertEquals("PENDING", ((CheckAuthenticationStatusResponse) response).getSta... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldAddErrorTheMessageOnTheRightFieldOfTheRightElement() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.setName("#{not-found}");
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineCon... |
public Config read() {
var federationEntityStatementJwksPath = loadJwks(CONFIG_FEDERATION_ENTITY_STATEMENT_JWKS_PATH);
var baseUri =
configProvider
.get(CONFIG_BASE_URI)
.map(URI::create)
.orElseThrow(() -> new IllegalArgumentException("no 'base_uri' configured"));
... | @Test
void read_defaults() {
var provider = mock(ConfigProvider.class);
var sut = new ConfigReader(provider);
var baseUri = "https://rp.example.com";
var idpDiscoveryUri = "https://sso.example.com/.well-known/openid-configuration";
var appName = "Awesome DiGA";
when(provider.get(ConfigReade... |
public static Expression convert(Filter[] filters) {
Expression expression = Expressions.alwaysTrue();
for (Filter filter : filters) {
Expression converted = convert(filter);
Preconditions.checkArgument(
converted != null, "Cannot convert filter to Iceberg: %s", filter);
expression =... | @Test
public void testNotIn() {
Not filter = Not.apply(In.apply("col", new Integer[] {1, 2}));
Expression actual = SparkFilters.convert(filter);
Expression expected =
Expressions.and(Expressions.notNull("col"), Expressions.notIn("col", 1, 2));
Assert.assertEquals("Expressions should match", ex... |
public static byte[] encode(Predicate predicate) {
Objects.requireNonNull(predicate, "predicate");
Slime slime = new Slime();
encode(predicate, slime.setObject());
return com.yahoo.slime.BinaryFormat.encode(slime);
} | @Test
void requireThatEncodeNullThrows() {
try {
BinaryFormat.encode(null);
fail();
} catch (NullPointerException e) {
assertEquals("predicate", e.getMessage());
}
} |
@Nullable
public static ValueReference of(Object value) {
if (value instanceof Boolean) {
return of((Boolean) value);
} else if (value instanceof Double) {
return of((Double) value);
} else if (value instanceof Float) {
return of((Float) value);
} ... | @Test
public void deserializeBoolean() throws IOException {
assertThat(objectMapper.readValue("{\"@type\":\"boolean\",\"@value\":true}", ValueReference.class)).isEqualTo(ValueReference.of(true));
assertThat(objectMapper.readValue("{\"@type\":\"boolean\",\"@value\":false}", ValueReference.class)).isE... |
@PostMapping("/api/v1/meetings")
public ResponseEntity<MomoApiResponse<MeetingCreateResponse>> create(
@RequestBody @Valid MeetingCreateRequest request
) {
MeetingCreateResponse response = meetingService.create(request);
String path = cookieManager.pathOf(response.uuid());
St... | @DisplayName("존재하지 않는 약속을 잠금 해제 시도하면 400 Bad Request를 반환한다.")
@Test
void unlockWithInvalidUUID() {
String invalidUUID = "INVALID_UUID";
Meeting meeting = meetingRepository.save(MeetingFixture.DINNER.create());
Attendee attendee = attendeeRepository.save(AttendeeFixture.HOST_JAZZ.create(m... |
public List<Job> toScheduledJobs(Instant from, Instant upTo) {
List<Job> jobs = new ArrayList<>();
Instant nextRun = getNextRun(from);
while (nextRun.isBefore(upTo)) {
jobs.add(toJob(new ScheduledState(nextRun, this)));
nextRun = getNextRun(nextRun);
}
ret... | @Test
void testToScheduledJobsGetsAllJobsBetweenStartAndEnd() {
final RecurringJob recurringJob = aDefaultRecurringJob()
.withCronExpression("*/5 * * * * *")
.build();
final List<Job> jobs = recurringJob.toScheduledJobs(now(), now().plusSeconds(5));
assertTh... |
@Override
public void updateSmsReceiveResult(Long id, Boolean success, LocalDateTime receiveTime,
String apiReceiveCode, String apiReceiveMsg) {
SmsReceiveStatusEnum receiveStatus = Objects.equals(success, true) ?
SmsReceiveStatusEnum.SUCCESS : SmsRecei... | @Test
public void testUpdateSmsReceiveResult() {
// mock 数据
SmsLogDO dbSmsLog = randomSmsLogDO(
o -> o.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus()));
smsLogMapper.insert(dbSmsLog);
// 准备参数
Long id = dbSmsLog.getId();
Boolean success = random... |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void shouldPrintDropConnector() {
// Given:
final KsqlEntity entity = new DropConnectorEntity("statementText", "connectorName");
// When:
console.printKsqlEntityList(ImmutableList.of(entity));
// Then:
final String output = terminal.getOutputString();
Approvals.verify(output... |
public static boolean isJavaIdentifier(String s) {
if (isEmpty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
... | @Test
void testIsJavaIdentifier() throws Exception {
assertThat(StringUtils.isJavaIdentifier(""), is(false));
assertThat(StringUtils.isJavaIdentifier("1"), is(false));
assertThat(StringUtils.isJavaIdentifier("abc123"), is(true));
assertThat(StringUtils.isJavaIdentifier("abc(23)"), is... |
@Override
public CompletableFuture<Acknowledge> sendEvent(OperatorEvent evt) {
if (!isReady()) {
throw new FlinkRuntimeException("SubtaskGateway is not ready, task not yet running.");
}
final SerializedValue<OperatorEvent> serializedEvent;
try {
serializedEve... | @Test
void eventsPassThroughOpenGateway() {
final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks();
final SubtaskGatewayImpl gateway =
new SubtaskGatewayImpl(
getUniqueElement(receiver.getAccessesForSubtask(11)),
... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldThrowOnDropTableWhenConstraintExist() {
// Given:
final CreateTableCommand table1 = buildCreateTable(SourceName.of("t1"),
false, false);
final CreateTableCommand table2 = buildCreateTable(SourceName.of("t2"),
false, false);
final CreateTableCommand table3 = buil... |
@Override
public Iterable<Intent> getIntents() {
return intentStore.getIntents(networkId);
} | @Test
public void testGetIntents() {
VirtualNetwork virtualNetwork = setupVirtualNetworkTopology();
Key intentKey = Key.of("test", APP_ID);
List<Constraint> constraints = new ArrayList<>();
constraints.add(new EncapsulationConstraint(EncapsulationType.VLAN));
VirtualNetwor... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
try {
for(final DavResource resource : this.list(file)) {
... | @Test
public void testFindDefaultAttributesFinderCryptomator() throws Exception {
final Path home = new DefaultHomeFinderService(session).find();
final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
final CryptoVault cryptomator ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.