focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean enableSendingOldValues(final boolean forceMaterialization) {
if (queryableName != null) {
sendOldValues = true;
return true;
}
if (parent.enableSendingOldValues(forceMaterialization)) {
sendOldValues = true;
}
ret... | @Test
public void shouldNotEnableSendingOldValuesOnParentIfMapValuesMaterialized() {
final StreamsBuilder builder = new StreamsBuilder();
final String topic1 = "topic1";
final KTableImpl<String, String, String> table1 =
(KTableImpl<String, String, String>) builder.table(topic1, ... |
@VisibleForTesting
static void enforceStreamStateDirAvailability(final File streamsStateDir) {
if (!streamsStateDir.exists()) {
final boolean mkDirSuccess = streamsStateDir.mkdirs();
if (!mkDirSuccess) {
throw new KsqlServerException("Could not create the kafka streams state directory: "
... | @Test
public void shouldFailIfStreamsStateDirectoryIsNotDirectory() {
// Given:
when(mockStreamsStateDir.isDirectory()).thenReturn(false);
// When:
final Exception e = assertThrows(
KsqlServerException.class,
() -> KsqlServerMain.enforceStreamStateDirAvailability(mockStreamsStateDir)
... |
public final void buildListing(Path pathToListFile,
DistCpContext distCpContext) throws IOException {
validatePaths(distCpContext);
doBuildListing(pathToListFile, distCpContext);
Configuration config = getConf();
config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, pathToListFile.toString());... | @Test(timeout=10000)
public void testBuildListing() {
FileSystem fs = null;
try {
fs = FileSystem.get(getConf());
List<Path> srcPaths = new ArrayList<Path>();
Path p1 = new Path("/tmp/in/1");
Path p2 = new Path("/tmp/in/2");
Path p3 = new Path("/tmp/in2/2");
Path target = n... |
@Override
public void processElement(StreamRecord<RowData> element) throws Exception {
RowData inputRow = element.getValue();
long timestamp;
if (windowAssigner.isEventTime()) {
if (inputRow.isNullAt(rowtimeIndex)) {
// null timestamp would be dropped
... | @Test
public void testHopWindows() throws Exception {
final SlidingWindowAssigner assigner =
SlidingWindowAssigner.of(Duration.ofSeconds(3), Duration.ofSeconds(1));
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(assigner, shiftTime... |
@Override
protected SchemaTransform from(ManagedConfig managedConfig) {
managedConfig.validate();
SchemaTransformProvider schemaTransformProvider =
Preconditions.checkNotNull(
getAllProviders().get(managedConfig.getTransformIdentifier()),
"Could not find a transform with the id... | @Test
public void testBuildWithYamlFile() throws URISyntaxException {
String yamlConfigPath =
Paths.get(getClass().getClassLoader().getResource("test_config.yaml").toURI())
.toFile()
.getAbsolutePath();
ManagedConfig config =
ManagedConfig.builder()
.setTra... |
public static Map<String, Object> replaceKeyCharacter(Map<String, Object> map, char oldChar, char newChar) {
final Map<String, Object> result = new HashMap<>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
final String key = entry.getKey().replace(oldChar, newChar);
... | @Test
public void renameKeyReturnsMutatedMap() {
final Map<String, Object> map = ImmutableMap.of(
"foo.bar", "test",
"baz@quux", "test");
assertThat(MapUtils.replaceKeyCharacter(map, '.', '_'))
.hasSameSizeAs(map)
.containsEntry("foo_ba... |
public static ImmutableList<String> glob(final String glob) {
Path path = getGlobPath(glob);
int globIndex = getGlobIndex(path);
if (globIndex < 0) {
return of(glob);
}
return doGlob(path, searchPath(path, globIndex));
} | @Test
public void should_glob_relative_files() {
ImmutableList<String> files = Globs.glob("src/test/resources/details/*.json");
assertThat(files.contains("src/test/resources/details/foo.json"), is(true));
assertThat(files.contains("src/test/resources/details/bar.json"), is(true));
} |
protected void serviceStop() throws Exception {
//stop all services that were started
int numOfServicesToStop = serviceList.size();
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": stopping services, size=" + numOfServicesToStop);
}
stop(numOfServicesToStop, STOP_ONLY_STARTED_SERVICES);
... | @Test
public void testServiceStop() {
ServiceManager serviceManager = new ServiceManager("ServiceManager");
// Add services
for (int i = 0; i < NUM_OF_SERVICES; i++) {
CompositeServiceImpl service = new CompositeServiceImpl(i);
if (i == FAILED_SERVICE_SEQ_NUMBER) {
service.setThrowExc... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testFieldAccess() throws IllegalAccessException {
FieldAccessDescriptor descriptor = FieldAccessDescriptor.withFieldNames("foo", "bar");
DoFn<String, String> doFn =
new DoFn<String, String>() {
@FieldAccess("foo")
final FieldAccessDescriptor fieldAccess = descript... |
@Override
public void put(String key, String value) {
// Assume any header property that begins with 'Camel' is for internal use
if (!key.startsWith("Camel")) {
this.map.put(encodeDash(key), value);
}
} | @Test
public void putProperties() {
CamelMessagingHeadersInjectAdapter adapter = new CamelMessagingHeadersInjectAdapter(map, true);
adapter.put("key1", "value1");
adapter.put("key2", "value2");
adapter.put("key1", "value3");
assertEquals("value3", map.get("key1"));
as... |
public static String describe(Object o) {
try {
if (o.getClass().getMethod("toString").getDeclaringClass() != Object.class) {
String str = o.toString();
if (str != null) {
return str;
}
}
} catch (Exception e) {
// fallback
}
return o.getClass().getNa... | @Test
public void describe() {
assertThat(ScannerUtils.describe(new Object())).isEqualTo("java.lang.Object");
assertThat(ScannerUtils.describe(new TestClass())).isEqualTo("overridden");
} |
public KafkaFuture<Void> all() {
final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>();
this.future.whenComplete((memberErrors, throwable) -> {
if (throwable != null) {
result.completeExceptionally(throwable);
} else {
if (removeAll()) {
... | @Test
public void testTopLevelErrorConstructor() throws InterruptedException {
memberFutures.completeExceptionally(Errors.GROUP_AUTHORIZATION_FAILED.exception());
RemoveMembersFromConsumerGroupResult topLevelErrorResult =
new RemoveMembersFromConsumerGroupResult(memberFutures, membersToR... |
@Udf(description = "When filtering a map, "
+ "the function provided must have a boolean result. "
+ "For each map entry, the function will be applied to the "
+ "key and value arguments in that order. The filtered map is returned."
)
public <K, V> Map<K, V> filterMap(
@UdfParameter(descript... | @Test
public void shouldThrowErrorOnNullMapInput() {
final Map<Integer, Integer> m1 = new HashMap<>();
m1.put(null, 4);
final Map<String, String> m2 = new HashMap<>();
m2.put("nope", null);
assertThrows(NullPointerException.class, () -> udf.filterMap(m1, biFunction1()));
assertThrows(NullPoint... |
@Override
protected boolean hasPluginInfo() {
return metadataStore().getPluginInfo(getPluginId()) != null;
} | @Test
public void shouldReturnTrueIfPluginInfoIsDefined() {
final ArtifactPluginInfo pluginInfo = new ArtifactPluginInfo(pluginDescriptor("plugin_id"), null, null, null, null, null);
store.setPluginInfo(pluginInfo);
final ArtifactStore artifactStore = new ArtifactStore("id", "plugin_id");
... |
@Override
public boolean encode(
@NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = resource.get();
Transformation<Bitmap> transformation = drawable.getFrameTransformation();
boolean isTransformed = !(transformation instanceof UnitTransfor... | @Test
public void testWritesTransformedBitmaps() {
final Bitmap frame = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
when(decoder.getFrameCount()).thenReturn(1);
when(decoder.getNextFrame()).thenReturn(frame);
when(gifEncoder.start(any(OutputStream.class))).thenReturn(true);
int expec... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
final FilesApi files = new FilesApi(session.getClient());
final CreateFolderRequest request = new CreateFolderRequest();
request.setName(folder.getName());
... | @Test
public void testCreateDirectory() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path folder = new StoregateDirectoryFeature(session, nodeid).mkdir(
new Path(String.format("/My files/%s", new AlphanumericRandomStringService().rando... |
@Override
public String toString() {
// we can't use uri.toString(), which escapes everything, because we want
// illegal characters unescaped in the string, for glob processing, etc.
StringBuilder buffer = new StringBuilder();
if (uri.getScheme() != null) {
buffer.append(uri.getScheme())
... | @Test (timeout = 5000)
public void testWindowsPaths() throws URISyntaxException, IOException {
assumeWindows();
assertEquals(new Path("c:\\foo\\bar").toString(), "c:/foo/bar");
assertEquals(new Path("c:/foo/bar").toString(), "c:/foo/bar");
assertEquals(new Path("/c:/foo/bar").toString(), "c:/foo/bar"... |
@Override
public OffsetFetchResponseData data() {
return data;
} | @Test
public void testNullableMetadataV8AndAbove() {
PartitionData pd = new PartitionData(
offset,
leaderEpochOne,
null,
Errors.UNKNOWN_TOPIC_OR_PARTITION);
// test PartitionData.equals with null metadata
assertEquals(pd, pd);
partition... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> table,
final TableFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(table, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldFilterMaterialization() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(materializationBuilder).filter(
predicateFactoryCaptor.capture(),
eq(queryContext));
// Given:
final KsqlTransformer<Object, Optional<GenericRow>> predicate = predica... |
@Bean
public TimeLimiterRegistry timeLimiterRegistry(
TimeLimiterConfigurationProperties timeLimiterConfigurationProperties,
EventConsumerRegistry<TimeLimiterEvent> timeLimiterEventConsumerRegistry,
RegistryEventConsumer<TimeLimiter> timeLimiterRegistryEventConsumer,
@Qualifier("comp... | @Test
public void testTimeLimiterRegistry() {
// Given
io.github.resilience4j.common.timelimiter.configuration.CommonTimeLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new io.github.resilience4j.common.timelimiter.configuration.CommonTimeLimiterConfigurationProperties.Insta... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
.download(StringUtils.removeStart(file.getAbsolute(), String.v... | @Test
public void testReadRangeUnknownLength() throws Exception {
final Path room = new BrickDirectoryFeature(session).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path test = new Path(roo... |
@Override
public long extractWatermark(IcebergSourceSplit split) {
return split.task().files().stream()
.map(
scanTask -> {
Preconditions.checkArgument(
scanTask.file().lowerBounds() != null
&& scanTask.file().lowerBounds().get(eventTimeFie... | @TestTemplate
public void testSingle() throws IOException {
ColumnStatsWatermarkExtractor extractor =
new ColumnStatsWatermarkExtractor(SCHEMA, columnName, TimeUnit.MILLISECONDS);
assertThat(extractor.extractWatermark(split(0)))
.isEqualTo(MIN_VALUES.get(0).get(columnName).longValue());
} |
public Set<MediaType> getSupportedTypes(ParseContext context) {
return SUPPORTED_TYPES;
} | @Test
public void testExcelXLSB() throws Exception {
Detector detector = new DefaultDetector();
Metadata m = new Metadata();
m.add(TikaCoreProperties.RESOURCE_NAME_KEY, "excel.xlsb");
// Should be detected correctly
MediaType type;
try (InputStream input = getResour... |
@Override
public void fetchSegmentToLocal(URI downloadURI, File dest)
throws Exception {
// Create a RoundRobinURIProvider to round robin IP addresses when retry uploading. Otherwise may always try to
// download from a same broken host as: 1) DNS may not RR the IP addresses 2) OS cache the DNS resoluti... | @Test
public void testFetchSegmentToLocalSucceedAtFirstAttempt()
throws Exception {
FileUploadDownloadClient client = mock(FileUploadDownloadClient.class);
when(client.downloadFile(any(), any(), any())).thenReturn(200);
HttpSegmentFetcher segmentFetcher = getSegmentFetcher(client);
List<URI> uri... |
@Nullable
public static TraceContextOrSamplingFlags parseB3SingleFormat(CharSequence b3) {
return parseB3SingleFormat(b3, 0, b3.length());
} | @Test void parseB3SingleFormat_parent_debug() {
assertThat(parseB3SingleFormat(traceId + "-" + spanId + "-d-" + parentId).context())
.isEqualToComparingFieldByField(TraceContext.newBuilder()
.traceId(Long.parseUnsignedLong(traceId, 16))
.parentId(Long.parseUnsignedLong(parentId, 16))
.... |
public boolean isUserAnAdmin(final CaseInsensitiveString userName, List<Role> memberRoles) {
return adminsConfig.isAdmin(new AdminUser(userName), memberRoles);
} | @Test
public void shouldReturnTrueIfAnUserBelongsToAnAdminRole() {
Authorization authorization = new Authorization(new AdminsConfig(new AdminRole(new CaseInsensitiveString("bar1")), new AdminRole(new CaseInsensitiveString("bar2"))));
assertThat(authorization.isUserAnAdmin(new CaseInsensitiveString("... |
public boolean isBroadcast() {
for (final byte b : this.address) {
if (b != -1) {
return false;
}
}
return true;
} | @Test
public void testIsBroadcast() throws Exception {
assertFalse(MAC_NORMAL.isBroadcast());
assertTrue(MAC_BCAST.isBroadcast());
assertFalse(MAC_MCAST.isBroadcast());
assertFalse(MAC_MCAST_2.isBroadcast());
assertFalse(MAC_LLDP.isBroadcast());
assertFalse(MAC_LLDP_2... |
public Set<ContentPackInstallation> findByContentPackIdAndRevision(ModelId id, int revision) {
final DBQuery.Query query = DBQuery
.is(ContentPackInstallation.FIELD_CONTENT_PACK_ID, id)
.is(ContentPackInstallation.FIELD_CONTENT_PACK_REVISION, revision);
try (final DBCurso... | @Test
@MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json")
public void findByContentPackIdAndRevisionWithInvalidId() {
final Set<ContentPackInstallation> contentPack = persistenceService.findByContentPackIdAndRevision(ModelId.of("4e3d7025-881e-6870-da03-cafebabe0001"), 3);
ass... |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void shouldNotMatchStageWithDifferentName() {
NotificationFilter filter = new NotificationFilter("cruise", "xyz", StageEvent.All, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise", "dev"), StageEvent.All)).isFalse();
} |
public CompletableFuture<CompletedCheckpoint> triggerCheckpoint(boolean isPeriodic) {
return triggerCheckpointFromCheckpointThread(checkpointProperties, null, isPeriodic);
} | @Test
void testCheckpointStatsTrackerPendingCheckpointCallback() throws Exception {
// set up the coordinator and validate the initial state
CheckpointStatsTracker tracker = mock(CheckpointStatsTracker.class);
CheckpointCoordinator checkpointCoordinator =
new CheckpointCoordi... |
@Override
public AWSCredentials getCredentials() {
return this.credentials.getCredentials();
} | @Test
public void encryptSecretKeyFromPluginConfigUsingSystemSecret() {
when(systemConfiguration.getPasswordSecret()).thenReturn("encryptionKey123");
final AWSPluginConfiguration config = AWSPluginConfiguration.createDefault()
.toBuilder()
.accessKey("MyAccessKey")
... |
public static Validator mapWithIntKeyDoubleValue() {
return (name, val) -> {
if (!(val instanceof String)) {
throw new ConfigException(name, val, "Must be a string");
}
final String str = (String) val;
final Map<String, String> map = KsqlConfig.parseStringAsMap(name, str);
map... | @Test
public void shouldParseIntKeyDoubleValueInMap() {
// Given:
final Validator validator = ConfigValidators.mapWithIntKeyDoubleValue();
validator.ensureValid("propName", "123:1.2,345:9.0");
} |
public abstract List<String> cipherSuites(); | @Test
public void testSupportedCiphers() throws KeyManagementException, NoSuchAlgorithmException, SSLException {
SSLContext jdkSslContext = SSLContext.getInstance("TLS");
jdkSslContext.init(null, null, null);
SSLEngine sslEngine = jdkSslContext.createSSLEngine();
String unsupportedC... |
public TolerantFloatComparison isWithin(float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expe... | @Test
public void isWithinZeroTolerance() {
float max = Float.MAX_VALUE;
assertThat(max).isWithin(0.0f).of(max);
assertThat(NEARLY_MAX).isWithin(0.0f).of(NEARLY_MAX);
assertThatIsWithinFails(max, 0.0f, NEARLY_MAX);
assertThatIsWithinFails(NEARLY_MAX, 0.0f, max);
float negativeMax = -1.0f * Fl... |
public static CloudConfiguration buildCloudConfigurationForStorage(Map<String, String> properties) {
return buildCloudConfigurationForStorage(properties, false);
} | @Test
public void testHDFSCloudConfiguration() {
Map<String, String> map = new HashMap<String, String>() {
{
put(CloudConfigurationConstants.HDFS_AUTHENTICATION, "simple");
put(CloudConfigurationConstants.HDFS_USERNAME, "XX");
put(CloudConfiguratio... |
@Override
public BigDecimal getBigNumber( Object object ) throws KettleValueException {
InetAddress address = getInternetAddress( object );
if ( null == address ) {
return null;
}
BigInteger bi = BigInteger.ZERO;
byte[] addr = address.getAddress();
for ( byte aByte : addr ) {
bi =... | @Test
public void testGetBigNumber_Success() throws UnknownHostException, KettleValueException {
ValueMetaInternetAddress vm = new ValueMetaInternetAddress();
String[] addresses = {
// Some IPv6 addresses
"1080:0:0:0:8:800:200C:417A", "1080::8:800:200C:417A",
"::1", "0:0:0:0:0:0:0:1",
... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldHandleNegativeValueExpression() {
// Given:
givenSourceStreamWithSchema(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of());
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(COL0, COL1),
ImmutableList.of(
new StringLit... |
public SAExposureConfig getExposureConfig() {
return exposureConfig;
} | @Test
public void getExposureConfig() {
SAExposureData exposureData = new SAExposureData("ExposeEvent");
Assert.assertNull(exposureData.getExposureConfig());
} |
synchronized void ensureTokenInitialized() throws IOException {
// we haven't inited yet, or we used to have a token but it expired
if (!hasInitedToken || (action != null && !action.isValid())) {
//since we don't already have a token, go get one
Token<?> token = fs.getDelegationToken(null);
//... | @Test
public void testGetRemoteToken() throws IOException, URISyntaxException {
Configuration conf = new Configuration();
DummyFs fs = spy(new DummyFs());
Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234"));
doRet... |
@Override
public void handle(ContainerLauncherEvent event) {
try {
eventQueue.put(event);
} catch (InterruptedException e) {
throw new YarnRuntimeException(e);
}
} | @Test(timeout = 5000)
public void testOutOfOrder() throws Exception {
LOG.info("STARTING testOutOfOrder");
AppContext mockContext = mock(AppContext.class);
@SuppressWarnings("unchecked")
EventHandler<Event> mockEventHandler = mock(EventHandler.class);
when(mockContext.getEventHandler()).thenReturn... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchNormal() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
// normal fetch
assertEquals(1, sendFetches());
assertFalse(fetcher.hasCompletedFetches());
client.prepareResponse(fullFetchResponse(tidp0, rec... |
public static int appendToLabel(
final AtomicBuffer metaDataBuffer, final int counterId, final String value)
{
Objects.requireNonNull(metaDataBuffer);
if (counterId < 0)
{
throw new IllegalArgumentException("counter id " + counterId + " is negative");
}
f... | @Test
void appendToLabelShouldAddSuffix()
{
final CountersManager countersManager = new CountersManager(
new UnsafeBuffer(new byte[CountersReader.METADATA_LENGTH]),
new UnsafeBuffer(ByteBuffer.allocateDirect(CountersReader.COUNTER_LENGTH)),
StandardCharsets.US_ASCII);... |
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
decodeMsg(msg);
} catch (Throwable t) {
notifyAllChannelsOfErrorAndClose(t);
}
} | @Test
void testNotifyCreditAvailableAfterReleased() throws Exception {
final CreditBasedPartitionRequestClientHandler handler =
new CreditBasedPartitionRequestClientHandler();
final EmbeddedChannel channel = new EmbeddedChannel(handler);
final PartitionRequestClient client =
... |
public static UUnary create(Kind unaryOp, UExpression expression) {
checkArgument(
UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp);
return new AutoValue_UUnary(unaryOp, expression);
} | @Test
public void equality() {
ULiteral sevenLit = ULiteral.intLit(7);
ULiteral threeLit = ULiteral.intLit(3);
ULiteral falseLit = ULiteral.booleanLit(false);
new EqualsTester()
.addEqualityGroup(UUnary.create(Kind.UNARY_MINUS, sevenLit))
.addEqualityGroup(UUnary.create(Kind.UNARY_MINU... |
public static ImmutableByteSequence copyAndFit(ByteBuffer original, int bitWidth)
throws ByteSequenceTrimException {
checkArgument(original != null && original.capacity() > 0,
"Cannot copy from an empty or null byte buffer");
checkArgument(bitWidth > 0,
... | @Test
public void testCopyAndFit() throws Exception {
int originalByteWidth = 3;
int paddedByteWidth = 4;
int trimmedByteWidth = 2;
int indexFirstNonZeroByte = 1;
byte byteValue = (byte) 1;
byte[] arrayValue = new byte[originalByteWidth];
arrayValue[indexFirs... |
@Override
public String getServiceId() {
return serviceId;
} | @Test
public void testGetServiceId() {
assertThat(polarisRegistration1.getServiceId()).isEqualTo(SERVICE_PROVIDER);
} |
RegistryEndpointProvider<Optional<URL>> initializer() {
return new Initializer();
} | @Test
public void testInitializer_getApiRoute_nullSource() throws MalformedURLException {
Assert.assertEquals(
new URL("http://someApiBase/someImageName/blobs/uploads/"),
testBlobPusher.initializer().getApiRoute("http://someApiBase/"));
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testCompletedFetchRemoval() {
// Ensure the removal of completed fetches that cause an Exception if and only if they contain empty records.
buildFetcher(OffsetResetStrategy.NONE, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationL... |
public static KeyFormat sanitizeKeyFormat(
final KeyFormat keyFormat,
final List<SqlType> newKeyColumnSqlTypes,
final boolean allowKeyFormatChangeToSupportNewKeySchema
) {
return sanitizeKeyFormatWrapping(
!allowKeyFormatChangeToSupportNewKeySchema ? keyFormat :
sanitizeKeyFormat... | @Test
public void shouldConvertFormatForMulticolKeysWhenSanitizingFromKafkaFormat() {
// Given:
final KeyFormat format = KeyFormat.nonWindowed(
FormatInfo.of(KafkaFormat.NAME),
SerdeFeatures.of());
// When:
final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format, MUL... |
static Map<String, String> generateConfig(int scale, Function<Integer, String> zkNodeAddress) {
Map<String, String> servers = new HashMap<>(scale);
for (int i = 0; i < scale; i++) {
// The Zookeeper server IDs starts with 1, but pod index starts from 0
String key = String.form... | @Test
public void testGenerateConfigOneNode() {
Map<String, String> expected = new HashMap<>(3);
expected.put("server.1", "my-cluster-zookeeper-0.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181");
assertThat(ZookeeperScaler.generateConfig(1, zkNodeAddress), is... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void testRetryBadGateway() {
BasicHttpResponse response502 = new BasicHttpResponse(502, "Bad gateway failure");
assertThat(retryStrategy.retryRequest(response502, 3, null)).isTrue();
} |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void doc_string_is_not_converted() {
DocString docString = DocString.create("{\"hello\":\"world\"}");
DocString converted = converter.convert(docString, DocString.class);
assertThat(converted, is(docString));
} |
public void incrementCount() {
long now = System.currentTimeMillis();
if (count.incrementAndGet() == 1) {
first.compareAndSet(0L, now);
}
last.updateAndGet(v -> Math.max(v, now));
} | @Test
void testIncrementCount() {
PrioritizedFilterStatistics stats = new PrioritizedFilterStatistics("test");
long first = stats.getFirst();
Assertions.assertEquals(0, stats.getCount());
stats.incrementCount();
Assertions.assertEquals(1, stats.getCount());
long last ... |
@Override
protected Result[] run(String value) {
final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly);
// the extractor instance is rebuilt every second anyway
final Match match = grok.match(value);
final Map<String, Object> matches = matc... | @Test
public void testIssue4773() {
// See: https://github.com/Graylog2/graylog2-server/issues/4773
final Map<String, Object> config = new HashMap<>();
config.put("named_captures_only", true);
// Using an OR with the same named capture should only return one value "2015" instead of... |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void endpointsByNamespaceWithMultipleNodePortPublicIpMatchByServicePerPodLabel() throws JsonProcessingException {
// given
String servicePerPodLabel = "sample-service-per-pod-service-label";
String servicePerPodLabelValue = "sample-service-per-pod-service-label-value";
c... |
@Override
public void updateSubnet(Subnet osSubnet) {
checkNotNull(osSubnet, ERR_NULL_SUBNET);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getId()), ERR_NULL_SUBNET_ID);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getNetworkId()), ERR_NULL_SUBNET_NET_ID);
checkArgument(!Strings.i... | @Test(expected = IllegalArgumentException.class)
public void testUpdateSubnetWithNullId() {
final Subnet testSubnet = NeutronSubnet.builder()
.networkId(NETWORK_ID)
.cidr("192.168.0.0/24")
.build();
target.updateSubnet(testSubnet);
} |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldInsertIntoWithAllPermissionsAllowed() {
// Given:
final Statement statement = givenStatement(String.format(
"INSERT INTO %s SELECT * FROM %s;", AVRO_STREAM_TOPIC, KAFKA_STREAM_TOPIC)
);
// When/then:
authorizationValidator.checkAuthorization(securityContext, metaSt... |
public Future<Void> scale(int scaleTo) {
return connect()
.compose(zkAdmin -> {
Promise<Void> scalePromise = Promise.promise();
getCurrentConfig(zkAdmin)
.compose(servers -> scaleTo(zkAdmin, servers, scaleTo))
... | @Test
public void testConnectionToNonExistingHost(VertxTestContext context) {
// Real "dummy" certificates to test the non-TLS connection error
String certificate = """
-----BEGIN CERTIFICATE-----
MIIB+DCCAaKgAwIBAgIUM7rPDjaMHJdrfgoO6IDeE19O47EwDQYJKoZIhvcNAQEL
... |
public static SchedulerFactory getInstance() {
return SchedulerFactoryInstance.lazyInstance;
} | @Test
public void shouldBeSameSchedulerFactoryInstance() {
SchedulerFactory instance = SchedulerFactory.getInstance();
SchedulerFactory instance2 = SchedulerFactory.getInstance();
assertThat(instance).isEqualTo(instance2);
} |
public int hashCode()
{
return Objects.hash(super.hashCode(), mapStatistics);
} | @Test(dataProvider = "keySupplier")
public void testEqualsHashCode(KeyInfo[] keys)
{
MapColumnStatisticsBuilder builder1 = new MapColumnStatisticsBuilder(true);
builder1.addMapStatistics(keys[0], new ColumnStatistics(3L, null, 1L, 2L));
builder1.addMapStatistics(keys[1], new ColumnStatis... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> left,
final KTableHolder<K> right,
final TableTableJoin<K> join
) {
final LogicalSchema leftSchema;
final LogicalSchema rightSchema;
if (join.getJoinType().equals(RIGHT)) {
leftSchema = right.getSchema();
rightSc... | @Test
public void shouldReturnCorrectSchema() {
// Given:
givenInnerJoin(R_KEY);
// When:
final KTableHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
assertThat(
result.getSchema(),
is(LogicalSchema.builder()
.keyColumns(RIGHT_SCHEMA.key())
... |
@Udf
public String concat(@UdfParameter final String... jsonStrings) {
if (jsonStrings == null) {
return null;
}
final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length);
boolean allObjects = true;
for (final String jsonString : jsonStrings) {
if (jsonString == null) {
... | @Test
public void shouldMerge3Args() {
// When:
final String result = udf.concat("1", "2", "3");
// Then:
assertEquals("[1,2,3]", result);
} |
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
for (Class<?> t = type.getRawType();
(t != Object.class) && (t.getSuperclass() != null);
t = t.getSuperclass()) {
for (Method m : t.getDeclaredMethods()) {
if (m.isAnnotationPresent(PostConstruct.class)) {
... | @Test
public void testList() {
MultipleSandwiches sandwiches =
new MultipleSandwiches(
Arrays.asList(new Sandwich("white", "cheddar"), new Sandwich("whole wheat", "swiss")));
Gson gson =
new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create();
... |
@Override
public void close() throws IOException {
loggers.close();
connectionFactory.destroy();
} | @Test
public void testNewerVersionOfSegmentWins() throws Exception {
setupEdgeCaseOneJnHasSegmentWithAcceptedRecovery();
// Now start writing again without JN0 present:
cluster.getJournalNode(0).stopAndJoin(0);
qjm = createSpyingQJM();
try {
assertEquals(100, QJMTestUtil.recoverAnd... |
public static String[] toStringArray(ArrayList<String> src) {
return src.toArray(new String[0]);
} | @Test
public void toStringArray() {
class TestCase {
String[] mExpected;
public TestCase(String... strings) {
mExpected = strings;
}
}
List<TestCase> testCases = new ArrayList<>();
testCases.add(new TestCase());
testCases.add(new TestCase("foo"));
testCases.add(new ... |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_YELLOW_when_two_YELLOW_application_nodes() {
Set<NodeHealth> nodeHealths = nodeHealths(YELLOW, YELLOW).collect(toSet());
Health check = underTest.check(nodeHealths);
assertThat(check)
.forInput(nodeHealths)
.hasStatus(Health.Status.YELLOW)
.andCauses("Status of... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesNullAsObject() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "null");
JType result = rule.apply("fooBar", objectNode, null, j... |
public RegistryBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
} | @Test
void transporter() {
RegistryBuilder builder = new RegistryBuilder();
builder.transporter("transporter");
Assertions.assertEquals("transporter", builder.build().getTransporter());
} |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schemas to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVi... | @Test
public void testVisit4() {
String s4 = "{\"type\": \"record\", \"name\": \"st1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}"
+ "]}";
Assert.assertEquals("st1.!", Schemas.visit(new Schema.Parser().parse(s4), new TestVisitor()));
} |
public T lookup(final CacheReference<T> reference) {
final T value = reverse.get(reference);
if(MISSING_ITEM == value) {
log.warn(String.format("Lookup failed for %s in reverse cache", reference));
return null;
}
return value;
} | @Test
public void testLookup() {
final Cache<Path> cache = new ReverseLookupCache<>(new PathCache(1), 1);
assertNull(cache.lookup(new SimplePathPredicate(new Path("/", EnumSet.of(Path.Type.directory)))));
final AttributedList<Path> list = new AttributedList<>();
final Path directory ... |
public Set<Integer> nodesThatShouldBeDown(ClusterState state) {
return calculate(state).nodesThatShouldBeDown();
} | @Test
void maintenance_node_not_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
"distributor:6 storage:6 .4.s:m")), equa... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(c,... | @Test
public void compositedKeyword() throws ScanException {
{
List<Token> tl = new TokenStream("%d(A)",
new AlmostAsIsEscapeUtil()).tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(Token.PERCENT_TOKEN);
witness.add(new Token(Token.COMPOSITE_KEYWORD, "d")... |
public boolean containAck(String ackId) {
return ackMap.containsKey(ackId);
} | @Test
void testContainAck() {
when(ackMap.containsKey("1111")).thenReturn(true);
assertTrue(udpConnector.containAck("1111"));
} |
@Override
public Boolean mSet(Map<byte[], byte[]> tuple) {
if (isQueueing() || isPipelined()) {
for (Entry<byte[], byte[]> entry: tuple.entrySet()) {
write(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue());
}
return... | @Test
public void testMSet() {
testInCluster(connection -> {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(("test" + i).getBytes(), ("test" + i*100).getBytes());
}
connection.mSet(map);
for (Map.E... |
public static Read read() {
return new AutoValue_InfluxDbIO_Read.Builder()
.setDisableCertificateValidation(false)
.setRetentionPolicy(DEFAULT_RETENTION_POLICY)
.build();
} | @Test
public void validateReadTest() {
String influxHost = "http://localhost";
String userName = "admin";
String password = "admin";
String influxDatabaseName = "testDataBase";
InfluxDB influxDb = Mockito.mock(InfluxDB.class);
PowerMockito.when(
InfluxDBFactory.connect(
... |
@Override
public String getOtp() throws OtpInfoException {
checkSecret();
try {
OTP otp = TOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getPeriod());
return otp.toString();
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
thro... | @Test
public void testTotpInfoOtp() throws OtpInfoException {
for (TOTPTest.Vector vector : TOTPTest.VECTORS) {
byte[] seed = TOTPTest.getSeed(vector.Algo);
TotpInfo info = new TotpInfo(seed, vector.Algo, 8, TotpInfo.DEFAULT_PERIOD);
assertEquals(vector.OTP, info.getOtp(v... |
public void exportData(OutputStream outputStream, List<Env> exportEnvs) {
if (CollectionUtils.isEmpty(exportEnvs)) {
exportEnvs = portalSettings.getActiveEnvs();
}
exportApps(exportEnvs, outputStream);
} | @Test
public void testNamespaceExportImport() throws FileNotFoundException {
File temporaryFolder = Files.newTemporaryFolder();
temporaryFolder.deleteOnExit();
String filePath = temporaryFolder + File.separator + "export.zip";
//export config
UserInfo userInfo = genUser();
when(userInfoHolder... |
@Override
public int hashCode() {
if (value == null) {
return 31;
}
// Using recommended hashing algorithm from Effective Java for longs and doubles
if (isIntegral(this)) {
long value = getAsNumber().longValue();
return (int) (value ^ (value >>> 32));
}
if (value instanceof N... | @Test
public void testIntegerEqualsBigInteger() {
JsonPrimitive p1 = new JsonPrimitive(10);
JsonPrimitive p2 = new JsonPrimitive(new BigInteger("10"));
assertThat(p1).isEqualTo(p2);
assertThat(p1.hashCode()).isEqualTo(p2.hashCode());
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final String resourceId = fileid.getFileId(file);
final UiFsModel uiFsModel = new ListResourceApi(new EueApiClient(session)).resourceR... | @Test
public void testReadRange() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path container = new EueDirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory... |
public void add(T element) {
Preconditions.checkNotNull(element);
if (elements.add(element) && elements.size() > maxSize) {
elements.poll();
}
} | @Test
void testSizeWithMaxSize0() {
final BoundedFIFOQueue<Integer> testInstance = new BoundedFIFOQueue<>(0);
assertThat(testInstance).isEmpty();
testInstance.add(1);
assertThat(testInstance).isEmpty();
} |
@Override
public DescribeProducersResult describeProducers(Collection<TopicPartition> topicPartitions, DescribeProducersOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, DescribeProducersResult.PartitionProducerState> future =
DescribeProducersHandler.newFuture(topicPartitio... | @Test
public void testDescribeProducersRetryAfterDisconnect() throws Exception {
MockTime time = new MockTime();
int retryBackoffMs = 100;
Cluster cluster = mockCluster(3, 0);
Map<String, Object> configOverride = newStrMap(AdminClientConfig.RETRY_BACKOFF_MS_CONFIG, "" + retryBackoffM... |
public static Map<Integer, Map<RowExpression, VariableReferenceExpression>> collectCSEByLevel(List<? extends RowExpression> expressions)
{
if (expressions.isEmpty()) {
return ImmutableMap.of();
}
CommonSubExpressionCollector expressionCollector = new CommonSubExpressionCollector... | @Test
void testNoRedundantCSE()
{
List<RowExpression> expressions = ImmutableList.of(rowExpression("x * 2 + y + z"), rowExpression("(x * 2 + y + z) * 2"), rowExpression("x * 2"));
Map<Integer, Map<RowExpression, VariableReferenceExpression>> cseByLevel = collectCSEByLevel(expressions);
/... |
public static Impl join(By clause) {
return new Impl(new JoinArguments(clause));
} | @Test
@Category(NeedsRunner.class)
public void testNoMainInput() {
PCollection<Row> pc1 =
pipeline
.apply(
"Create1",
Create.of(Row.withSchema(CG_SCHEMA_1).addValues("user1", 1, "us").build()))
.setRowSchema(CG_SCHEMA_1);
PCollection<Row> pc2 =... |
public static Read read() {
return new Read(null, "", new Scan());
} | @Test
public void testReadBuildsCorrectly() {
HBaseIO.Read read = HBaseIO.read().withConfiguration(conf).withTableId("table");
assertEquals("table", read.getTableId());
assertNotNull("configuration", read.getConfiguration());
} |
public static String acquireHost(final ServerWebExchange exchange) {
return SpringBeanUtils.getInstance().getBean(RemoteAddressResolver.class).resolve(exchange).getHostString();
} | @Test
public void acquireHostTest() {
assertEquals("0.0.0.0", HostAddressUtils.acquireHost(exchange));
} |
public DataNode elementToDataNode( RepositoryElementInterface element ) throws KettleException {
SlaveServer slaveServer = (SlaveServer) element;
DataNode rootNode = new DataNode( NODE_ROOT );
/*
* // Check for naming collision ObjectId slaveId = repo.getSlaveID(slaveServer.getName()); if (slaveId != ... | @Test
public void testElementToDataNode() throws KettleException {
DataNode dataNode = slaveDelegate.elementToDataNode( mockSlaveServer );
Assert.assertEquals( PROP_HOST_NAME_VALUE, slaveDelegate.getString( dataNode, SlaveDelegate.PROP_HOST_NAME ) );
Assert.assertEquals( PROP_USERNAME_VALUE, slaveDelegat... |
@Nonnull
public static <T> AggregateOperation1<T, LongDoubleAccumulator, Double> averagingDouble(
@Nonnull ToDoubleFunctionEx<? super T> getDoubleValueFn
) {
checkSerializable(getDoubleValueFn, "getDoubleValueFn");
// count == accumulator.value1
// sum == accumulator.value2
... | @Test
public void when_averagingDouble_tooManyItems_then_exception() {
// Given
AggregateOperation1<Double, LongDoubleAccumulator, Double> aggrOp = averagingDouble(Double::doubleValue);
LongDoubleAccumulator acc = new LongDoubleAccumulator(Long.MAX_VALUE, 0.0d);
// When
BiC... |
@Override
public String toString() {
if(useJdkToStringStyle){
return super.toString();
}
return toString(this.timeZone);
} | @Test
public void toStringTest2() {
DateTime dateTime = new DateTime("2017-01-05 12:34:23", DatePattern.NORM_DATETIME_FORMAT);
String dateStr = dateTime.toString(DatePattern.UTC_WITH_ZONE_OFFSET_PATTERN);
assertEquals("2017-01-05T12:34:23+0800", dateStr);
dateStr = dateTime.toString(DatePattern.UTC_WITH_XXX_... |
public static Transaction read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException {
return Transaction.read(payload, ProtocolVersion.CURRENT.intValue());
} | @Test
public void parseTransactionWithHugeDeclaredInputsSize() {
Transaction tx = new HugeDeclaredSizeTransaction(true, false, false);
byte[] serializedTx = tx.serialize();
try {
Transaction.read(ByteBuffer.wrap(serializedTx));
fail("We expect BufferUnderflowException... |
public static List<PKafkaOffsetProxyResult> getBatchOffsets(List<PKafkaOffsetProxyRequest> requests)
throws UserException {
return PROXY_API.getBatchOffsets(requests);
} | @Test
public void testNoAliveComputeNode() throws UserException {
new Expectations() {
{
service.getBackendOrComputeNode(anyLong);
result = null;
}
};
KafkaUtil.ProxyAPI api = new KafkaUtil.ProxyAPI();
LoadException e = Assert.... |
public Set<String> errorLogDirs() {
return errorLogDirs;
} | @Test
public void testErrorLogDirsForEmpty() {
assertEquals(new HashSet<>(), EMPTY.errorLogDirs());
} |
public static int removeSpecificPerms(int perms, int remove) {
return perms ^ remove;
} | @Test
public void testRemoveSpecificPerms() {
int perms = Perms.ALL;
int remove = Perms.CREATE;
int newPerms = ZKUtil.removeSpecificPerms(perms, remove);
assertEquals("Removal failed", 0, newPerms & Perms.CREATE);
} |
public CustomToggle config(Properties properties) {
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
key = key.toLowerCase();
// compare with legal configuration names
for (Property p: Property.values()) {
if (key.equals(p.key())) {
... | @Test
public void canProcessAbilitiesThroughProperties() {
Properties properties = new Properties();
try {
properties.load(Files.newInputStream(Paths.get(filename)));
toggle = new CustomToggle().config(properties);
} catch (IOException e) {
System.out.println("No such file");
}
... |
public Object set(final String property, final Object value) {
Objects.requireNonNull(value, "value");
final Object parsed = parser.parse(property, value);
return props.put(property, parsed);
} | @Test(expected = IllegalArgumentException.class)
public void shouldThrowIfParserThrows() {
// Given:
when(parser.parse("prop-1", "new-val"))
.thenThrow(new IllegalArgumentException("Boom"));
// When:
propsWithMockParser.set("prop-1", "new-val");
} |
static UContinue create(@Nullable CharSequence label) {
return new AutoValue_UContinue((label == null) ? null : StringName.of(label));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(UContinue.create("bar"));
} |
public String getPasswordSecret() {
return passwordSecret.trim();
} | @Test
public void testPasswordSecretIsValid() throws ValidationException, RepositoryException {
validProperties.put("password_secret", "abcdefghijklmnopqrstuvwxyz");
Configuration configuration = initConfig(new Configuration(), validProperties);
assertThat(configuration.getPasswordSecret()... |
@Override
public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) {
checkNotNull(rekeyedProjects, "rekeyedProjects can't be null");
if (rekeyedProjects.isEmpty()) {
return;
}
Arrays.stream(listeners)
.forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProj... | @Test
public void onProjectsRekeyed_throws_NPE_if_set_is_null_even_if_no_listeners() {
assertThatThrownBy(() -> underTestNoListeners.onProjectsRekeyed(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("rekeyedProjects can't be null");
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldThrowOnNonIntegerId() {
// Given:
final SingleStatementContext stmt =
givenQuery("ASSERT SCHEMA ID FALSE TIMEOUT 10 SECONDS;");
// When:
final Exception e = assertThrows(KsqlException.class, () -> builder.buildStatement(stmt));
// Then:
assertThat(e.getMessage... |
@Override
public Collection<Subscriber> getSubscribers(String namespaceId, String serviceName) {
String serviceNameWithoutGroup = NamingUtils.getServiceName(serviceName);
String groupName = NamingUtils.getGroupName(serviceName);
Service service = Service.newService(namespaceId, groupName, se... | @Test
void testGetSubscribersByService() {
Collection<Subscriber> actual = subscriberService.getSubscribers(service);
assertEquals(1, actual.size());
assertEquals(service.getGroupedServiceName(), actual.iterator().next().getServiceName());
} |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testMatchingPositions() {
assertThatThrownBy(() -> parser.parse("foo:"))
.hasMessageContaining("Cannot parse 'foo:': Encountered \"<EOF>\" at line 1, column 3.");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.