focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T> WindowedValue<T> of(
T value, Instant timestamp, Collection<? extends BoundedWindow> windows, PaneInfo pane) {
checkArgument(pane != null, "WindowedValue requires PaneInfo, but it was null");
checkArgument(windows.size() > 0, "WindowedValue requires windows, but there were none");
i... | @Test
public void testExplodeWindowsInNoWindowsCrash() {
thrown.expect(IllegalArgumentException.class);
WindowedValue.of("foo", Instant.now(), ImmutableList.of(), PaneInfo.NO_FIRING);
} |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test(expected = IllegalArgumentException.class)
public void of_withWrongURN() {
ScheduledTaskHandler.of("iamwrong");
} |
public static boolean evaluate(IncrementallyUpdatedFilterPredicate pred) {
return Objects.requireNonNull(pred, "pred cannot be null").accept(INSTANCE);
} | @Test
public void testShortCircuit() {
ValueInspector neverCalled = new ValueInspector() {
@Override
public boolean accept(Visitor visitor) {
throw new ShortCircuitException();
}
};
try {
evaluate(neverCalled);
fail("this should throw");
} catch (ShortCircuitExce... |
static List<LocalObjectReference> imagePullSecrets(PodTemplate template, List<LocalObjectReference> defaultValue) {
return template != null && template.getImagePullSecrets() != null ? template.getImagePullSecrets() : defaultValue;
} | @Test
public void testImagePullSecrets() {
List<LocalObjectReference> defaults = List.of(new LocalObjectReferenceBuilder().withName("default").build());
List<LocalObjectReference> custom = List.of(new LocalObjectReferenceBuilder().withName("custom").build());
assertThat(WorkloadUtils.image... |
@Override
public boolean add(ResourceConfig resourceConfig) {
if (this.contains(resourceConfig) || isBlank(resourceConfig.getName())) {
return false;
}
super.add(resourceConfig);
return true;
} | @Test
public void shouldNotBeAbleToAddResourceWithWhiteSpaceAsName() {
ResourceConfigs actual = new ResourceConfigs();
actual.add(new ResourceConfig(" "));
assertThat(actual.size(), is(0));
} |
public static <T> CompletionStage<Collection<T>> flattenFutures(
Collection<CompletionStage<T>> inputFutures) {
CompletableFuture<T>[] futures = inputFutures.toArray(new CompletableFuture[0]);
return CompletableFuture.allOf(futures)
.thenApply(
ignored -> {
final List<T>... | @Test
public void testFlattenFuturesForFailedFuture() {
CompletionStage<Collection<String>> resultFuture =
FutureUtils.flattenFutures(
ImmutableList.of(
CompletableFuture.completedFuture("hello"),
createFailedFuture(new RuntimeException())));
CompletionStag... |
@Override
public RouteContext route(final RouteContext routeContext, final BroadcastRule broadcastRule) {
RouteContext result = new RouteContext();
for (String each : broadcastRule.getDataSourceNames()) {
if (resourceMetaData.getAllInstanceDataSourceNames().contains(each)) {
... | @Test
void assertRoute() {
ResourceMetaData resourceMetaData = mock(ResourceMetaData.class);
when(resourceMetaData.getAllInstanceDataSourceNames()).thenReturn(Collections.singleton("ds_0"));
BroadcastInstanceBroadcastRoutingEngine engine = new BroadcastInstanceBroadcastRoutingEngine(resource... |
public int computeThreshold(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor,
@Nullable SegmentZKMetadata committingSegmentZKMetadata, String newSegmentName) {
long desiredSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes();
if (desiredSegmentSizeBytes <= ... | @Test
public void testUseLastSegmentsThresholdIfSegmentSizeMissing() {
long segmentSizeBytes = 0L;
int segmentSizeThreshold = 5_000;
SegmentFlushThresholdComputer computer = new SegmentFlushThresholdComputer();
StreamConfig streamConfig = mock(StreamConfig.class);
when(streamConfig.getFlushThresh... |
@Override
public void addLogListener(@Nonnull Level level, @Nonnull LogListener logListener) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testAddLogListener() {
loggingService.addLogListener(Level.INFO, logListener);
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testHandleSequentialRequests(MultiplexerRunMode multiplexerRunMode) throws Exception
{
SynchronousRequestHandler mockHandler = createMockHandler();
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(mockHandler, multiplexerRunMode);
... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
if (tradingRecord != null && !tradingRecord.isClosed()) {
Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice();
Num currentPrice = this.referencePrice.getValue(index);
N... | @Test
public void testCustomReferencePrice() {
ZonedDateTime initialEndDateTime = ZonedDateTime.now();
for (int i = 0; i < 10; i++) {
series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100);
}
ClosePriceIndicator customReference = new ClosePriceIndicator(series... |
@Description("Inverse of ChiSquared cdf given df parameter and probability")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double inverseChiSquaredCdf(
@SqlType(StandardTypes.DOUBLE) double df,
@SqlType(StandardTypes.DOUBLE) double p)
{
checkCondition(p >= ... | @Test
public void testInverseChiSquaredCdf()
{
assertFunction("inverse_chi_squared_cdf(3, 0.0)", DOUBLE, 0.0);
assertFunction("round(inverse_chi_squared_cdf(3, 0.99), 4)", DOUBLE, 11.3449);
assertFunction("round(inverse_chi_squared_cdf(3, 0.3),2)", DOUBLE, 1.42);
assertFunction("... |
public QueryMetadata parse(String queryString) {
if (Strings.isNullOrEmpty(queryString)) {
return QueryMetadata.empty();
}
Map<String, List<SubstringMultilinePosition>> positions = new LinkedHashMap<>();
final String[] lines = queryString.split("\n");
for (int line... | @Test
void testCharacterSpaceOfParameterNames() {
assertThat(parse("foo:$some parameter$")).isEmpty();
assertThat(parse("foo:$some-parameter$")).isEmpty();
assertThat(parse("foo:$some/parameter$")).isEmpty();
assertThat(parse("foo:$some42parameter$")).containsExactly("some42parameter... |
public static Integer parseInt(String value) {
return parseInt(value, ZERO_RADIX);
} | @Test
public void parseInt() {
Assertions.assertNull(TbUtils.parseInt(null));
Assertions.assertNull(TbUtils.parseInt(""));
Assertions.assertNull(TbUtils.parseInt(" "));
Assertions.assertEquals((Integer) 0, TbUtils.parseInt("0"));
Assertions.assertEquals((Integer) 0, TbUtils.... |
public String parseToHTML() throws IOException, SAXException, TikaException {
ContentHandler handler = new ToXMLContentHandler();
AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata();
try (InputStream stream = ContentHandlerExample.class.getResourceAsStre... | @Test
public void testParseToHTML() throws IOException, SAXException, TikaException {
String result = example
.parseToHTML()
.trim();
assertContains("<html", result);
assertContains("<head>", result);
assertContains("<meta name=\"dc:creator\"", result... |
@Override
public Map<String, String> getProperties() {
final List<String> properties = this.list(PROPERTIES_KEY);
if(properties.isEmpty()) {
return parent.getProperties();
}
return properties.stream().distinct().collect(Collectors.toMap(
property -> String... | @Test
public void testProperties() {
final Profile profile = new Profile(new TestProtocol(), new Deserializer<String>() {
@Override
public String stringForKey(final String key) {
return null;
}
@Override
public String objectForKey(... |
public void validate(DataConnectionConfig dataConnectionConfig) {
int numberOfSetItems = getNumberOfSetItems(dataConnectionConfig, CLIENT_XML_PATH, CLIENT_YML_PATH, CLIENT_XML,
CLIENT_YML);
if (numberOfSetItems != 1) {
throw new HazelcastException("HazelcastDataConnection wit... | @Test
public void testValidateBothStringsSet() {
DataConnectionConfig dataConnectionConfig = new DataConnectionConfig();
dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_XML, "xml");
dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_YML, "yaml");
Hazelca... |
@Override
protected void encode(ChannelHandlerContext ctx, byte[] msg, List<Object> out) throws Exception {
out.add(Unpooled.wrappedBuffer(msg));
} | @Test
public void testEncode() {
byte[] b = new byte[2048];
new Random().nextBytes(b);
ch.writeOutbound(b);
ByteBuf encoded = ch.readOutbound();
assertThat(encoded, is(wrappedBuffer(b)));
encoded.release();
} |
public Account updatePniKeys(final Account account,
final IdentityKey pniIdentityKey,
final Map<Byte, ECSignedPreKey> deviceSignedPreKeys,
@Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
final List<IncomingMessage> deviceMessages,
final Map<Byte, Integer> pniRegistrat... | @Test
void updatePniKeysSetPrimaryDevicePrekeyPqAndSendMessages() throws Exception {
final UUID aci = UUID.randomUUID();
final UUID pni = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getPhoneNumberIdentifier()).thenReturn(pn... |
public static void unitize1(double[] array) {
double n = norm1(array);
for (int i = 0; i < array.length; i++) {
array[i] /= n;
}
} | @Test
public void testUnitize1() {
System.out.println("unitize1");
double[] data = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
MathEx.unitize1(data);
assertEquals(1, MathEx.norm1(data), 1E-7);
} |
public static PluginOption parse(String pluginSpecification) {
Matcher pluginWithFile = PLUGIN_WITH_ARGUMENT_PATTERN.matcher(pluginSpecification);
if (!pluginWithFile.matches()) {
Class<? extends Plugin> pluginClass = parsePluginName(pluginSpecification, pluginSpecification);
ret... | @Test
void throws_for_unknown_plugins() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> PluginOption.parse("no-such-plugin"));
assertThat(exception.getMessage(), is("The plugin specification 'no-such-plugin' has a problem:\n" +
"... |
static void setConstructor(final String segmentName,
final String generatedClassName,
final ConstructorDeclaration constructorDeclaration,
final String kiePMMLModelClass,
final boolean isInterpret... | @Test
void setConstructorInterpreted() throws IOException {
ConstructorDeclaration constructorDeclaration = MODEL_TEMPLATE.getDefaultConstructor().get();
String segmentName = "SEGMENTNAME";
String generatedClassName = "GENERATEDCLASSNAME";
String kiePMMLModelClass = "KIEPMMLMODELCLAS... |
static KiePMMLDiscretizeBin getKiePMMLDiscretizeBin(final DiscretizeBin discretizeBin) {
KiePMMLInterval interval = KiePMMLIntervalInstanceFactory.getKiePMMLInterval(discretizeBin.getInterval());
String binValue = discretizeBin.getBinValue() != null ? discretizeBin.getBinValue().toString() : null;
... | @Test
void getKiePMMLDiscretizeBin() {
DiscretizeBin toConvert = getRandomDiscretizeBin();
KiePMMLDiscretizeBin retrieved = KiePMMLDiscretizeBinInstanceFactory.getKiePMMLDiscretizeBin(toConvert);
commonVerifyKiePMMLDiscretizeBin(retrieved, toConvert);
} |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Map<String, String> savedSearchToViewsMap = new HashMap<>();
final Map<View, Search> newViews = this.savedSearchService.streamAll()
... | @Test
@MongoDBFixtures("sample_saved_search_with_stream.json")
public void migrateSavedSearchWithStreamId() throws Exception {
this.migration.upgrade();
final MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(migrationCompleted.savedSearchIds())
... |
static double estimatePixelCount(final Image image, final double widthOverHeight) {
if (image.getHeight() == HEIGHT_UNKNOWN) {
if (image.getWidth() == WIDTH_UNKNOWN) {
// images whose size is completely unknown will be in their own subgroups, so
// any one of them wil... | @Test
public void testEstimatePixelCountAllKnown() {
assertEquals(20000.0, estimatePixelCount(img(100, 200), 1.0), 0.0);
assertEquals(20000.0, estimatePixelCount(img(100, 200), 12.0), 0.0);
assertEquals( 100.0, estimatePixelCount(img(100, 1), 12.0), 0.0);
assertEquals( 100.0, es... |
public Map<String, String> findTableNames(final Collection<ColumnSegment> columns, final ShardingSphereSchema schema) {
if (1 == simpleTables.size()) {
return findTableNameFromSingleTable(columns);
}
Map<String, String> result = new CaseInsensitiveMap<>();
Map<String, Collect... | @Test
void assertFindTableNameWhenColumnSegmentOwnerAbsent() {
SimpleTableSegment tableSegment1 = createTableSegment("table_1", "tbl_1");
SimpleTableSegment tableSegment2 = createTableSegment("table_2", "tbl_2");
ColumnSegment columnSegment = createColumnSegment(null, "col");
Map<Str... |
@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
&& (node.has("minLength") || node.has("maxLength"))
&& isApplicableType(field... | @Test
public void testNotUsed() {
when(config.isIncludeJsr303Annotations()).thenReturn(true);
when(node.has("minLength")).thenReturn(false);
when(node.has("maxLength")).thenReturn(false);
when(fieldVar.type().boxify().fullName()).thenReturn(fieldClass.getTypeName());
JFieldV... |
public static ECKeyPair deserialize(byte[] input) {
if (input.length != PRIVATE_KEY_SIZE + PUBLIC_KEY_SIZE) {
throw new RuntimeException("Invalid input key size");
}
BigInteger privateKey = Numeric.toBigInt(input, 0, PRIVATE_KEY_SIZE);
BigInteger publicKey = Numeric.toBigInt... | @Test
public void testDeserializeECKey() {
assertEquals(Keys.deserialize(ENCODED), (SampleKeys.KEY_PAIR));
} |
public InnerCNode getTree() throws CodegenRuntimeException {
try {
if (root == null) parse();
} catch (DefParserException | IOException e) {
throw new CodegenRuntimeException("Error parsing or reading config definition." + e.getMessage(), e);
}
return root;
} | @Test
void testFileWithNamespaceInFilename() throws IOException {
File defFile = new File(TEST_DIR + "baz.bar.foo.def");
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertEquals("31a0f9bda0e5ff929762a29569575a7e", root.defMd5);
} |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
final Optional<String> header = getBearerHeader(requestContext);
if (header.isEmpty()) {
// no JWT token, we'll fail immediately
abortRequest(requestContext);
} else {
... | @Test
void verifyValidToken() throws IOException {
final String key = "gTVfiF6A0pB70A3UP1EahpoR6LId9DdNadIkYNygK5Z8lpeJIpw9vN0jZ6fdsfeuV9KIg9gVLkCHIPj6FHW5Q9AvpOoGZO3h";
final JwtTokenAuthFilter validator = new JwtTokenAuthFilter(key);
final ContainerRequest mockedRequest = mockRequest("Bear... |
public final void contains(@Nullable Object element) {
if (!Iterables.contains(checkNotNull(actual), element)) {
List<@Nullable Object> elementList = newArrayList(element);
if (hasMatchingToStringPair(actual, elementList)) {
failWithoutActual(
fact("expected to contain", element),
... | @Test
public void iterableContainsFailure() {
expectFailureWhenTestingThat(asList(1, 2, 3)).contains(5);
assertFailureKeys("expected to contain", "but was");
assertFailureValue("expected to contain", "5");
} |
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" )... | @Test( expected = KettleDatabaseException.class )
public void testGetLegacyColumnNameNullRSMetaDataException() throws Exception {
new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), null, 1 );
} |
Map<String, String> getShardIterators() {
if (streamArn == null) {
streamArn = getStreamArn();
}
// Either return cached ones or get new ones via GetShardIterator requests.
if (currentShardIterators.isEmpty()) {
DescribeStreamResponse streamDescriptionResult
... | @Test
void shouldThrowIllegalArgumentExceptionIfNoStreamsAreReturned() throws Exception {
AmazonDDBStreamlessClientMock dynamoDbStreamsClient = new AmazonDDBStreamlessClientMock();
component.getConfiguration().setAmazonDynamoDbStreamsClient(dynamoDbStreamsClient);
Ddb2StreamEndpoint endpoin... |
@Override
public void convertWeightsForChildQueues(FSQueue queue,
CapacitySchedulerConfiguration csConfig) {
List<FSQueue> children = queue.getChildQueues();
if (queue instanceof FSParentQueue || !children.isEmpty()) {
QueuePath queuePath = new QueuePath(queue.getName());
if (queue.getName(... | @Test
public void testAutoCreateV2FlagOnParentWithoutChildren() {
FSQueue root = createParent(new ArrayList<>());
converter.convertWeightsForChildQueues(root, csConfig);
assertEquals("Number of properties", 21,
csConfig.getPropsWithPrefix(PREFIX).size());
assertTrue("root autocreate v2 enable... |
public void retain(IndexSet indexSet,
@Nullable Integer maxNumberOfIndices,
RetentionExecutor.RetentionAction action,
String actionName) {
final Map<String, Set<String>> deflectorIndices = indexSet.getAllIndexAliases();
final int ind... | @Test
public void shouldRetainOldestIndices() {
underTest.retain(indexSet, 4, action, "action");
verify(action, times(1)).retain(retainedIndexName.capture(), eq(indexSet));
// Ensure that the oldest indices come first
assertThat(retainedIndexName.getAllValues().get(0)).containsExact... |
@Override
public void write(String propertyKey, @Nullable String value) {
checkPropertyKey(propertyKey);
try (DbSession dbSession = dbClient.openSession(false)) {
if (value == null || value.isEmpty()) {
dbClient.internalPropertiesDao().saveAsEmpty(dbSession, propertyKey);
} else {
... | @Test
public void write_calls_dao_save_when_value_is_neither_null_nor_empty() {
underTest.write(SOME_KEY, SOME_VALUE);
verify(internalPropertiesDao).save(dbSession, SOME_KEY, SOME_VALUE);
verify(dbSession).commit();
} |
@Override
protected Optional<Retry> createProcessor(String businessName, RetryRule rule) {
final io.sermant.flowcontrol.common.handler.retry.Retry retry = RetryContext.INSTANCE.getRetry();
if (retry == null) {
return Optional.empty();
}
final RetryConfig retryConfig = Ret... | @Test
public void test() {
final RetryHandlerV2 retryHandlerV2 = new RetryHandlerV2();
final AlibabaDubboRetry alibabaDubboRetry = new AlibabaDubboRetry();
RetryContext.INSTANCE.markRetry(alibabaDubboRetry);
final Retry test = retryHandlerV2.createProcessor("test", new RetryRule()).g... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testAvroCoderNestedRecords() {
// Nested Record
assertDeterministic(
AvroCoder.of(
SchemaBuilder.record("nestedRecord")
.fields()
.name("subRecord")
.type()
.record("subRecord")
.fields()
... |
public Unmarshaller createUnmarshaller(Class<?> clazz) throws JAXBException {
Unmarshaller unmarshaller = getContext(clazz).createUnmarshaller();
if (unmarshallerEventHandler != null) {
unmarshaller.setEventHandler(unmarshallerEventHandler);
}
unmarshaller.setSchema(unmashallerSchema);
return ... | @Test
void buildsUnmarshallerWithDefaultEventHandler() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder().build();
Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class);
assertThat(unmarshaller.getEventHandler()).isNotNull();
} |
public String getClusterProfileChangedRequestBody(ClusterProfilesChangedStatus status, Map<String, String> oldClusterProfile, Map<String, String> newClusterProfile) {
return switch (status) {
case CREATED -> getClusterCreatedRequestBody(newClusterProfile);
case UPDATED -> getClusterUpdat... | @Test
public void shouldGetClusterProfilesChangedRequestBodyWhenClusterProfileIsCreated() {
ClusterProfilesChangedStatus status = ClusterProfilesChangedStatus.CREATED;
Map<String, String> oldClusterProfile = null;
Map<String, String> newClusterProfile = Map.of("key1", "key2");
Strin... |
protected String getUserName() {
return System.getProperty("user.name");
} | @Test
public void testGetUserName() throws Exception {
PseudoAuthenticator authenticator = new PseudoAuthenticator();
Assert.assertEquals(System.getProperty("user.name"), authenticator.getUserName());
} |
@Override
public void insert(Person person) {
Optional<Person> elem = personList.stream().filter(p -> p.getPersonNationalId() == person.getPersonNationalId()).findFirst();
if (elem.isPresent()) {
LOGGER.info("Record already exists.");
return;
}
personList.add(person);
} | @Test
void testInsert(){
// DataBase initialization.
PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation();
Assertions.assertEquals(0,db.size(),"Size of null database should be 0");
// Dummy persons.
Person person1 = new Person(1, "Thomas", 27304159);
Person person2 = new ... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Map<String, Object> headers = message.getHeaders();
CloudEvent cloudEvent = CloudEvents.v1_0;
headers.putIfAbsent(cloudEvent.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_ID).http(),
... | @Test
void shouldMapToHttpCloudEvent() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
exchange.getMessage().setHeader(CloudEvent.CAMEL_CLOUD_EVENT_SUBJECT, "test1.txt");
exchange.getMessage().setHeader(CloudEvent.CAMEL_CLOUD_EVENT_TYPE, "org.apache.camel.event.tes... |
@Override
public ConfigInfo findConfigInfo(long id) {
try {
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO);
return this.jt.queryForObject(configInfoMapper.select(
A... | @Test
void testFindConfigInfoByIdGetConFail() {
long id = 1234567890876L;
ConfigInfo configInfo = new ConfigInfo();
configInfo.setId(id);
Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER)))
.thenThrow(new CannotGet... |
@Override
public void onDelete(Extension extension) {
if (isDisposed() || !matchers.onDeleteMatcher().match(extension)) {
return;
}
// TODO filter the event
queue.addImmediately(new Request(extension.getMetadata().getName()));
} | @Test
void shouldDeleteExtensionWhenDeletePredicateAlwaysTrue() {
when(matchers.onDeleteMatcher()).thenReturn(getEmptyMatcher());
watcher.onDelete(createFake("fake-name"));
verify(matchers, times(1)).onDeleteMatcher();
verify(queue, times(1)).addImmediately(
argThat(requ... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCorrectCodeForDateStringEQ() {
// Given:
final ComparisonExpression compExp = new ComparisonExpression(
Type.EQUAL,
DATECOL,
new StringLiteral("2021-06-23")
);
// When:
final String java = sqlToJavaVisitor.process(compExp);
// Then:
... |
@Override
public void onPinch() {} | @Test
public void testOnPinch() {
mUnderTest.onPinch();
Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction);
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testSpdyHeadersFrameHeaderBlock() throws Exception {
short type = 8;
byte flags = 0;
int length = 4;
int headerBlockLength = 1024;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
... |
@Override
public XmppDevice getDevice(XmppDeviceId xmppDeviceId) {
return connectedDevices.get(xmppDeviceId);
} | @Test
public void testAddRemoveConnectedDevice() {
// test adding connected devices
boolean add1 = agent.addConnectedDevice(jid1, device1);
assertThat(add1, is(true));
assertThat(testXmppDeviceListener.addedDevices, hasSize(1));
boolean add2 = agent.addConnectedDevice(jid2, d... |
@Override
public String getDocumentationLink(@Nullable String suffix) {
return documentationBaseUrl + Optional.ofNullable(suffix).orElse("");
} | @Test
public void getDocumentationLink_suffixNotProvided_withPropertyOverride_missingSlash() {
String propertyValue = "https://new-url.sonarqube.org";
when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue));
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(... |
public static Write write() {
return new AutoValue_RedisIO_Write.Builder()
.setConnectionConfiguration(RedisConnectionConfiguration.create())
.setMethod(Write.Method.APPEND)
.build();
} | @Test
public void testWriteWithMethodSetWithExpiration() {
String key = "testWriteWithMethodSet";
client.set(key, "value");
String newValue = "newValue";
PCollection<KV<String, String>> write = p.apply(Create.of(KV.of(key, newValue)));
write.apply(
RedisIO.write()
.withEndpoin... |
public ZonedDateTime getDateTime() {
return dateTime;
} | @Test
void getDateTime() {
DateTimeStamp dateTimeStamp = new DateTimeStamp(.586);
assertNull(dateTimeStamp.getDateTime());
dateTimeStamp = new DateTimeStamp("2018-04-04T09:10:00.586-0100");
assertEquals(ZonedDateTime.from(formatter.parse("2018-04-04T09:10:00.586-0100")), dateTimeSta... |
public static byte[] getNullableSizePrefixedArray(final ByteBuffer buffer) {
final int size = buffer.getInt();
return getNullableArray(buffer, size);
} | @Test
public void getNullableSizePrefixedArrayInvalid() {
// -2
byte[] input = {-1, -1, -1, -2};
final ByteBuffer buffer = ByteBuffer.wrap(input);
assertThrows(NegativeArraySizeException.class, () -> Utils.getNullableSizePrefixedArray(buffer));
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = models.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = 0;
for (int ... | @Test
public void test2DPlanes() {
test("2dplanes", Planes.formula, Planes.data, 1.3581);
} |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String generic = invoker.getUrl().getParameter(GENERIC_KEY);
// calling a generic impl service
if (isCallingGenericImpl(generic, invocation)) {
RpcInvocation invocation2 = new RpcInvoc... | @Test
void testInvoke() throws Exception {
RpcInvocation invocation = new RpcInvocation(
"getPerson",
"org.apache.dubbo.rpc.support.DemoService",
"org.apache.dubbo.rpc.support.DemoService:dubbo",
new Class[] {Person.class},
new... |
public String getHostname() {
return hostNameSupplier.getHostName();
} | @Test
void testGetHostname0() {
try {
InetAddress address = mock(InetAddress.class);
when(address.getCanonicalHostName()).thenReturn("worker2.cluster.mycompany.com");
when(address.getHostName()).thenReturn("worker2.cluster.mycompany.com");
when(address.getHost... |
@Override
public void checkSubjectAccess(
final KsqlSecurityContext securityContext,
final String subjectName,
final AclOperation operation
) {
checkAccess(new CacheKey(securityContext,
AuthObjectType.SUBJECT,
subjectName,
operation));
} | @Test
public void shouldCheckCacheValidatorOnSecondSubjectAccessRequest() {
// When
cache.checkSubjectAccess(securityContext, SUBJECT_1, AclOperation.READ);
when(fakeTicker.read()).thenReturn(ONE_SEC_IN_NS);
cache.checkSubjectAccess(securityContext, SUBJECT_1, AclOperation.READ);
// Then
veri... |
@Override
public SchemaResult getKeySchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true);
} | @Test
public void shouldThrowFromGetKeyWithIdSchemaOnOtherRestExceptions() throws Exception {
// Given:
when(srClient.getSchemaBySubjectAndId(any(), anyInt()))
.thenThrow(new RestClientException("failure", 1, 1));
// When:
final Exception e = assertThrows(
KsqlException.class,
... |
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
return (entryName.equals(name)) ? entry : ((baseConfig != null)
? baseConfig.getAppConfigurationEntry(name) : null);
} | @Test
public void test() throws Exception {
String krb5LoginModuleName;
if (System.getProperty("java.vendor").contains("IBM")) {
krb5LoginModuleName = "com.ibm.security.auth.module.Krb5LoginModule";
} else {
krb5LoginModuleName = "com.sun.security.auth.module.Krb5LoginModule";
}
JaasC... |
public static <N, E> void replaceDirectedNetworkNodes(
MutableNetwork<N, E> network, Function<N, N> function) {
checkArgument(network.isDirected(), "Only directed networks are supported, given %s", network);
checkArgument(
!network.allowsSelfLoops(),
"Only networks without self loops are s... | @Test
public void testNodeReplacementInEmptyNetwork() {
MutableNetwork<String, String> network = createEmptyNetwork();
Networks.replaceDirectedNetworkNodes(
network,
new Function<String, String>() {
@Override
public @Nullable String apply(@Nullable String input) {
... |
public List<Integer> getMsgIds() {
return msgIds;
} | @Test
void getMsgIds() {
BatchResultMessage batchResultMessage = new BatchResultMessage();
Assertions.assertTrue(batchResultMessage.getMsgIds().isEmpty());
} |
@Override
public void onRuleChanged(final List<RuleData> ruleDataList, final DataEventTypeEnum eventType) {
WebsocketData<RuleData> configData =
new WebsocketData<>(ConfigGroupEnum.RULE.name(), eventType.name(), ruleDataList);
WebsocketCollector.send(GsonUtils.getInstance().toJson(co... | @Test
public void testOnRuleChanged() {
String message = "{\"groupType\":\"RULE\",\"eventType\":\"UPDATE\",\"data\":[{\"id\":\"1336350040008105984\","
+ "\"name\":\"test\",\"pluginName\":\"waf\",\"selectorId\":\"1336349806465064960\","
+ "\"matchMode\":1,\"sort\":1,\"enabled\... |
@Override
public int compare(Object o1, Object o2) {
if (o1 == null && o2 == null) {
return 0; // o1 == o2
}
if (o1 == null) {
return -1; // o1 < o2
}
if (o2 == null) {
return 1; // o1 > o2
}
return nonNullC... | @Test
public void twoNullArgs() {
assertTrue("two nulls", cmp.compare(null, null) == 0);
} |
@Override
public HedgeDurationSupplier getDurationSupplier() {
return durationSupplier;
} | @Test
public void shouldDefaultToPreconfiguredSupplier() {
then(hedge.getDurationSupplier()).isOfAnyClassIn(PreconfiguredDurationSupplier.class);
} |
public CompletableFuture<Void> handlePullQuery(
final ServiceContext serviceContext,
final PullPhysicalPlan pullPhysicalPlan,
final ConfiguredStatement<Query> statement,
final RoutingOptions routingOptions,
final PullQueryWriteStream pullQueryQueue,
final CompletableFuture<Void> shou... | @Test
public void forwardingError_errorRow() {
// Given:
locate(location5);
when(ksqlClient.makeQueryRequest(eq(node2.location()), any(), any(), any(), any(), any(), any()))
.thenAnswer(i -> {
Map<String, ?> requestProperties = i.getArgument(3);
WriteStream<List<StreamedRow>> r... |
CompletableFuture<Void> setPublicKey(final UUID accountIdentifier, final byte deviceId, final ECPublicKey publicKey) {
return dynamoDbAsyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.item(Map.of(
KEY_ACCOUNT_UUID, getPartitionKey(accountIdentifier),
... | @Test
void setPublicKey() {
final UUID accountIdentifier = UUID.randomUUID();
final byte deviceId = Device.PRIMARY_ID;
final ECPublicKey publicKey = Curve.generateKeyPair().getPublicKey();
assertEquals(Optional.empty(), clientPublicKeys.findPublicKey(accountIdentifier, deviceId).join());
clientP... |
@Draft
public boolean sendPicture(Socket socket, String picture, Object... args)
{
if (!FORMAT.matcher(picture).matches()) {
throw new ZMQException(picture + " is not in expected format " + FORMAT.pattern(), ZError.EPROTO);
}
ZMsg msg = new ZMsg();
for (int pictureInd... | @Test(expected = ZMQException.class)
public void testSendInvalidPictureFormat()
{
String picture = " ";
pic.sendPicture(null, picture, 255);
} |
public boolean hasMajorMinorAndPatchVersionHigherOrEqualTo(String majorMinorAndPatchVersion) {
return hasMajorMinorAndPatchVersionHigherOrEqualTo(new VersionNumber(majorMinorAndPatchVersion));
} | @Test
void hasMajorMinorAndPatchVersionHigherOrEqualTo() {
assertThat(v("8.3.0").hasMajorMinorAndPatchVersionHigherOrEqualTo("8.0.1")).isTrue();
assertThat(v("5.8.0").hasMajorMinorAndPatchVersionHigherOrEqualTo("8.0.1")).isFalse();
assertThat(v("8.0.0").hasMajorMinorAndPatchVersionHigherOrE... |
public PullResult getOpMessage(int queueId, long offset, int nums) {
String group = TransactionalMessageUtil.buildConsumerGroup();
String topic = TransactionalMessageUtil.buildOpTopic();
SubscriptionData sub = new SubscriptionData(topic, "*");
return getMessage(group, topic, queueId, off... | @Test
public void testGetOpMessage() {
when(messageStore.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))).thenReturn(createGetMessageResult(GetMessageStatus.NO_MESSAGE_IN_QUEUE));
PullResult result = transactionBridge.getOpMessage(... |
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) {
// Start of evaluate
boolean retval = false;
// If we have 0 items in the list, evaluate the current condition
// Otherwise, evaluate all sub-conditions
//
try {
if ( isAtomic() ) {
if ( function == FUNC_TRUE ) {
... | @Test
public void testNegatedTrueFuncEvaluatesAsFalse() throws Exception {
String left = "test_filed";
String right = "test_value";
int func = Condition.FUNC_TRUE;
boolean negate = true;
Condition condition = new Condition( negate, left, func, right, null );
assertFalse( condition.evaluate( n... |
@SqlNullable
@Description("Returns the lower left and upper right corners of bounding rectangular polygon of a Geometry")
@ScalarFunction("ST_EnvelopeAsPts")
@SqlType("array(" + GEOMETRY_TYPE_NAME + ")")
public static Block stEnvelopeAsPts(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
Envelope... | @Test
public void testSTEnvelopeAsPts()
{
assertEnvelopeAsPts("MULTIPOINT (1 2, 2 4, 3 6, 4 8)", new Point(1, 2), new Point(4, 8));
assertFunction("ST_EnvelopeAsPts(ST_GeometryFromText('LINESTRING EMPTY'))", new ArrayType(GEOMETRY), null);
assertEnvelopeAsPts("LINESTRING (1 1, 2 2, 1 3)"... |
@Override
public Collection<V> values() {
return targetMap.values();
} | @Test
void values() {
List<String> values = new ArrayList<>();
values.add("Value");
values.add("Value2");
Assertions.assertArrayEquals(values.toArray(), lowerCaseLinkHashMap.values().toArray());
} |
protected static void parseParams(String queryString, CommandRequest request) {
if (queryString == null || queryString.length() < 1) {
return;
}
int offset = 0, pos = -1;
// check anchor
queryString = removeAnchor(queryString);
while (true) {
of... | @Test
public void parseParams() {
CommandRequest request;
// mixed
request = new CommandRequest();
HttpEventTask.parseParams("a=1&&b&=3&&c=4&a_+1=3_3%20&%E7%9A%84=test%E7%9A%84#mark", request);
assertEquals(4, request.getParameters().size());
assertEquals("1"... |
public static boolean isEmptyOrAllElementsNull(Collection<?> collection) {
for (Object o : collection) {
if (o != null) {
return false;
}
}
return true;
} | @Test
void testIsEmptyOrAllElementsNull() {
assertThat(CollectionUtil.isEmptyOrAllElementsNull(Collections.emptyList())).isTrue();
assertThat(CollectionUtil.isEmptyOrAllElementsNull(Collections.singletonList(null)))
.isTrue();
assertThat(CollectionUtil.isEmptyOrAllElementsNul... |
@Override
public void doRun() {
if (versionOverride.isPresent()) {
LOG.debug("Elasticsearch version is set manually. Not running check.");
return;
}
final Optional<SearchVersion> probedVersion = this.versionProbe.probe(this.elasticsearchHosts);
probedVersion... | @Test
void createsNotificationIfCurrentVersionIsIncompatibleWithInitialOne() {
returnProbedVersion(Version.of(9, 2, 3));
createPeriodical(SearchVersion.elasticsearch(8, 1, 2)).doRun();
assertNotificationWasRaised();
} |
@Override
public long get(K key) {
return complete(asyncCounterMap.get(key));
} | @Test(expected = ConsistentMapException.Timeout.class)
public void testTimeout() {
AtomicCounterMapWithErrors<String> atomicCounterMap =
new AtomicCounterMapWithErrors<>();
atomicCounterMap.setErrorState(TestingCompletableFutures.ErrorState.TIMEOUT_EXCEPTION);
DefaultAtomicCo... |
@Override
public void validate() throws TelegramApiValidationException {
if (inlineQueryId.isEmpty()) {
throw new TelegramApiValidationException("InlineQueryId can't be empty", this);
}
for (InlineQueryResult result : results) {
result.validate();
}
i... | @Test
void testInlineQueryIdCanNotBeEmpty() {
answerInlineQuery.setInlineQueryId("");
try {
answerInlineQuery.validate();
} catch (TelegramApiValidationException e) {
assertEquals("InlineQueryId can't be empty", e.getMessage());
}
} |
@Override
public CoordinatorRecord deserialize(
ByteBuffer keyBuffer,
ByteBuffer valueBuffer
) throws RuntimeException {
final short recordType = readVersion(keyBuffer, "key");
final ApiMessage keyMessage = apiMessageKeyFor(recordType);
readMessage(keyMessage, keyBuffer, ... | @Test
public void testDeserializeWithValueEmptyBuffer() {
GroupCoordinatorRecordSerde serde = new GroupCoordinatorRecordSerde();
ApiMessageAndVersion key = new ApiMessageAndVersion(
new ConsumerGroupMetadataKey().setGroupId("foo"),
(short) 3
);
ByteBuffer key... |
public static byte[] readPem(InputStream keyStream) {
final PemObject pemObject = readPemObject(keyStream);
if (null != pemObject) {
return pemObject.getContent();
}
return null;
} | @Test
@Disabled
public void readECPrivateKeyTest2() {
// https://gitee.com/dromara/hutool/issues/I37Z75
final byte[] d = PemUtil.readPem(FileUtil.getInputStream("d:/test/keys/priv.key"));
final byte[] publicKey = PemUtil.readPem(FileUtil.getInputStream("d:/test/keys/pub.key"));
final SM2 sm2 = new SM2(d, pub... |
public double getLatitudeSpan() {
return this.maxLatitude - this.minLatitude;
} | @Test
public void getLatitudeSpanTest() {
BoundingBox boundingBox = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE);
Assert.assertEquals(MAX_LATITUDE - MIN_LATITUDE, boundingBox.getLatitudeSpan(), 0);
} |
public static SeaTunnelRuntimeException deserializeError(String payload) {
return deserializeError(payload, null);
} | @Test
public void testError() {
SeaTunnelRuntimeException error = GoogleSheetsError.deserializeError("{}");
Assertions.assertEquals(
GoogleSheetsErrorCode.DESERIALIZE_FAILED.getCode(),
error.getSeaTunnelErrorCode().getCode());
String expectedMsg =
... |
public long getRevisedRowCount(final SelectStatementContext selectStatementContext) {
if (isMaxRowCount(selectStatementContext)) {
return Integer.MAX_VALUE;
}
return rowCountSegment instanceof LimitValueSegment ? actualOffset + actualRowCount : actualRowCount;
} | @Test
void assertGetRevisedRowCountForSQL92() {
getRevisedRowCount(new SQL92SelectStatement());
} |
@Override
public TaskID acquireTaskIdLock(Configuration conf) {
JobID jobId = HadoopFormats.getJobId(conf);
boolean lockAcquired = false;
int taskIdCandidate = 0;
while (!lockAcquired) {
taskIdCandidate = RANDOM_GEN.nextInt(Integer.MAX_VALUE);
Path path =
new Path(
... | @Test
public void testTaskIdLockAcquire() {
int tasksCount = 100;
for (int i = 0; i < tasksCount; i++) {
TaskID taskID = tested.acquireTaskIdLock(configuration);
assertTrue(isFileExists(getTaskIdPath(taskID)));
}
String jobFolderName = getFileInJobFolder("");
File jobFolder = new File... |
public static void main(final String[] args) {
var task = new SimpleTask();
task.executeWith(() -> LOGGER.info("I'm done now."));
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public void createUser(User body) throws RestClientException {
createUserWithHttpInfo(body);
} | @Test
public void createUserTest() {
User body = null;
api.createUser(body);
// TODO: test validations
} |
@Override
public boolean intersects(PointList pointList) {
// similar code to LocationIndexTree.checkAdjacent
int len = pointList.size();
if (len == 0)
throw new IllegalArgumentException("PointList must not be empty");
double tmpLat = pointList.getLat(0);
double ... | @Test
public void testIntersectPointList() {
Circle circle = new Circle(1.5, 0.3, DistanceCalcEarth.DIST_EARTH.calcDist(0, 0, 0, 0.7));
PointList pointList = new PointList();
pointList.add(5, 5);
pointList.add(5, 0);
assertFalse(circle.intersects(pointList));
pointLi... |
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransf... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullValueTransformerSupplierOnFlatTransformValuesWithStores() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
(org.apache.kafk... |
public static void refreshSuperUserGroupsConfiguration() {
//load server side configuration;
refreshSuperUserGroupsConfiguration(new Configuration());
} | @Test(expected = IllegalArgumentException.class)
public void testProxyUsersWithNullPrefix() throws Exception {
ProxyUsers.refreshSuperUserGroupsConfiguration(new Configuration(false),
null);
} |
@Override
public void processDeviceCreatedState(OpenstackNode osNode) {
try {
if (!isOvsdbConnected(osNode, ovsdbPortNum, ovsdbController, deviceService)) {
ovsdbController.connect(osNode.managementIp(), tpPort(ovsdbPortNum));
return;
}
if... | @Test
public void testGatewayNodeProcessDeviceCreatedState() {
testNodeManager.createNode(GATEWAY_2);
TEST_DEVICE_SERVICE.devMap.put(GATEWAY_2_OVSDB_DEVICE.id(), GATEWAY_2_OVSDB_DEVICE);
TEST_DEVICE_SERVICE.devMap.put(GATEWAY_2_INTG_DEVICE.id(), GATEWAY_2_INTG_DEVICE);
TEST_DEVICE_SE... |
@Override
public String named() {
return PluginEnum.CRYPTOR_RESPONSE.getName();
} | @Test
public void namedTest() {
final String result = cryptorResponsePlugin.named();
assertEquals(PluginEnum.CRYPTOR_RESPONSE.getName(), result);
} |
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf)
throws UnknownHostException, URISyntaxException {
String sourceUriHost = "";
if (sourceHost != null && !sourceHost.isEmpty()) {
sourceUriHost = new URI(sourceHost).getHost();
sourceUriHost = (sourceUriHost ==... | @Test
void isValidFromStar()
throws URISyntaxException, UnknownHostException {
assertTrue(CorsUtils.isValidOrigin("http://anyhost.com",
ZeppelinConfiguration.load("zeppelin-site-star.xml")));
} |
@Nullable
public static TraceContextOrSamplingFlags parseB3SingleFormat(CharSequence b3) {
return parseB3SingleFormat(b3, 0, b3.length());
} | @Test void parseB3SingleFormat_sampled() {
assertThat(parseB3SingleFormat("1"))
.isEqualTo(TraceContextOrSamplingFlags.SAMPLED);
} |
@Override
public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Error... | @Test
public void testIgnoreHeartbeatWhenLeavingGroup() {
ShareMembershipManager membershipManager = createMemberInStableState();
mockLeaveGroup();
CompletableFuture<Void> leaveResult = membershipManager.leaveGroup();
membershipManager.onHeartbeatSuccess(createShareGroupHeartbeatRe... |
@Override
public void setChannelStateWriter(ChannelStateWriter channelStateWriter) {
checkState(this.channelStateWriter == null, "Already initialized");
this.channelStateWriter = checkNotNull(channelStateWriter);
} | @TestTemplate
void testConsumeTimeoutableCheckpointBarrierQuickly() throws Exception {
PipelinedSubpartition subpartition = createSubpartition();
subpartition.setChannelStateWriter(ChannelStateWriter.NO_OP);
assertSubpartitionChannelStateFuturesAndQueuedBuffers(subpartition, null, true, 0, f... |
@Override
public List<String> filter(final ReadwriteSplittingDataSourceGroupRule rule, final List<String> toBeFilteredReadDataSources) {
List<String> result = new LinkedList<>(toBeFilteredReadDataSources);
result.removeIf(rule.getDisabledDataSourceNames()::contains);
return result;
} | @Test
void assertGetEnabledReplicaDataSources() {
rule.disableDataSource("read_ds_0");
assertThat(new DisabledReadDataSourcesFilter().filter(rule, Arrays.asList("read_ds_0", "read_ds_1")), is(Collections.singletonList("read_ds_1")));
} |
@UdafFactory(description = "sum int values in a list into a single int")
public static TableUdaf<List<Integer>, Integer, Integer> sumIntList() {
return new TableUdaf<List<Integer>, Integer, Integer>() {
@Override
public Integer initialize() {
return 0;
}
@Override
public In... | @Test
public void shouldIgnoreNull() {
final TableUdaf<List<Integer>, Integer, Integer> udaf = ListSumUdaf.sumIntList();
final Integer[] values = new Integer[] {1, 1, null, 1};
final List<Integer> list = Arrays.asList(values);
final Integer sum = udaf.aggregate(list, 0);
assertThat(3, equalT... |
public String compile(final String xls,
final String template,
int startRow,
int startCol) {
return compile( xls,
template,
InputType.XLS,
startRow,
... | @Test
public void testLoadFromClassPath() {
final String drl = converter.compile("/data/MultiSheetDST.drl.xls",
"/templates/test_template1.drl",
11,
2);
assertTha... |
@Override
@SuppressWarnings("nullness")
public synchronized List<Map<String, Object>> runSQLQuery(String sql) {
try (Statement stmt = driver.getConnection(getUri(), username, password).createStatement()) {
List<Map<String, Object>> result = new ArrayList<>();
ResultSet resultSet = stmt.executeQuery(... | @Test
public void testRunSQLStatementShouldThrowErrorWhenJDBCFailsToExecuteSQL() throws SQLException {
when(container.getHost()).thenReturn(HOST);
when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT);
Statement statement = driver.getConnection(any(), any(), any()).createStatement();
doThro... |
protected String generateQueryString(MultiValuedTreeMap<String, String> parameters, boolean encode, String encodeCharset)
throws ServletException {
if (parameters == null || parameters.isEmpty()) {
return null;
}
if (queryString != null) {
return queryString;
... | @Test
void queryStringWithMultipleValues_generateQueryString_validQuery() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(multipleParams, mockContext, null, config);
String parsedString = null;
try {
parsedString = request.generateQueryString(request.getAws... |
@Override
public SarifSchema210 deserialize(Path reportPath) {
try {
return mapper
.enable(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION)
.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleInstantiationProblem(DeserializationContext ctxt, Clas... | @Test
public void deserialize_shouldFail_whenJsonSyntaxIsIncorrect() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("invalid-json-syntax.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstance... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.