focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T> WindowedValue.WindowedValueCoder<T> instantiateWindowedCoder(
String collectionId, RunnerApi.Components components) {
PipelineNode.PCollectionNode collectionNode =
PipelineNode.pCollection(collectionId, components.getPcollectionsOrThrow(collectionId));
try {
return (Windowe... | @Test
public void testInstantiateWindowedCoder() throws IOException {
Coder<KV<Long, String>> expectedValueCoder =
KvCoder.of(VarLongCoder.of(), StringUtf8Coder.of());
SdkComponents components = SdkComponents.create();
components.registerEnvironment(Environments.createDockerEnvironment("java"));
... |
public DirectoryEntry lookUp(
File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
DirectoryEntry result = lookUp(workingDirectory, path, options, 0);
if (result == null) {
// an intermediate file in the path... | @Test
public void testLookup_relative_withDotsInPath() throws IOException {
assertExists(lookup("."), "/", "work");
assertExists(lookup("././."), "/", "work");
assertExists(lookup("./one/./././two/three"), "two", "three");
assertExists(lookup("./one/./././two/././three"), "two", "three");
assertEx... |
public void setMaxAMShare(Resource resource) {
maxAMShareMB.set(resource.getMemorySize());
maxAMShareVCores.set(resource.getVirtualCores());
if (customResources != null) {
customResources.setMaxAMShare(resource);
}
} | @Test
public void testSetMaxAMShare() {
FSQueueMetrics metrics = setupMetrics(RESOURCE_NAME);
Resource res = Resource.newInstance(2048L, 4, ImmutableMap.of(RESOURCE_NAME,
20L));
metrics.setMaxAMShare(res);
assertEquals(getErrorMessage("maxAMShareMB"),
2048L, metrics.getMaxAMShareMB()... |
static MethodCallExpr getKiePMMLTargetValueVariableInitializer(final TargetValue targetValueField) {
final MethodDeclaration methodDeclaration =
TARGETVALUE_TEMPLATE.getMethodsByName(GETKIEPMMLTARGETVALUE).get(0).clone();
final BlockStmt targetValueBody =
methodDeclaratio... | @Test
void getKiePMMLTargetValueVariableInitializer() throws IOException {
TargetValue targetValue = convertToKieTargetValue(getRandomTargetValue());
MethodCallExpr retrieved = KiePMMLTargetValueFactory.getKiePMMLTargetValueVariableInitializer(targetValue);
String text = getFileContent(TEST_... |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testParseNewStyleResourceWithCustomResourceVcoresNegative()
throws Exception {
expectNegativeValueOfResource("vcores");
parseResourceConfigValue("vcores=-2,memory-mb=-5120,test1=4");
} |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test(expected=AclException.class)
public void testFilterAclEntriesByAclSpecInputTooLarge() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, NONE))
.build... |
public InputSplit[] getSplits(JobConf job, int numSplits)
throws IOException {
StopWatch sw = new StopWatch().start();
FileStatus[] stats = listStatus(job);
// Save the number of input files for metrics/loadgen
job.setLong(NUM_INPUT_FILES, stats.length);
long totalSize = 0; ... | @Test
public void testListLocatedStatus() throws Exception {
Configuration conf = getConfiguration();
conf.setBoolean("fs.test.impl.disable.cache", false);
conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads);
conf.set(org.apache.hadoop.mapreduce.lib.input.FileInputFormat.INPUT_DIR,
... |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
AvroSerial... | @Test
void addingARequiredMakesSerializersIncompatible() {
assertThat(
AvroSerializerSnapshot.resolveSchemaCompatibility(
FIRST_REQUIRED_LAST_OPTIONAL, BOTH_REQUIRED))
.is(isIncompatible());
} |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldSanitizeInterNodeListenerWithTrailingSlash() {
// Given:
final URL expected = url("https://example.com:12345");
final URL configured = url("https://example.com:12345/");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.putAll(MIN... |
@Override
public Rule getByUuid(String uuid) {
ensureInitialized();
Rule rule = rulesByUuid.get(uuid);
checkArgument(rule != null, "Can not find rule for uuid %s. This rule does not exist in DB", uuid);
return rule;
} | @Test
public void getByUuid_returns_Rule_if_it_exists_in_DB() {
Rule rule = underTest.getByUuid(AB_RULE.getUuid());
assertIsABRule(rule);
} |
@Override
public int getMaxConnections() {
return 0;
} | @Test
void assertGetMaxConnections() {
assertThat(metaData.getMaxConnections(), is(0));
} |
@Override
public Object read(final PostgreSQLPacketPayload payload, final int parameterValueLength) {
byte[] bytes = new byte[parameterValueLength];
payload.getByteBuf().readBytes(bytes);
return ARRAY_PARAMETER_DECODER.decodeFloat4Array(bytes, '{' != bytes[0]);
} | @Test
void assertRead() {
String parameterValue = "{\"11.1\",\"12.1\"}";
int expectedLength = 4 + parameterValue.length();
ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(expectedLength);
byteBuf.writeInt(parameterValue.length());
byteBuf.writeCharSequence(parameterValue, St... |
@Override public Message receive() {
Message message = delegate.receive();
handleReceive(message);
return message;
} | @Test void receive_retains_baggage_properties() throws Exception {
ActiveMQTextMessage message = new ActiveMQTextMessage();
B3Propagation.B3_STRING.injector(SETTER).inject(parent, message);
message.setStringProperty(BAGGAGE_FIELD_KEY, "");
receive(message);
assertThat(message.getProperties())
... |
public static String summarizeCollection(Object obj) {
if (obj instanceof Collection) {
return String.format(
"%s{%d entries}", obj.getClass().getSimpleName(), ((Collection<?>) obj).size());
} else if (obj instanceof Map) {
return String.format("Map{%d entries}", ((Map<?, ?>) obj).size());... | @Test
public void summarizeCollection() {
Set<Integer> set = Sets.newHashSet(1, 2);
assertEquals("HashSet{2 entries}", CommonUtils.summarizeCollection(set));
Map<Integer, Long> map = ImmutableMap.of(0, 3L, 1, 1L);
assertEquals("Map{2 entries}", CommonUtils.summarizeCollection(map));
TestClassA a... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testBasicDoFnProcessContext() throws Exception {
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<String, String>() {
@ProcessElement
public void process(ProcessContext c) {}
}.getClass());
assertThat(sig.processElement().... |
public Map<String, Object> getTemplateData() {
return templateData;
} | @Test
public void givenTemplateFile_whenTemplateDataRendered_ThenTemplateTagsReplacedWithDataInOutput() throws IOException {
inStream = WordDocumentFromTemplate.class.getClassLoader()
.getResourceAsStream("template.docx");
XWPFTemplate template = XWPFTemplate.compile(inStream, builder.b... |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testExtract() {
run("extract.feature");
} |
public Ligature(String successor, String ligature)
{
this.successor = successor;
this.liga = ligature;
} | @Test
void testLigature()
{
Ligature ligature = new Ligature("successor", "ligature");
assertEquals("successor", ligature.getSuccessor());
assertEquals("ligature", ligature.getLigature());
} |
public static void extractZipFile(ZipFile zipFile, File toDir, String prefix) throws IOException {
ensureDirectory(toDir);
final String base = toDir.getCanonicalPath();
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry ... | @Test
public void testExtractZipFileDisallowsPathTraversalWhenUsingPrefix() throws Exception {
try (TmpPath path = new TmpPath()) {
Path testRoot = Paths.get(path.getPath());
Path destParent = testRoot.resolve("outer");
Path extractionDest = destParent.resolve("resources"... |
public static Map<String, String> initQueryParams(final String query) {
final Map<String, String> queryParams = new LinkedHashMap<>();
if (StringUtils.hasLength(query)) {
final Matcher matcher = PATTERN.matcher(query);
while (matcher.find()) {
String name = decode... | @Test
public void testInitQueryParams() {
Map<String, String> params = HttpParamConverter.initQueryParams("a=1&b=2&c=&d");
assertThat(params,
allOf(IsMapContaining.hasEntry("a", "1"),
IsMapContaining.hasEntry("b", "2"),
IsMapContaining.... |
@Override
public NativeQuerySpec<Record> select(String sql, Object... args) {
return new NativeQuerySpecImpl<>(this, sql, args, DefaultRecord::new, false);
} | @Test
public void testDistinct() {
DefaultQueryHelper helper = new DefaultQueryHelper(database);
database.dml()
.insert("s_test")
.value("id", "distinct-test")
.value("name", "testDistinct")
.value("testName", "distinct")
... |
@Override
public boolean isNotDevelopment() {
return original.isNotDevelopment();
} | @Test
public void isNotDevelopment() {
assertEquals(pluginManager.isNotDevelopment(), wrappedPluginManager.isNotDevelopment());
} |
public int merge(final K key, final int value, final IntIntFunction remappingFunction)
{
requireNonNull(key);
requireNonNull(remappingFunction);
final int missingValue = this.missingValue;
if (missingValue == value)
{
throw new IllegalArgumentException("cannot acc... | @Test
void mergeThrowsNullPointerExceptionIfKeyIsNull()
{
assertThrowsExactly(NullPointerException.class, () -> objectToIntMap.merge(null, 42, (v1, v2) -> 7));
} |
public ConnectorType connectorType(Map<String, String> connConfig) {
if (connConfig == null) {
return ConnectorType.UNKNOWN;
}
String connClass = connConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG);
if (connClass == null) {
return ConnectorType.UNKNOWN;
... | @Test
public void testGetConnectorTypeWithNullConfig() {
AbstractHerder herder = testHerder();
assertEquals(ConnectorType.UNKNOWN, herder.connectorType(null));
} |
@Udf
public <T> String toJsonString(@UdfParameter final T input) {
return toJson(input);
} | @Test
public void shouldSerializeInt() {
// When:
final String result = udf.toJsonString(123);
// Then:
assertEquals("123", result);
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeRoundingDown() {
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.24)), BigDecimal.valueOf(10));
FunctionTestUtil.assertResult(roundHalfDownFunction.invoke(BigDecimal.valueOf(10.24), BigDecimal.ONE),
BigDecimal.va... |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldParseFullLocalDateWithNanoSeconds() {
// Given
final String format = "yyyy-MM-dd HH:mm:ss:nnnnnnnnn";
// Note that there is an issue when resolving nanoseconds that occur below the
// micro-second granularity. Since this is a private API (the only one exposed
// converts it... |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldThrowIfCanNotCoerceArrayElement() {
// Given:
final KsqlJsonDeserializer<List> deserializer = givenDeserializerForSchema(
SchemaBuilder
.array(Schema.OPTIONAL_INT32_SCHEMA)
.build(),
List.class
);
final List<String> expected = ImmutableL... |
public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) {
checkArgument(repetitions >= 0, () ->
"repetitions cannot be negative: " + repetitions);
List<Integer> decimalGroups = new ArrayList<>(repetitions);
for (int i = 0; i < repetitions; i++)
dec... | @Test
public void repeatOptionalDecimals() {
assertEquals("0.00000001", formatRepeat(SATOSHI, 2, 4));
assertEquals("0.00000010", formatRepeat(SATOSHI.multiply(10), 2, 4));
assertEquals("0.01", formatRepeat(CENT, 2, 4));
assertEquals("0.10", formatRepeat(CENT.multiply(10), 2, 4));
... |
@Override
@SuppressWarnings("DuplicatedCode")
public Integer cleanErrorLog(Integer exceedDay, Integer deleteLimit) {
int count = 0;
LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
// 循环删除,直到没有满足条件的数据
for (int i = 0; i < Short.MAX_VALUE; i++) {
int... | @Test
public void testCleanJobLog() {
// mock 数据
ApiErrorLogDO log01 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3))));
apiErrorLogMapper.insert(log01);
ApiErrorLogDO log02 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofD... |
@Override
public String selectForUpdateSkipLocked() {
return supportsSelectForUpdateSkipLocked ? " FOR UPDATE SKIP LOCKED" : "";
} | @Test
void otherDBDoesNotSupportSelectForUpdateSkipLocked() {
assertThat(new MariaDbDialect("MySQL", "10.6").selectForUpdateSkipLocked()).isEmpty();
} |
public static InetAddress getRemoteAddress() {
return REMOTE_ADDRESS_CONTEXT_KEY.get();
} | @Test
void getRemoteAddress() {
when(clientConnectionManager.getRemoteAddress(any()))
.thenReturn(Optional.empty());
GrpcTestUtils.assertStatusException(Status.INTERNAL, this::getRequestAttributes);
final String remoteAddressString = "6.7.8.9";
when(clientConnectionManager.getRemoteAddress(... |
private void insertUndoLog(String xid, long branchId, String rollbackCtx, byte[] undoLogContent,
State state, Connection conn) throws SQLException {
try (PreparedStatement pst = conn.prepareStatement(INSERT_UNDO_LOG_SQL)) {
pst.setLong(1, branchId);
pst.set... | @Test
public void testInsertUndoLog() throws SQLException {
Assertions.assertDoesNotThrow(() -> undoLogManager.insertUndoLogWithGlobalFinished("xid", 1L, new JacksonUndoLogParser(),
dataSource.getConnection()));
Assertions.assertDoesNotThrow(() -> undoLogManager.insertUndoLogWithNormal(... |
@Override
public SeekableByteChannel getChannel() {
return new RedissonByteChannel();
} | @Test
public void testChannelTruncate() throws IOException {
RBinaryStream stream = redisson.getBinaryStream("test");
SeekableByteChannel c = stream.getChannel();
c.write(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7}));
assertThat(c.size()).isEqualTo(7);
c.truncate(3);
... |
public EqualityPartition generateEqualitiesPartitionedBy(Predicate<VariableReferenceExpression> variableScope)
{
ImmutableSet.Builder<RowExpression> scopeEqualities = ImmutableSet.builder();
ImmutableSet.Builder<RowExpression> scopeComplementEqualities = ImmutableSet.builder();
ImmutableSet.... | @Test(dataProvider = "testRowExpressions")
public void testExpressionsThatMayReturnNullOnNonNullInput(RowExpression candidate)
{
EqualityInference.Builder builder = new EqualityInference.Builder(METADATA);
builder.extractInferenceCandidates(equals(variable("b"), variable("x")));
builder.... |
@SuppressWarnings("unchecked")
public final <T> T getValue(final E key) {
return (T) cache.get(key).getValue();
} | @Test
void assertGetValue() {
Properties props = createProperties();
TypedPropertiesFixture actual = new TypedPropertiesFixture(props);
assertTrue((Boolean) actual.getValue(TypedPropertyKeyFixture.BOOLEAN_VALUE));
assertTrue((Boolean) actual.getValue(TypedPropertyKeyFixture.BOOLEAN_O... |
public static Predicate[] acceptVisitor(Predicate[] predicates, Visitor visitor, IndexRegistry indexes) {
Predicate[] target = predicates;
boolean copyCreated = false;
for (int i = 0; i < predicates.length; i++) {
Predicate predicate = predicates[i];
if (predicate instanc... | @Test
public void acceptVisitor_whenThereIsNonVisitablePredicateAndNewArraysIsCreated_thenJustCopyTheNonVisitablePredicate() {
Visitor mockVisitor = mock(Visitor.class);
Predicate[] predicates = new Predicate[3];
Predicate p1 = mock(Predicate.class);
predicates[0] = p1;
Pre... |
@Nullable
public static URI uriWithTrailingSlash(@Nullable final URI uri) {
if (uri == null) {
return null;
}
final String path = firstNonNull(uri.getPath(), "/");
if (path.endsWith("/")) {
return uri;
} else {
try {
return... | @Test
public void uriWithTrailingSlashReturnsURIWithTrailingSlashIfTrailingSlashIsMissing() throws URISyntaxException {
final String uri = "http://example.com/api/";
assertEquals(URI.create(uri), Tools.uriWithTrailingSlash(URI.create("http://example.com/api")));
} |
@Override
public CompletableFuture<ConsumerRunningInfo> getConsumerRunningInfo(String address,
GetConsumerRunningInfoRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<ConsumerRunningInfo> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createR... | @Test
public void assertGetConsumerRunningInfoWithError() {
setResponseError();
GetConsumerRunningInfoRequestHeader requestHeader = mock(GetConsumerRunningInfoRequestHeader.class);
CompletableFuture<ConsumerRunningInfo> actual = mqClientAdminImpl.getConsumerRunningInfo(defaultBrokerAddr, req... |
@Override
public void define(Context context) {
NewController controller = context.createController("api/monitoring")
.setDescription("Monitoring")
.setSince("9.3");
for (MonitoringWsAction action : actions) {
action.define(controller);
}
controller.done();
} | @Test
public void define_controller() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/monitoring");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat... |
public static SearchTypeError parse(Query query, String searchTypeId, ElasticsearchException ex) {
if (isSearchTypeAbortedError(ex)) {
return new SearchTypeAbortedError(query, searchTypeId, ex);
}
Throwable possibleResultWindowException = ex;
int attempt = 0;
while ... | @Test
void returnsResultWindowLimitErrorIfPresentInTheExceptionsCauseChain() {
final ElasticsearchException elasticsearchException = new ElasticsearchException(
"Something is wrong!",
new IllegalStateException(
"Run for your lives!!!",
... |
public String getUtf8CString() throws IOException
{
ArrayList<ByteBuffer> bufferList = null;
boolean foundZeroByte = false;
int numBytes = 0;
while (foundZeroByte == false && advanceBufferIfCurrentBufferHasNoRemaining())
{
int position = _currentBuffer.position();
byte[] array = _curr... | @Test
public void testGetUTF8CString() throws Exception
{
for (Map.Entry<String, String> entry : _strings.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
for (int bufferSize : _bufferSizes)
{
// out.println("testing " + key + " with buffer size " +... |
public CompletableFuture<Optional<Account>> getByUsernameHash(final byte[] usernameHash) {
final Timer.Sample sample = Timer.start();
return accounts.getByUsernameHash(usernameHash)
.whenComplete((ignoredResult, ignoredThrowable) -> sample.stop(getByUsernameHashTimer));
} | @Test
void testGetAccountByUsernameHash() {
UUID uuid = UUID.randomUUID();
Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, UUID.randomUUID(), new ArrayList<>(),
new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]);
account.setUsernameHash(USERNAME_HASH_1);
... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void tableZeroArgCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.table("input-topic")
.groupBy((key, value) -> null)
.count();
final Topology topology = builder.build();
final TopologyDescripti... |
@Override
public Class<? extends StorageBuilder> builder() {
return SumPerMinStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
long time = 1597113447737L;
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), time);
function.calculate();
StorageBuilder<SumPerMinFunction> storageBuilder = function.builder... |
public static BBox parseTwoPoints(String objectAsString) {
String[] splittedObject = objectAsString.split(",");
if (splittedObject.length != 4)
throw new IllegalArgumentException("BBox should have 4 parts but was " + objectAsString);
double minLat = Double.parseDouble(splittedObjec... | @Test
public void testParseTwoPoints() {
assertEquals(new BBox(2, 4, 1, 3), BBox.parseTwoPoints("1,2,3,4"));
// stable parsing, i.e. if first point is in north or south it does not matter:
assertEquals(new BBox(2, 4, 1, 3), BBox.parseTwoPoints("3,2,1,4"));
} |
@Override
public void run() {
if (!redoService.isConnected()) {
LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task");
return;
}
try {
redoForInstances();
redoForSubscribes();
} catch (Exception e) {
... | @Test
void testRunRedoWithDisconnection() {
when(redoService.isConnected()).thenReturn(false);
redoTask.run();
verify(redoService, never()).findInstanceRedoData();
verify(redoService, never()).findSubscriberRedoData();
} |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) {
return aggregate(initializer, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullNamedOnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, null, Materialized.as("test")));
} |
public DoubleArrayAsIterable usingExactEquality() {
return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_containsNoneOf_primitiveDoubleArray_failure() {
expectFailureWhenTestingThat(array(1.1, 2.2, 3.3))
.usingExactEquality()
.containsNoneOf(array(99.99, 2.2));
assertFailureKeys(
"value of",
"expected not to contain any of",
"testing wh... |
public CompletableFuture<Void> getAvailabilityFuture() {
return currentFuture;
} | @Test
public void testUnavailableWhenEmpty() {
final FutureCompletingBlockingQueue<Object> queue = new FutureCompletingBlockingQueue<>();
assertThat(queue.getAvailabilityFuture().isDone()).isFalse();
} |
@Override
public boolean contains(Object o) {
for (M member : members) {
if (selector.select(member) && o.equals(member)) {
return true;
}
}
return false;
} | @Test
public void testDoesNotContainThisMemberWhenLiteMembersSelectedAndNoLocalMember() {
Collection<MemberImpl> collection = new MemberSelectingCollection<>(members,
and(LITE_MEMBER_SELECTOR, NON_LOCAL_MEMBER_SELECTOR));
assertFalse(collection.contains(thisMember));
} |
@Override
public ObjectNode encode(Metric metric, CodecContext context) {
checkNotNull(metric, "Metric cannot be null");
ObjectNode objectNode = context.mapper().createObjectNode();
ObjectNode dataNode = context.mapper().createObjectNode();
if (metric instanceof Counter) {
... | @Test
public void testMetricEncode() {
Counter counter = new Counter();
Meter meter = new Meter();
Timer timer = new Timer();
counter.inc();
meter.mark();
timer.update(1, TimeUnit.MILLISECONDS);
ObjectNode counterJson = metricCodec.encode(counter, context);
... |
@VisibleForTesting
public static void validateAndResolveService(Service service,
SliderFileSystem fs, org.apache.hadoop.conf.Configuration conf) throws
IOException {
boolean dnsEnabled = conf.getBoolean(RegistryConstants.KEY_DNS_ENABLED,
RegistryConstants.DEFAULT_DNS_ENABLED);
if (dnsEnabl... | @Test
public void testComponentNameSameAsServiceName() throws IOException {
SliderFileSystem sfs = ServiceTestUtils.initMockFs();
Service app = new Service();
app.setName("test");
app.setVersion("v1");
app.addComponent(createValidComponent("test"));
//component name same as service name
t... |
public static void deleteIfExists(final File file)
{
try
{
Files.deleteIfExists(file.toPath());
}
catch (final IOException ex)
{
LangUtil.rethrowUnchecked(ex);
}
} | @Test
void deleteIfExistsErrorHandlerFailsOnNonEmptyDirectory() throws IOException
{
final ErrorHandler errorHandler = mock(ErrorHandler.class);
final Path dir = tempDir.resolve("dir");
Files.createDirectory(dir);
Files.createFile(dir.resolve("file.txt"));
IoUtil.deleteI... |
public synchronized FetchPosition positionOrNull(TopicPartition tp) {
final TopicPartitionState state = assignedStateOrNull(tp);
if (state == null) {
return null;
}
return assignedState(tp).position;
} | @Test
public void testPositionOrNull() {
state.assignFromUser(Collections.singleton(tp0));
final TopicPartition unassignedPartition = new TopicPartition("unassigned", 0);
state.seek(tp0, 5);
assertEquals(5, state.positionOrNull(tp0).offset);
assertNull(state.positionOrNull(u... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(file.getType().contains(Path.Type.upload)) {
return new NullInputStream(0L);
}
final HttpRange range = ... | @Test
public void testReadCloseReleaseEntity() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
... |
@Override
public void appendOrOverwriteRegion(int subpartition, T newRegion) throws IOException {
// This method will only be called when we want to eliminate a region. We can't let the
// region be reloaded into the cache, otherwise it will lead to an infinite loop.
long oldRegionOffset = f... | @Test
void testAppendOrOverwriteRegion() throws Exception {
CompletableFuture<Void> cachedRegionFuture = new CompletableFuture<>();
try (FileDataIndexSpilledRegionManager<TestingFileDataIndexRegion> spilledRegionManager =
createSpilledRegionManager(
(ignore1, ... |
public static Sensor processRecordsSensor(final String threadId,
final StreamsMetricsImpl streamsMetrics) {
final Sensor sensor =
streamsMetrics.threadLevelSensor(threadId, PROCESS + RECORDS_SUFFIX, RecordingLevel.INFO);
final Map<String, String>... | @Test
public void shouldGetProcessRecordsSensor() {
final String operation = "process-records";
final String avgDescription = "The average number of records processed within an iteration";
final String maxDescription = "The maximum number of records processed within an iteration";
wh... |
Boolean processPayment() {
try {
ResponseEntity<Boolean> paymentProcessResult = restTemplateBuilder
.build()
.postForEntity("http://localhost:30301/payment/process", "processing payment",
Boolean.class);
LOGGER.info("Payment processing result: {}", paymentProcessResult.... | @Test
void testProcessPayment() {
// Arrange
when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class)))
.thenReturn(ResponseEntity.ok(true));
// Act
Boolean result = orderService.processPayment();
// Assert
assertEquals(true, result);... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
final File entry = share.get().openFile(new SMBPathContainerService(ses... | @Test
public void testReadWriteConcurrency() throws Exception {
final Path home = new DefaultHomeFinderService(session).find();
final ExecutorService executor = Executors.newFixedThreadPool(50);
final List<Future<Object>> results = new ArrayList<>();
for(int i = 0; i < 100; i++) {
... |
public ProviderBuilder server(String server) {
this.server = server;
return getThis();
} | @Test
void server() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.server("server");
Assertions.assertEquals("server", builder.build().getServer());
} |
public static ModelLocalUriId getModelLocalUriIdObject(String localUriString) throws JsonProcessingException {
return objectMapper.readValue(localUriString, ModelLocalUriId.class);
} | @Test
void getModelLocalUriIdObject() throws JsonProcessingException {
String localUriIdString = "{\"model\":\"foo\",\"basePath\":\"/this/is/modelLocalUriId\",\"fullPath\":\"/foo/this/is/modelLocalUriId\"}";
ModelLocalUriId retrieved = JSONUtils.getModelLocalUriIdObject(localUriIdString);
as... |
public List<String> toList(boolean trim) {
return toList((str) -> trim ? StrUtil.trim(str) : str);
} | @Test
public void splitByCharTrimTest(){
String str1 = "a, ,,efedsfs, ddf,";
SplitIter splitIter = new SplitIter(str1,
new CharFinder(',', false),
Integer.MAX_VALUE,
true
);
final List<String> strings = splitIter.toList(true);
assertEquals(3, strings.size());
assertEquals("a", strings.get(0... |
public boolean shouldRestartTask(TaskStatus status) {
return includeTasks && (!onlyFailed || status.state() == AbstractStatus.State.FAILED);
} | @Test
public void restartAnyStatusTasks() {
RestartRequest restartRequest = new RestartRequest(CONNECTOR_NAME, false, true);
assertTrue(restartRequest.shouldRestartTask(createTaskStatus(AbstractStatus.State.FAILED)));
assertTrue(restartRequest.shouldRestartTask(createTaskStatus(AbstractStatu... |
@Override
public Iterable<K> loadAllKeys() {
// If loadAllKeys property is disabled, don't load anything
if (!genericMapStoreProperties.loadAllKeys) {
return Collections.emptyList();
}
awaitSuccessfulInit();
String sql = queries.loadAllKeys();
SqlResult ... | @Test
public void givenFalse_whenLoadAllKeys_thenReturnNull() {
ObjectSpec spec = objectProvider.createObject(mapName, true);
objectProvider.insertItems(spec, 1);
Properties properties = new Properties();
properties.setProperty(DATA_CONNECTION_REF_PROPERTY, TEST_DATABASE_REF);
... |
@Deprecated
@SuppressWarnings("deprecation")
public void recordEviction() {
// This method is scheduled for removal in version 3.0 in favor of recordEviction(weight)
recordEviction(1);
} | @Test
public void evictionWithCause() {
// With JUnit 5, this would be better done with @ParameterizedTest + @EnumSource
for (RemovalCause cause : RemovalCause.values()) {
stats.recordEviction(3, cause);
assertThat(registry.histogram(PREFIX + ".evictions." + cause.name()).getCount()).isEqualTo(1);... |
@Override
public void add(IndexSpec indexSpec) {
checkIndexSpec(indexSpec);
var indexName = indexSpec.getName();
var existingSpec = indexSpecs.putIfAbsent(indexName, indexSpec);
if (existingSpec != null) {
throw new IllegalArgumentException(
"IndexSpec wit... | @Test
void add() {
var specs = new DefaultIndexSpecs();
specs.add(primaryKeyIndexSpec(FakeExtension.class));
assertThat(specs.contains(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isTrue();
} |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetBiFunctionVariadic() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("biFunctionType", BiFunction.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getVarArgsSchemaFromType(type);
assertThat(schema, instanceOf(Lambd... |
@Override
public <KEY> URIMappingResult<KEY> mapUris(List<URIKeyPair<KEY>> requestUriKeyPairs)
throws ServiceUnavailableException
{
if (requestUriKeyPairs == null || requestUriKeyPairs.isEmpty())
{
return new URIMappingResult<>(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap... | @Test
public void testMapUrisStickyRoutingOnly() throws ServiceUnavailableException, PartitionAccessException
{
int partitionCount = 1;
int requestPerPartition = 1000;
int totalHostCount = 100;
HashRingProvider ringProvider = createStaticHashRingProvider(totalHostCount, partitionCount, getHashFunct... |
protected String addDatetimeToFilename( String filename, boolean addDate, String datePattern, boolean addTime,
String timePattern, boolean specifyFormat, String datetimeFormat ) {
if ( Utils.isEmpty( filename ) ) {
return null;
}
// Replace possible environm... | @Test
public void testAddDatetimeToFilename_ZipWithDotsInFolderWithoutDots() {
JobEntryBase jobEntryBase = new JobEntryBase();
String fullFilename;
String filename = "/folder_without_dots/zip.with.dots.in.folder.without.dots";
String regexFilename = regexDotEscape( filename );
// add nothing
... |
public static void readFully(InputStream stream, byte[] bytes, int offset, int length)
throws IOException {
int bytesRead = readRemaining(stream, bytes, offset, length);
if (bytesRead < length) {
throw new EOFException(
"Reached the end of stream with " + (length - bytesRead) + " bytes lef... | @Test
public void testReadFully() throws Exception {
byte[] buffer = new byte[5];
MockInputStream stream = new MockInputStream();
IOUtil.readFully(stream, buffer, 0, buffer.length);
assertThat(buffer)
.as("Byte array contents should match")
.isEqualTo(Arrays.copyOfRange(MockInputStre... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateJobStatus(Long id, Integer status) throws SchedulerException {
// 校验 status
if (!containsAny(status, JobStatusEnum.NORMAL.getStatus(), JobStatusEnum.STOP.getStatus())) {
throw exception(JOB_CHANGE_STATUS_INVALI... | @Test
public void testUpdateJobStatus_changeStatusInvalid() {
// 调用,并断言异常
assertServiceException(() -> jobService.updateJobStatus(1L, JobStatusEnum.INIT.getStatus()),
JOB_CHANGE_STATUS_INVALID);
} |
public static String trimStart( final String source, char c ) {
if ( source == null ) {
return null;
}
int length = source.length();
int index = 0;
while ( index < length && source.charAt( index ) == c ) {
index++;
}
return source.substring( index );
} | @Test
public void testTrimStart_Many() {
assertEquals( "file/path/", StringUtil.trimStart( "////file/path/", '/' ) );
} |
@Override
public Collection<String> getSystemSchemas() {
return SYSTEM_SCHEMAS;
} | @Test
void assertGetSystemSchemas() {
assertThat(systemDatabase.getSystemSchemas(), is(new HashSet<>(Arrays.asList("information_schema", "pg_catalog", "shardingsphere"))));
} |
@Override
public boolean containsAll(IntSet set) {
int size = set.size();
return size == 0 || size == 1 && set.contains(value);
} | @Test
public void testContainsAll() throws Exception {
IntSet sis = new SingletonIntSet(3);
IntSet sis2 = new SingletonIntSet(3);
assertTrue(sis.containsAll(sis2));
assertTrue(sis2.containsAll(sis));
IntSet sis3 = new RangeSet(4);
assertTrue(sis3.containsAll(sis));
assert... |
@Override
public void publish(Message message) throws JMSException {
getTopicPublisher().publish((Topic) getDestination(), message);
} | @Test(timeout = 60000)
public void testPooledConnectionFactory() throws Exception {
ActiveMQTopic topic = new ActiveMQTopic("test");
pcf = new PooledConnectionFactory();
pcf.setConnectionFactory(new ActiveMQConnectionFactory(
"vm://test?broker.persistent=false&broker.useJmx=false... |
@Operation(summary = "秒杀场景五(数据库原子性更新update set num = num -1)")
@PostMapping("/procedure")
public Result doWithProcedure(@RequestBody @Valid SeckillWebMockRequestDTO dto) {
processSeckill(dto, ATOMIC_UPDATE);
return Result.ok();
//待mq监听器处理完成打印日志,不在此处打印日志
} | @Test
void doWithProcedure() {
SeckillWebMockRequestDTO requestDTO = new SeckillWebMockRequestDTO();
requestDTO.setSeckillId(1L);
requestDTO.setRequestCount(1);
SeckillMockRequestDTO any = new SeckillMockRequestDTO();
any.setSeckillId(1L);
Result response = seckillMoc... |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (!httpAuth.isAllowed(req, resp)) {
return;
}
// post du formulaire d'ajout d'application à monitorer
I18N.bindLocale(req.getLocale());
try {
addCollectorApplication(req, resp)... | @Test
public void testDoPost() throws ServletException, IOException {
final List<String> nullUrl = Collections.singletonList(null);
doPost(null, nullUrl, false);
doPost(null, nullUrl, true);
doPost(TEST, nullUrl, true);
doPost(TEST, List.of("http://localhost:8090/test", "http://localhost:8090/test"), true);
... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void renameTopLevelAndNestedFields() {
Schema nestedSchema = Schema.builder().addStringField("field1").addInt32Field("field2").build();
Schema schema =
Schema.builder().addStringField("field1").addRowField("nested", nestedSchema).build();
PCollection<Ro... |
public static synchronized void configure(DataflowWorkerLoggingOptions options) {
if (!initialized) {
throw new RuntimeException("configure() called before initialize()");
}
// For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions
// to config the logging for l... | @Test
public void testWithSdkHarnessConfigurationOverride() {
SdkHarnessOptions options = PipelineOptionsFactory.as(SdkHarnessOptions.class);
options.setDefaultSdkHarnessLogLevel(SdkHarnessOptions.LogLevel.WARN);
DataflowWorkerLoggingInitializer.configure(options.as(DataflowWorkerLoggingOptions.class));
... |
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) {
if (hl7Bytes == null) {
return "HL7 payload is null";
}
return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length);
} | @Test
public void testGenerateInvalidPayloadExceptionMessageWithInvalidStartingSegment() throws Exception {
byte[] invalidStartingSegment = "MSA|AA|00001|\r".getBytes();
byte[] basePayload = TEST_MESSAGE.getBytes();
ByteArrayOutputStream payloadStream = new ByteArrayOutputStream(invalidStar... |
@Override
public OracleConnectorEmbeddedDebeziumConfiguration getConfiguration() {
return configuration;
} | @Test
void testIfConnectorEndpointCreatedWithConfig() throws Exception {
final Map<String, Object> params = new HashMap<>();
params.put("offsetStorageFileName", "/offset_test_file");
params.put("databaseHostname", "localhost");
params.put("databaseUser", "dbz");
params.put("d... |
@Override
public synchronized void loadApiDocument() {
if (!isEnabledLoad()) {
return;
}
List<UpstreamInstance> serviceList = this.getAllClusterLastUpdateInstanceList();
if (CollectionUtils.isEmpty(serviceList)) {
LOG.info("load api document No service registe... | @Test
public void testLoadApiDocument() {
ShenyuDictVO shenyuInitData = new ShenyuDictVO();
shenyuInitData.setDictValue("true");
when(shenyuDictService.findByDictCodeName(any(), any())).thenReturn(shenyuInitData);
List<PluginDO> pluginDOList = new ArrayList<>();
PluginDO plug... |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Merger<? super K, V> sessionMerger) {
return aggregate(initializer, sessionMerger, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullMaterializedOnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT,
sessionMerger, (Named) null));
} |
static PDImageXObject convertPNGImage(PDDocument doc, byte[] imageData) throws IOException
{
PNGConverterState state = parsePNGChunks(imageData);
if (!checkConverterState(state))
{
// There is something wrong, we can't convert this PNG
return null;
}
... | @Test
void testImageConversionIntentIndexed() throws IOException
{
checkImageConvert("929316.png");
try (PDDocument doc = new PDDocument())
{
InputStream in = PNGConverterTest.class.getResourceAsStream("929316.png");
byte[] imageBytes = in.readAllBytes();
... |
public ECKey signingKey() {
return signingKey;
} | @Test
void signingKey() throws JOSEException {
var sut = new KeyStore();
var key = sut.signingKey();
assertEquals(KeyUse.SIGNATURE, key.getKeyUse());
assertNotNull(key.toECPrivateKey());
} |
@Deprecated
@Override
public <K, T> List<RequestInfo> scatterRequest(Request<T> request, RequestContext requestContext,
Map<URI, Set<K>> mappedKeys)
{
return defaultScatterRequestImpl(request, requestContext, mappedKeys);
} | @Test(expectedExceptions = {IllegalArgumentException.class})
public void testUnsupportedRequestScatter()
{
Request<?> request = mock(Request.class);
when(request.getMethod()).thenReturn(ResourceMethod.BATCH_CREATE);
_sgStrategy.scatterRequest(request, new RequestContext(), new URIMappingResult<Long>(Col... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testNoRetryOnSaslError() throws Exception {
RetryPolicy policy = mock(RetryPolicy.class);
RetryPolicy realPolicy = RetryPolicies.failoverOnNetworkException(5);
setupMockPolicy(policy, realPolicy);
UnreliableInterface unreliable = (UnreliableInterface) RetryProxy.create(
Unre... |
public static Write<String> write() {
return new AutoValue_MongoDbGridFSIO_Write.Builder<String>()
.setConnectionConfiguration(ConnectionConfiguration.create())
.setWriteFn(
(output, outStream) -> {
outStream.write(output.getBytes(StandardCharsets.UTF_8));
out... | @Test
public void testWriteMessage() throws Exception {
ArrayList<String> data = new ArrayList<>(100);
ArrayList<Integer> intData = new ArrayList<>(100);
for (int i = 0; i < 1000; i++) {
data.add("Message " + i);
}
for (int i = 0; i < 100; i++) {
intData.add(i);
}
pipeline
... |
static boolean isDialectSupported(SqlDialect dialect) {
return dialect instanceof H2SqlDialect ||
dialect instanceof MssqlSqlDialect ||
dialect instanceof MysqlSqlDialect ||
dialect instanceof OracleSqlDialect ||
dialect instanceof PostgresqlSqlDialect... | @Test
public void testUpsertDialectNotSupported() {
boolean result = SupportedDatabases.isDialectSupported(sybaseSqlDialect);
assertFalse(result);
} |
@Override
public void execute(ComputationStep.Context context) {
Metric qProfilesMetric = metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY);
new PathAwareCrawler<>(new QProfileAggregationComponentVisitor(qProfilesMetric))
.visit(treeRootHolder.getRoot());
} | @Test
public void add_quality_profile_measure_on_project() {
treeRootHolder.setRoot(MULTI_MODULE_PROJECT);
QualityProfile qpJava = createQProfile(QP_NAME_1, LANGUAGE_KEY_1);
QualityProfile qpPhp = createQProfile(QP_NAME_2, LANGUAGE_KEY_2);
analysisMetadataHolder.setQProfilesByLanguage(ImmutableMap.of(... |
public static boolean isLinkLocalIPv6WithZoneIndex(String input) {
if (input.length() > FIVE && input.substring(ZERO, FIVE).equalsIgnoreCase(FE80)) {
int lastIndex = input.lastIndexOf(PERCENT);
if (lastIndex > ZERO && lastIndex < (input.length() - 1)) {
String ipPart = in... | @Test
void isLinkLocalIPv6WithZoneIndex() {
assertTrue(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("fe80::1%lo0"));
assertFalse(InetAddressValidator.isLinkLocalIPv6WithZoneIndex("2000:0000:0000:0000:0001:2345:6789:abcd"));
} |
public void setIdentity(final Local file) {
this.identity = file;
this.passed = false;
} | @Test
public void testSetIdentity() throws Exception {
Credentials c = new Credentials();
c.setIdentity(new Local("~/.ssh/unknown.rsa"));
assertFalse(c.isPublicKeyAuthentication());
final Local t = new Local(PreferencesFactory.get().getProperty("tmp.dir"), "id_rsa");
LocalTou... |
public static String encodeParams(String urlWithParams, Charset charset) {
if (StrUtil.isBlank(urlWithParams)) {
return StrUtil.EMPTY;
}
String urlPart = null; // url部分,不包括问号
String paramPart; // 参数部分
final int pathEndPos = urlWithParams.indexOf('?');
if (pathEndPos > -1) {
// url + 参数
urlPart = S... | @Test
public void encodeParamTest() {
// ?单独存在去除之,&单位位于末尾去除之
String paramsStr = "?a=b&c=d&";
String encode = HttpUtil.encodeParams(paramsStr, CharsetUtil.CHARSET_UTF_8);
assertEquals("a=b&c=d", encode);
// url不参与转码
paramsStr = "http://www.abc.dd?a=b&c=d&";
encode = HttpUtil.encodeParams(paramsStr, Chars... |
public synchronized boolean remove(long item1, long item2) {
boolean removed = false;
int index = 0;
for (int i = 0; i < this.size; i++) {
if (data[index] == item1 && data[index + 1] == item2) {
removeAtWithoutLock(index);
removed = true;
... | @Test
public void testRemove() {
GrowablePriorityLongPairQueue queue = new GrowablePriorityLongPairQueue();
assertTrue(queue.isEmpty());
queue.add(1, 1);
assertFalse(queue.isEmpty());
assertFalse(queue.remove(1, 0));
assertFalse(queue.isEmpty());
assertTrue(... |
@Nonnull
public static <T, A> AggregateOperation1<T, MutableReference<A>, A> reducing(
@Nonnull A emptyAccValue,
@Nonnull FunctionEx<? super T, ? extends A> toAccValueFn,
@Nonnull BinaryOperatorEx<A> combineAccValuesFn,
@Nullable BinaryOperatorEx<A> deductAccValueFn
... | @Test
public void when_reducing() {
validateOp(reducing(0, Integer::intValue, Integer::sum, (x, y) -> x - y),
MutableReference::get,
1, 2, 1, 3, 3);
} |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
payload.writeInt4(AUTH_REQ_SHA256);
payload.writeInt4(PASSWORD_STORED_METHOD_SHA256);
payload.writeBytes(authHexData.getSalt().getBytes());
payload.writeBytes(authHexData.getNonce().getBytes());
if (versi... | @Test
void assertWriteProtocol300Packet() {
PostgreSQLPacketPayload payload = mock(PostgreSQLPacketPayload.class);
OpenGaussAuthenticationSCRAMSha256Packet packet = new OpenGaussAuthenticationSCRAMSha256Packet(OpenGaussProtocolVersion.PROTOCOL_350.getVersion() - 1, 2048, authHexData, "");
pa... |
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 getFieldNamesNot() throws ParseException {
final ParsedQuery parsedQuery = parser.parse("NOT _exists_ : type");
assertThat(parsedQuery.allFieldNames()).contains("type");
} |
@VisibleForTesting
AzureADToken getTokenUsingJWTAssertion(String clientAssertion) throws IOException {
return AzureADAuthenticator
.getTokenUsingJWTAssertion(authEndpoint, clientId, clientAssertion);
} | @Test
public void testTokenFetchWithEmptyTokenFile() throws Exception {
File tokenFile = File.createTempFile("azure-identity-token", "txt");
AzureADToken azureAdToken = new AzureADToken();
WorkloadIdentityTokenProvider tokenProvider = Mockito.spy(
new WorkloadIdentityTokenProvider(AUTHORITY, TENAN... |
@VisibleForTesting
public ListenableFuture<?> internalExecute(CreateTable statement, Metadata metadata, AccessControl accessControl, Session session, List<Expression> parameters, WarningCollector warningCollector)
{
checkArgument(!statement.getElements().isEmpty(), "no columns for table");
Map<... | @Test(expectedExceptions = SemanticException.class, expectedExceptionsMessageRegExp = ".*does not support Primary Key constraints")
public void testCreateWithPrimaryKeyConstraintWithUnsupportedConnector()
{
List<TableElement> inputColumns = ImmutableList.of(
new ColumnDefinition(identifi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.