focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Deprecated
@Override
public V remove(final Object key) {
throw new UnsupportedOperationException("Removing from registeredStores is not allowed");
} | @SuppressWarnings("deprecation")
@Test
public void shouldForbidConditionalRemove() {
final FixedOrderMap<String, Integer> map = new FixedOrderMap<>();
map.put("a", 0);
assertThrows(UnsupportedOperationException.class, () -> map.remove("a", 0));
assertEquals(0, map.get("a"));
... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testSimpleGroupOffsetCommitWithInstanceId() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> result = context.commitOffset(
new OffsetCommitRequestData()
... |
@Override
public EntryEventType getEventType() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetEventType() {
singleIMapEvent.getEventType();
} |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeEndpointWithPercentSignInParameter() throws Exception {
String out = URISupport.normalizeUri("http://someendpoint?username=james&password=%25test");
assertNotNull(out);
// Camel will safe encode the URI
assertEquals("http://someendpoint?password=%25test... |
public void writeTo(T object, DataWriter writer) throws IOException {
writeTo(object, 0, writer);
} | @Test
public void testNotExportedBean() throws IOException {
ExportConfig config = new ExportConfig().withFlavor(Flavor.JSON).withExportInterceptor(new ExportInterceptor1()).withSkipIfFail(true);
StringWriter writer = new StringWriter();
ExportableBean b = new ExportableBean();
build... |
@Override
public boolean add(final Integer value) {
return add(value.intValue());
} | @Test
public void worksCorrectlyWhenFull() {
final IntHashSet set = new IntHashSet(2, 0);
set.add(1);
set.add(2);
assertContains(set, 2);
assertNotContains(set, 3);
} |
@Override
public String version() {
return AppInfoParser.getVersion();
} | @Test
public void testValueToKeyVersionRetrievedFromAppInfoParser() {
assertEquals(AppInfoParser.getVersion(), xform.version());
} |
@Override
public PortNumber decode(int value) {
return PortNumber.portNumber(value);
} | @Test
public void testDecode() {
assertThat(sut.decode(100), is(PortNumber.portNumber(100)));
} |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterministicNonDeterministicChild() {
// Super class has non deterministic fields.
assertNonDeterministic(
AvroCoder.of(SubclassOfUnorderedMapClass.class),
reasonField(UnorderedMapClass.class, "mapField", "may not be deterministically ordered"));
} |
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 shouldParseTimestampStringAsTimestampInArray() throws Exception {
String tsStr = "2019-08-23T14:34:54.346Z";
String arrayStr = "[" + tsStr + "]";
SchemaAndValue result = Values.parseString(arrayStr);
assertEquals(Type.ARRAY, result.schema().type());
Schema e... |
public CoordinatorResult<TxnOffsetCommitResponseData, CoordinatorRecord> commitTransactionalOffset(
RequestContext context,
TxnOffsetCommitRequestData request
) throws ApiException {
validateTransactionalOffsetCommit(context, request);
final TxnOffsetCommitResponseData response = ne... | @Test
public void testGenericGroupTransactionalOffsetCommitWithIllegalGenerationId() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Create a group.
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup(
... |
@Override
public OpenstackNode updateIntbridge(DeviceId newIntgBridge) {
return new Builder()
.type(type)
.hostname(hostname)
.intgBridge(newIntgBridge)
.managementIp(managementIp)
.dataIp(dataIp)
.vlanIntf(vlanI... | @Test
public void testUpdateIntBridge() {
OpenstackNode updatedNode = refNode.updateIntbridge(DeviceId.deviceId("br-tun"));
checkCommonProperties(updatedNode);
assertEquals(updatedNode.intgBridge(), DeviceId.deviceId("br-tun"));
} |
@Override
public CompletableFuture<Void> cleanupAsync(JobID jobId) {
mainThreadExecutor.assertRunningInMainThread();
CompletableFuture<Void> cleanupFuture = FutureUtils.completedVoidFuture();
for (CleanupWithLabel<T> cleanupWithLabel : prioritizedCleanup) {
cleanupFuture =
... | @Test
void testSuccessfulConcurrentCleanup() {
final SingleCallCleanup cleanup0 = SingleCallCleanup.withoutCompletionOnCleanup();
final SingleCallCleanup cleanup1 = SingleCallCleanup.withoutCompletionOnCleanup();
final CompletableFuture<Void> cleanupResult =
createTestInstan... |
public static OffsetDateTimeByInstantComparator getInstance() {
return INSTANCE;
} | @Test
void should_have_one_instance() {
assertThat(comparator).isSameAs(OffsetDateTimeByInstantComparator.getInstance());
} |
public XmlStreamInfo information() throws IOException {
if (information.problem != null) {
return information;
}
if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) {
information.problem = new IllegalStateException("Expected START_DOCUMENT");
retu... | @Test
public void simpleRoute() throws IOException {
String xml = readAllFromFile("simpleRoute.xml");
XmlStreamDetector detector
= new XmlStreamDetector(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
XmlStreamInfo info = detector.information();
asse... |
static Integer findNextUnusedIdFromGap(NavigableSet<Integer> setWithGaps) {
int next = 0;
while (setWithGaps.contains(next)) {
next++;
}
return next;
} | @Test
public void testFindingIdsInGaps() {
assertThat(NodeIdAssignor.findNextUnusedIdFromGap(new TreeSet<>(Set.of(0, 2))), is(1));
assertThat(NodeIdAssignor.findNextUnusedIdFromGap(new TreeSet<>(Set.of(0, 2, 3, 4, 5))), is(1));
assertThat(NodeIdAssignor.findNextUnusedIdFromGap(new TreeSet<>(... |
public void addEntry(WhitelistEntry entry) {
final UrlWhitelist modified = addEntry(getWhitelist(), entry);
saveWhitelist(modified);
} | @Test
public void addEntry() {
final WhitelistEntry existingEntry = LiteralWhitelistEntry.create("a", "a", "a");
final UrlWhitelist existingWhitelist = UrlWhitelist.createEnabled(Collections.singletonList(existingEntry));
final WhitelistEntry newEntry = LiteralWhitelistEntry.create("b", "b",... |
@Override
public void removeRule(final RuleData ruleData) {
Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData)));
} | @Test
public void removeRuleTest() {
contextPathPluginDataHandler.removeRule(RuleData.builder().handle("{}").build());
} |
public static MetadataExtractor create(String metadataClassName) {
String metadataExtractorClassName = metadataClassName;
try {
LOGGER.info("Instantiating MetadataExtractor class {}", metadataExtractorClassName);
MetadataExtractor metadataExtractor = (MetadataExtractor) Class.forName(metadataExtract... | @Test
public void testDefaultMetadataProvider() {
Assert.assertTrue(MetadataExtractorFactory.create(null) instanceof DefaultMetadataExtractor);
} |
protected static boolean startMarketActivity(
@NonNull Context context, @NonNull String marketKeyword) {
try {
Intent search = new Intent(Intent.ACTION_VIEW);
Uri uri =
new Uri.Builder()
.scheme("market")
.authority("search")
.appendQueryParamete... | @Test
public void testUtilityNoMarketError() {
Application context = ApplicationProvider.getApplicationContext();
Assert.assertTrue(AddOnStoreSearchController.startMarketActivity(context, "play"));
var intent = Shadows.shadowOf(context).getNextStartedActivity();
Assert.assertEquals(Intent.ACTION_VIEW... |
public Map<String, MinionEventObserver> getMinionEventObserverWithGivenState(MinionTaskState taskState) {
return _taskEventObservers.entrySet().stream()
.filter(e -> e.getValue().getTaskState() == taskState)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} | @Test
public void testGetMinionEventObserverWithGivenState() {
MinionEventObserver observer1 = new MinionProgressObserver();
observer1.notifyTaskStart(null);
MinionEventObservers.getInstance().addMinionEventObserver("t01", observer1);
MinionEventObserver observer2 = new MinionProgressObserver();
... |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testInt64WithDefault() throws Exception {
Schema schema = Schema.of(Schema.Field.nullable("f0", FieldType.INT64));
Row row1 = Row.withSchema(schema).addValue(1L).build();
Row row2 = Row.withSchema(schema).addValue(null).build();
Row row3 = Row.withSchema(schema).addValue(3L).build();... |
public long minOffset(MessageQueue mq) throws MQClientException {
String brokerAddr = this.mQClientFactory.findBrokerAddressInPublish(this.mQClientFactory.getBrokerNameFromMessageQueue(mq));
if (null == brokerAddr) {
this.mQClientFactory.updateTopicRouteInfoFromNameServer(mq.getTopic());
... | @Test
public void assertMinOffset() throws MQClientException {
assertEquals(0, mqAdminImpl.minOffset(new MessageQueue()));
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = false;
boolean containsNull = false;
// Spec. definiti... | @Test
void invokeArrayParamReturnTrue() {
FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{Boolean.TRUE, Boolean.TRUE}), true);
FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{Boolean.TRUE, Boolean.FALSE}), true);
FunctionTestUtil.assertResult(anyFunction.invoke(ne... |
static File getQualifiedBinInner(File hadoopHomeDir, String executable)
throws FileNotFoundException {
String binDirText = "Hadoop bin directory ";
File bin = new File(hadoopHomeDir, "bin");
if (!bin.exists()) {
throw new FileNotFoundException(addOsText(binDirText + E_DOES_NOT_EXIST
+ ... | @Test
public void testBinWinUtilsFound() throws Throwable {
try {
File bin = new File(methodDir, "bin");
File winutils = new File(bin, WINUTILS_EXE);
touch(winutils);
assertEquals(winutils.getCanonicalPath(),
getQualifiedBinInner(methodDir, WINUTILS_EXE).getCanonicalPath());
... |
@SuppressWarnings({"deprecation", "checkstyle:linelength"})
public void convertSiteProperties(Configuration conf,
Configuration yarnSiteConfig, boolean drfUsed,
boolean enableAsyncScheduler, boolean userPercentage,
FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) {
yarnSiteConfig... | @Test
public void testSiteAssignMultipleConversion() {
yarnConfig.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true);
converter.convertSiteProperties(yarnConfig, yarnConvertedConfig, false,
false, false, null);
assertTrue("Assign multiple",
yarnConvertedConfig.getBoolean(
... |
@Override
public MySQLPacket getQueryRowPacket() throws SQLException {
return new MySQLTextResultSetRowPacket(proxyBackendHandler.getRowData().getData());
} | @Test
void assertGetQueryRowPacket() throws SQLException {
assertThat(new MySQLComQueryPacketExecutor(packet, connectionSession).getQueryRowPacket(), instanceOf(MySQLTextResultSetRowPacket.class));
} |
@Override
public GroupVersion groupVersion() {
return PublicApiUtils.groupVersion(new Category());
} | @Test
void groupVersion() {
GroupVersion groupVersion = endpoint.groupVersion();
assertThat(groupVersion.toString()).isEqualTo("api.content.halo.run/v1alpha1");
} |
public DicomWebPath parseDicomWebpath(String unparsedWebpath) throws IOException {
String[] webPathSplit = unparsedWebpath.split("/dicomWeb/");
if (webPathSplit.length != 2) {
throw new IOException("Invalid DICOM web path");
}
DicomWebPath dicomWebPath = new DicomWebPath();
dicomWebPath.dic... | @Test
public void test_parsedAllElements() throws IOException {
String webpathStr =
"projects/foo/location/earth/datasets/bar/dicomStores/fee/dicomWeb/studies/abc/series/xyz/instances/123";
WebPathParser parser = new WebPathParser();
WebPathParser.DicomWebPath dicomWebPath = parser.parseDicomWebp... |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testReadAllEntrySet() throws InterruptedException {
RMapCacheNative<Integer, String> map = redisson.getMapCacheNative("simple12");
map.put(1, "12");
map.put(2, "33", Duration.ofMinutes(10));
map.put(3, "43");
assertThat(map.readAllEntrySet()).isEqua... |
Record convert(Object data) {
return convert(data, null);
} | @Test
public void testNestedMapConvert() {
Table table = mock(Table.class);
when(table.schema()).thenReturn(NESTED_SCHEMA);
RecordConverter converter = new RecordConverter(table, config);
Map<String, Object> nestedData = createNestedMapData();
Record record = converter.convert(nestedData);
as... |
public static Collection<java.nio.file.Path> listFilesInDirectory(
final java.nio.file.Path directory, final Predicate<java.nio.file.Path> fileFilter)
throws IOException {
checkNotNull(directory, "directory");
checkNotNull(fileFilter, "fileFilter");
if (!Files.exists(dir... | @Test
void testListAFileFailsBecauseDirectoryIsExpected() throws IOException {
final String fileName = "a.jar";
final File file = TempDirUtils.newFile(temporaryFolder, fileName);
assertThatThrownBy(
() -> FileUtils.listFilesInDirectory(file.toPath(), FileUtils::isJarF... |
public void setTarget(LogOutput target) {
this.target = target;
} | @Test
public void testChangeTarget() {
listener = mock(LogOutput.class);
appender.setTarget(listener);
testLevelTranslation();
} |
Map<TaskId, Task> allOwnedTasks() {
// not bothering with an unmodifiable map, since the tasks themselves are mutable, but
// if any outside code modifies the map or the tasks, it would be a severe transgression.
return tasks.allTasksPerId();
} | @Test
public void shouldNotReturnStateUpdaterTasksInOwnedTasks() {
final StreamTask activeTask = statefulTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RUNNING)
.withInputPartitions(taskId03Partitions).build();
final StandbyTask standbyTask = standbyTask(taskId02,... |
@Override
public ParsedSchema toParsedSchema(final PersistenceSchema schema) {
SerdeUtils.throwOnUnsupportedFeatures(schema.features(), format.supportedFeatures());
final ConnectSchema outerSchema = ConnectSchemas.columnsToConnectSchema(schema.columns());
final ConnectSchema innerSchema = SerdeUtils
... | @Test
public void shouldSupportBuildingPrimitiveSchemas() {
// Given:
when(format.supportedFeatures()).thenReturn(ImmutableSet.of(SerdeFeature.UNWRAP_SINGLES));
// When:
translator.toParsedSchema(
PersistenceSchema.from(
ImmutableList.of(createColumn("bob", SqlTypes.INTEGER)),
... |
@Implementation
public static synchronized String getTokenWithNotification(
Context context, Account account, String scope, Bundle extras)
throws IOException, UserRecoverableNotifiedException, GoogleAuthException {
return googleAuthUtilImpl.getTokenWithNotification(context, account, scope, extras);
... | @Test
public void getTokenWithNotification_nullCallBackThrowIllegalArgumentException()
throws Exception {
thrown.expect(IllegalArgumentException.class);
GoogleAuthUtil.getTokenWithNotification(
RuntimeEnvironment.getApplication(), "name", "scope", null, null);
} |
public static Permission getPermission(String name, String serviceName, String... actions) {
PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName);
if (permissionFactory == null) {
throw new IllegalArgumentException("No permissions found for service: " + serviceName);... | @Test
public void getPermission_Map() {
Permission permission = ActionConstants.getPermission("foo", MapService.SERVICE_NAME);
assertNotNull(permission);
assertTrue(permission instanceof MapPermission);
} |
public IndexRecord getIndexInformation(String mapId, int reduce,
Path fileName, String expectedIndexOwner)
throws IOException {
IndexInformation info = cache.get(mapId);
if (info == null) {
info = readIndexFileToCache(fileName, mapId, expectedIndexOwner);
... | @Test
public void testInvalidReduceNumberOrLength() throws Exception {
fs.delete(p, true);
conf.setInt(MRJobConfig.SHUFFLE_INDEX_CACHE, 1);
final int partsPerMap = 1000;
final int bytesPerFile = partsPerMap * 24;
IndexCache cache = new IndexCache(conf);
// fill cache
Path feq = new Path(p... |
@Override
protected VertexFlameGraph handleRequest(
HandlerRequest<EmptyRequestBody> request, AccessExecutionJobVertex jobVertex)
throws RestHandlerException {
@Nullable Integer subtaskIndex = getSubtaskIndex(request, jobVertex);
if (isTerminated(jobVertex, subtaskIndex)) {
... | @Test
void testHandleMixedSubtasks() throws Exception {
final ArchivedExecutionJobVertex archivedExecutionJobVertex =
new ArchivedExecutionJobVertex(
new ArchivedExecutionVertex[] {
generateExecutionVertex(0, ExecutionState.FINISHED),
... |
public static Map<String, Object> parseParameters(URI uri) throws URISyntaxException {
String query = prepareQuery(uri);
if (query == null) {
// empty an empty map
return new LinkedHashMap<>(0);
}
return parseQuery(query);
} | @Test
public void testParseParameters() throws Exception {
URI u = new URI("quartz:myGroup/myTimerName?cron=0%200%20*%20*%20*%20?");
Map<String, Object> params = URISupport.parseParameters(u);
assertEquals(1, params.size());
assertEquals("0 0 * * * ?", params.get("cron"));
u... |
public boolean transitionToFinished()
{
return state.setIf(FINISHED, currentState -> !currentState.isDone());
} | @Test
public void testFinished()
{
StageExecutionStateMachine stateMachine = createStageStateMachine();
assertTrue(stateMachine.transitionToFinished());
assertFinalState(stateMachine, StageExecutionState.FINISHED);
} |
@Override
public void upgrade() {
if (shouldSkip()) {
return;
}
final ImmutableSet<String> eventIndexPrefixes = ImmutableSet.of(
elasticsearchConfig.getDefaultEventsIndexPrefix(),
elasticsearchConfig.getDefaultSystemEventsIndexPrefix());
... | @Test
void writesMigrationCompletedAfterSuccess() {
mockConfiguredEventPrefixes("events-prefix", "system-events-prefix");
this.sut.upgrade();
final V20200730000000_AddGl2MessageIdFieldAliasForEvents.MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(mi... |
@GET
@Path("/{pluginName}/config")
@Operation(summary = "Get the configuration definition for the specified pluginName")
public List<ConfigKeyInfo> getConnectorConfigDef(final @PathParam("pluginName") String pluginName) {
synchronized (this) {
return herder.connectorPluginConfig(pluginNa... | @Test
public void testGetConnectorConfigDef() {
String connName = ConnectorPluginsResourceTestConnector.class.getName();
when(herder.connectorPluginConfig(eq(connName))).thenAnswer(answer -> {
List<ConfigKeyInfo> results = new ArrayList<>();
for (ConfigDef.ConfigKey configKey... |
public MetadataBlockType getType() {
return _errCodeToExceptionMap.isEmpty() ? MetadataBlockType.EOS : MetadataBlockType.ERROR;
} | @Test
public void v0EosWithExceptionsIsDecodedAsV2ErrorWithSameExceptions()
throws IOException {
// Given:
// MetadataBlock used to be encoded without any data, we should make sure that
// during rollout or if server versions are mismatched that we can still handle
// the old format
V0Metada... |
@Override
public Flux<ExtensionStore> listByNamePrefix(String prefix) {
return repository.findAllByNameStartingWith(prefix);
} | @Test
void listByNamePrefix() {
var expectedExtensions = List.of(
new ExtensionStore("/registry/posts/hello-world", "this is post".getBytes(), 1L),
new ExtensionStore("/registry/posts/hello-halo", "this is post".getBytes(), 1L)
);
when(repository.findAllByNameStartin... |
public static Object fromJson(String json, Type originType) throws RuntimeException {
if (!isSupportGson()) {
throw new RuntimeException("Gson is not supported. Please import Gson in JVM env.");
}
Type type = TypeToken.get(originType).getType();
try {
return getGs... | @Test
void test1() {
Object user = GsonUtils.fromJson("{'name':'Tom','age':24}", User.class);
Assertions.assertInstanceOf(User.class, user);
Assertions.assertEquals("Tom", ((User) user).getName());
Assertions.assertEquals(24, ((User) user).getAge());
try {
GsonUt... |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (boolean.class == type) {
return resultSet.getBoolean(columnIndex);
}
if (byte.class == type) {
return resultSet.getByte(columnIndex);
}
if (short.cla... | @Test
void assertGetValueByArray() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
Array value = mock(Array.class);
when(resultSet.getArray(1)).thenReturn(value);
assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, Array.class), is(value));
} |
public RepositoryList searchRepos(String encodedCredentials, String workspace, @Nullable String repoName, Integer page, Integer pageSize) {
String filterQuery = String.format("q=name~\"%s\"", repoName != null ? repoName : "");
HttpUrl url = buildUrl(String.format("/repositories/%s?%s&page=%s&pagelen=%s", worksp... | @Test
public void get_repos() {
server.enqueue(new MockResponse()
.setHeader("Content-Type", "application/json;charset=UTF-8")
.setBody("{\n" +
" \"values\": [\n" +
" {\n" +
" \"slug\": \"banana\",\n" +
" \"uuid\": \"BANANA-UUID\",\n" +
" \"na... |
@Override
public void execute(Context context) {
List<MeasureComputerWrapper> wrappers = Arrays.stream(measureComputers).map(ToMeasureWrapper.INSTANCE).toList();
validateMetrics(wrappers);
measureComputersHolder.setMeasureComputers(sortComputers(wrappers));
} | @Test
public void return_empty_list_when_no_measure_computers() {
ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()));
underTest.execute(new TestComputationStepContext());
assertThat(holder.getMeasureComputers()).isEmpty();
} |
public QueryObjectBundle rewriteQuery(@Language("SQL") String query, QueryConfiguration queryConfiguration, ClusterType clusterType)
{
return rewriteQuery(query, queryConfiguration, clusterType, false);
} | @Test
public void testRewriteTimestampWithTimeZone()
{
QueryBundle queryBundle = getQueryRewriter().rewriteQuery("SELECT now(), now() now", CONFIGURATION, CONTROL);
assertCreateTableAs(queryBundle.getQuery(), "SELECT\n" +
" CAST(now() AS varchar)\n" +
", CAST(now... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize"));
} | @Test
public void testListFilePlusCharacter() throws Exception {
final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatu... |
public GaussianDistribution(double mu, double sigma) {
this.mu = mu;
this.sigma = sigma;
variance = sigma * sigma;
entropy = Math.log(sigma) + LOG2PIE_2;
pdfConstant = Math.log(sigma) + LOG2PI_2;
} | @Test
public void testGaussianDistribution() {
System.out.println("GaussianDistribution");
MathEx.setSeed(19650218); // to get repeatable results.
GaussianDistribution instance = new GaussianDistribution(3, 2.1);
double[] data = instance.rand(1000);
GaussianDistribution est =... |
@Override
public AuthUser getAuthUser(Integer socialType, Integer userType, String code, String state) {
// 构建请求
AuthRequest authRequest = buildAuthRequest(socialType, userType);
AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build();
// 执行请求
AuthR... | @Test
public void testAuthSocialUser_fail() {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String code = randomString();
String state = randomString();
// mock 方法(AuthRequest)
Au... |
protected int sendSms(String numberTo, String message) throws ThingsboardException {
if (this.smsSender == null) {
throw new ThingsboardException("Unable to send SMS: no SMS provider configured!", ThingsboardErrorCode.GENERAL);
}
return this.sendSms(this.smsSender, numberTo, message)... | @Test
public void testLimitSmsMessagingByTenantProfileSettings() throws Exception {
tenantProfile = getDefaultTenantProfile();
DefaultTenantProfileConfiguration config = createTenantProfileConfigurationWithSmsLimits(10, true);
saveTenantProfileWitConfiguration(tenantProfile, config);
... |
public SSLContext createContext(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, UnrecoverableKeyException, KeyStoreException, CertificateException {
SSLContext sslContext = getProvider() != null ? SSLContext.getInstance(getProtocol(), getProvi... | @Test
public void testCreateDefaultContext() throws Exception {
// should be able to create a context with no configuration at all
assertNotNull(factoryBean.createContext(context));
assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN));
} |
@Override
@Nonnull
public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) {
throwRejectedExecutionExceptionIfShutdown();
ArrayList<Future<T>> result = new ArrayList<>();
for (Callable<T> task : tasks) {
try {
result.add(new Co... | @Test
void testRejectedInvokeAllWithEmptyListAndTimeout() {
testRejectedExecutionException(
testInstance -> testInstance.invokeAll(Collections.emptyList(), 1L, TimeUnit.DAYS));
} |
@Override
public final boolean isWrapperFor(final Class<?> iface) {
return iface.isInstance(this);
} | @Test
void assertIsWrapperFor() {
assertTrue(wrapperAdapter.isWrapperFor(Object.class));
} |
@Override
public void linkNodes(K parentKey, K childKey, BiConsumer<TreeEntry<K, V>, TreeEntry<K, V>> consumer) {
consumer = ObjectUtil.defaultIfNull(consumer, (parent, child) -> {
});
final TreeEntryNode<K, V> parentNode = nodes.computeIfAbsent(parentKey, t -> new TreeEntryNode<>(null, t));
TreeEntryNode<K, V... | @Test
public void getTreeNodesTest() {
final ForestMap<String, String> map = new LinkedForestMap<>(false);
map.linkNodes("a", "b");
map.linkNodes("b", "c");
final List<String> expected = CollUtil.newArrayList("a", "b", "c");
List<String> actual = CollStreamUtil.toList(map.getTreeNodes("a"), TreeEntry::getKe... |
public static void main(String[] args) throws Exception {
TikaCLI cli = new TikaCLI();
if (cli.testForHelp(args)) {
cli.usage();
return;
} else if (cli.testForBatch(args)) {
String[] batchArgs = BatchCommandLineBuilder.build(args);
BatchProcessDri... | @Test
public void testContentAllOutput() throws Exception {
String[] params = {"-A", resourcePrefix + "testJsonMultipleInts.html"};
TikaCLI.main(params);
String out = outContent.toString(UTF_8.name());
assertTrue(out.contains("this is a title"));
assertTrue(out.contains("body... |
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
String domain = exchange.getAttribute(Constants.HTTP_DOMAIN);
if (StringUtils.isBlank(domain)) {
return chain.execute(exchange);
}
final URI uri = RequestUrlUtils.buildR... | @Test
public void testDoExecute() {
when(exchange.getAttribute(Constants.HTTP_DOMAIN)).thenReturn("http://localhost:8090");
when(chain.execute(exchange)).thenReturn(Mono.empty());
StepVerifier.create(uriPlugin.execute(exchange, chain)).expectSubscription().verifyComplete();
assertEqu... |
public boolean isSuppressed(Device device) {
if (suppressedDeviceType.contains(device.type())) {
return true;
}
final Annotations annotations = device.annotations();
if (containsSuppressionAnnotation(annotations)) {
return true;
}
return false;
... | @Test
public void testNotSuppressedDevice() {
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
assertFalse(rules.isSuppr... |
public static List<BindAddress> validateBindAddresses(ServiceConfiguration config, Collection<String> schemes) {
// migrate the existing configuration properties
List<BindAddress> addresses = migrateBindAddresses(config);
// parse the list of additional bind addresses
Arrays
... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testMalformed() {
ServiceConfiguration config = newEmptyConfiguration();
config.setBindAddresses("internal:");
List<BindAddress> addresses = BindAddressValidator.validateBindAddresses(config, null);
assertEquals(0... |
Optional<TimeRange> parse(final String shortTimerange) {
if (shortTimerange != null && SHORT_FORMAT_PATTERN.matcher(shortTimerange).matches()) {
final String numberPart = shortTimerange.substring(0, shortTimerange.length() - 1);
final String periodPart = shortTimerange.substring(shortTim... | @Test
void returnsEmptyOptionalOnBadInput() {
assertThat(toTest.parse("#$%")).isEmpty();
assertThat(toTest.parse("13days")).isEmpty();
assertThat(toTest.parse("42x")).isEmpty();
assertThat(toTest.parse("-13days")).isEmpty();
assertThat(toTest.parse("1,5d")).isEmpty();
... |
public void scheduleUpdateIfAbsent(String serviceName, String groupName, String clusters) {
if (!asyncQuerySubscribeService) {
return;
}
String serviceKey = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters);
if (futureMap.get(serviceKey) != null... | @Test
void testScheduleUpdateIfAbsentWithOtherException()
throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException {
nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true");
serviceInfoUpdateService = new ServiceIn... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds);
intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub);
for (String feature : FEATURES_IN_ORDER)
{
... | @Test
void testApplyTransforms_locl()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(642);
// when
List<Integer> result = gsubWorkerForDevanagari.applyTransforms(getGlyphIds("प्त"));
System.out.println("result: " + result);
// then
assertEquals... |
@PublicAPI(usage = ACCESS)
public static Transformer matching(String packageIdentifier) {
PackageMatchingSliceIdentifier sliceIdentifier = new PackageMatchingSliceIdentifier(packageIdentifier);
String description = "slices matching " + sliceIdentifier.getDescription();
return new Transformer... | @Test
public void matches_slices() {
JavaClasses classes = importClassesWithContext(Object.class, String.class, List.class, Set.class, Pattern.class);
assertThat(Slices.matching("java.(*)..").transform(classes)).hasSize(2);
assertThat(Slices.matching("(**)").transform(classes)).hasSize(3);
... |
@Override
public Mono<String> generateBundleVersion() {
if (pluginManager.isDevelopment()) {
return Mono.just(String.valueOf(clock.instant().toEpochMilli()));
}
return Flux.fromIterable(new ArrayList<>(pluginManager.getStartedPlugins()))
.sort(Comparator.comparing(Plu... | @Test
void generateBundleVersionTest() {
var plugin1 = mock(PluginWrapper.class);
var plugin2 = mock(PluginWrapper.class);
var plugin3 = mock(PluginWrapper.class);
when(pluginManager.getStartedPlugins()).thenReturn(List.of(plugin1, plugin2, plugin3));
var descriptor1 = mock(... |
@Nullable
public static <T> T getWithoutException(CompletableFuture<T> future) {
if (isCompletedNormally(future)) {
try {
return future.get();
} catch (InterruptedException | ExecutionException ignored) {
}
}
return null;
} | @Test
void testGetWithoutException() {
final int expectedValue = 1;
final CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
completableFuture.complete(expectedValue);
assertThat(FutureUtils.getWithoutException(completableFuture)).isEqualTo(expectedValue);
... |
public static void validate(
FederationPolicyInitializationContext policyContext, String myType)
throws FederationPolicyInitializationException {
if (myType == null) {
throw new FederationPolicyInitializationException(
"The myType parameter" + " should not be null.");
}
if (pol... | @Test(expected = FederationPolicyInitializationException.class)
public void nullContext() throws Exception {
FederationPolicyInitializationContextValidator.validate(null,
MockPolicyManager.class.getCanonicalName());
} |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepListWithInteger() throws Exception {
List<Integer> data = new ArrayList<>();
data.add(1);
@SuppressWarnings("rawtypes")
RubyArray rubyArray = (RubyArray)Rubyfier.deep(RubyUtil.RUBY, data);
// toJavaArray does not newFromRubyArray inner elements to ... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testStateIdDuplicate() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Duplicate");
thrown.expectMessage("StateId");
thrown.expectMessage("my-id");
thrown.expectMessage("myfield1");
thrown.expectMessage("myfield2");
thrown.expectMes... |
public void addVariable(String variable) throws YarnException {
if (immutableVariables.contains(variable)) {
throw new YarnException("Variable '" + variable + "' is immutable " +
"cannot add to the modified variable list.");
}
knownVariables.add(variable);
} | @Test
public void testDynamicQueueValidation() {
//Setting up queue manager and emulated queue hierarchy
CapacitySchedulerQueueManager qm =
mock(CapacitySchedulerQueueManager.class);
MockQueueHierarchyBuilder.create()
.withQueueManager(qm)
.withQueue("root.unmanaged")
.wit... |
@Converter(fallback = true)
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
if (NodeInfo.class.isAssignableFrom(value.getClass())) {
// use a fallback type converter so we can convert the embedded body if the value is NodeInfo
... | @Test
public void convertToNode() {
Node node = context.getTypeConverter().convertTo(Node.class, exchange, doc);
assertNotNull(node);
String string = context.getTypeConverter().convertTo(String.class, exchange, node);
assertEquals(CONTENT, string);
} |
@Override
public byte[] getFileContent(Long configId, String path) throws Exception {
FileClient client = fileConfigService.getFileClient(configId);
Assert.notNull(client, "客户端({}) 不能为空", configId);
return client.getContent(path);
} | @Test
public void testGetFileContent() throws Exception {
// 准备参数
Long configId = 10L;
String path = "tudou.jpg";
// mock 方法
FileClient client = mock(FileClient.class);
when(fileConfigService.getFileClient(eq(10L))).thenReturn(client);
byte[] content = new byt... |
public static TableIdentifier fromJson(String json) {
Preconditions.checkArgument(
json != null, "Cannot parse table identifier from invalid JSON: null");
Preconditions.checkArgument(
!json.isEmpty(), "Cannot parse table identifier from invalid JSON: ''");
return JsonUtil.parse(json, TableId... | @Test
public void testTableIdentifierFromJson() {
String json = "{\"namespace\":[\"accounting\",\"tax\"],\"name\":\"paid\"}";
TableIdentifier identifier = TableIdentifier.of(Namespace.of("accounting", "tax"), "paid");
assertThat(TableIdentifierParser.fromJson(json))
.as("Should be able to deserial... |
@Override
public Result invoke(final Invocation invocation) throws RpcException {
checkWhetherDestroyed();
// binding attachments into invocation.
// Map<String, Object> contextAttachments = RpcContext.getClientAttachment().getObjectAttachments();
// if (contextAttachm... | @Disabled(
"RpcContext attachments will be set to Invocation twice, first in ConsumerContextFilter, second AbstractInvoker")
@Test
void testBindingAttachment() {
final String attachKey = "attach";
final String attachValue = "value";
// setup attachment
RpcContext.get... |
public static List<String> loadAndModifyConfiguration(String[] args) throws FlinkException {
return ConfigurationParserUtils.loadAndModifyConfiguration(
filterCmdArgs(args, ModifiableClusterConfigurationParserFactory.options()),
BashJavaUtils.class.getSimpleName());
} | @TestTemplate
void testloadAndModifyConfigurationRemoveKeysNotMatched() throws Exception {
String key = "key";
String value = "value";
String removeKey = "removeKey";
String[] args = {
"--configDir",
confDir.toFile().getAbsolutePath(),
String.form... |
@Override
public boolean hasSetCookieWithName(String cookieName) {
for (String setCookieValue : getHeaders().getAll(HttpHeaderNames.SET_COOKIE)) {
Cookie cookie = ClientCookieDecoder.STRICT.decode(setCookieValue);
if (cookie.name().equalsIgnoreCase(cookieName)) {
retu... | @Test
void testHasSetCookieWithName() {
response.getHeaders()
.add(
"Set-Cookie",
"c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com");
response.getHeaders()
.add(
... |
public Grok cachedGrokForPattern(String pattern) {
return cachedGrokForPattern(pattern, false);
} | @Test
public void cachedGrokForPatternWithNamedCaptureOnly() {
final Grok grok = grokPatternRegistry.cachedGrokForPattern("%{TESTNUM}", true);
assertThat(grok.getPatterns()).containsEntry(GROK_PATTERN.name(), GROK_PATTERN.pattern());
} |
@Override
public Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor(
List<ExecutionAttemptID> executionAttemptIds) {
Map<ExecutionAttemptID, ExecutionSlotAssignment> result = new HashMap<>();
Map<SlotRequestId, ExecutionAttemptID> remainingExecutionsToSlotRequest =
... | @Test
void testPhysicalSlotReleasesLogicalSlots() throws Exception {
final AllocationContext context = new AllocationContext();
final CompletableFuture<LogicalSlot> slotFuture =
context.allocateSlotsFor(EXECUTION_ATTEMPT_ID);
final TestingPayload payload = new TestingPayload(... |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldUseExplicitInterNodeListenerIfSetToLocalHost() {
// Given:
final URL expected = url("https://localHost:52368");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.putAll(MIN_VALID_CONFIGS)
.put(ADVERTISED_LISTENER_CONFIG, expec... |
public static String encodeInUtf8(String url) {
String[] parts = url.split("/");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
builder.append(URLEncoder.encode(part, StandardCharsets.UTF_8));
if (... | @Test
public void shouldKeepPrecedingSlash() {
assertThat(UrlUtil.encodeInUtf8("/a%b/c%d"), is("/a%25b/c%25d"));
} |
public Set<Long> findCmdIds(List<Status> statusList) throws JobDoesNotExistException {
Set<Long> set = new HashSet<>();
for (Map.Entry<Long, CmdInfo> x : mInfoMap.entrySet()) {
if (statusList.isEmpty()
|| statusList.contains(getCmdStatus(
x.getValue().getJobControlId())... | @Test
public void testFindCmdIdsForComplete() throws Exception {
long completedId = generateMigrateCommandForStatus(Status.COMPLETED);
mSearchingCriteria.add(Status.COMPLETED);
Set<Long> completedCmdIds = mCmdJobTracker.findCmdIds(mSearchingCriteria);
Assert.assertEquals(completedCmdIds.size(), 1);
... |
@ApiOperation(value = "Update a user’s info", tags = { "Users" }, nickname = "updateUserInfo")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the user was found and the info has been updated."),
@ApiResponse(code = 400, message = "Indicates the value was missing from t... | @Test
public void testGetUserInfoCollection() throws Exception {
User savedUser = null;
try {
User newUser = identityService.newUser("testuser");
newUser.setFirstName("Fred");
newUser.setLastName("McDonald");
newUser.setEmail("no-reply@flowable.org");
... |
public RowExpression extract(PlanNode node)
{
return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null);
} | @Test
public void testInnerJoinWithFalseFilter()
{
Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV)));
TableScanNode leftScan = tableScanNode(leftAssignments);
Map<VariableReferenceExpression, Co... |
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.size() < 2) {
printInfo(err);
return 1;
}
int index = 0;
String input = args.get(index);
String option = "all";
if ("-o".equals(input)) {
option = args... | @Test
void repairAllCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "all", corruptRecordFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 8 N... |
public Output run(RunContext runContext) throws Exception {
Logger logger = runContext.logger();
URI from = new URI(runContext.render(this.uri));
File tempFile = runContext.workingDir().createTempFile(filenameFromURI(from)).toFile();
// output
Output.OutputBuilder builder = Out... | @Test
void noResponse() {
EmbeddedServer embeddedServer = applicationContext.getBean(EmbeddedServer.class);
embeddedServer.start();
Download task = Download.builder()
.id(DownloadTest.class.getSimpleName())
.type(DownloadTest.class.getName())
.uri(embedde... |
@Override
public ProducerImpl.OpSendMsg createOpSendMsg() {
throw new UnsupportedOperationException();
} | @Test(expectedExceptions = UnsupportedOperationException.class)
public void testCreateOpSendMsg() {
RawBatchMessageContainerImpl container = new RawBatchMessageContainerImpl();
container.createOpSendMsg();
} |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds);
intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub);
for (String feature : FEATURES_IN_ORDER)
{
... | @Test
void testApplyTransforms_abvs()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(92,255,92,258,91,102,336);
// when
List<Integer> result = gsubWorkerForGujarati.applyTransforms(getGlyphIds("રેંરૈંર્યાં"));
// then
assertEquals(glyphsAfterGsub, resu... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testNoNulls() {
boolean shouldRead = new StrictMetricsEvaluator(SCHEMA, isNull("all_nulls")).eval(FILE);
assertThat(shouldRead).as("Should match: all values are null").isTrue();
shouldRead = new StrictMetricsEvaluator(SCHEMA, isNull("some_nulls")).eval(FILE);
assertThat(shouldRead).... |
@Override
public SessionStore<K, V> build() {
return new MeteredSessionStore<>(
maybeWrapCaching(maybeWrapLogging(storeSupplier.get())),
storeSupplier.metricsScope(),
keySerde,
valueSerde,
time);
} | @Test
public void shouldHaveCachingStoreWhenEnabled() {
setUp();
final SessionStore<String, String> store = builder.withCachingEnabled().build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(MeteredSessionStore.class));
assert... |
@Override
public boolean containsChar(K name, char value) {
return false;
} | @Test
public void testContainsChar() {
assertFalse(HEADERS.containsChar("name1", 'x'));
} |
@Override
public SelLong field(SelString field) {
String fieldName = field.getInternalVal();
if ("SUNDAY".equals(fieldName)) {
return SelLong.of(DateTimeConstants.SUNDAY);
}
throw new UnsupportedOperationException(type() + " DO NOT support accessing field: " + field);
} | @Test
public void testSundayField() {
SelLong res = SelMiscFunc.INSTANCE.field(SelString.of("SUNDAY"));
assertEquals(7, res.longVal());
} |
@Override
public boolean dropTable(TableIdentifier identifier, boolean purge) {
TableOperations ops = newTableOps(identifier);
TableMetadata lastMetadata = null;
if (purge) {
try {
lastMetadata = ops.current();
} catch (NotFoundException e) {
LOG.warn(
"Failed to lo... | @Test
public void testDropTable() {
TableIdentifier testTable = TableIdentifier.of("db", "ns1", "ns2", "tbl");
TableIdentifier testTable2 = TableIdentifier.of("db", "ns1", "ns2", "tbl2");
catalog.createTable(testTable, SCHEMA, PartitionSpec.unpartitioned());
catalog.createTable(testTable2, SCHEMA, Par... |
public PaginationContext createPaginationContext(final Collection<ExpressionSegment> expressions, final ProjectionsContext projectionsContext, final List<Object> params) {
Optional<String> rowNumberAlias = findRowNumberAlias(projectionsContext);
if (!rowNumberAlias.isPresent()) {
return new ... | @Test
void assertCreatePaginationContextWhenRowNumberAliasNotPresent() {
ProjectionsContext projectionsContext = new ProjectionsContext(0, 0, false, Collections.emptyList());
PaginationContext paginationContext =
new RowNumberPaginationContextEngine(new OracleDatabaseType()).createPa... |
@Override
public void setConfigAttributes(Object attributes) {
clear();
if (attributes == null) {
return;
}
List<Map> attrList = (List<Map>) attributes;
for (Map attrMap : attrList) {
String type = (String) attrMap.get("artifactTypeValue");
... | @Test
public void setConfigAttributes_shouldSetExternalArtifactWithPlainTextValuesIfPluginIdIsProvided() {
ArtifactPluginInfo artifactPluginInfo = mock(ArtifactPluginInfo.class);
PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class);
when(artifactPluginInfo.getDescriptor()).thenRe... |
static void validateBundlingRelatedOptions(SamzaPipelineOptions pipelineOptions) {
if (pipelineOptions.getMaxBundleSize() > 1) {
final Map<String, String> configs =
pipelineOptions.getConfigOverride() == null
? new HashMap<>()
: pipelineOptions.getConfigOverride();
... | @Test(expected = IllegalArgumentException.class)
public void testBundleEnabledInMultiThreadedModeThrowsException() {
SamzaPipelineOptions mockOptions = mock(SamzaPipelineOptions.class);
Map<String, String> config = ImmutableMap.of(JOB_CONTAINER_THREAD_POOL_SIZE, "10");
when(mockOptions.getMaxBundleSize()... |
public Optional<ClusterResources> resources() {
return resources;
} | @Test
public void test_resize() {
var min = new ClusterResources(7, 1, new NodeResources( 2, 10, 384, 1));
var now = new ClusterResources(7, 1, new NodeResources( 3.4, 16.2, 450.1, 1));
var max = new ClusterResources(7, 1, new NodeResources( 4, 32, 768, 1));
var fixture = DynamicP... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void testBuilderThrowsExceptionWhenParentTokenMissing() {
assertThrows(
"parentToken",
IllegalStateException.class,
() ->
PartitionMetadata.newBuilder()
.setPartitionToken(PARTITION_TOKEN)
.setStartTimestamp(START_TIMESTAMP)
... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldRegisterKeyOverrideSchemaAvroForCreateAs()
throws IOException, RestClientException {
// Given:
when(schemaRegistryClient.register(anyString(), any(ParsedSchema.class))).thenReturn(1);
final SchemaAndId keySchemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCHEMA, 1);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.