focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void push(int v) {
if (endIndexPlusOne >= arr.length) {
arr = Arrays.copyOf(arr, (int) (arr.length * growFactor));
}
arr[endIndexPlusOne] = v;
endIndexPlusOne++;
} | @Test
public void testPush() {
SimpleIntDeque deque = new SimpleIntDeque(8, 2f);
for (int i = 0; i < 60; i++) {
deque.push(i);
assertEquals(i + 1, deque.getSize());
}
assertEquals(60, deque.getSize());
assertEquals(0, deque.pop());
assertEqu... |
public static void touch(String path, String fileName) throws IOException {
FileUtils.touch(Paths.get(path, fileName).toFile());
} | @Test
void testTouch() throws IOException {
File file = Paths.get(EnvUtil.getNacosTmpDir(), "touch.ut").toFile();
assertFalse(file.exists());
DiskUtils.touch(file);
assertTrue(file.exists());
file.deleteOnExit();
} |
@ConstantFunction(name = "mod", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT)
public static ConstantOperator modSMALLINT(ConstantOperator first, ConstantOperator second) {
if (second.getSmallint() == 0) {
return ConstantOperator.createNull(Type.SMALLINT);
}
return Const... | @Test
public void modSMALLINT() {
assertEquals(0, ScalarOperatorFunctions.modSMALLINT(O_SI_10, O_SI_10).getSmallint());
} |
@Operation(summary = "stop", description = "TASK_INSTANCE_STOP")
@Parameters({
@Parameter(name = "id", description = "TASK_INSTANCE_ID", required = true, schema = @Schema(implementation = int.class, example = "12"))
})
@PostMapping(value = "/{id}/stop")
@ResponseStatus(HttpStatus.OK)
@Ap... | @Test
public void testStopTask() {
Result mockResult = new Result();
putMsg(mockResult, Status.SUCCESS);
when(taskInstanceService.stopTask(any(), Mockito.anyLong(), Mockito.anyInt())).thenReturn(mockResult);
Result taskResult = taskInstanceV2Controller.stopTask(null, 1L, 1);
... |
public static <T> Map<String, T> translateDeprecatedConfigs(Map<String, T> configs, String[][] aliasGroups) {
return translateDeprecatedConfigs(configs, Stream.of(aliasGroups)
.collect(Collectors.toMap(x -> x[0], x -> Stream.of(x).skip(1).collect(Collectors.toList()))));
} | @Test
public void testAllowDeprecatedNulls() {
Map<String, String> config = new HashMap<>();
config.put("foo.bar.deprecated", null);
config.put("foo.bar", "baz");
Map<String, String> newConfig = ConfigUtils.translateDeprecatedConfigs(config, new String[][]{
{"foo.bar", "f... |
@NonNull @Override
@SuppressWarnings("ConstantConditions")
public String getHostUrl() {
return Jenkins.get().getRootUrl();
} | @Test
public void verify(){
List<JwtTokenServiceEndpoint> jwtTokenServiceEndpoints = JwtTokenServiceEndpoint.all();
assertEquals(1, jwtTokenServiceEndpoints.size());
assertEquals(Jenkins.get().getRootUrl(), jwtTokenServiceEndpoints.get(0).getHostUrl());
} |
@Override
public <VR> KTable<K, VR> transformValues(final ValueTransformerWithKeySupplier<? super K, ? super V, ? extends VR> transformerSupplier,
final String... stateStoreNames) {
return doTransformValues(transformerSupplier, null, NamedInternal.empty(), state... | @SuppressWarnings("unchecked")
@Test
public void shouldThrowNullPointerOnTransformValuesWithKeyWhenMaterializedIsNull() {
final ValueTransformerWithKeySupplier<String, String, ?> valueTransformerSupplier =
mock(ValueTransformerWithKeySupplier.class);
assertThrows(NullPointerException... |
@Override
protected InputStream readInputStreamParam(String key) {
Part part = readPart(key);
return (part == null) ? null : part.getInputStream();
} | @Test
public void read_input_stream() throws Exception {
when(source.getContentType()).thenReturn("multipart/form-data");
InputStream file = mock(InputStream.class);
Part part = mock(Part.class);
when(part.getInputStream()).thenReturn(file);
when(part.getSize()).thenReturn(10L);
when(source.ge... |
@Override
public void doRun() {
// Point deflector to a new index if required.
if (cluster.isConnected()) {
indexSetRegistry.forEach((indexSet) -> {
try {
if (indexSet.getConfig().isWritable()) {
checkAndRepair(indexSet);
... | @Test
public void testDoNotPerformRotationIfClusterIsDown() throws NoTargetIndexException {
final Provider<RotationStrategy> provider = spy(new RotationStrategyProvider());
when(cluster.isConnected()).thenReturn(false);
final IndexRotationThread rotationThread = new IndexRotationThread(
... |
public static Status unblock(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int blockedOffset,
final int tailOffset,
final int termId)
{
Status status = NO_ACTION;
int frameLength = frameLengthVolatile(termBuffer, blockedOffset);
... | @Test
void shouldTakeNoActionWhenMessageIsComplete()
{
final int termOffset = 0;
final int tailOffset = TERM_BUFFER_CAPACITY;
when(mockTermBuffer.getIntVolatile(termOffset)).thenReturn(HEADER_LENGTH);
assertEquals(
NO_ACTION, TermUnblocker.unblock(mockLogMetaDataBuff... |
@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 namedParamShouldSetName() {
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, String> stream = builder.stream(TOPIC, Consumed
.with(Serdes.String(), Serdes.String()));
groupedStream = stream.groupByKey(Grouped.with(Serdes.String(), S... |
@SuppressWarnings("ReturnValueIgnored")
void startStreams() {
getWorkStream.get();
getDataStream.get();
commitWorkStream.get();
workCommitter.get().start();
// *stream.get() is all memoized in a threadsafe manner.
started.set(true);
} | @Test
public void testStartStream_onlyStartsStreamsOnce() {
long itemBudget = 1L;
long byteBudget = 1L;
WindmillStreamSender windmillStreamSender =
newWindmillStreamSender(
GetWorkBudget.builder().setBytes(byteBudget).setItems(itemBudget).build());
windmillStreamSender.startStrea... |
public static URL appendTrailingSlash(URL originalURL) {
try {
return originalURL.getPath().endsWith("/") ? originalURL :
new URL(originalURL.getProtocol(),
originalURL.getHost(),
originalURL.getPort(),
... | @Test
void appendTrailingSlashAddsASlash() {
final URL url = getClass().getResource("/META-INF");
assertThat(url.toExternalForm())
.doesNotMatch(".*/$");
assertThat(ResourceURL.appendTrailingSlash(url).toExternalForm())
.endsWith("/");
} |
@Override public boolean alterDatabase(String catName, String dbName, Database db)
throws NoSuchObjectException, MetaException {
boolean succ = rawStore.alterDatabase(catName, dbName, db);
if (succ && !canUseEvents) {
// in case of event based cache update, cache will be updated during commit.
... | @Test public void testAlterDatabase() throws Exception {
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true);
MetastoreConf.setVar(conf, MetastoreConf.ConfVars.CACHED_RAW_STORE_MAX_CACHE_MEMORY, "-1Kb");
MetaStoreTestUtils.setC... |
public static RawTransaction decode(final String hexTransaction) {
final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction);
TransactionType transactionType = getTransactionType(transaction);
switch (transactionType) {
case EIP1559:
return decodeEIP155... | @Test
public void testDecodingSigned4844() throws SignatureException {
final RawTransaction rawTransaction = createEip4844RawTransaction();
final Transaction4844 transaction4844 = (Transaction4844) rawTransaction.getTransaction();
final byte[] signedMessage =
TransactionEnco... |
@Override
protected CompletableFuture<ProfilingInfo> handleRequest(
@Nonnull HandlerRequest<ProfilingRequestBody> request,
@Nonnull ResourceManagerGateway gateway)
throws RestHandlerException {
ProfilingRequestBody profilingRequest = request.getRequestBody();
int ... | @Test
void testGetTaskManagerProfilingForUnknownTaskExecutorException() throws Exception {
resourceManagerGateway.setRequestProfilingListFunction(
EXPECTED_TASK_MANAGER_ID ->
FutureUtils.completedExceptionally(
new UnknownTaskExecutorEx... |
@Override
public void execute(ComputationStep.Context context) {
// no notification on pull requests as there is no real Quality Gate on those
if (analysisMetadataHolder.isPullRequest()) {
return;
}
executeForProject(treeRootHolder.getRoot());
} | @Test
public void verify_branch_name_is_not_set_in_notification_when_main() {
analysisMetadataHolder.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME));
when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric))
.thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(OK... |
public static UTypeVar create(String name, UType lowerBound, UType upperBound) {
return new UTypeVar(name, lowerBound, upperBound);
} | @Test
public void equality() {
UType nullType = UPrimitiveType.create(TypeKind.NULL);
UType objectType = UClassType.create("java.lang.Object", ImmutableList.<UType>of());
UType charSequenceType = UClassType.create("java.lang.CharSequence", ImmutableList.<UType>of());
UType stringType = UClassType.crea... |
public Object evaluate(
final GenericRow row,
final Object defaultValue,
final ProcessingLogger logger,
final Supplier<String> errorMsg
) {
try {
return expressionEvaluator.evaluate(new Object[]{
spec.resolveArguments(row),
defaultValue,
logger,
... | @Test
public void shouldPerformThreadSafeParameterEvaluation() throws Exception {
// Given:
spec.addParameter(
ColumnName.of("foo1"),
Integer.class,
0
);
spec.addParameter(
ColumnName.of("foo2"),
Integer.class,
1
);
final CountDownLatch threadLa... |
public Mono<Void> resetToEarliest(
KafkaCluster cluster, String group, String topic, Collection<Integer> partitions) {
return checkGroupCondition(cluster, group)
.flatMap(ac ->
offsets(ac, topic, partitions, OffsetSpec.earliest())
.flatMap(offsets -> resetOffsets(ac, group,... | @Test
void resetToEarliest() {
sendMsgsToPartition(Map.of(0, 10, 1, 10, 2, 10));
commit(Map.of(0, 5L, 1, 5L, 2, 5L));
offsetsResetService.resetToEarliest(cluster, groupId, topic, List.of(0, 1)).block();
assertOffsets(Map.of(0, 0L, 1, 0L, 2, 5L));
commit(Map.of(0, 5L, 1, 5L, 2, 5L));
offsetsR... |
public static boolean isInvalidStanzaSentPriorToResourceBinding(final Packet stanza, final ClientSession session)
{
// Openfire sets 'authenticated' only after resource binding.
if (session.getStatus() == Session.Status.AUTHENTICATED) {
return false;
}
// Beware, the 'to... | @Test
public void testIsInvalid_noToAddress_unauthenticated() throws Exception
{
// Setup test fixture.
final Packet stanza = new Message();
final LocalClientSession session = mock(LocalClientSession.class, withSettings().strictness(Strictness.LENIENT));
when(session.getStatus())... |
@Override
public String convert(ILoggingEvent event) {
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
if (mdcPropertyMap == null) {
return defaultValue;
}
if (key == null) {
return outputMDCForAllKeys(mdcPropertyMap);
} else {
String value = mdcPropertyMap.get... | @Test
public void testConvertWithMultipleEntries() {
MDC.put("testKey", "testValue");
MDC.put("testKey2", "testValue2");
ILoggingEvent le = createLoggingEvent();
String result = converter.convert(le);
boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?");
assertTru... |
public static String encodeHexString(byte[] bytes) {
int l = bytes.length;
char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS_LOWER[(XF0 & bytes[i]) >>> DISPLACEMENT];
out[j++] = DIGITS_LOWER[XF & bytes[i]];
}
return new ... | @Test
public void assetEncodeHexString() {
String encodeHexString = "00010f107f80203040506070";
byte[] bytes = {0, 1, 15, 16, 127, -128, 32, 48, 64, 80, 96, 112};
Assert.isTrue(encodeHexString.equals(Md5Util.encodeHexString(bytes)));
} |
public static boolean safeContains(final Range<Comparable<?>> range, final Comparable<?> endpoint) {
try {
return range.contains(endpoint);
} catch (final ClassCastException ex) {
Comparable<?> rangeUpperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null;
... | @Test
void assertSafeContainsForLong() {
Range<Comparable<?>> range = Range.closed(12L, 1000L);
assertTrue(SafeNumberOperationUtils.safeContains(range, 500));
} |
public void logRequest(Config config, HttpRequest request) {
requestCount++;
String uri = request.getUrl();
HttpLogModifier requestModifier = logModifier(config, uri);
String maskedUri = requestModifier == null ? uri : requestModifier.uri(uri);
StringBuilder sb = new StringBuilde... | @Test
void testRequestLoggingPlain() {
HttpRequest httpRequest = httpRequestBuilder.body("hello").contentType("text/plain").path("/plain").build();
httpLogger.logRequest(config, httpRequest);
String logs = logAppender.collect();
assertTrue(logs.contains("hello"));
assertTrue(... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testGreaterThanEquals() {
UnboundPredicate<Integer> expected =
org.apache.iceberg.expressions.Expressions.greaterThanOrEqual("field1", 1);
Optional<org.apache.iceberg.expressions.Expression> actual =
FlinkFilters.convert(resolve(Expressions.$("field1").isGreaterOrEqual(Expre... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowAlterTable() throws AnalysisException, DdlException {
ShowAlterStmt stmt = new ShowAlterStmt(ShowAlterStmt.AlterType.OPTIMIZE, "testDb", null, null, null);
stmt.setNode(new OptimizeProcDir(globalStateMgr.getSchemaChangeHandler(), globalStateMgr.getDb("testDb")));
S... |
public Properties getProperties()
{
return properties;
} | @Test
public void testUriWithExtraCredentials()
throws SQLException, UnsupportedEncodingException
{
String extraCredentials = "test.token.foo:bar;test.token.abc:xyz;test.scopes:read_only|read_write";
String encodedExtraCredentials = URLEncoder.encode(extraCredentials, StandardCharset... |
public Pair<Boolean, GroupExpression> insertGroupExpression(GroupExpression groupExpression, Group targetGroup) {
if (groupExpressions.get(groupExpression) != null) {
GroupExpression existedGroupExpression = groupExpressions.get(groupExpression);
Group existedGroup = existedGroupExpressi... | @Test
public void testInsertGroupExpression(@Mocked OlapTable olapTable1,
@Mocked OlapTable olapTable2) {
new Expectations() {
{
olapTable1.getId();
result = 0;
minTimes = 0;
olapTable2.get... |
public boolean isTaintVulnerability(DefaultIssue issue) {
return taintRepositories.contains(issue.getRuleKey().repository())
&& issue.getLocations() != null
&& !RuleType.SECURITY_HOTSPOT.equals(issue.type());
} | @Test
public void test_isTaintVulnerability() {
DefaultIssue taintWithoutLocation = createIssueWithRepository("noTaintIssue", "roslyn.sonaranalyzer.security.cs")
.toDefaultIssue();
DefaultIssue taint = createIssueWithRepository("taintIssue", "roslyn.sonaranalyzer.security.cs")
.setLocations(DbIssu... |
OutputT apply(InputT input) throws UserCodeExecutionException {
Optional<UserCodeExecutionException> latestError = Optional.empty();
long waitFor = 0L;
while (waitFor != BackOff.STOP) {
try {
sleepIfNeeded(waitFor);
incIfPresent(getCallCounter());
return getThrowableFunction().... | @Test
public void givenSetupQuotaErrorsExceedsLimit_throws() {
pipeline
.apply(Create.of(1))
.apply(
ParDo.of(
new DoFnWithRepeaters(
new CallerImpl(0),
new SetupTeardownImpl(LIMIT + 1, UserCodeQuotaException.class)))
... |
protected void declareRuleFromAttribute(final Attribute attribute, final String parentPath,
final int attributeIndex,
final List<KiePMMLDroolsRule> rules,
final String statusToSet,
... | @Test
void declareRuleFromAttributeWithSimplePredicateNotLastCharacteristic() {
Attribute attribute = getSimplePredicateAttribute();
final String parentPath = "parent_path";
final int attributeIndex = 2;
final List<KiePMMLDroolsRule> rules = new ArrayList<>();
final String st... |
NewCookie createAuthenticationCookie(SessionResponse token, ContainerRequestContext requestContext) {
return makeCookie(token.getAuthenticationToken(), token.validUntil(), requestContext);
} | @Test
void pathFromConfig() throws Exception {
final HttpConfiguration httpConfiguration = new HttpConfiguration();
new JadConfig(new InMemoryRepository(
Map.of("http_external_uri", "http://graylog.local/path/from/config/")), httpConfiguration)
.process();
Sy... |
public static PTransformMatcher createViewWithViewFn(final Class<? extends ViewFn> viewFnType) {
return application -> {
if (!(application.getTransform() instanceof CreatePCollectionView)) {
return false;
}
CreatePCollectionView<?, ?> createView =
(CreatePCollectionView<?, ?>) ap... | @Test
public void createViewWithViewFnDifferentViewFn() {
PCollection<Integer> input = p.apply(Create.of(1));
PCollectionView<Iterable<Integer>> view = input.apply(View.asIterable());
// Purposely create a subclass to get a different class then what was expected.
IterableViewFn<Integer> viewFn =
... |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty()) {
return new GroupAssignment(Collections.emptyMap());
} else if (groupSpec.subscr... | @Test
public void testReassignmentWhenOneMemberRemovedAfterInitialAssignmentWithTwoMembersTwoTopics() {
Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>();
topicMetadata.put(topic1Uuid, new TopicMetadata(
topic1Uuid,
topic1Name,
3,
Collections.em... |
public void logTerminationPosition(
final int memberId,
final long logLeadershipTermId,
final long logPosition)
{
final int length = terminationPositionLength();
final int captureLength = captureLength(length);
final int encodedLength = encodedLength(captureLength);
... | @Test
void logTerminationPosition()
{
final long logLeadershipTermId = 96;
final long logPosition = 128L;
final int memberId = 222;
final int offset = 64;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
logger.logTerminationPosition(memberId, logLeade... |
void checkIsStart() {
if (!initialized) {
throw new IllegalStateException("Publisher does not start");
}
} | @Test
void testCheckIsStart() {
assertThrows(IllegalStateException.class, () -> {
publisher.shutdown();
publisher = new DefaultPublisher();
publisher.checkIsStart();
});
} |
public static ULocalVarIdent create(CharSequence identifier) {
return new AutoValue_ULocalVarIdent(StringName.of(identifier));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(ULocalVarIdent.create("foo"));
} |
@Override
public boolean resolve(final Path file) {
if(PreferencesFactory.get().getBoolean("path.symboliclink.resolve")) {
// Follow links instead
return false;
}
// Create symbolic link only if supported by the local file system
if(feature != null) {
... | @Test
public void testResolve() {
final ArrayList<TransferItem> files = new ArrayList<>();
files.add(new TransferItem(new Path("/a", EnumSet.of(Path.Type.directory))));
DownloadSymlinkResolver resolver = new DownloadSymlinkResolver(files);
Path p = new Path("/a/b", EnumSet.of(Path.Ty... |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void readAll() throws IOException, AlluxioException {
int len = CHUNK_SIZE * 5;
int start = 0;
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE * 5);
byte[] res = new byte[CHUNK_SIZE];
try (FileInStream inStream = getStream(ufsPath)) {
while (start < len) {
... |
@Override
public String getUnderFSType() {
return "cos";
} | @Test
public void getUnderFSType() {
Assert.assertEquals("cos", mCOSUnderFileSystem.getUnderFSType());
} |
static String indent(String item) {
// '([^']|'')*': Matches the escape sequence "'...'" where the content between "'"
// characters can contain anything except "'" unless its doubled ('').
//
// Then each match is checked. If it starts with "'", it's left unchanged
// (escaped ... | @Test
void testIndentChildWithLiteralWithNewline() {
String sourceQuery = "SELECT *, '\n' FROM source_t";
String s =
String.format(
"SELECT * FROM (%s\n) WHERE a > 5", OperationUtils.indent(sourceQuery));
assertThat(s)
.isEqualTo(
... |
@Override
public void update(Object elem) throws Exception {
// Increment object counter.
if (objectCount != null) {
objectCount.addValue(1L);
}
// Increment byte counter.
if ((byteCountObserver != null || meanByteCountObserver != null)
&& (sampleElement() || elementByteSizeObservab... | @Test
public void testUpdate() throws Exception {
TestOutputCounter outputCounter =
new TestOutputCounter(NameContextsForTests.nameContextForTest());
outputCounter.update("hi");
outputCounter.finishLazyUpdate("hi");
outputCounter.update("bob");
outputCounter.finishLazyUpdate("bob");
C... |
@Override
public void stop() throws Exception {
factory.close();
dataSource.stop();
} | @Test
void closesTheFactoryOnStopping() throws Exception {
manager.stop();
verify(factory).close();
} |
public void addConditions(Condition... conditions) {
if (null == this.conditions) {
this.conditions = conditions;
} else {
this.conditions = ArrayUtil.addAll(this.conditions, conditions);
}
} | @Test
public void ConditionGroupToStringTest() {
Condition condition1 = new Condition("a", "A");
Condition condition2 = new Condition("b", "B");
condition2.setLinkOperator(LogicalOperator.OR);
Condition condition3 = new Condition("c", "C");
Condition condition4 = new Condition("d", "D");
ConditionGroup cg... |
public static <K, V> AsMultimap<K, V> asMultimap() {
return new AsMultimap<>(false);
} | @Test
@Category({ValidatesRunner.class})
public void testWindowedMultimapSideInputWithNonDeterministicKeyCoder() {
final PCollectionView<Map<String, Iterable<Integer>>> view =
pipeline
.apply(
"CreateSideInput",
Create.timestamped(
Tim... |
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
} | @Test
public void cascadedTransformation() throws ScanException {
propertyContainer0.putProperty("x", "${a}");
propertyContainer0.putProperty("a", "b");
propertyContainer0.putProperty("b", "c");
String result = transform("${${x}}");
Assertions.assertEquals("c", result);
} |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void shouldRoundTripWithParseTimestamp() {
final String pattern = "yyyy-MM-dd HH:mm:ss.SSS'Freya'";
final ParseTimestamp parseTimestamp = new ParseTimestamp();
IntStream.range(-10_000, 20_000)
.parallel()
.forEach(idx -> {
final Timestamp timestamp = new Timestamp(15... |
public void delete(DbSession dbSession, GroupDto group) {
checkGroupIsNotDefault(dbSession, group);
checkNotTryingToDeleteLastAdminGroup(dbSession, group);
removeGroupPermissions(dbSession, group);
removeGroupFromPermissionTemplates(dbSession, group);
removeGroupMembers(dbSession, group);
remov... | @Test
public void delete_whenDefaultGroup_throwAndDontDeleteGroup() {
GroupDto groupDto = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS))
.thenReturn(Optional.of(groupDto));
assertThatThrownBy(() -> groupService.delete(dbSession, groupDto))
.isInstanceO... |
public void unregisterEventDefinition(String id) {
removeGrantsForTarget(grnRegistry.newGRN(GRNTypes.EVENT_DEFINITION, id));
} | @Test
void unregisterEventDefinition() {
entityOwnershipService.unregisterEventDefinition("1234");
assertGrantRemoval(GRNTypes.EVENT_DEFINITION, "1234");
} |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testInValuesContainNull() {
String col = "strCol";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue nullValue = new LiteralValue(null, DataTypes.StringType);
LiteralValue value1 = new LiteralValue("value1", DataTypes.StringType);
LiteralValue value2 = new L... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldFillInMissingColumnsWithNulls() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(K0, COL0),
ImmutableList.of(
new StringLiteral("str"),
new StringLiteral("str"))
);
// When:
executor... |
@Override
public Optional<ConstraintMetaData> revise(final String tableName, final ConstraintMetaData originalMetaData, final ShardingRule rule) {
for (DataNode each : shardingTable.getActualDataNodes()) {
String referencedTableName = originalMetaData.getReferencedTableName();
Option... | @Test
void assertReviseWhenTableMatches() {
ConstraintMetaData originalMetaData = new ConstraintMetaData("test_table_name_1", "referenced_table_name");
Optional<ConstraintMetaData> actual = reviser.revise("table_name_1", originalMetaData, shardingRule);
assertTrue(actual.isPresent());
... |
public Map<String, List<QueryHeaderRewriteRule>> getQueryParamRewriteRules() {
return queryParamRewriteRules;
} | @Test
public void testQueryParamRewriteRules() {
Assert.assertNotNull(routerConfig.getQueryParamRewriteRules());
Assert.assertEquals(routerConfig.getQueryParamRewriteRules().size(), 4);
} |
public static void validateMaterializedViewPartitionColumns(
SemiTransactionalHiveMetastore metastore,
MetastoreContext metastoreContext,
Table viewTable,
MaterializedViewDefinition viewDefinition)
{
SchemaTableName viewName = new SchemaTableName(viewTable.get... | @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Materialized view schema.table must have at least one partition column that exists in table as well")
public void testValidateMaterializedViewPartitionColumnsNoneCommonPartition()
{
TestingSemiTransactionalHiveMetastore... |
@Override
public void deregister(ServiceCombRegistration registration) {
RegisterCenterService registerService = getRegisterCenterService();
if (registerService == null) {
LOGGER.severe("registerCenterService is null, fail to unRegister!");
return;
}
registerS... | @Test
public void deregister() {
registry.deregister(Mockito.mock(ServiceCombRegistration.class));
Mockito.verify(spyService, Mockito.times(1)).unRegister();
} |
public Map<String, Object> getAllLocalProperties() {
Map<String, Object> result = new LinkedHashMap<>(
connectionPropertySynonyms.getLocalProperties().size() + poolPropertySynonyms.getLocalProperties().size() + customProperties.getProperties().size(), 1F);
result.putAll(connectionPropert... | @SuppressWarnings("unchecked")
@Test
void assertGetDataSourceConfigurationWithConnectionInitSqls() {
MockedDataSource actualDataSource = new MockedDataSource();
actualDataSource.setDriverClassName(MockedDataSource.class.getName());
actualDataSource.setUrl("jdbc:mock://127.0.0.1/foo_ds");... |
public int calculateBufferSize(long totalBufferSizeInBytes, int totalBuffers) {
checkArgument(totalBufferSizeInBytes >= 0, "Size of buffer should be non negative");
checkArgument(totalBuffers > 0, "Number of buffers should be positive");
// Since the result value is always limited by max buffer... | @Test
void testSizeLessThanMinSize() {
BufferSizeEMA calculator = new BufferSizeEMA(200, 10, 3);
// Impossible to less than min.
assertThat(calculator.calculateBufferSize(0, 1)).isEqualTo(100);
assertThat(calculator.calculateBufferSize(0, 1)).isEqualTo(50);
assertThat(calcul... |
@Override
public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix, final PS prefixKeySerializer) {
Objects.requireNonNull(prefix);
Objects.requireNonNull(prefixKeySerializer);
final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = n... | @Test
public void shouldThrowInvalidStoreExceptionOnPrefixScanDuringRebalance() {
assertThrows(InvalidStateStoreException.class, () -> rebalancing().prefixScan("anything", new StringSerializer()));
} |
static <T> T copy(T object, DataComplexTable alreadyCopied) throws CloneNotSupportedException
{
if (object == null)
{
return null;
}
else if (isComplex(object))
{
DataComplex src = (DataComplex) object;
@SuppressWarnings("unchecked")
T found = (T) alreadyCopied.get(src);
... | @Test
public void mapClonesHaveDifferentHashValues() throws CloneNotSupportedException
{
DataMap originalMap = new DataMap();
originalMap.put("key", "value");
DataMap copyMap = originalMap.copy();
// The objects should be "equal," but not identical.
assertTrue(copyMap.equals(originalMap));
... |
void precheckMaxResultLimitOnLocalPartitions(String mapName) {
// check if feature is enabled
if (!isPreCheckEnabled) {
return;
}
// limit number of local partitions to check to keep runtime constant
PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa... | @Test(expected = QueryResultSizeExceededException.class)
public void testLocalPreCheckEnabledWitDifferentPartitionSizesOverLimit() {
int[] partitionSizes = {0, 2200, Integer.MIN_VALUE};
populatePartitions(partitionSizes);
initMocksWithConfiguration(200000, 2);
limiter.precheckMaxRes... |
public static KiePMMLTransformationDictionary getKiePMMLTransformationDictionary(final TransformationDictionary toConvert,
final List<Field<?>> fields) {
final List<KiePMMLDerivedField> kiePMMLDerivedFields = getKiePMMLDerivedF... | @Test
void getKiePMMLTransformationDictionary() {
final TransformationDictionary toConvert = getRandomTransformationDictionary();
KiePMMLTransformationDictionary retrieved =
KiePMMLTransformationDictionaryInstanceFactory.getKiePMMLTransformationDictionary(toConvert,
... |
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder)
throws CoderException {
if (value == null) {
return noopMutationDetector();
} else {
return new CodedValueMutationDetector<>(value, coder);
}
} | @Test
public void testEquivalentListOfArrays() throws Exception {
List<byte[]> value = Arrays.asList(new byte[] {0x1}, new byte[] {0x2, 0x3}, new byte[] {0x4});
MutationDetector detector =
MutationDetectors.forValueWithCoder(value, ListCoder.of(ByteArrayCoder.of()));
value.set(0, new byte[] {0x1})... |
@Override
public AppResponse process(Flow flow, ConfirmRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
var authAppSession = appSessionService.getSession(request.getAuthSessionId());
if (!isAppSessionAuthenticated(authAppSession) || !request.getUserAppId().eq... | @Test
public void processReturnsNokResponseIfNotExisting() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
//given
when(appAuthenticatorService.exists(mockedAppAuthenticator)).thenReturn(false);
when(appSessionService.getSession(confirmRequest.getAuthSessionId())).the... |
@Override
public int hashCode() {
return key.hashCode();
} | @Test
public void test_equals_and_hashcode() {
NewAdHocRule adHocRule1 = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build());
NewAdHocRule adHocRule2 = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no... |
public Optional<Path> getMountPoint() {
return Optional.ofNullable(mMountPoint);
} | @Test
public void testGetMountPoint() {
mJCommander.parse("-m", "/tmp/fuse-mp");
assertEquals(Optional.of(Paths.get("/tmp/fuse-mp")), mOptions.getMountPoint());
} |
public Set<ContentPack> loadAllLatest() {
final Set<ContentPack> allContentPacks = loadAll();
final ImmutableMultimap.Builder<ModelId, ContentPack> byIdBuilder = ImmutableMultimap.builder();
for (ContentPack contentPack : allContentPacks) {
byIdBuilder.put(contentPack.id(), contentPa... | @Test
@MongoDBFixtures("ContentPackPersistenceServiceTest.json")
public void loadAllLatest() {
final Set<ContentPack> contentPacks = contentPackPersistenceService.loadAllLatest();
assertThat(contentPacks)
.hasSize(3)
.anyMatch(contentPack -> contentPack.id().equa... |
static TokenizerConfig loadTokenizer(Path tokenizerPath) throws IOException {
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
JsonNode rootNode = mapper.readTree(tokenizerPath.toFile());
// The tokenizer file is a JSON object with the following schema
/*
* {
... | @Test
public void testTokenizerLoading() throws URISyntaxException, IOException {
Path vocabPath = Paths.get(BERTFeatureExtractorTest.class.getResource("bert-base-cased-vocab.txt").toURI());
Path tokenizerPath = Paths.get(BERTFeatureExtractorTest.class.getResource("bert-base-cased-tokenizer.json").t... |
@Bean("GlobalTempFolder")
public TempFolder provide(ScannerProperties scannerProps, SonarUserHome userHome) {
var workingPathName = StringUtils.defaultIfBlank(scannerProps.property(CoreProperties.GLOBAL_WORKING_DIRECTORY), CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE);
var workingPath = Paths.get(wor... | @Test
void cleanUpOld(@TempDir Path workingDir) throws IOException {
long creationTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(100);
for (int i = 0; i < 3; i++) {
Path tmp = workingDir.resolve(".sonartmp_" + i);
Files.createDirectories(tmp);
setFileCreationDate(tmp, creationTi... |
public static ZoneTime of(LocalTime localTime, ZoneId zoneId, boolean hasSeconds) {
return new ZoneTime(localTime, zoneId, hasSeconds);
} | @Test
void of() {
ZoneTime retrieved = ZoneTime.of(localTime, zoneId, true);
assertNotNull(retrieved);
assertEquals(offsetTime, retrieved.getOffsetTime());
assertEquals(zoneId, retrieved.getZoneId());
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testSuccessfulMatch() {
StreamRule rule = getSampleRule();
Message msg = getSampleMessage();
msg.addField("something", "foo");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
@Override
public <R extends MessageResponse<?>> R chat(Prompt<R> prompt, ChatOptions options) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + getConfig().getApiKey());
Consumer<Map<String, Str... | @Test(expected = LlmException.class)
public void testChat() {
OpenAiLlmConfig config = new OpenAiLlmConfig();
config.setApiKey("sk-rts5NF6n*******");
Llm llm = new OpenAiLlm(config);
String response = llm.chat("请问你叫什么名字");
System.out.println(response);
} |
public CreateTableCommand createTableCommand(
final KsqlStructuredDataOutputNode outputNode,
final Optional<RefinementInfo> emitStrategy
) {
Optional<WindowInfo> windowInfo =
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo();
if (windowInfo.isPresent() && emitStrategy.isPresent()) ... | @Test
public void shouldBuildTimestampColumnForTable() {
// Given:
givenProperty(
CommonCreateConfigs.TIMESTAMP_NAME_PROPERTY,
new StringLiteral(quote(ELEMENT2.getName().text()))
);
final CreateTable statement =
new CreateTable(SOME_NAME, TABLE_ELEMENTS,
false, true... |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 1.1 校验优惠劵
if (param.getCouponId() == null) {
return;
}
CouponRespDTO coupon = couponApi.validateCoupon(new CouponValidReqDTO()
.setId(param.getCouponId()... | @Test
public void testCalculate() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(233L).setCouponId(1024L)
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2).setSelected(true), /... |
@Override
public Workspace duplicateWorkspace(Workspace workspace) {
synchronized (this) {
DuplicateTask duplicateTask = new DuplicateTask(workspace);
Future<WorkspaceImpl> res = longTaskExecutor.execute(duplicateTask, () -> {
WorkspaceImpl newWorkspace = duplicateTas... | @Test
public void testDuplicateWorkspace() {
MockServices.setServices(MockController.class);
ProjectControllerImpl pc = new ProjectControllerImpl();
pc.addWorkspaceListener(workspaceListener);
pc.newProject();
Workspace duplicate = pc.duplicateWorkspace(pc.getCurrentWorkspac... |
public long getNumSegmentsProcessed() {
return _brokerResponse.has(NUM_SEGMENTS_PROCESSED) ? _brokerResponse.get(NUM_SEGMENTS_PROCESSED).asLong() : -1L;
} | @Test
public void testGetNumSegmentsProcessed() {
// Run the test
final long result = _executionStatsUnderTest.getNumSegmentsProcessed();
// Verify the results
assertEquals(10L, result);
} |
@Override
public String getPluginIDOfFirstPluginInBundle(String bundleSymbolicName) {
return pluginRegistry.getBundleDescriptor(bundleSymbolicName).descriptors().get(0).id();
} | @Test
void shouldGetIDOfFirstPluginInBundle() {
final GoPluginDescriptor pluginDescriptor1 = GoPluginDescriptor.builder().id("plugin.1").build();
final GoPluginDescriptor pluginDescriptor2 = GoPluginDescriptor.builder().id("plugin.2").build();
final GoPluginBundleDescriptor bundleDescriptor ... |
@Override
public void start() {
DatabaseVersion.Status status = version.getStatus();
if (status == DatabaseVersion.Status.REQUIRES_DOWNGRADE) {
throw MessageException.of("Database was upgraded to a more recent version of SonarQube. "
+ "A backup must probably be restored or the DB settings are i... | @Test
public void log_warning_if_requires_upgrade() {
DatabaseVersion version = mock(DatabaseVersion.class);
when(version.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_UPGRADE);
when(version.getVersion()).thenReturn(Optional.of(DatabaseVersion.MIN_UPGRADE_VERSION));
new DatabaseServerCompati... |
@Override
public Map<String, ConfigChangeItem> doParse(String oldContent, String newContent, String type) throws IOException {
Properties oldProps = new Properties();
Properties newProps = new Properties();
if (StringUtils.isNotBlank(oldContent)) {
oldProps.load(new Stri... | @Test
void testRemoveKey() throws IOException {
Map<String, ConfigChangeItem> map = parser.doParse("app.name = nacos", "", type);
assertEquals("nacos", map.get("app.name").getOldValue());
assertNull(map.get("app.name").getNewValue());
} |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP);
if (args.isEmpty()) {
terminal.println(restClient.getServerAddress());
return;
} else {
final String serverAddress = args.get(0);
restClient.setS... | @Test(expected = KsqlRestClientException.class)
public void shouldThrowIfRestClientThrowsOnSet() {
// Given:
doThrow(new KsqlRestClientException("Boom")).when(restClient).setServerAddress("localhost:8088");
// When:
command.execute(ImmutableList.of("localhost:8088"), terminal);
} |
public static JibContainerBuilder create(
String baseImageReference,
Set<Platform> platforms,
CommonCliOptions commonCliOptions,
ConsoleLogger logger)
throws InvalidImageReferenceException, FileNotFoundException {
if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) {
r... | @Test
public void testCreate_dockerBaseImage()
throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException {
JibContainerBuilder containerBuilder =
ContainerBuilders.create(
"docker://docker-image-ref", Collections.emptySet(), mockCommonCliOptions, mockLogger);
... |
@Override
public boolean isScanAllowedUsingPermissionsFromDevopsPlatform() {
checkState(authAppInstallationToken != null, "An auth app token is required in case repository permissions checking is necessary.");
String[] orgaAndRepoTokenified = devOpsProjectCreationContext.fullName().split("/");
String org... | @Test
void isScanAllowedUsingPermissionsFromDevopsPlatform_whenUserIsNotAGitHubUser_returnsFalse() {
assertThat(githubProjectCreator.isScanAllowedUsingPermissionsFromDevopsPlatform()).isFalse();
} |
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) {
return mRxSharedPreferences.getBoolean(
mResources.getString(prefKey), mResources.getBoolean(defaultValue));
} | @Test
public void testBooleanHappyPath() {
RxSharedPrefs impl = new RxSharedPrefs(getApplicationContext(), this::testRestoreFunction);
final Preference<Boolean> preference =
impl.getBoolean(R.string.pref_test_key, R.bool.pref_test_value);
Assert.assertTrue(preference.get());
final AtomicRefe... |
public PaginationContext createPaginationContext(final LimitSegment limitSegment, final List<Object> params) {
return new PaginationContext(limitSegment.getOffset().orElse(null), limitSegment.getRowCount().orElse(null), params);
} | @Test
void assertPaginationContextCreatedProperlyWhenPaginationValueSegmentIsNumberLiteralPaginationValueSegment() {
LimitSegment limitSegment = new LimitSegment(0, 10, new NumberLiteralLimitValueSegment(0, 10, 1L), new NumberLiteralLimitValueSegment(10, 20, 2L));
PaginationContext paginationContext... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesBigIntegerOverridingLong() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "integer");
// isUseBigIntegers should override isUs... |
@Override
public String getSource() {
return source;
} | @Test
public void testGetSource() {
assertEquals("source", batchEventData.getSource());
assertEquals("source", batchEventDataSameAttribute.getSource());
assertEquals("otherSource", batchEventDataOtherSource.getSource());
assertEquals("source", batchEventDataOtherPartitionId.getSource... |
@Override
public List<Change> computeDiff(final List<T> source, final List<T> target, DiffAlgorithmListener progress) {
Objects.requireNonNull(source, "source list must not be null");
Objects.requireNonNull(target, "target list must not be null");
if (progress != null) {
progres... | @Test
public void testDiffMyersExample1ForwardWithListener() {
List<String> original = Arrays.asList("A", "B", "C", "A", "B", "B", "A");
List<String> revised = Arrays.asList("C", "B", "A", "B", "A", "C");
List<String> logdata = new ArrayList<>();
final Patch<String> patch = ... |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void format_set_html_message_with_issues_grouped_by_status_closed_or_any_other_when_change_from_analysis() {
Project project = newProject("foo");
Rule rule = newRandomNotAHotspotRule("bar");
Set<ChangedIssue> changedIssues = Arrays.stream(ISSUE_STATUSES)
.map(status -> newChangedIssue(s... |
static long deleteObsoleteCounterFiles(String application) {
final Calendar nowMinusOneYearAndADay = Calendar.getInstance();
nowMinusOneYearAndADay.add(Calendar.DAY_OF_YEAR, -getObsoleteStatsDays());
nowMinusOneYearAndADay.add(Calendar.DAY_OF_YEAR, -1);
// filtre pour ne garder que les fichiers d'extension .ser... | @Test
public void testDeleteObsoleteCounterFiles() throws IOException {
final Counter counter = new Counter("http", null);
counter.setApplication("test counter");
final File storageDir = Parameters.getStorageDirectory(counter.getApplication());
final File obsoleteFile = new File(storageDir, "obsolete.ser.gz");... |
@Override
public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey,
SubscriberPermissionsOnProject subscriberPermissionsOnProject) {
verifyProjectKey(projectKey);
try (DbSession dbSession = dbClient.openSession(false)) {
Set<EmailSubscriberDto> emailSubscribe... | @Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_logins_is_null() {
String dispatcherKey = randomAlphabetic(12);
String projectKey = randomAlphabetic(6);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER)... |
static void dissectString(
final DriverEventCode code, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
final int encodedLength = dissectLogHeader(CONTEXT, code, buffer, offset, builder);
builder.append(": ").append(buffer.getStringAscii(offset + encodedLeng... | @Test
void dissectString()
{
internalEncodeLogHeader(buffer, 0, 1, 1, () -> 1_100_000_000L);
buffer.putStringAscii(LOG_HEADER_LENGTH, "Hello, World!");
DriverEventDissector.dissectString(CMD_IN_CLIENT_CLOSE, buffer, 0, builder);
assertEquals("[1.100000000] " + CONTEXT + ": " + ... |
@VisibleForTesting
static Optional<String> performUpdateCheck(
Path configDir,
String currentVersion,
String versionUrl,
String toolName,
Consumer<LogEvent> log) {
Path lastUpdateCheck = configDir.resolve(LAST_UPDATE_CHECK_FILENAME);
try {
// Check time of last update chec... | @Test
public void testPerformUpdateCheck_lastUpdateCheckTooSoon() throws IOException {
FileTime modifiedTime = FileTime.from(Instant.now().minusSeconds(12));
setupLastUpdateCheck();
Files.write(
configDir.resolve("lastUpdateCheck"),
modifiedTime.toString().getBytes(StandardCharsets.UTF_8))... |
static boolean isTableUsingInstancePoolAndReplicaGroup(@Nonnull TableConfig tableConfig) {
boolean status = true;
Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = tableConfig.getInstanceAssignmentConfigMap();
if (instanceAssignmentConfigMap != null) {
for (InstanceAssignmentConfig i... | @Test
public void testValidIGnRGRealtimeTable() {
InstanceAssignmentConfig config =
new InstanceAssignmentConfig(new InstanceTagPoolConfig("DefaultTenant", true, 0, null), null,
new InstanceReplicaGroupPartitionConfig(true, 0, 0, 0, 0, 0, false, null), null, false);
TableConfig tableConfi... |
public ScopedSpan startScopedSpan(String name) {
return startScopedSpanWithParent(name, currentTraceContext.get());
} | @Test void startScopedSpan_isInScope() {
assertRealRoot(tracer.startScopedSpan("foo"));
assertRealRoot(tracer.startScopedSpan("foo", deferDecision(), false));
} |
public Certificate add(CvCertificate cert) {
final Certificate db = Certificate.from(cert);
if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) {
throw new ClientException(String.format(
"Certificate of subject %s and issuer %s already exists", db.ge... | @Test
public void shouldCheckIfPublicKeyExistAndIsEqualIfWhenAddingAT() throws Exception {
final HsmClient.KeyInfo keyInfo = new HsmClient.KeyInfo();
keyInfo.setPublicKey(Hex.decode("04"
+ "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"
+ "S... |
public static void checkParam(String dataId, String group, String content) throws NacosException {
checkKeyParam(dataId, group);
if (StringUtils.isBlank(content)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, CONTENT_INVALID_MSG);
}
} | @Test
void testCheckParam2Fail() throws NacosException {
Throwable exception = assertThrows(NacosException.class, () -> {
String dataId = "b";
String group = "c";
String datumId = "d";
String content = "";
ParamUtils.checkParam(dataId,... |
@Override
public boolean accept(File pathname) {
final boolean accepted = super.accept(pathname);
return accepted && !isExcludedJar(pathname);
} | @Test
public void testAcceptSupportedExtensions() throws Exception {
JarAnalyzer instance = new JarAnalyzer();
instance.initialize(getSettings());
instance.prepare(null);
instance.setEnabled(true);
String[] files = {"test.jar", "test.war"};
for (String name : files) {... |
@SuppressWarnings("unchecked")
public List<String> getList(String key) {
return (List<String>) get(key);
} | @Test
public void testEmptyList() {
AbstractConfig conf;
ConfigDef configDef = new ConfigDef().define("a", Type.LIST, "", new ConfigDef.NonNullValidator(), Importance.HIGH, "doc");
conf = new AbstractConfig(configDef, Collections.emptyMap());
assertEquals(Collections.emptyList(), co... |
@Description("unescape a URL-encoded string")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice urlDecode(@SqlType("varchar(x)") Slice value)
{
try {
return slice(URLDecoder.decode(value.toStringUtf8(), UTF_8.name()));
}
catch (Uns... | @Test
public void testUrlDecode()
{
String[][] inputOutputPairs = {
{"http%3A%2F%2Ftest", "http://test"},
{"http%3A%2F%2Ftest%3Fa%3Db%26c%3Dd", "http://test?a=b&c=d"},
{"http%3A%2F%2F%E3%83%86%E3%82%B9%E3%83%88", "http://\u30c6\u30b9\u30c8"},
... |
@PostMapping
@Operation(
security = @SecurityRequirement(name = "keycloak"),
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
content = @Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
sche... | @Test
void createProduct_RequestIsInvalid_ReturnsBadRequest() {
// given
var payload = new NewProductPayload(" ", null);
var bindingResult = new MapBindingResult(Map.of(), "payload");
bindingResult.addError(new FieldError("payload", "title", "error"));
var uriComponentsBuil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.