focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public JavaCommand<CeJvmOptions> createCeCommand() {
File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey());
CeJvmOptions jvmOptions = new CeJvmOptions(tempDir)
.addFromMandatoryProperty(props, CE_JAVA_OPTS.getKey())
.addFromMandatoryProperty(props, CE_JAVA_ADDITIONAL_OPTS.getKey()... | @Test
public void createCeCommand_returns_command_for_default_settings() {
JavaCommand command = newFactory(new Properties()).createCeCommand();
assertThat(command.getClassName()).isEqualTo("org.sonar.ce.app.CeServer");
assertThat(command.getWorkDir().getAbsolutePath()).isEqualTo(homeDir.getAbsolutePath(... |
public Privacy privacy() {
return privacy;
} | @Test
void privacyCannotBeNull() {
Assertions.assertThrows(NullPointerException.class, () -> DefaultBot.getDefaultBuilder().privacy(null).build());
} |
public static <Req extends MessagingRequest> Matcher<Req> channelKindEquals(String channelKind) {
if (channelKind == null) throw new NullPointerException("channelKind == null");
if (channelKind.isEmpty()) throw new NullPointerException("channelKind is empty");
return new MessagingChannelKindEquals<Req>(chan... | @Test void channelKindEquals_unmatched_null() {
assertThat(channelKindEquals("queue").matches(request)).isFalse();
} |
public BoardFoundResponse findBoardById(final Long boardId, final Long memberId) {
return boardRepository.findByIdForRead(boardId, memberId)
.orElseThrow(BoardNotFoundException::new);
} | @Test
void 게시글이_없으면_에외를_발생시킨다() {
// when & then
assertThatThrownBy(() -> boardQueryService.findBoardById(1L, 1L))
.isInstanceOf(BoardNotFoundException.class);
} |
public void valid(String extensionName) {
if (!inputExtensions.map().containsKey(extensionName))
throw new IllegalArgumentException(String.format("Extension %s was not found in the original extensions", extensionName));
validatedExtensions.put(extensionName, inputExtensions.map().get(extensi... | @Test
public void testCannotValidateExtensionWhichWasNotGiven() {
Map<String, String> extensions = new HashMap<>();
extensions.put("hello", "bye");
OAuthBearerExtensionsValidatorCallback callback = new OAuthBearerExtensionsValidatorCallback(TOKEN, new SaslExtensions(extensions));
a... |
public static CompletableFuture<Map<String, String>> labelFailure(
final Throwable cause,
final Context context,
final Executor mainThreadExecutor,
final Collection<FailureEnricher> failureEnrichers) {
// list of CompletableFutures to enrich failure with labels fr... | @Test
public void testLabelFutureWithValidEnricher() {
// validate labelFailure by enricher with correct outputKeys
final Throwable cause = new RuntimeException("test exception");
final Set<FailureEnricher> failureEnrichers = new HashSet<>();
final FailureEnricher validEnricher = new... |
@SuppressWarnings("deprecation")
@Override
public Integer call() throws Exception {
super.call();
try (var files = Files.walk(directory)) {
List<String> flows = files
.filter(Files::isRegularFile)
.filter(YamlFlowParser::isValidExtension)
... | @Test
void helper() {
URL directory = FlowNamespaceUpdateCommandTest.class.getClassLoader().getResource("helper");
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Env... |
@Override
public SccResult<V, E> search(Graph<V, E> graph, EdgeWeigher<V, E> weigher) {
SccResult<V, E> result = new SccResult<>(graph);
for (V vertex : graph.getVertexes()) {
VertexData data = result.data(vertex);
if (data == null) {
connect(graph, vertex, we... | @Test
public void basic() {
graph = new AdjacencyListsGraph<>(vertexes(), edges());
TarjanGraphSearch<TestVertex, TestEdge> gs = new TarjanGraphSearch<>();
SccResult<TestVertex, TestEdge> result = gs.search(graph, null);
validate(result, 6);
} |
@Override
public DataSource getDataSource(String column) {
IndexContainer indexContainer = _indexContainerMap.get(column);
if (indexContainer != null) {
// Physical column
return indexContainer.toDataSource();
} else {
// Virtual column
FieldSpec fieldSpec = _schema.getFieldSpecFor... | @Test
public void testDataSourceForMVColumns()
throws IOException {
for (FieldSpec fieldSpec : _schema.getAllFieldSpecs()) {
if (!fieldSpec.isSingleValueField()) {
String column = fieldSpec.getName();
DataSource actualDataSource = _mutableSegmentImpl.getDataSource(column);
Data... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testExtractorsWithExceptions() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.callback(new Callable<Result[]>() {
@Override
public Result[] call() throws Exception {
throw new E... |
@Override
protected String transform(ILoggingEvent event, String in) {
AnsiElement element = ELEMENTS.get(getFirstOption());
List<Marker> markers = event.getMarkerList();
if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) {
... | @Test
void transformShouldReturnInputStringWhenMarkerListIsEmpty() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getMarkerList()).thenReturn(null);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLF... |
public boolean isEmpty() {
return size() == 0;
} | @Test
void testIsEmpty() {
HeapPriorityQueue<TestElement> priorityQueue = newPriorityQueue(1);
assertThat(priorityQueue.isEmpty()).isTrue();
assertThat(priorityQueue.add(new TestElement(4711L, 42L))).isTrue();
assertThat(priorityQueue.isEmpty()).isFalse();
priorityQueue.po... |
@Override
public ChannelFuture writePriority(ChannelHandlerContext ctx, int streamId,
int streamDependency, short weight, boolean exclusive, ChannelPromise promise) {
try {
verifyStreamId(streamId, STREAM_ID);
verifyStreamOrConnectionId(streamDependency, STREAM_DEPENDENCY... | @Test
public void writePriority() {
frameWriter.writePriority(
ctx, /* streamId= */ 1, /* dependencyId= */ 2, /* weight= */ (short) 256, /* exclusive= */ true, promise);
expectedOutbound = Unpooled.copiedBuffer(new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x05, // paylo... |
@Override
public Class<? extends AvgPercentileFunctionBuilder> builder() {
return AvgPercentileFunctionBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
PercentileFunctionInst inst = new PercentileFunctionInst();
inst.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
new PercentileArgument(
new BucketedValues(
... |
public QueueStoreConfig setClassName(@Nonnull String className) {
this.className = checkHasText(className, "Queue store class name must contain text");
this.storeImplementation = null;
return this;
} | @Test
public void testEqualsAndHashCode() {
assumeDifferentHashCodes();
EqualsVerifier.forClass(QueueStoreConfig.class)
.suppress(Warning.NONFINAL_FIELDS)
.withPrefabValues(QueueStoreConfigReadOnly.class,
new QueueStoreConfigReadOnly(new QueueS... |
boolean hasNonDeterministicFunctions(Expr expr) {
if (expr instanceof FunctionCallExpr) {
FunctionCallExpr callExpr = (FunctionCallExpr) expr;
String funcName = callExpr.getFn().functionName();
if (FunctionSet.nonDeterministicFunctions.contains(funcName)) {
re... | @Test
public void testNondetermisticTimeFunction() {
FragmentNormalizer fragmentNormalizer = new FragmentNormalizer(null, null);
ConnectContext ctx = UtFrameUtils.createDefaultCtx();
for (String funcName : FunctionSet.nonDeterministicTimeFunctions) {
String sql = String.format("s... |
public FEELFnResult<Boolean> invoke(@ParameterName( "point1" ) Comparable point1, @ParameterName( "point2" ) Comparable point2) {
if ( point1 == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point1", "cannot be null"));
}
if ( point2 == null ) {
... | @Test
void invokeParamRangeAndRange() {
FunctionTestUtil.assertResult( afterFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ),
... |
@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 noRetryOnSSLFailure() {
HttpGet request = new HttpGet("/");
assertThat(retryStrategy.retryRequest(request, new SSLException("encryption failed"), 1, null))
.isFalse();
} |
public CompoundPluginDescriptorFinder add(PluginDescriptorFinder finder) {
if (finder == null) {
throw new IllegalArgumentException("null not allowed");
}
finders.add(finder);
return this;
} | @Test
public void add() {
CompoundPluginDescriptorFinder descriptorFinder = new CompoundPluginDescriptorFinder();
assertEquals(0, descriptorFinder.size());
descriptorFinder.add(new PropertiesPluginDescriptorFinder());
assertEquals(1, descriptorFinder.size());
} |
public static AtomicInteger getLongConnectionMonitor() {
return longConnection;
} | @Test
void testGetLongConnectionMonitor() {
AtomicInteger atomicInteger = MetricsMonitor.getLongConnectionMonitor();
assertEquals(0, atomicInteger.get());
} |
@Override
public Response replaceLabelsOnNode(Set<String> newNodeLabelsName,
HttpServletRequest hsr, String nodeId) throws Exception {
// Step1. Check the parameters to ensure that the parameters are not empty.
if (StringUtils.isBlank(nodeId)) {
routerMetrics.incrReplaceLabelsOnNodeFailedRetrieve... | @Test
public void testReplaceLabelsOnNode() throws Exception {
// subCluster3 -> node3:3 -> label:NodeLabel3
String nodeId = "node3:3";
Set<String> labels = Collections.singleton("NodeLabel3");
// We expect the following result: subCluster#3:Success;
String expectValue = "subCluster#3:Success;";
... |
@Override
public void open() throws Exception {
super.open();
windowSerializer = windowAssigner.getWindowSerializer(new ExecutionConfig());
internalTimerService = getInternalTimerService("window-timers", windowSerializer, this);
triggerContext = new TriggerContext();
trigge... | @Test
void testGroupWindowAggregateFunction() throws Exception {
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
getTestHarness(new Configuration());
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetPartialGenericTriFunctionVariadic() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericTriFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType);
// T... |
public static long readLong(byte[] bytes, int offset) {
return (((long) (bytes[offset] & 0xff) << 56)
| ((long) (bytes[offset + 1] & 0xff) << 48)
| ((long) (bytes[offset + 2] & 0xff) << 40)
| ((long) (bytes[offset + 3] & 0xff) << 32)
| ((long) (bytes[offset + 4] & 0xff) << 24)
... | @Test
public void testReadLong() {
assertEquals(-4020014679618420408L, IOUtils.readLong(BYTE_ARRAY, 0));
assertEquals(3893910145419266185L, IOUtils.readLong(BYTE_ARRAY, 1));
assertEquals(716817247016356198L, IOUtils.readLong(BYTE_ARRAY, 2));
} |
@SuppressWarnings("checkstyle:npathcomplexity")
public PartitionServiceState getPartitionServiceState() {
PartitionServiceState state = getPartitionTableState();
if (state != SAFE) {
return state;
}
if (!checkAndTriggerReplicaSync()) {
return REPLICA_NOT_SYN... | @Test
public void shouldBeSafe_whenNotInitialized() {
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory();
HazelcastInstance hz = factory.newHazelcastInstance();
InternalPartitionServiceImpl partitionService = getNode(hz).partitionService;
PartitionReplicaStateCh... |
public Certificate add(X509Certificate cert) {
final Certificate db;
try {
db = Certificate.from(cert);
} catch (CertificateEncodingException e) {
logger.error("Encoding error in certificate", e);
throw new ClientException("Encoding error in certificate", e);
... | @Test
public void shouldAllowToAddCertificateIfFirstOfDocumentType() throws Exception {
final Certificate rdw = loadCertificate("rdw/acc/csca.crt", true);
final X509Certificate cert = readCertificate("nik/tv/csca.crt");
final Certificate dbCert = service.add(cert);
assertEquals(X509F... |
@Override
public void handleTenantMenu(TenantMenuHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户,然后获得菜单
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
Set<Long> menuIds;
if (isSystemTenant(tenan... | @Test // 系统租户的情况
public void testHandleTenantMenu_system() {
// 准备参数
TenantMenuHandler handler = mock(TenantMenuHandler.class);
// mock 未禁用
when(tenantProperties.getEnable()).thenReturn(true);
// mock 租户
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackage... |
public void terminate(String executionId, WorkflowInstance.Status status, String reason) {
try {
workflowExecutor.terminateWorkflow(executionId, status + "-" + reason);
} catch (ApplicationException e) {
if (e.getCode() != CONFLICT) {
throw e;
}
}
} | @Test
public void testTerminate() {
runner.terminate("test-uuid", WorkflowInstance.Status.STOPPED, "test-reason");
verify(workflowExecutor, times(1)).terminateWorkflow("test-uuid", "STOPPED-test-reason");
} |
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
Configuration conf = FlinkOptions.fromMap(context.getCatalogTable().getOptions());
checkArgument(!StringUtils.isNullOrEmpty(conf.getString(FlinkOptions.PATH)),
"Option [path] should not be empty.");
setupTableOptions(conf.... | @Test
void testSetupHoodieKeyOptionsForSink() {
this.conf.setString(FlinkOptions.RECORD_KEY_FIELD, "dummyField");
this.conf.setString(FlinkOptions.KEYGEN_CLASS_NAME, "dummyKeyGenClass");
// definition with simple primary key and partition path
ResolvedSchema schema1 = SchemaBuilder.instance()
... |
public static boolean isUri(String potentialUri) {
if (StringUtils.isBlank(potentialUri)) {
return false;
}
try {
URI uri = new URI(potentialUri);
return uri.getScheme() != null && uri.getHost() != null;
} catch (URISyntaxException e) {
re... | @Test public void
returns_false_when_uri_is_empty() {
assertThat(UriValidator.isUri(""), is(false));
} |
@Override
public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final TimestampedSegment segment = super.getOrCreateSegmentIfLiv... | @Test
public void shouldCreateSegments() {
final TimestampedSegment segment1 = segments.getOrCreateSegmentIfLive(0, context, -1L);
final TimestampedSegment segment2 = segments.getOrCreateSegmentIfLive(1, context, -1L);
final TimestampedSegment segment3 = segments.getOrCreateSegmentIfLive(2, ... |
@Override
public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) {
if(Checksum.NONE == remote.getChecksum()) {
log.warn(String.format("No remote checksum available for comparison %s", remote));
return Comparison.unknown;
}
... | @Test
public void testDirectory() {
ComparisonService s = new ChecksumComparisonService();
assertEquals(Comparison.unknown, s.compare(Path.Type.directory, new PathAttributes(),
new PathAttributes()));
} |
@Override
public void handle(final RoutingContext routingContext) {
routingContext.addEndHandler(ar -> {
// After the response is complete, log results here.
final int status = routingContext.request().response().getStatusCode();
if (!loggingRateLimiter.shouldLog(logger, routingContext.request()... | @Test
public void shouldSkipRateLimited() {
// Given:
when(response.getStatusCode()).thenReturn(200);
when(loggingRateLimiter.shouldLog(logger, "/query", 200)).thenReturn(true, true, false, false);
// When:
loggingHandler.handle(routingContext);
loggingHandler.handle(routingContext);
logg... |
public Stopwatch stop() {
if (isRunning()) stopTime = Instant.now();
return this;
} | @Test
public void stop() {
stopwatch.stop();
} |
@Nonnull
@Override
public Optional<? extends INode> parse(
@Nullable final String str, @Nonnull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
for (IMapper mapper : jcaSpecificAlgorithmMappers) {
Optional<? extend... | @Test
void mac() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaAlgorithmMapper jcaAlgorithmMapper = new JcaAlgorithmMapper();
Optional<? extends INode> assetOptional =
jcaAlgorithmMapper.... |
@Override
public void saveProperty(DbSession session, PropertyDto property, @Nullable String userLogin,
@Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) {
// do nothing
} | @Test
public void insertProperty1() {
underTest.saveProperty(propertyDto);
assertNoInteraction();
} |
@Override
public ObjectNode encode(Instruction instruction, CodecContext context) {
checkNotNull(instruction, "Instruction cannot be null");
return new EncodeInstructionCodecHelper(instruction, context).encode();
} | @Test
public void pushHeaderInstructionsTest() {
final L2ModificationInstruction.ModMplsHeaderInstruction instruction =
(L2ModificationInstruction.ModMplsHeaderInstruction) Instructions.pushMpls();
final ObjectNode instructionJson = instructionCodec.encode(instruction, context);
... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetTransactionReceipt() throws Exception {
web3j.ethGetTransactionReceipt(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238")
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransact... |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testHierarchicalWithReserved() {
int[][] qData = new int[][] {
// / A B C D E F
{ 200, 100, 50, 50, 100, 10, 90 }, // abs
{ 200, 200, 200, 200, 200, 200, 200 }, // maxCap
{ 200, 110, 60, 50, 90, 90, 0 }, // used
{ 10, 0, 0, 0, 10,... |
private CompletableFuture<Boolean> verifyTxnOwnership(TxnID txnID) {
assert ctx.executor().inEventLoop();
return service.pulsar().getTransactionMetadataStoreService()
.verifyTxnOwnership(txnID, getPrincipal())
.thenComposeAsync(isOwner -> {
if (isOwner... | @Test(timeOut = 30000)
public void sendEndTxnOnPartitionResponse() throws Exception {
final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class);
when(txnStore.getTxnMeta(any())).thenReturn(CompletableFuture.completedFuture(mock(TxnMeta.class)));
when(txnSto... |
@Override
public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) {
if(input.getOptionValues(action.name()).length == 2) {
switch(action) {
case download:
return new DownloadTransferItemFinder().find(input, action... | @Test
public void testUploadFilesWithExpandedGlobToDirectoryTarget() throws Exception {
final CommandLineParser parser = new PosixParser();
final String temp = System.getProperty("java.io.tmpdir");
final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--uploa... |
public static long estimateSize(StructType tableSchema, long totalRecords) {
if (totalRecords == Long.MAX_VALUE) {
return totalRecords;
}
long result;
try {
result = LongMath.checkedMultiply(tableSchema.defaultSize(), totalRecords);
} catch (ArithmeticException e) {
result = Long.... | @Test
public void testEstimateSizeMaxValue() throws IOException {
Assert.assertEquals(
"estimateSize returns Long max value",
Long.MAX_VALUE,
SparkSchemaUtil.estimateSize(null, Long.MAX_VALUE));
} |
public long parseForStore(TimelineDataManager tdm, Path appDirPath,
boolean appCompleted, JsonFactory jsonFactory, ObjectMapper objMapper,
FileSystem fs) throws IOException {
LOG.debug("Parsing for log dir {} on attempt {}", appDirPath,
attemptDirName);
Path logPath = getPath(appDirPath);
... | @Test
void testParseDomain() throws Exception {
// Load test data
TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config);
DomainLogInfo domainLogInfo = new DomainLogInfo(TEST_ATTEMPT_DIR_NAME,
TEST_DOMAIN_FILE_NAME,
UserGroupInformation.getLoginUser().getUserName());
... |
public static Read read() {
return Read.create();
} | @Test
public void testReadingFailsTableDoesNotExist() throws Exception {
final String table = "TEST-TABLE";
BigtableIO.Read read =
BigtableIO.read()
.withBigtableOptions(BIGTABLE_OPTIONS)
.withTableId(table)
.withServiceFactory(factory);
// Exception will be t... |
public LogAggregationFileControllerFactory(Configuration conf) {
this.conf = conf;
Collection<String> fileControllers = conf.getStringCollection(
YarnConfiguration.LOG_AGGREGATION_FILE_FORMATS);
Map<String, String> controllerChecker = new HashMap<>();
for (String controllerName : fileController... | @Test
void testLogAggregationFileControllerFactory() throws Exception {
enableFileControllers(getConf(), ALL_FILE_CONTROLLERS, ALL_FILE_CONTROLLER_NAMES);
LogAggregationFileControllerFactory factory =
new LogAggregationFileControllerFactory(getConf());
List<LogAggregationFileController> list =
... |
private IcebergDecimalObjectInspector(int precision, int scale) {
super(new DecimalTypeInfo(precision, scale));
} | @Test
public void testIcebergDecimalObjectInspector() {
HiveDecimalObjectInspector oi = IcebergDecimalObjectInspector.get(38, 18);
Assert.assertEquals(ObjectInspector.Category.PRIMITIVE, oi.getCategory());
Assert.assertEquals(PrimitiveObjectInspector.PrimitiveCategory.DECIMAL, oi.getPrimitiveCategory());... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testPreferredReadReplicaOffsetError() {
buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(),
Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis());
subscriptions.assignFromUse... |
public <T> ProducerBuilder<T> createProducerBuilder(String topic, Schema<T> schema, String producerName) {
ProducerBuilder<T> builder = client.newProducer(schema);
if (defaultConfigurer != null) {
defaultConfigurer.accept(builder);
}
builder.blockIfQueueFull(true)
... | @Test
public void testCreateProducerBuilderWithSimpleProducerConfig() {
ProducerConfig producerConfig = new ProducerConfig();
producerConfig.setBatchBuilder("KEY_BASED");
ProducerBuilderFactory builderFactory = new ProducerBuilderFactory(pulsarClient, producerConfig, null, null);
bui... |
@Override
public void execute(GraphModel graphModel) {
Graph graph = graphModel.getGraphVisible();
execute(graph);
} | @Test
public void testCompleteGraphDegree() {
GraphModel graphModel = GraphGenerator.generateCompleteUndirectedGraph(5);
Graph graph = graphModel.getGraph();
Node n = graph.getNode("2");
WeightedDegree d = new WeightedDegree();
d.execute(graph);
assertEquals(n.getAttr... |
public static boolean isSensitive(String key) {
Preconditions.checkNotNull(key, "key is null");
final String keyInLower = key.toLowerCase();
for (String hideKey : SENSITIVE_KEYS) {
if (keyInLower.length() >= hideKey.length() && keyInLower.contains(hideKey)) {
return t... | @Test
void testHiddenKey() {
assertThat(GlobalConfiguration.isSensitive("password123")).isTrue();
assertThat(GlobalConfiguration.isSensitive("123pasSword")).isTrue();
assertThat(GlobalConfiguration.isSensitive("PasSword")).isTrue();
assertThat(GlobalConfiguration.isSensitive("Secret"... |
@Override
public int getOrder() {
return PluginEnum.GRPC.getCode();
} | @Test
public void testGetOrder() {
final int result = grpcPlugin.getOrder();
assertEquals(PluginEnum.GRPC.getCode(), result);
} |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
MessageNode messageNode = chatMessage.getMessageNode();
boolean update = false;
switch (chatMessage.getType())
{
case TRADEREQ:
if (chatMessage.getMessage().contains("wishes to trade with you."))
{
notifier.notify(config.notifyOn... | @Test
public void testLocalPlayerSelfMention()
{
final String localPlayerName = "Broo klyn";
MessageNode messageNode = mock(MessageNode.class);
Player localPlayer = mock(Player.class);
when(client.getLocalPlayer()).thenReturn(localPlayer);
when(localPlayer.getName()).thenReturn(localPlayerName);
lenien... |
static void parseTargetAddress(HttpHost target, Span span) {
if (span.isNoop()) return;
if (target == null) return;
InetAddress address = target.getAddress();
if (address != null) {
if (span.remoteIpAndPort(address.getHostAddress(), target.getPort())) return;
}
span.remoteIpAndPort(target.... | @Test void parseTargetAddress_prefersAddress() throws UnknownHostException {
when(span.isNoop()).thenReturn(false);
when(span.remoteIpAndPort("1.2.3.4", -1)).thenReturn(true);
HttpHost host = new HttpHost(InetAddress.getByName("1.2.3.4"), "3.4.5.6", -1, "http");
TracingHttpAsyncClientBuilder.parseTarge... |
private double totalBlockedTime(final Producer<?, ?> producer) {
return getMetricValue(producer.metrics(), "bufferpool-wait-time-ns-total")
+ getMetricValue(producer.metrics(), "flush-time-ns-total")
+ getMetricValue(producer.metrics(), "txn-init-time-ns-total")
+ getMetricVa... | @Test
public void shouldComputeTotalBlockedTime() {
setProducerMetrics(
nonEosMockProducer,
BUFFER_POOL_WAIT_TIME,
FLUSH_TME,
TXN_INIT_TIME,
TXN_BEGIN_TIME,
TXN_SEND_OFFSETS_TIME,
TXN_COMMIT_TIME,
TXN_ABORT_TIME,... |
public Optional<SearchVersion> getVersion() {
return nodeAdapter.version();
} | @Test
public void retrievingVersionSucceedsIfElasticsearchVersionIsValid() throws Exception {
when(nodeAdapter.version()).thenReturn(Optional.of(SearchVersion.elasticsearch("5.4.0")));
final Optional<SearchVersion> elasticsearchVersion = node.getVersion();
assertThat(elasticsearchVersion).... |
public static SubscriptionData build(final String topic, final String subString,
final String type) throws Exception {
if (ExpressionType.TAG.equals(type) || type == null) {
return buildSubscriptionData(topic, subString);
}
if (StringUtils.isEmpty(subString)) {
t... | @Test(expected = IllegalArgumentException.class)
public void testBuildSQLWithNullSubString() throws Exception {
FilterAPI.build("TOPIC", null, ExpressionType.SQL92);
} |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
... | @Test
public void eightBitDataCodingOverridesDefaultAlphabet() throws Exception {
final byte binDataCoding = (byte) 0x04; /* SMPP 8-bit */
byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };
Exchange exchange = new DefaultExchange(new DefaultCam... |
@Override
public List<String> getRegisterData(final String key) {
try {
List<String> children = client.getChildren().forPath(key);
List<String> datas = new ArrayList<>();
for (String child : children) {
String nodePath = key + "/" + child;
... | @Test
void getRegisterDataTest() throws Exception {
assertThrows(ShenyuException.class, () -> zookeeperDiscoveryServiceUnderTest.getRegisterData("/test"));
GetChildrenBuilder getChildrenBuilder = mock(GetChildrenBuilder.class);
when(curatorFramework.getChildren()).thenReturn(getChildrenBuild... |
@Override
public void createJobManagerComponent(KubernetesJobManagerSpecification kubernetesJMSpec) {
final Deployment deployment = kubernetesJMSpec.getDeployment();
final List<HasMetadata> accompanyingResources = kubernetesJMSpec.getAccompanyingResources();
// create Deployment
LOG... | @Test
void testCreateFlinkMasterComponent() throws Exception {
flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final List<Deployment> resultedDeployments =
kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems();
assertThat... |
@Override
public boolean addServiceSubscriber(Service service, Subscriber subscriber) {
if (null == subscribers.put(service, subscriber)) {
MetricsMonitor.incrementSubscribeCount();
}
return true;
} | @Test
void addServiceSubscriber() {
assertTrue(abstractClient.addServiceSubscriber(service, subscriber));
} |
@Override
public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle)
{
JdbcTableHandle jdbcTableHandle = (JdbcTableHandle) tableHandle;
ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder();
for (JdbcColumnHa... | @Test
public void testGetColumnHandles()
{
// known table
assertEquals(metadata.getColumnHandles(SESSION, tableHandle), ImmutableMap.of(
"text", new JdbcColumnHandle(CONNECTOR_ID, "TEXT", JDBC_VARCHAR, VARCHAR, true, Optional.empty()),
"text_short", new JdbcColumn... |
@Override
public void setRootResources(final Map<String, ResourceModel> rootResources)
{
log.debug("Setting root resources");
_rootResources = rootResources;
Collection<Class<?>> allResourceClasses = new HashSet<>();
for (ResourceModel resourceModel : _rootResources.values())
{
processCh... | @Test
public void testAmbiguousBeanResolution() throws Exception
{
Map<String, ResourceModel> pathRootResourceMap =
buildResourceModels(SomeResource1.class,
SomeResource2.class,
SomeResource4.class);
// set up mock ApplicationContext
BeanProvide... |
@Override
public boolean remove(Object o) {
if (!(o instanceof Integer)) {
throw new ClassCastException("PartitionIdSet can be only used with Integers");
}
return remove(((Integer) o).intValue());
} | @Test(expected = ClassCastException.class)
public void test_remove_whenNotInteger() {
partitionIdSet.remove(new Object());
} |
public static List<CredentialInfo> check(
final List<String> tokens,
final ExternalServiceCredentialsGenerator credentialsGenerator,
final long maxAgeSeconds) {
// the credential for the username with the latest timestamp (so far)
final Map<String, CredentialInfo> bestForUsername = new HashMa... | @Test
void multipleUsernames() {
final ExternalServiceCredentials cred1New = GEN1.generateForUuid(UUID1);
final ExternalServiceCredentials cred1Old = atTime(GEN1, -1, UUID1);
final ExternalServiceCredentials cred2New = GEN1.generateForUuid(UUID2);
final ExternalServiceCredentials cred2Old = atTime(GE... |
@Override
public Integer doCall() throws Exception {
// Operator id must be set
if (ObjectHelper.isEmpty(operatorId)) {
printer().println("Operator id must be set");
return -1;
}
delegate.setFile(name);
delegate.setSource(source);
delegate.set... | @Test
public void shouldUpdatePipe() throws Exception {
Pipe pipe = createPipe("timer-to-log");
kubernetesClient.resources(Pipe.class).resource(pipe).create();
Bind command = createCommand("timer", "log");
command.output = null;
command.properties = new String[] {
... |
@Override
protected String selectorHandler(final MetaDataRegisterDTO metaDataDTO) {
return "";
} | @Test
public void testSelectorHandler() {
MetaDataRegisterDTO metaDataRegisterDTO = MetaDataRegisterDTO.builder().build();
assertEquals(StringUtils.EMPTY, shenyuClientRegisterTarsService.selectorHandler(metaDataRegisterDTO));
} |
public static Map<String, String> deserialize2Map(String jsonStr) {
try {
if (StringUtils.hasText(jsonStr)) {
Map<String, Object> temp = OM.readValue(jsonStr, Map.class);
Map<String, String> result = new HashMap<>();
temp.forEach((key, value) -> {
result.put(String.valueOf(key), String.valueOf(val... | @Test
public void testDeserializeThrowsRuntimeException() {
String jsonStr = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"";
assertThatThrownBy(() -> JacksonUtils.deserialize2Map(jsonStr))
.isExactlyInstanceOf(RuntimeException.class).hasMessage("Json to map failed.");
} |
@Delete(uri = "{namespace}/{id}")
@ExecuteOn(TaskExecutors.IO)
@Operation(tags = {"Flows"}, summary = "Delete a flow")
@ApiResponse(responseCode = "204", description = "On success")
public HttpResponse<Void> delete(
@Parameter(description = "The flow namespace") @PathVariable String namespace,
... | @Test
void deleteFlowsByIds(){
Flow flow = generateFlow("toDelete","io.kestra.unittest.delete", "a");
client.toBlocking().retrieve(POST("/api/v1/flows", flow), String.class);
client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/flows/delete/by-query?namespace=io.kestra.unittest.delete")... |
@Override
public void metricChange(final KafkaMetric metric) {
if (!metric.metricName().name().equals("total-sst-files-size")) {
return;
}
handleNewSstFilesSizeMetric(
metric,
metric.metricName().tags().getOrDefault(TASK_ID_TAG, ""),
getQueryId(metric)
);
} | @Test
public void shouldAddNewGauges() {
// Given:
listener.metricChange(mockMetric(
KAFKA_METRIC_GROUP,
KAFKA_METRIC_NAME,
BigInteger.valueOf(2),
ImmutableMap.of("task-id", "t1", "thread-id", THREAD_ID))
);
// When:
final Gauge<?> queryGauge = verifyAndGetRegisteredMetri... |
@Override
public SelLong field(SelString field) {
String fieldName = field.getInternalVal();
if ("length".equals(fieldName)) {
return SelLong.of(val.length);
}
throw new UnsupportedOperationException(type() + " DO NOT support accessing field: " + field);
} | @Test
public void field() {
SelLong res = one.field(SelString.of("length"));
assertEquals(2, res.longVal());
} |
@Override
public GZIPCompressionInputStream createInputStream( InputStream in ) throws IOException {
return new GZIPCompressionInputStream( in, this );
} | @Test
public void testCreateInputStream() throws IOException {
GZIPCompressionProvider provider = (GZIPCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME );
// Create an in-memory GZIP output stream for use by the input stream (to avoid exceptions)
ByteArrayOutputStream baos = new B... |
@Override
public List<String> splitAndEvaluate() {
return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : flatten(evaluate(GroovyUtils.split(handlePlaceHolder(inlineExpression))));
} | @Test
void assertEvaluateForArray() {
List<String> expected = TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build(
new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "t_order_${[0, 1, 2]},t_order_item_${[0, 2]}"))).splitAndEvalu... |
public PickTableLayoutForPredicate pickTableLayoutForPredicate()
{
return new PickTableLayoutForPredicate(metadata);
} | @Test
public void doesNotFireIfRuleNotChangePlan()
{
tester().assertThat(pickTableLayout.pickTableLayoutForPredicate())
.on(p -> {
p.variable("nationkey", BIGINT);
return p.filter(p.rowExpression("nationkey % 17 = BIGINT '44' AND nationkey % 15 = ... |
@Override
public void report(SortedMap<MetricName, Gauge> gauges,
SortedMap<MetricName, Counter> counters,
SortedMap<MetricName, Histogram> histograms,
SortedMap<MetricName, Meter> meters,
SortedMap<MetricName, Timer> timers... | @Test
public void reportsCounterValues() throws Exception {
final Counter counter = mock(Counter.class);
when(counter.getCount()).thenReturn(100L);
when(logger.isInfoEnabled(marker)).thenReturn(true);
infoReporter.report(this.map(),
map("test.counter", counter),
... |
@Nonnull
public static <T> Traverser<T> traverseIterator(@Nonnull Iterator<? extends T> iterator) {
return () -> iterator.hasNext() ? requireNonNull(iterator.next(), "Iterator returned a null item") : null;
} | @Test
public void when_traverseIteratorIgnoringNulls_then_filteredOut() {
Traverser<Integer> trav = traverseIterator(asList(null, 1, null, 2, null).iterator(), true);
assertEquals(1, (int) trav.next());
assertEquals(2, (int) trav.next());
assertNull(trav.next());
} |
protected void saveAndRunJobFilters(List<Job> jobs) {
if (jobs.isEmpty()) return;
try {
jobFilterUtils.runOnStateElectionFilter(jobs);
storageProvider.save(jobs);
jobFilterUtils.runOnStateAppliedFilters(jobs);
} catch (ConcurrentJobModificationException concu... | @Test
void onConcurrentJobModificationExceptionTaskTriesToResolveAndThrowsNoExceptionIfResolved() {
Job jobInProgress = aJobInProgress().build();
Job deletedJob = aCopyOf(jobInProgress).withDeletedState().build();
when(storageProvider.save(anyList())).thenThrow(new ConcurrentJobModification... |
@Override
public void run(T configuration, Environment environment) throws Exception {
final PooledDataSourceFactory dbConfig = getDataSourceFactory(configuration);
this.sessionFactory = requireNonNull(sessionFactoryFactory.build(this, environment, dbConfig,
entities, name()));
r... | @Test
void registersATransactionalListener() throws Exception {
bundle.run(configuration, environment);
final ArgumentCaptor<UnitOfWorkApplicationListener> captor =
ArgumentCaptor.forClass(UnitOfWorkApplicationListener.class);
verify(jerseyEnvironment).register(captor.captur... |
public String getFormattedMessage() {
if (formattedMessage != null) {
return formattedMessage;
}
if (argumentArray != null) {
formattedMessage = MessageFormatter.arrayFormat(message, argumentArray)
.getMessage();
} else {
formattedMessage = message;
}
return form... | @Test
public void testFormattingOneArg() {
String message = "x={}";
Throwable throwable = null;
Object[] argArray = new Object[] {12};
LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray);
assertNull(event.formattedMessage);
assertEquals("x=12", event.ge... |
@Override
public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList();
}
Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId);
if (CollUtil.isEmpty(... | @Test
public void testUserListByPostIds() {
// 准备参数
Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据
AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
userMapper.insert(user1);
userPostMapper.insert(new UserPostDO().setUserId(user1... |
public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions, Timer timer) {
return beginningOrEndOffset(partitions, ListOffsetsRequest.EARLIEST_TIMESTAMP, timer);
} | @Test
public void testBeginningOffsetsEmpty() {
buildFetcher();
assertEquals(emptyMap(), offsetFetcher.beginningOffsets(emptyList(), time.timer(5000L)));
} |
public static String getUsername(String token) {
List<String> userInfo = Arrays.asList(getTokenBody(token).getSubject().split(Constants.SPLIT_COMMA));
return userInfo.get(1);
} | @Test
public void getUsername() {
String name = JwtTokenUtil.getUsername(token);
Assert.isTrue(username.equals(name));
} |
@Override
public InterpreterResult interpret(String st, InterpreterContext context)
throws InterpreterException {
try {
Properties finalProperties = new Properties();
finalProperties.putAll(getProperties());
Properties newProperties = new Properties();
newProperties.load(new StringR... | @Test
void testPropertyTrim() throws InterpreterException {
assertTrue(interpreterFactory.getInterpreter("test.conf", executionContext) instanceof ConfInterpreter);
ConfInterpreter confInterpreter = (ConfInterpreter) interpreterFactory.getInterpreter("test.conf", executionContext);
InterpreterContext con... |
public static boolean isGzipStream(byte[] bytes) {
int minByteArraySize = 2;
if (bytes == null || bytes.length < minByteArraySize) {
return false;
}
return GZIPInputStream.GZIP_MAGIC == ((bytes[1] << 8 | bytes[0]) & 0xFFFF);
} | @Test
void testIsGzipStreamWithNull() {
assertFalse(IoUtils.isGzipStream(null));
} |
static <T extends CompoundPredicate> T flattenCompound(Predicate predicateLeft, Predicate predicateRight, Class<T> klass) {
// The following could have been achieved with {@link com.hazelcast.query.impl.predicates.FlatteningVisitor},
// however since we only care for 2-argument flattening, we can avoid ... | @Test
public void testFlattenAnd_withOrAndPredicates() {
OrPredicate orPredicate = new OrPredicate(leftOfOr, rightOfOr);
AndPredicate andPredicate = new AndPredicate(leftOfAnd, rightOfAnd);
AndPredicate flattenedCompoundAnd = SqlPredicate.flattenCompound(orPredicate, andPredicate, AndPredic... |
@Override
public String getStorageAccountKey(String accountName, Configuration rawConfig)
throws KeyProviderException {
String envelope = super.getStorageAccountKey(accountName, rawConfig);
AbfsConfiguration abfsConfig;
try {
abfsConfig = new AbfsConfiguration(rawConfig, accountName);
} c... | @Test
public void testScriptPathNotSpecified() throws Exception {
if (!Shell.WINDOWS) {
return;
}
ShellDecryptionKeyProvider provider = new ShellDecryptionKeyProvider();
Configuration conf = new Configuration();
String account = "testacct";
String key = "key";
conf.set(Configuration... |
void refreshNamenodes(Configuration conf)
throws IOException {
LOG.info("Refresh request received for nameservices: " +
conf.get(DFSConfigKeys.DFS_NAMESERVICES));
Map<String, Map<String, InetSocketAddress>> newAddressMap = null;
Map<String, Map<String, InetSocketAddress>> newLifelineAddressMa... | @Test
public void testFederationRefresh() throws Exception {
Configuration conf = new Configuration();
conf.set(DFSConfigKeys.DFS_NAMESERVICES,
"ns1,ns2");
addNN(conf, "ns1", "mock1:8020");
addNN(conf, "ns2", "mock1:8020");
bpm.refreshNamenodes(conf);
assertEquals(
"create #1\n... |
@ApiOperation(value = "Get a process definition", tags = { "Process Definitions" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates request was successful and the process-definitions are returned"),
@ApiResponse(code = 404, message = "Indicates the requested process def... | @Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetProcessDefinition() throws Exception {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
HttpGet httpGet = new HttpGet... |
@Override
public RouteContext route(final ShardingRule shardingRule) {
RouteContext result = new RouteContext();
Collection<String> logicTableNames = getLogicTableNames();
if (logicTableNames.isEmpty()) {
result.getRouteUnits().addAll(getBroadcastTableRouteUnits(shardingRule, "")... | @Test
void assertRouteForNormalTable() {
Collection<String> tableNames = Collections.singletonList("t_order");
ShardingTableBroadcastRoutingEngine shardingTableBroadcastRoutingEngine =
new ShardingTableBroadcastRoutingEngine(mock(ShardingSphereDatabase.class), createSQLStatementConte... |
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// has the class loaded already?
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass == null) {
try {
// find the class from given jar urls as in first c... | @Test
public void canLoadClassFromChildClassLoaderWhenPresentInParentClassloader() throws Exception {
URL testClassesUrl = new File("./target/test-classes").toURI().toURL();
cl = new ChildFirstClassLoader(new URL[]{testClassesUrl}, ChildFirstClassLoader.class.getClassLoader());
String class... |
public static void closeQuietly(HttpURLConnection connection) {
if (connection != null) {
try {
closeQuietly(connection.getInputStream());
} catch (Exception ignore) {
}
}
} | @Test
public void testCloseQuietly() throws IOException {
Closeable closeable = new BrokenInputStream();
URL url = new URL("https://www.baidu.com");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
Assertions.assertDoesNotThrow(() -> IoUtil.closeQuietly... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
if(status.isExists()) {
if(log.isWarnEnabled()) {
log.warn(String.f... | @Test
public void testMoveDirectory() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
new BoxDirector... |
@Override
public void handlerRule(final RuleData ruleData) {
String key = CacheKeyUtils.INST.getKey(ruleData);
Resilience4JRegistryFactory.remove(key);
Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> {
final Resilience4JHandle resilience4JHandle = GsonUtils.getInstance()... | @Test
public void testHandlerRule() {
ruleData.setSelectorId("1");
ruleData.setHandle("{\"urlPath\":\"test\"}");
ruleData.setId("test");
resilience4JHandler.handlerRule(ruleData);
Supplier<CommonHandleCache<String, Resilience4JHandle>> cache = Resilience4JHandler.CACHED_HANDL... |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoun... | @Test
public void callingNativeMethodShouldInvokeClassHandler() throws Exception {
Class<?> exampleClass = loadClass(AClassWithNativeMethod.class);
Method normalMethod = exampleClass.getDeclaredMethod("nativeMethod", String.class, int.class);
Object exampleInstance = exampleClass.getDeclaredConstructor().... |
@Override
public void onStateElection(Job job, JobState newState) {
if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job))
return;
job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String.... | @Test
void retryFilterSchedulesJobAgainIfStateIsFailedButMaxNumberOfRetriesIsNotReached() {
final Job job = aJob()
.<TestService>withJobDetails(ts -> ts.doWorkThatFails())
.withState(new FailedState("a message", new RuntimeException("boem")))
.build();
... |
public static KafkaUserModel fromCrd(KafkaUser kafkaUser,
String secretPrefix,
boolean aclsAdminApiSupported) {
KafkaUserModel result = new KafkaUserModel(kafkaUser.getMetadata().getNamespace(),
kafkaUser.getMetada... | @Test
public void testFromCrdTlsUserWith65CharTlsUsernameThrows() {
KafkaUser tooLong = new KafkaUserBuilder(tlsUser)
.editMetadata()
.withName("User-123456789012345678901234567890123456789012345678901234567890")
.endMetadata()
.build();... |
@Override
public void processItems(List<IntentData> items) {
ready = false;
delegate.execute(reduce(items));
} | @Test
public void checkAccumulator() {
MockIntentBatchDelegate delegate = new MockIntentBatchDelegate();
IntentAccumulator accumulator = new IntentAccumulator(delegate);
List<IntentData> intentDataItems = ImmutableList.of(
new IntentData(intent1, IntentState.INSTALLING,
... |
String getProviderId() {
return configuration.get(PROVIDER_ID).orElseThrow(() -> new IllegalArgumentException("Provider ID is missing"));
} | @Test
public void fail_to_get_provider_id_when_null() {
assertThatThrownBy(() -> underTest.getProviderId())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Provider ID is missing");
} |
@Override
public void execute(Exchange exchange) throws SmppException {
byte[] message = getShortMessage(exchange.getIn());
ReplaceSm replaceSm = createReplaceSmTempate(exchange);
replaceSm.setShortMessage(message);
if (log.isDebugEnabled()) {
log.debug("Sending replace... | @Test
public void execute() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "ReplaceSm");
exchange.getIn().setHeader(SmppConstants.ID, "1");
exchange.getIn().setHeader(Smpp... |
@Override
public void handle(final RoutingContext routingContext) {
routingContext.addEndHandler(ar -> {
// After the response is complete, log results here.
final int status = routingContext.request().response().getStatusCode();
if (!loggingRateLimiter.shouldLog(logger, routingContext.request()... | @Test
public void shouldProduceLogWithQuery() {
// Given:
when(response.getStatusCode()).thenReturn(200);
config = new KsqlRestConfig(
ImmutableMap.of(KsqlRestConfig.KSQL_ENDPOINT_LOGGING_LOG_QUERIES_CONFIG, true)
);
when(server.getConfig()).thenReturn(config);
loggingHandler = new Log... |
@Override
public void start() {
File dbHome = new File(getRequiredSetting(PATH_DATA.getKey()));
if (!dbHome.exists()) {
dbHome.mkdirs();
}
startServer(dbHome);
} | @Test
public void start_supports_in_memory_H2_JDBC_URL() throws IOException {
int port = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort();
settings
.setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath())
.setProperty(JDBC_URL.getKey(), "jdbc:h2:mem:sonar")
.se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.