focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public char readChar()
throws EOFException {
return (char) readUnsignedShort();
} | @Test
void testReadChar()
throws EOFException {
char read = _dataBufferPinotInputStream.readChar();
assertEquals(read, _byteBuffer.getChar(0));
assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), Character.BYTES);
} |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatCreateOrReplaceTableStatement() {
// Given:
final CreateSourceProperties props = CreateSourceProperties.from(
new ImmutableMap.Builder<String, Literal>()
.putAll(SOME_WITH_PROPS.copyOfOriginalLiterals())
.build()
);
final CreateTable create... |
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
} | @Test
public void testCallbacksFromMultipleRequestsAreNotifiedOnPreDraw() {
SizeReadyCallback firstCb = mock(SizeReadyCallback.class);
SizeReadyCallback secondCb = mock(SizeReadyCallback.class);
target.getSize(firstCb);
target.getSize(secondCb);
int width = 68;
int height = 875;
LayoutPar... |
static void populateCorrectSegmentId(final Segment segment, final String modelName, final int i) {
String toSet;
if (segment.getId() == null || segment.getId().isEmpty()) {
toSet = String.format(SEGMENTID_TEMPLATE,
modelName,
... | @Test
void populateCorrectSegmentId() throws Exception {
final InputStream inputStream = getFileInputStream(NO_MODELNAME_NO_SEGMENTID_SAMPLE_NAME);
final PMML pmml = org.jpmml.model.PMMLUtil.unmarshal(inputStream);
final Model retrieved = pmml.getModels().get(0);
assertThat(retrieved... |
public String failureMessage(
int epoch,
OptionalLong deltaUs,
boolean isActiveController,
long lastCommittedOffset
) {
StringBuilder bld = new StringBuilder();
if (deltaUs.isPresent()) {
bld.append("event failed with ");
} else {
bld.a... | @Test
public void testRejectedExecutionExceptionFailureMessage() {
assertEquals("event unable to start processing because of RejectedExecutionException (treated " +
"as TimeoutException).",
REJECTED_EXECUTION.failureMessage(123, OptionalLong.empty(), true, 456L));
} |
@Override
public CompletableFuture<RemotingCommand> invoke(String addr, RemotingCommand request,
long timeoutMillis) {
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
try {
final ChannelFuture channelFuture = this.getAndCreateChannelAsync(addr);
... | @Test
public void testRemotingTimeoutException() throws Exception {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, null);
RemotingCommand response = RemotingCommand.createResponseCommand(null);
response.setCode(ResponseCode.SUCCESS);
Complet... |
public static ProducingResult createProducingResult(
ResolvedSchema inputSchema, @Nullable Schema declaredSchema) {
// no schema has been declared by the user,
// the schema will be entirely derived from the input
if (declaredSchema == null) {
// go through data type to ... | @Test
void testOutputToDeclaredSchema() {
final ResolvedSchema tableSchema =
ResolvedSchema.of(
Column.physical("id", BIGINT()),
Column.physical("rowtime", TIMESTAMP_LTZ(3)),
Column.physical("name", STRING()));
... |
public int[] difference(SparseVector other) {
List<Integer> diffIndicesList = new ArrayList<>();
if (other.numActiveElements() == 0) {
return Arrays.copyOf(indices,indices.length);
} else if (indices.length == 0) {
return new int[0];
} else {
Iterator... | @Test
public void difference() {
SparseVector a = generateVectorA();
SparseVector b = generateVectorB();
SparseVector c = generateVectorC();
assertArrayEquals(a.difference(b), new int[0]);
assertArrayEquals(a.difference(c), new int[]{0,4,8});
assertArrayEquals(c.diff... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDecodeStructMultipleDynamicStaticArray2() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000... |
@Override
public boolean isDone() {
return state.isDoneState();
} | @Test
public void testIsDone() throws Exception {
assertThat(promise.isDone()).isEqualTo(false);
promise.set("Done");
assertThat(promise.isDone()).isEqualTo(true);
} |
@Override
@Nonnull
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks)
throws ExecutionException {
throwRejectedExecutionExceptionIfShutdown();
Exception exception = null;
for (Callable<T> task : tasks) {
try {
return task.ca... | @Test
void testInvokeAnyWithTimeout() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testTaskSubmissionBeforeShutdown(
testInstance ->
testInstance.invokeAny(
callableCollectionFromFuture(future), 1, TimeU... |
public void createBucket(String projectId, Bucket bucket) throws IOException {
createBucket(projectId, bucket, createBackOff(), Sleeper.DEFAULT);
} | @Test
public void testCreateBucket() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class);
Storage mockStorage = Mockito.mock(Storage.class);
gcsUt... |
@Override
public ValidationResult validate(Object value) {
if (value == null || value instanceof String) {
return new ValidationResult.ValidationPassed();
} else {
return new ValidationResult.ValidationFailed("Value \"" + value + "\" is not a valid string!");
}
} | @Test
public void validateEmptyString() {
assertThat(validator.validate("")).isInstanceOf(ValidationResult.ValidationPassed.class);
} |
public void clear() {
checkState(
!isClosed,
"Bag user state is no longer usable because it is closed for %s",
request.getStateKey());
isCleared = true;
newValues = new ArrayList<>();
} | @Test
public void testClear() throws Exception {
FakeBeamFnStateClient fakeClient =
new FakeBeamFnStateClient(
StringUtf8Coder.of(), ImmutableMap.of(key("A"), asList("A1", "A2", "A3")));
BagUserState<String> userState =
new BagUserState<>(
Caches.noop(), fakeClient, "in... |
@Override
public final Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
ShardingSpherePreconditions.checkNotContains(INVALID_MEMORY_TYPES, type, () -> new SQLFeatureNotSupportedException(String.format("Get value from `%s`", type.getName())));
Object result = currentR... | @Test
void assertGetValueForInputStream() {
assertThrows(SQLFeatureNotSupportedException.class, () -> memoryMergedResult.getValue(1, InputStream.class));
} |
public JcrProducer(JcrEndpoint jcrEndpoint) {
super(jcrEndpoint);
} | @Test
public void testJcrProducer() throws Exception {
Exchange exchange = createExchangeWithBody("<hello>world!</hello>");
exchange.getIn().setHeader(JcrConstants.JCR_NODE_NAME, "node");
exchange.getIn().setHeader("my.contents.property", exchange.getIn().getBody());
Exchange out = t... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testInfoXML() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("info").accept("application/xml").get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8,
... |
@Override
public List<CodegenColumnDO> getCodegenColumnListByTableId(Long tableId) {
return codegenColumnMapper.selectListByTableId(tableId);
} | @Test
public void testGetCodegenColumnListByTableId() {
// mock 数据
CodegenColumnDO column01 = randomPojo(CodegenColumnDO.class);
codegenColumnMapper.insert(column01);
CodegenColumnDO column02 = randomPojo(CodegenColumnDO.class);
codegenColumnMapper.insert(column02);
/... |
public String[] getRemainingArgs() {
return (commandLine == null) ? new String[]{} : commandLine.getArgs();
} | @Test
public void testNullArgs() throws IOException {
GenericOptionsParser parser = new GenericOptionsParser(conf, null);
parser.getRemainingArgs();
} |
@JsonProperty("ksql")
public String getUnmaskedKsql() {
return ksql;
} | @Test
public void shouldHandleNullStatement() {
assertThat(
new KsqlRequest(null, SOME_PROPS, SOME_REQUEST_PROPS, SOME_COMMAND_NUMBER).getUnmaskedKsql(),
is(""));
} |
public boolean isValid() throws IOException {
if (contractBinary.equals(BIN_NOT_PROVIDED)) {
throw new UnsupportedOperationException(
"Contract binary not present in contract wrapper, "
+ "please generate your wrapper using -abiFile=<file>");
}... | @Test
public void testIsValidDifferentCode() throws Exception {
prepareEthGetCode(TEST_CONTRACT_BINARY + "0");
Contract contract = deployContract(createTransactionReceipt());
assertFalse(contract.isValid());
} |
public int getBulkActivitiesFailedRetrieved(){
return numGetBulkActivitiesFailedRetrieved.value();
} | @Test
public void testGetBulkActivitiesRetrievedFailed() {
long totalBadBefore = metrics.getBulkActivitiesFailedRetrieved();
badSubCluster.getBulkActivitiesFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getBulkActivitiesFailedRetrieved());
} |
public boolean putIfDifferentValues(final K key,
final ValueAndTimestamp<V> newValue,
final byte[] oldSerializedValue) {
try {
return maybeMeasureLatency(
() -> {
final byte[] newSeria... | @Test
public void shouldPutIfOutOfOrder() {
setUp();
doNothing().when(inner).put(KEY_BYTES, VALUE_AND_TIMESTAMP_BYTES);
init();
metered.put(KEY, VALUE_AND_TIMESTAMP);
final ValueAndTimestampSerde<String> stringSerde = new ValueAndTimestampSerde<>(Serdes.String());
f... |
@Override
public void init(Properties config) throws ServletException {
try {
String principal = config.getProperty(PRINCIPAL);
if (principal == null || principal.trim().length() == 0) {
throw new ServletException("Principal not defined in configuration");
}
keytab = config.getProp... | @Test
public void testInit() throws Exception {
Assert.assertEquals(KerberosTestUtils.getKeytabFile(), handler.getKeytab());
Set<KerberosPrincipal> principals = handler.getPrincipals();
Principal expectedPrincipal =
new KerberosPrincipal(KerberosTestUtils.getServerPrincipal());
Assert.assertTr... |
@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 shouldParseDateTimeWithDayOfYear() {
// Given
final String format = "yyyy-DDD HH";
final String timestamp = String.format("1605-%d 10", FIFTH_OF_NOVEMBER.getDayOfYear());
// When
final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID);
// The... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void noRetryOnAbortedRequests() {
HttpGet request = new HttpGet("/");
request.cancel();
assertThat(retryStrategy.retryRequest(request, new IOException(), 1, null)).isFalse();
} |
@Override
public ServiceConfig<U> build() {
ServiceConfig<U> serviceConfig = new ServiceConfig<>();
super.build(serviceConfig);
serviceConfig.setInterface(interfaceName);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(ref);
serviceConfig.setPath(pat... | @Test
void build() {
MethodConfig method = new MethodConfig();
ProviderConfig provider = new ProviderConfig();
ServiceBuilder builder = new ServiceBuilder();
builder.path("path")
.addMethod(method)
.provider(provider)
.providerIds("pro... |
public static CodecFactory fromHadoopString(String hadoopCodecClass) {
CodecFactory o = null;
try {
String avroCodec = HADOOP_AVRO_NAME_MAP.get(hadoopCodecClass);
if (avroCodec != null) {
o = CodecFactory.fromString(avroCodec);
}
} catch (Exception e) {
throw new AvroRuntime... | @Test
void hadoopCodecFactoryGZip() {
CodecFactory hadoopSnappyCodec = HadoopCodecFactory.fromHadoopString("org.apache.hadoop.io.compress.GZipCodec");
CodecFactory avroSnappyCodec = CodecFactory.fromString("deflate");
assertEquals(hadoopSnappyCodec.getClass(), avroSnappyCodec.getClass());
} |
public void onStreamRequest(StreamRequest req, final RequestContext requestContext, final Map<String, String> wireAttrs,
final NextFilter<StreamRequest, StreamResponse> nextFilter)
{
//Set accepted encoding for compressed response
String operation = (String) requestContext.getLoc... | @Test(dataProvider = "requestData")
public void testAcceptEncodingHeader(CompressionConfig requestCompressionConfig,
CompressionOption requestCompressionOverride,
boolean headerShouldBePresent,
String ... |
@Udf(description = "Returns the inverse (arc) tangent of y / x")
public Double atan2(
@UdfParameter(
value = "y",
description = "The ordinate (y) coordinate."
) final Integer y,
@UdfParameter(
value = "x",
descriptio... | @Test
public void shouldHandleNegativeYZeroX() {
assertThat(udf.atan2(-1.1, 0.0), closeTo(-1.5707963267948966, 0.000000000000001));
assertThat(udf.atan2(-6.0, 0.0), closeTo(-1.5707963267948966, 0.000000000000001));
assertThat(udf.atan2(-2, 0), closeTo(-1.5707963267948966, 0.000000000000001));
assertTh... |
@Override
public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) {
if(TransferStatus.UNKNOWN_LENGTH != local.getSize() && TransferStatus.UNKNOWN_LENGTH != remote.getSize()) {
if(local.getSize() == remote.getSize()) {
if(log.isDebu... | @Test
public void testCompare() {
ComparisonService s = new SizeComparisonService();
assertEquals(Comparison.remote, s.compare(Path.Type.file, new PathAttributes().withSize(0L), new PathAttributes().withSize(1L)));
assertEquals(Comparison.local, s.compare(Path.Type.file, new PathAttributes()... |
public static File generate(String content, int width, int height, File targetFile) {
String extName = FileUtil.extName(targetFile);
switch (extName) {
case QR_TYPE_SVG:
String svg = generateAsSvg(content, new QrConfig(width, height));
FileUtil.writeString(svg, targetFile, StandardCharsets.UTF_8);
br... | @Test
@Disabled
public void generateWithLogoTest() {
final String icon = FileUtil.isWindows() ? "d:/test/pic/face.jpg" : "~/Desktop/hutool/pic/face.jpg";
final String targetPath = FileUtil.isWindows() ? "d:/test/qrcodeWithLogo.jpg" : "~/Desktop/hutool/qrcodeWithLogo.jpg";
QrCodeUtil.generate(//
"https://hut... |
public ConfigCenterBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
} | @Test
void appendParameters() {
Map<String, String> source = new HashMap<>();
source.put("default.num", "one");
source.put("num", "ONE");
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.appendParameters(source);
Map<String, String> parameters... |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsSignatureNotRequiredV1() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V1);
Callback<Void> taskConfigCb = mock(Callback.class);
List<String> stages = expectRecordStages(taskConfigCb);
herder.putTaskConfigs(CONN1, TASK_CONFIGS... |
@Override
public Set<FSTFlags> getFlags() {
return _flags;
} | @Test
public void testVersion5()
throws IOException {
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data/abc.native.fst")) {
FST fst = FST.read(inputStream);
assertFalse(fst.getFlags().contains(FSTFlags.NUMBERS));
verifyContent(fst, _expected);
}
} |
@VisibleForTesting
public int getAppsFailedCreated() {
return numAppsFailedCreated.value();
} | @Test
public void testAppsFailedCreated() {
long totalBadbefore = metrics.getAppsFailedCreated();
badSubCluster.getNewApplication();
Assert.assertEquals(totalBadbefore + 1, metrics.getAppsFailedCreated());
} |
void handleTestStepFinished(TestStepFinished event) {
if (event.getTestStep() instanceof PickleStepTestStep && event.getResult().getStatus().is(Status.PASSED)) {
PickleStepTestStep testStep = (PickleStepTestStep) event.getTestStep();
addUsageEntry(event.getResult(), testStep);
}
... | @Test
void resultWithZeroDuration() {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
TestStep testStep = mockTestStep();
Result result = new Result(Status.PASSED, Duration.ZERO, null);
usageFormatter
.... |
@Override
public void export(RegisterTypeEnum registerType) {
if (this.exported) {
return;
}
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensu... | @Test
void testMethodConfigWithUnknownArgumentType() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
... |
@Deprecated
@Override
public KStream<K, V> through(final String topic) {
return through(topic, Produced.with(keySerde, valueSerde, null));
} | @Deprecated // specifically testing the deprecated variant
@Test
public void shouldNotAllowNullTopicOnThrough() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.through(null));
assertThat(exception.getMessage(), equalTo("... |
@Override
public void checkBeforeUpdate(final DropReadwriteSplittingRuleStatement sqlStatement) {
if (!sqlStatement.isIfExists()) {
checkToBeDroppedRuleNames(sqlStatement);
}
checkToBeDroppedInUsed(sqlStatement);
} | @Test
void assertCheckSQLStatementWithInUsed() throws RuleDefinitionException {
DataSourceMapperRuleAttribute dataSourceMapperRuleAttribute = mock(DataSourceMapperRuleAttribute.class);
when(database.getRuleMetaData().getAttributes(DataSourceMapperRuleAttribute.class)).thenReturn(Collections.singleto... |
@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_noLastUpdateCheck() throws IOException, InterruptedException {
Instant before = Instant.now();
Thread.sleep(100);
Optional<String> message =
UpdateChecker.performUpdateCheck(
configDir, "1.0.2", testWebServer.getEndpoint(), "tool-name", ignored ... |
public static Credentials loadJsonCredentials(String password, String content)
throws IOException, CipherException {
WalletFile walletFile = objectMapper.readValue(content, WalletFile.class);
return Credentials.create(Wallet.decrypt(password, walletFile));
} | @Test
public void testLoadJsonCredentials() throws Exception {
Credentials credentials =
WalletUtils.loadJsonCredentials(
PASSWORD,
convertStreamToString(
WalletUtilsTest.class.getResourceAsStream(
... |
public boolean isJoin() {
return sourceSchemas.size() > 1;
} | @Test
public void shouldNotBeJoinIfSingleSchema() {
// When:
sourceSchemas = new SourceSchemas(ImmutableMap.of(ALIAS_1, SCHEMA_1));
// Then:
assertThat(sourceSchemas.isJoin(), is(false));
} |
public static Long validateIssuedAt(String claimName, Long claimValue) throws ValidateException {
if (claimValue != null && claimValue < 0)
throw new ValidateException(String.format("%s value must be null or non-negative; value given was \"%s\"", claimName, claimValue));
return claimValue;
... | @Test
public void testValidateIssuedAtAllowsNull() {
Long expected = null;
Long actual = ClaimValidationUtils.validateIssuedAt("iat", expected);
assertEquals(expected, actual);
} |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName;
B... | @Test
public void testAggregateMultiStatsWhenOnlySomeAvailable() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3", "part4");
ColumnStatisticsData data1 = new ColStatsBuilder<>(byte[].class).numNulls(1).avgColLen(20.0 / 3).maxColLen(13).build();
ColumnStatisticsData... |
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) {
return serviceAccount()
.compose(i -> certificatesSecret(clock))
.compose(i -> networkPolicy())
.compose(i -> deploym... | @Test
public void reconcileWithDisabledExporterWithoutNetworkPolicies(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
ServiceAccountOperator mockSaOps = supplier.serviceAccountOperations;
ArgumentCaptor<ServiceAccount> saCaptor = Argum... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> buckets = new AttributedList<Path>();
for(B2BucketResponse bucket : session.getClient().listBuckets()) {
... | @Test
@Ignore
public void testList() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final AttributedList<Path> list = new B2BucketListService(session, fileid).list(
new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path... |
public SimplePayload(String xmlPayload) {
XmlPullParser parser;
try {
parser = PacketParserUtils.getParserFor(xmlPayload);
}
catch (XmlPullParserException | IOException e) {
throw new AssertionError(e);
}
QName qname = parser.getQName();
p... | @Test
public void simplePayloadTest() {
String xmlPayload = "<element xmlns='https://example.org'><foo>Test</foo><bar/></element>";
SimplePayload simplePayload = new SimplePayload(xmlPayload);
assertEquals("element", simplePayload.getElementName());
assertEquals("https://example.org... |
public static String getFieldToNullName( LogChannelInterface log, String field, boolean isUseExtId ) {
String fieldToNullName = field;
if ( isUseExtId ) {
// verify if the field has correct syntax
if ( !FIELD_NAME_WITH_EXTID_PATTERN.matcher( field ).matches() ) {
if ( log.isDebug() ) {
... | @Test
public void testIncorrectExternalKeySyntaxWarnIsLoggedInDebugMode() {
when( logMock.isDebug() ).thenReturn( true );
inputFieldName = "AccountId";
verify( logMock, never() ).logDebug( anyString() );
SalesforceUtils.getFieldToNullName( logMock, inputFieldName, true );
verify( logMock ).logDebu... |
public static PTransformMatcher emptyFlatten() {
return new PTransformMatcher() {
@Override
public boolean matches(AppliedPTransform<?, ?, ?> application) {
return (application.getTransform() instanceof Flatten.PCollections)
&& application.getInputs().isEmpty();
}
@Overr... | @Test
public void emptyFlattenWithNonFlatten() {
AppliedPTransform application =
AppliedPTransform
.<PCollection<Iterable<Integer>>, PCollection<Integer>, Flatten.Iterables<Integer>>of(
"EmptyFlatten",
Collections.emptyMap(),
Collections.singleto... |
static void encodeImageRemoval(
final UnsafeBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final String channel,
final int sessionId,
final int streamId,
final long id)
{
int encodedLength = encodeLogHeader(... | @Test
void encodeImageRemovalShouldTruncateChannelIfItExceedsMaxMessageLength()
{
final char[] data = new char[MAX_EVENT_LENGTH + 8];
fill(data, 'a');
final int offset = 0;
final int length = data.length + SIZE_OF_LONG + SIZE_OF_INT * 3;
final int captureLength = captureL... |
public boolean isEncrypted(String value) {
return value.indexOf('{') == 0 && value.indexOf('}') > 1;
} | @Test
public void isEncrypted() {
Encryption encryption = new Encryption(null);
assertThat(encryption.isEncrypted("{aes}ADASDASAD")).isTrue();
assertThat(encryption.isEncrypted("{b64}ADASDASAD")).isTrue();
assertThat(encryption.isEncrypted("{abc}ADASDASAD")).isTrue();
assertThat(encryption.isEncr... |
@Override
public void lock() {
try {
lockInterruptibly(-1, null);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
} | @Test
public void testConcurrency_MultiInstance() throws InterruptedException {
int iterations = 100;
final AtomicInteger lockedCounter = new AtomicInteger();
testMultiInstanceConcurrency(iterations, r -> {
Lock lock = r.getSpinLock("testConcurrency_MultiInstance2");
... |
public static synchronized void d(final String tag, String text) {
if (msLogger.supportsD()) {
msLogger.d(tag, text);
addLog(LVL_D, tag, text);
}
} | @Test
public void testD() throws Exception {
Logger.d("mTag", "Text with %d digits", 1);
Mockito.verify(mMockLog).d("mTag", "Text with 1 digits");
Logger.d("mTag", "Text with no digits");
Mockito.verify(mMockLog).d("mTag", "Text with no digits");
} |
@Override
public ObjectNode encode(RemoteMepEntry remoteMepEntry, CodecContext context) {
checkNotNull(remoteMepEntry, "Mep cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put("remoteMepId", remoteMepEntry.remoteMepId().toString())
.put("rem... | @Test
public void testEncodeIterableOfRemoteMepEntryCodecContext()
throws CfmConfigException {
RemoteMepEntry remoteMep2 = DefaultRemoteMepEntry
.builder(MepId.valueOf((short) 20), RemoteMepState.RMEP_IDLE)
.build();
ArrayList<RemoteMepEntry> remoteMeps =... |
public static ConsumingResult createConsumingResult(
DataTypeFactory dataTypeFactory,
TypeInformation<?> inputTypeInfo,
@Nullable Schema declaredSchema) {
final DataType inputDataType =
TypeInfoDataTypeConverter.toDataType(dataTypeFactory, inputTypeInfo);
... | @Test
void testInputFromRowWithPhysicalDeclaredSchema() {
final TypeInformation<?> inputTypeInfo =
Types.ROW(Types.INT, Types.LONG, Types.GENERIC(BigDecimal.class), Types.BOOLEAN);
final ConsumingResult result =
SchemaTranslator.createConsumingResult(
... |
public static List<?> convertToList(Schema schema, Object value) {
return convertToArray(ARRAY_SELECTOR_SCHEMA, value);
} | @Test
public void shouldConvertIntegralTypesToFloat() {
float thirdValue = Float.MAX_VALUE;
List<?> list = Values.convertToList(Schema.STRING_SCHEMA, "[1, 2, " + thirdValue + "]");
assertEquals(3, list.size());
assertEquals(1, ((Number) list.get(0)).intValue());
assertEquals(... |
public Set<String> getDeadlockedThreads() {
final long[] ids = threads.findDeadlockedThreads();
if (ids != null) {
final Set<String> deadlocks = new HashSet<>();
for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) {
final StringBuilder stackT... | @Test
public void returnsASetOfThreadsIfAnyAreDeadlocked() {
final ThreadInfo thread1 = mock(ThreadInfo.class);
when(thread1.getThreadName()).thenReturn("thread1");
when(thread1.getLockName()).thenReturn("lock2");
when(thread1.getLockOwnerName()).thenReturn("thread2");
when(t... |
@Override
public SortedRangeSet union(ValueSet other)
{
SortedRangeSet otherRangeSet = checkCompatibility(other);
return new Builder(type)
.addAll(this.getOrderedRanges())
.addAll(otherRangeSet.getOrderedRanges())
.build();
} | @Test
public void testUnion()
{
assertUnion(SortedRangeSet.none(BIGINT), SortedRangeSet.none(BIGINT), SortedRangeSet.none(BIGINT));
assertUnion(SortedRangeSet.all(BIGINT), SortedRangeSet.all(BIGINT), SortedRangeSet.all(BIGINT));
assertUnion(SortedRangeSet.none(BIGINT), SortedRangeSet.all... |
public CompletableFuture<GetResult> get(byte[] user, byte[] hmac) {
return getUser(user).thenApply(getItemResponse -> {
if (!getItemResponse.hasItem()) {
return GetResult.NOT_STORED;
}
Record record = Record.from(user, getItemResponse.item());
if (!MessageDigest.isEqual(hmac, record... | @Test
void testGet() {
byte[] wrongUser = TestRandomUtil.nextBytes(16);
byte[] wrongPassword = TestRandomUtil.nextBytes(16);
assertThat(subscriptions.create(user, password, created)).succeedsWithin(DEFAULT_TIMEOUT);
assertThat(subscriptions.get(user, password)).succeedsWithin(DEFAULT_TIMEOUT).satisfi... |
@VisibleForTesting
public void validateDictDataValueUnique(Long id, String dictType, String value) {
DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value);
if (dictData == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典数据
if (id == null) ... | @Test
public void testValidateDictDataValueUnique_valueDuplicateForCreate() {
// 准备参数
String dictType = randomString();
String value = randomString();
// mock 数据
dictDataMapper.insert(randomDictDataDO(o -> {
o.setDictType(dictType);
o.setValue(value);
... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, INIT_CONTEXT);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void redirect_with_context_when_failing_because_of_Exception() throws Exception {
when(request.getContextPath()).thenReturn("/sonarqube");
IdentityProvider identityProvider = new FailWithIllegalStateException("failing");
when(request.getRequestURI()).thenReturn("/sessions/init/" + identityPro... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 1, 1, HELP);
final String filePath = args.get(0);
final String content = loadScript(filePath);
requestExecutor.makeKsqlRequest(content);
} | @Test
public void shouldThrowIfNoArgSupplied() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> cmd.execute(ImmutableList.of(), terminal)
);
// Then:
assertThat(e.getMessage(), containsString(
"Too few parameters"));
} |
@Override
public InputFile newInputFile(String path) {
return S3InputFile.fromLocation(path, client(), s3FileIOProperties, metrics);
} | @Test
public void testReadMissingLocation() {
String location = "s3://bucket/path/to/data.parquet";
InputFile in = s3FileIO.newInputFile(location);
assertThatThrownBy(() -> in.newStream().read())
.isInstanceOf(NotFoundException.class)
.hasMessage("Location does not exist: " + location);
... |
protected AccessControlList toAcl(final Acl acl) {
if(Acl.EMPTY.equals(acl)) {
return null;
}
if(Acl.CANNED_PRIVATE.equals(acl)) {
return AccessControlList.REST_CANNED_PRIVATE;
}
if(Acl.CANNED_BUCKET_OWNER_FULLCONTROL.equals(acl)) {
return Acce... | @Test
public void testCannedLists() {
final S3AccessControlListFeature f = new S3AccessControlListFeature(session);
assertSame(Acl.CANNED_PRIVATE, f.toAcl(AccessControlList.REST_CANNED_PRIVATE));
assertSame(Acl.CANNED_PUBLIC_READ, f.toAcl(AccessControlList.REST_CANNED_PUBLIC_READ));
... |
Path downloadRemoteZip(Path targetPath) throws IOException, UserException {
LOG.info("download plugin zip from: " + source);
Path zip = Files.createTempFile(targetPath, ".plugin_", ".zip");
cleanPathList.add(zip);
// download zip
try (InputStream in = getInputStreamFromUrl(sour... | @Test
public void testDownloadAndValidateZipIOException() {
PluginZip util = new PluginZip("http://io-exception", null);
try {
Path zipPath = util.downloadRemoteZip(PluginTestUtil.getTestPath("target"));
} catch (Exception e) {
assertTrue(e instanceof IOException);
... |
@Override
public AlterConsumerGroupOffsetsResult alterConsumerGroupOffsets(
String groupId,
Map<TopicPartition, OffsetAndMetadata> offsets,
AlterConsumerGroupOffsetsOptions options
) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, Errors>> future =
Alte... | @Test
public void testAlterConsumerGroupOffsetsFindCoordinatorRetriableErrors() throws Exception {
// Retriable FindCoordinatorResponse errors should be retried
final TopicPartition tp1 = new TopicPartition("foo", 0);
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster... |
@Override
public int run() throws IOException {
Preconditions.checkArgument(sourceFiles != null && !sourceFiles.isEmpty(), "Missing file name");
// Ensure all source files have the columns specified first
Map<String, Schema> schemas = new HashMap<>();
for (String source : sourceFiles) {
Schema ... | @Test
public void testCatCommandWithSpecificColumns() throws IOException {
File file = parquetFile();
CatCommand command = new CatCommand(createLogger(), 0);
command.sourceFiles = Arrays.asList(file.getAbsolutePath());
command.columns = Arrays.asList(INT32_FIELD, INT64_FIELD);
command.setConf(new ... |
@VisibleForTesting
static void instantiateNonHeapMemoryMetrics(final MetricGroup metricGroup) {
instantiateMemoryUsageMetrics(
metricGroup, () -> ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage());
} | @Test
void testNonHeapMetricsCompleteness() {
final InterceptingOperatorMetricGroup nonHeapMetrics =
new InterceptingOperatorMetricGroup();
MetricUtils.instantiateNonHeapMemoryMetrics(nonHeapMetrics);
assertThat(nonHeapMetrics.get(MetricNames.MEMORY_USED)).isNotNull();
... |
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY).get();
if ((service == null || service.length() == 0) && (args == null || args.length == 0)) {
ret... | @Test
void testCountByServiceKey() throws Exception {
String methodName = "sayHello";
RpcStatus.removeStatus(url, methodName);
String[] args = new String[] {"g/demo:1.0.0", "sayHello", "1"};
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtoc... |
public static NameStep newBuilder() {
return new CharacterSteps();
} | @Test
void testBuildWarrior() {
final var character = CharacterStepBuilder.newBuilder()
.name("Cuauhtemoc")
.fighterClass("aztec")
.withWeapon("spear")
.withAbility("speed")
.withAbility("strength")
.noMoreAbilities()
.build();
assertEquals("Cuauhtemoc"... |
public void start(Callback<None> callback)
{
_managerStarted = true;
if (!_startupCallback.compareAndSet(null, callback))
{
throw new IllegalStateException("Already starting");
}
try
{
_zkConnection.start();
//Trying to start store here. If the connection is not ready, will r... | @Test (invocationCount = 1, timeOut = 5000)
public void testWarmup() throws Exception
{
ScheduledExecutorService warmupExecutorService = Executors.newSingleThreadScheduledExecutor();
boolean isDarkWarmupEnabled = true;
String warmupClusterName = "warmup" + _cluster;
String expectedWarmupUriNodePath ... |
@Override
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
if (context.validate()) {
try {
String accessKey = context.getAccessKey();
String secretKey = context.getSecretKey();
// STS 临时凭证鉴权的优先级高于 AK... | @Test
void testDoInjectWithGroup() throws Exception {
resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build();
LoginIdentityContext actual = new LoginIdentityContext();
namingResourceInjector.doInject(resource, ramContext, actual);
assertEquals(3... |
protected RemotingCommand request(ChannelHandlerContext ctx, RemotingCommand request,
ProxyContext context, long timeoutMillis) throws Exception {
String brokerName;
if (request.getCode() == RequestCode.SEND_MESSAGE_V2) {
if (request.getExtFields().get(BROKER_NAME_FIELD_FOR_SEND_MESS... | @Test
public void testRequestBrokerException() throws Exception {
ArgumentCaptor<RemotingCommand> captor = ArgumentCaptor.forClass(RemotingCommand.class);
String brokerName = "broker";
String remark = "exception";
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();... |
public static boolean containsUpperCase(final long word) {
return applyUpperCasePattern(word) != 0;
} | @Test
void containsUpperCaseInt() {
// given
final byte[] asciiTable = getExtendedAsciiTable();
shuffleArray(asciiTable, random);
// when
for (int idx = 0; idx < asciiTable.length; idx += Integer.BYTES) {
final int value = getInt(asciiTable, idx);
fin... |
@Override
public void run() {
boolean isNeedFlush = false;
boolean sqlShowEnabled = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps().getValue(ConfigurationPropertyKey.SQL_SHOW);
try {
if (sqlShowEnabled) {
fillLogMDC();... | @Test
void assertRunByCommandExecutor() throws SQLException, BackendConnectionException {
when(commandExecutor.execute()).thenReturn(Collections.singleton(databasePacket));
when(engine.getCommandExecuteEngine().getCommandPacket(payload, commandPacketType, connectionSession)).thenReturn(commandPacket... |
public static CreateSourceProperties from(final Map<String, Literal> literals) {
try {
return new CreateSourceProperties(literals, DurationParser::parse, false);
} catch (final ConfigException e) {
final String message = e.getMessage().replace(
"configuration",
"property"
)... | @Test
public void shouldThrowIfValueFormatAndFormatProvided() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> CreateSourceProperties.from(
ImmutableMap.<String, Literal>builder()
.putAll(MINIMUM_VALID_PROPS)
.put(VALUE_FORMAT_... |
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
if (response.status() == 404 || response.status() == 204)
if (JSONObject.class.isAssignableFrom((Class<?>) type))
return new JSONObject();
else if (JSONArray.class.isAssignableFrom((Class<?>) typ... | @Test
void checkedException() throws IOException {
Response.Body body = mock(Response.Body.class);
when(body.asReader(any())).thenThrow(new IOException("test exception"));
Response response = Response.builder()
.status(200)
.reason("OK")
.headers(Collections.emptyMap())
.bo... |
static KafkaNodePoolTemplate convertTemplate(KafkaClusterTemplate template) {
if (template != null) {
return new KafkaNodePoolTemplateBuilder()
.withPodSet(template.getPodSet())
.withPod(template.getPod())
.withPerPodService(template.getP... | @Test
public void testConvertTemplateWithSomeValues() {
KafkaClusterTemplate kafkaTemplate = new KafkaClusterTemplateBuilder()
.withNewKafkaContainer()
.addToEnv(new ContainerEnvVarBuilder().withName("MY_ENV_VAR").withValue("my-env-var-value").build())
.e... |
public static ExpressionStmt createArraysAsListFromList(List<?> source) {
ExpressionStmt toReturn = createArraysAsListExpression();
MethodCallExpr arraysCallExpression = toReturn.getExpression().asMethodCallExpr();
NodeList<Expression> arguments = new NodeList<>();
source.forEach(value -... | @Test
void createArraysAsListFromList() {
List<String> strings = IntStream.range(0, 3)
.mapToObj(i -> "Element" + i)
.collect(Collectors.toList());
ExpressionStmt retrieved = CommonCodegenUtils.createArraysAsListFromList(strings);
assertThat(retrieved).isNotNu... |
@Override
public ProcessingLogger getLogger(
final String name
) {
return getLogger(name, Collections.emptyMap());
} | @Test
public void shouldReturnExistingLogger() {
// When:
factory.getLogger("boo.far", Collections.singletonMap("tag-value", "some-id-1"));
factory.getLogger("boo.far", Collections.singletonMap("tag-value", "some-id-2"));
factory.getLogger("boo.far", Collections.singletonMap("tag-value", "some-id-3"))... |
@Override
public void logoutFailure(HttpRequest request, String errorMessage) {
checkRequest(request);
requireNonNull(errorMessage, "error message can't be null");
if (!LOGGER.isDebugEnabled()) {
return;
}
LOGGER.debug("logout failure [error|{}][IP|{}|{}]",
emptyIfNull(errorMessage),
... | @Test
public void logout_logs_X_Forwarded_For_header_from_request() {
HttpRequest request = mockRequest("1.2.3.4", List.of("2.3.4.5"));
underTest.logoutFailure(request, "bad token");
verifyLog("logout failure [error|bad token][IP|1.2.3.4|2.3.4.5]", Set.of("login", "logout success"));
} |
@Override
public List<String> listPartitionNames(String dbName, String tblName, TableVersionRange version) {
return hmsOps.getPartitionKeys(dbName, tblName);
} | @Test
public void testGetPartitionKeys() {
Assert.assertEquals(
Lists.newArrayList("col1"), hiveMetadata.listPartitionNames("db1", "tbl1", TableVersionRange.empty()));
} |
@Override
public String getTableName(final int column) {
Preconditions.checkArgument(1 == column);
return "";
} | @Test
void assertGetTableName() throws SQLException {
assertThat(actualMetaData.getTableName(1), is(""));
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testFunctionEmptyStringResultDecode() {
Function function =
new Function(
"test",
Collections.emptyList(),
Collections.singletonList(new TypeReference<Utf8String>() {}));
List<Type> utf8Strings... |
public static void setProtocolEngine(Configuration conf,
Class<?> protocol, Class<?> engine) {
if (conf.get(ENGINE_PROP+"."+protocol.getName()) == null) {
conf.setClass(ENGINE_PROP+"."+protocol.getName(), engine,
RpcEngine.class);
}
} | @Test
public void testSetProtocolEngine() {
Configuration conf = new Configuration();
RPC.setProtocolEngine(conf, StoppedProtocol.class, StoppedRpcEngine.class);
RpcEngine rpcEngine = RPC.getProtocolEngine(StoppedProtocol.class, conf);
assertTrue(rpcEngine instanceof StoppedRpcEngine);
RPC.setPro... |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof PojoSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
PojoSeria... | @Test
void testResolveSchemaCompatibilityWithRemovedFields() {
final PojoSerializerSnapshot<TestPojo> oldSnapshot =
buildTestSnapshot(
Arrays.asList(
mockRemovedField(ID_FIELD),
NAME_FIELD,
... |
public Optional<Session> login(@Nullable String currentSessionId, String host,
ActorAwareAuthenticationToken authToken) throws AuthenticationServiceUnavailableException {
final String previousSessionId = StringUtils.defaultIfBlank(currentSessionId, null);
final Subjec... | @Test
public void serviceUnavailable() {
setUpUserMock();
assertFalse(SecurityUtils.getSubject().isAuthenticated());
// First realm will throw, second realm will be unable to authenticate because user has no account
securityManager.setRealms(ImmutableList.of(throwingRealm(), new Si... |
@Override
public boolean overlap(final Window other) throws IllegalArgumentException {
if (getClass() != other.getClass()) {
throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type "
+ other.getClass() + ".");
}
final Ti... | @Test
public void shouldOverlapIfOtherWindowStartIsWithinThisWindow() {
/*
* This: [-------)
* Other: [-------)
*/
assertTrue(window.overlap(new TimeWindow(start, end + 1)));
assertTrue(window.overlap(new TimeWindow(start, 150)));
assertTru... |
@Override
public DictDataDO parseDictData(String dictType, String label) {
return dictDataMapper.selectByDictTypeAndLabel(dictType, label);
} | @Test
public void testParseDictData() {
// mock 数据
DictDataDO dictDataDO = randomDictDataDO().setDictType("yunai").setLabel("1");
dictDataMapper.insert(dictDataDO);
DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setLabel("2");
dictDataMapper.insert(dictData... |
public URLNormalizer removeDuplicateSlashes() {
String urlRoot = HttpURL.getRoot(url);
String path = toURL().getPath();
String urlRootAndPath = urlRoot + path;
String newPath = path.replaceAll("/{2,}", "/");
String newUrlRootAndPath = urlRoot + newPath;
url = StringUtils.... | @Test
public void testRemoveDuplicateSlashes() {
s = "http://www.example.com/a//b///c////d/////e.html";
t = "http://www.example.com/a/b/c/d/e.html";
assertEquals(t, n(s).removeDuplicateSlashes().toString());
s = "http://www.example.com/a//b//c.html?path=/d//e///f";
t = "http:... |
@Override
public Connection getConnection() throws SQLException {
XAConnection xaConnection = xaDataSource.getXAConnection();
return getConnectionProxy(xaConnection);
} | @Test
public void testGetConnection() throws SQLException {
// Mock
Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.getAutoCommit()).thenReturn(true);
DatabaseMetaData metaData = Mockito.mock(DatabaseMetaData.class);
Mockito.when(metaData.getUR... |
@Bean
public ShenyuPlugin rewritePlugin() {
return new RewritePlugin();
} | @Test
public void testRewritePlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RewritePluginConfiguration.class))
.withBean(RewritePluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
... |
@Override
public Object getValue() {
if (value == null) {
value = serializationService.toObject(record.getValue());
}
return value;
} | @Test
public void test_getValue() {
assertEquals(value, view.getValue());
} |
@Override
public Object postProcessAfterInitialization(Object instance, String name) throws Exception {
if (instance instanceof ScopeModelAware) {
ScopeModelAware modelAware = (ScopeModelAware) instance;
modelAware.setScopeModel(scopeModel);
if (this.moduleModel != null) ... | @Test
void testPostProcessAfterInitialization() throws Exception {
ScopeModelAwareExtensionProcessor processor = new ScopeModelAwareExtensionProcessor(moduleModel);
MockScopeModelAware mockScopeModelAware = new MockScopeModelAware();
Object object = processor.postProcessAfterInitialization(
... |
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_ResourceAccessException() {
// Arrange
when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class)))
.thenThrow(new ResourceAccessException("Service unavailable"));
// Act
Boolean result = orderService.processPaymen... |
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
throws Http2Exception {
if (endOfStream || data.isReadable()) {
emptyDataFrames = 0;
} else if (emptyDataFrames++ == maxConsecutiveEmptyFrames && !violatio... | @Test
public void testEmptyDataFramesWithNonEmptyInBetween() throws Http2Exception {
final Http2EmptyDataFrameListener listener = new Http2EmptyDataFrameListener(frameListener, 2);
listener.onDataRead(ctx, 1, Unpooled.EMPTY_BUFFER, 0, false);
listener.onDataRead(ctx, 1, nonEmpty, 0, false);
... |
public void addPipeline(String groupName, PipelineConfig pipeline) {
String sanitizedGroupName = BasicPipelineConfigs.sanitizedGroupName(groupName);
if (!this.hasGroup(sanitizedGroupName)) {
createNewGroup(sanitizedGroupName, pipeline);
return;
}
for (PipelineConf... | @Test
public void shouldReturnTrueWhenGroupNameIsEmptyAndDefaultGroupExists() {
PipelineConfig existingPipeline = createPipelineConfig("pipeline1", "stage1");
PipelineConfigs defaultGroup = createGroup("defaultGroup", existingPipeline);
PipelineGroups pipelineGroups = new PipelineGroups(defa... |
@Deactivate
public void deactivate() {
deviceToPipeconf.removeListener(mapListener);
deviceToPipeconf = null;
pipeconfToDevices = null;
log.info("Stopped");
} | @Test
public void deactivate() {
store.deactivate();
assertNull("Should be null", store.deviceToPipeconf);
assertNull("Should be null", store.pipeconfToDevices);
} |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsAnnotatedWithRecurringAnnotationNoCronOrIntervalWillThrowException() {
// GIVEN
final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor();
// WHEN & THEN
assertThatThrownBy(() -> recurringJobPostProcessor.postProcessAfterIn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.