focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
private void successResponseTrigger(final Upstream upstream) {
upstream.getSucceededElapsed().addAndGet(System.currentTimeMillis() - beginTime);
upstream.getSucceeded().incrementAndGet();
} | @Test
public void successResponseTriggerTest() throws Exception {
dividePlugin = DividePlugin.class.newInstance();
Field field = DividePlugin.class.getDeclaredField("beginTime");
field.setAccessible(true);
field.set(dividePlugin, 0L);
Method method = DividePlugin.class.getDec... |
@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 testPerQueueDisablePreemptionInheritParent() {
int[][] qData = new int[][] {
// / A E
// B C D F G H
{1000, 500, 200, 200, 100, 500, 200, 200, 100 }, // abs (guar)
{1000,1000,1000,1000,1000,1000,1000,... |
@Override
public HttpResponse handle(HttpRequest request) {
log.log(Level.FINE, () -> request.getMethod() + " " + request.getUri().toString());
try {
return switch (request.getMethod()) {
case POST -> handlePOST(request);
case GET -> handleGET(request);
... | @Test
public void testResponse() throws IOException {
final String message = "failed";
HttpHandler httpHandler = new HttpTestHandler(new InvalidApplicationException(message));
HttpResponse response = httpHandler.handle(HttpRequest.createTestRequest("foo", com.yahoo.jdisc.http.HttpRequest.Met... |
static double estimatePixelCount(final Image image, final double widthOverHeight) {
if (image.getHeight() == HEIGHT_UNKNOWN) {
if (image.getWidth() == WIDTH_UNKNOWN) {
// images whose size is completely unknown will be in their own subgroups, so
// any one of them wil... | @Test
public void testEstimatePixelCountAllKnown() {
assertEquals(20000.0, estimatePixelCount(img(100, 200), 1.0), 0.0);
assertEquals(20000.0, estimatePixelCount(img(100, 200), 12.0), 0.0);
assertEquals( 100.0, estimatePixelCount(img(100, 1), 12.0), 0.0);
assertEquals( 100.0, es... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<Path>();
// At least one entry successfully parsed
boolean success = false;
// Call hook for those im... | @Test
public void testParseMD1766() throws Exception {
final List<String> lines = new FTPStatListService(null, null).parse(
211, new String[]{
"lrwxrwxrwx 1 sss 7 Nov 2 2015 bin",
"lrwxrwxrwx 1 sss 6 Nov 2 2015 home1",
"... |
@Override
public void verifyCompatibility(WindowFn<?, ?> other) throws IncompatibleWindowException {
if (!this.isCompatible(other)) {
throw new IncompatibleWindowException(
other,
String.format(
"Only %s objects with the same size and offset are compatible.",
... | @Test
public void testVerifyCompatibility() throws IncompatibleWindowException {
FixedWindows.of(Duration.millis(10)).verifyCompatibility(FixedWindows.of(Duration.millis(10)));
thrown.expect(IncompatibleWindowException.class);
FixedWindows.of(Duration.millis(10)).verifyCompatibility(FixedWindows.of(Durati... |
@Override
protected Function3<EntityColumnMapping, Object[], Map<String, Object>, Object> compile(String sql) {
StringBuilder builder = new StringBuilder(sql.length());
int argIndex = 0;
for (int i = 0; i < sql.length(); i++) {
char c = sql.charAt(i);
if (c == '?') {... | @Test
void testSnake() {
SpelSqlExpressionInvoker invoker = new SpelSqlExpressionInvoker();
EntityColumnMapping mapping = Mockito.mock(EntityColumnMapping.class);
{
Function3<EntityColumnMapping,Object[], Map<String, Object>, Object> func = invoker.compile("count_value + ?");
... |
public void clearQueryContext() {
queryContext = null;
} | @Test
void assertClearQueryContext() {
connectionSession.setQueryContext(mock(QueryContext.class));
assertNotNull(connectionSession.getQueryContext());
connectionSession.clearQueryContext();
assertNull(connectionSession.getQueryContext());
} |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldSupportInsertIntoWithSchemaInferenceMatchAndCustomMetadata() throws Exception {
// Given:
when(srClient.getLatestSchemaMetadata(Mockito.any()))
.thenReturn(new SchemaMetadata(1, 1, ""));
when(srClient.getSchemaById(1))
.thenReturn(new AvroSchema(AVRO_RAW_ONE_KEY_SCH... |
@Override
public Serde<List<?>> getSerde(
final PersistenceSchema schema,
final Map<String, String> formatProperties,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final boolean isKey) {
FormatProperties.validateProperties(name(), formatProperties... | @Test(expected = IllegalArgumentException.class)
public void shouldThrowOnUnsupportedFeatures() {
// Given:
when(schema.features()).thenReturn(SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES));
// When:
format.getSerde(schema, formatProps, ksqlConfig, srClientFactory, false);
} |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testListOffsetUpdateEpoch() {
buildFetcher();
// Set up metadata with leaderEpoch=1
subscriptions.assignFromUser(singleton(tp0));
MetadataResponse metadataWithLeaderEpochs = RequestTestUtils.metadataUpdateWithIds(
"kafka-cluster", 1, Collections.emp... |
@Udf
public int field(
@UdfParameter final String str,
@UdfParameter final String... args
) {
if (str == null || args == null) {
return 0;
}
for (int i = 0; i < args.length; i++) {
if (str.equals(args[i])) {
return i + 1;
}
}
return 0;
} | @Test
public void shouldNotFindIfNoArgs() {
// When:
final int pos = field.field("missing");
// Then:
assertThat(pos, equalTo(0));
} |
@Override
public void apply(final Record<Windowed<KOut>, Change<VOut>> record) {
@SuppressWarnings("rawtypes") final ProcessorNode prev = context.currentNode();
context.setCurrentNode(myNode);
try {
context.forward(record.withTimestamp(record.key().window().end()));
} fin... | @Test
public void shouldForwardKeyNewValueOldValueAndTimestamp() {
@SuppressWarnings("unchecked")
final InternalProcessorContext<Windowed<String>, Change<String>> context = mock(InternalProcessorContext.class);
doNothing().when(context).forward(
new Record<>(
new ... |
public static Combine.BinaryCombineIntegerFn ofIntegers() {
return new SumIntegerFn();
} | @Test
public void testSumIntegerFn() {
testCombineFn(Sum.ofIntegers(), Lists.newArrayList(1, 2, 3, 4), 10);
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldThrowInconsistentKeySchemaTypeExceptionWithOverrideSchema() {
// Given:
final SchemaAndId schemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCHEMA, 1);
givenStatement("CREATE STREAM source (id int key, f1 varchar) "
+ "WITH ("
+ "kafka_topic='expectedName',... |
@Override
public UUID generateId() {
long counterValue = counter.incrementAndGet();
if (counterValue == MAX_COUNTER_VALUE) {
throw new CucumberException(
"Out of " + IncrementingUuidGenerator.class.getSimpleName() +
" capacity. Please generate usin... | @Test
void different_classloaderId_leads_to_different_uuid_when_ignoring_epoch_time() {
// Given the two generator have the different classloaderId
UuidGenerator generator1 = getUuidGeneratorFromOtherClassloader(1);
UuidGenerator generator2 = getUuidGeneratorFromOtherClassloader(2);
... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
return FEELFnResult.ofResult( BigDecimal.valueOf( list.size() ) );
} | @Test
void invokeParamListNull() {
FunctionTestUtil.assertResultError(countFunction.invoke((List) null), InvalidParametersEvent.class);
} |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
return -Math.log(1 - p) / lambda;
} | @Test
public void testQuantile() {
System.out.println("quantile");
ExponentialDistribution instance = new ExponentialDistribution(2.0);
instance.rand();
assertEquals(0.05268026, instance.quantile(0.1), 1E-7);
assertEquals(0.1783375, instance.quantile(0.3), 1E-7);
asse... |
@VisibleForTesting
static List<Tuple2<ConfigGroup, String>> generateTablesForClass(
Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) {
ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class);
List<OptionWithMetaInfo> allOptions = selectOptions... | @Test
void testCreatingDescription() {
final String expectedTable =
"<table class=\"configuration table table-bordered\">\n"
+ " <thead>\n"
+ " <tr>\n"
+ " <th class=\"text-left\" style=\"width: 20%\... |
public static Event[] fromJson(final String json) throws IOException {
return fromJson(json, BasicEventFactory.INSTANCE);
} | @Test
public void testFromJsonWithBlankString() throws Exception {
Event[] events = Event.fromJson(" ");
assertEquals(0, events.length);
} |
@Override
public void handleRequest(HttpServerExchange httpServerExchange) {
if (!httpServerExchange.getRequestMethod().equals(HttpString.tryFromString("GET"))) {
httpServerExchange.setStatusCode(HTTP_METHOD_NOT_ALLOWED);
httpServerExchange.getResponseSender().send("");
} else {
httpServerEx... | @Test
void methodNotAllowed() {
// when
var httpServerExchange = mock(HttpServerExchange.class);
var sender = mock(Sender.class);
when(httpServerExchange.getResponseSender()).thenReturn(sender);
when(httpServerExchange.getRequestMethod()).thenReturn(HttpString.tryFromString("POST"));
// give... |
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
} | @Test
public void testSizeCallbackIsCalledSynchronouslyIfLayoutParamsConcreteSizeSet() {
int dimens = 444;
LayoutParams layoutParams = new FrameLayout.LayoutParams(dimens, dimens);
view.setLayoutParams(layoutParams);
view.requestLayout();
target.getSize(cb);
verify(cb).onSizeReady(eq(dimens)... |
public MessageType convert(Descriptors.Descriptor descriptor) {
// Remember classes seen with depths to avoid cycles.
int depth = 0;
ImmutableSetMultimap<String, Integer> seen = ImmutableSetMultimap.of(descriptor.getFullName(), depth);
LOG.trace("convert:\n{}", descriptor.toProto());
MessageType mes... | @Test
public void testDeepRecursion() {
// The general idea is to test the fanout of the schema.
// TODO: figured out closed forms of the binary tree and struct series.
long expectedBinaryTreeSize = 4;
long expectedStructSize = 7;
for (int i = 0; i < 10; ++i) {
MessageType deepSchema = new P... |
public static boolean isNotEmpty(final Object[] array) {
return !isEmpty(array);
} | @Test
void isNotEmpty() {
assertFalse(ArrayUtils.isNotEmpty(null));
assertFalse(ArrayUtils.isNotEmpty(new Object[0]));
assertTrue(ArrayUtils.isNotEmpty(new Object[] {"abc"}));
} |
FeatureControlManager featureControl() {
return featureControl;
} | @Test
public void testUpgradeMigrationStateFrom34() throws Exception {
try (LocalLogManagerTestEnv logEnv = new LocalLogManagerTestEnv.Builder(1).build()) {
// In 3.4, we only wrote a PRE_MIGRATION to the log. In that software version, we defined this
// as enum value 1. In 3.5+ soft... |
@Override
public boolean supportsAlterTableWithAddColumn() {
return false;
} | @Test
void assertSupportsAlterTableWithAddColumn() {
assertFalse(metaData.supportsAlterTableWithAddColumn());
} |
public static <P> Builder<P> newBuilder() {
return new Builder<P>();
} | @Test void putAllRules() {
Matcher<Void> one = v -> false;
Matcher<Void> two = v -> true;
Matcher<Void> three = v -> Boolean.FALSE;
Matcher<Void> four = v -> Boolean.TRUE;
ParameterizedSampler<Void> base = ParameterizedSampler.<Void>newBuilder()
.putRule(one, Sampler.ALWAYS_SAMPLE)
.putR... |
public void checkForUpgradeAndExtraProperties() throws IOException {
if (upgradesEnabled()) {
checkForUpgradeAndExtraProperties(systemEnvironment.getAgentMd5(), systemEnvironment.getGivenAgentLauncherMd5(),
systemEnvironment.getAgentPluginsMd5(), systemEnvironment.getTfsImplMd5()... | @Test
void checkForUpgradeShouldNotKillAgentIfAllDownloadsAreCompatible() throws Exception {
setupForNoChangesToMD5();
agentUpgradeService.checkForUpgradeAndExtraProperties();
verify(jvmExitter, never()).jvmExit(anyString(), anyString(), anyString());
} |
@Override
public Encoder getMapValueEncoder() {
return encoder;
} | @Test
public void shouldSerializeTheStringCorrectly() throws Exception {
assertThat(mapCodec.getMapValueEncoder().encode("foo").toString(CharsetUtil.UTF_8))
.isEqualTo("\"foo\"");
} |
public static Collection<WhereSegment> getSubqueryWhereSegments(final SelectStatement selectStatement) {
Collection<WhereSegment> result = new LinkedList<>();
for (SubquerySegment each : SubqueryExtractUtils.getSubquerySegments(selectStatement)) {
each.getSelect().getWhere().ifPresent(result... | @Test
void assertGetWhereSegmentsFromSubQueryJoin() {
JoinTableSegment joinTableSegment = new JoinTableSegment();
joinTableSegment.setLeft(new SimpleTableSegment(new TableNameSegment(37, 39, new IdentifierValue("t_order"))));
joinTableSegment.setRight(new SimpleTableSegment(new TableNameSegm... |
@Override
public PurgeExecutions.Output run(RunContext runContext) throws Exception {
ExecutionService executionService = ((DefaultRunContext)runContext).getApplicationContext().getBean(ExecutionService.class);
FlowService flowService = ((DefaultRunContext)runContext).getApplicationContext().getBean... | @Test
void run() throws Exception {
// create an execution to delete
String namespace = "run.namespace";
String flowId = "run-flow-id";
var execution = Execution.builder()
.id(IdUtils.create())
.namespace(namespace)
.flowId(flowId)
.sta... |
@Override
public void removeProvider(ProviderGroup providerGroup) {
if (ProviderHelper.isEmpty(providerGroup)) {
return;
}
wLock.lock();
try {
getProviderGroup(providerGroup.getName()).removeAll(providerGroup.getProviderInfos());
} finally {
... | @Test
public void removeProvider() throws Exception {
SingleGroupAddressHolder addressHolder = new SingleGroupAddressHolder(null);
addressHolder.addProvider(new ProviderGroup("xxx", Arrays.asList(
ProviderHelper.toProviderInfo("127.0.0.1:12200"),
ProviderHelper.toProviderInfo... |
protected boolean init() {
return true;
} | @Test
public void testInit() {
assertEquals( true, avroInput.init() );
} |
@SafeVarargs
public static Optional<Predicate<Throwable>> createExceptionsPredicate(
Predicate<Throwable> exceptionPredicate,
Class<? extends Throwable>... exceptions) {
return PredicateCreator.createExceptionsPredicate(exceptions)
.map(predicate -> exceptionPredicate == null ? p... | @Test
public void buildRecordExceptionsPredicate() {
Predicate<Throwable> predicate = PredicateCreator
.createExceptionsPredicate(RuntimeException.class, IOException.class)
.orElseThrow();
then(predicate.test(new RuntimeException())).isTrue();
then(predicate.test(new... |
public StepInstanceActionResponse bypassStepDependencies(
WorkflowInstance instance, String stepId, User user, boolean blocking) {
validateStepId(instance, stepId, Actions.StepInstanceAction.BYPASS_STEP_DEPENDENCIES);
StepInstance stepInstance =
getStepInstanceAndValidateBypassStepDependencyCondit... | @Test
public void testBypassSignalDependencies() {
stepInstance.getRuntimeState().setStatus(StepInstance.Status.WAITING_FOR_SIGNALS);
stepInstance.getStepRetry().setRetryable(false);
((TypedStep) stepInstance.getDefinition()).setFailureMode(FailureMode.FAIL_AFTER_RUNNING);
stepInstanceDao.insertOrUpse... |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testSetMyCommandsWithEmptyScope() {
SetMyCommands setMyCommands = SetMyCommands
.builder()
.command(BotCommand.builder().command("test").description("Test description").build())
.languageCode("en")
.build();
assertEqua... |
public static String trimSemicolon(final String sql) {
return sql.endsWith(SQL_END) ? sql.substring(0, sql.length() - 1) : sql;
} | @Test
void assertTrimSemiColon() {
assertThat(SQLUtils.trimSemicolon("SHOW DATABASES;"), is("SHOW DATABASES"));
assertThat(SQLUtils.trimSemicolon("SHOW DATABASES"), is("SHOW DATABASES"));
} |
@Override
public int getOrder() {
return PluginEnum.KEY_AUTH.getCode();
} | @Test
public void testGetOrder() {
assertEquals(PluginEnum.KEY_AUTH.getCode(), keyAuthPlugin.getOrder());
} |
public static <T> AsIterable<T> asIterable() {
return new AsIterable<>();
} | @Test
@Category(ValidatesRunner.class)
public void testEmptyIterableSideInput() throws Exception {
final PCollectionView<Iterable<Integer>> view =
pipeline.apply("CreateEmptyView", Create.empty(VarIntCoder.of())).apply(View.asIterable());
PCollection<Integer> results =
pipeline
... |
public static int removeConsecutiveDuplicates(int[] arr, int end) {
int curr = 0;
for (int i = 1; i < end; ++i) {
if (arr[i] != arr[curr])
arr[++curr] = arr[i];
}
return curr + 1;
} | @Test
public void removeConsecutiveDuplicates() {
int[] arr = new int[]{3, 3, 4, 2, 1, -3, -3, 9, 3, 6, 6, 7, 7};
assertEquals(9, ArrayUtil.removeConsecutiveDuplicates(arr, arr.length));
// note that only the first 9 elements should be considered the 'valid' range
assertEquals(IntArr... |
public static final String[] getVariableNames( VariableSpace space ) {
String[] variableNames = space.listVariables();
for ( int i = 0; i < variableNames.length; i++ ) {
for ( int j = 0; j < Const.DEPRECATED_VARIABLES.length; j++ ) {
if ( variableNames[i].equals( Const.DEPRECATED_VARIABLES[j] ) ) ... | @Test
public void testGetVariableNames() {
Assert.assertTrue( Const.DEPRECATED_VARIABLES.length > 0 );
String deprecatedVariableName = Const.DEPRECATED_VARIABLES[0];
String deprecatedPrefix = Const.getDeprecatedPrefix();
String[] variableNames = new String[] { "test_variable1", "test_variable2", depr... |
@Override
public void run() {
updateElasticSearchHealthStatus();
updateFileSystemMetrics();
} | @Test
public void when_elasticsearch_down_status_is_updated_to_red() {
ClusterHealthResponse clusterHealthResponse = new ClusterHealthResponse();
clusterHealthResponse.setStatus(ClusterHealthStatus.RED);
when(esClient.clusterHealth(any())).thenReturn(clusterHealthResponse);
underTest.run();
veri... |
@Override
public boolean contains(String clientId) {
return clients.containsKey(clientId);
} | @Test
void testContainsEphemeralIpPortId() {
assertTrue(ephemeralIpPortClientManager.contains(ephemeralIpPortId));
assertTrue(ephemeralIpPortClientManager.contains(syncedClientId));
String unUsedClientId = "127.0.0.1:8888#true";
assertFalse(ephemeralIpPortClientManager.contains(unUse... |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeTime() throws SQLException {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("INSERT");
tableData.setColumnsName(new String[]{"data"});
tableData.setColumnsType(new String[]{"time without time zone... |
@InvokeOnHeader(Web3jConstants.ETH_ACCOUNTS)
void ethAccounts(Message message) throws IOException {
Request<?, EthAccounts> request = web3j.ethAccounts();
setRequestId(message, request);
EthAccounts response = request.send();
message.setBody(response.getAccounts());
boolean h... | @Test
public void ethAccountsTest() throws Exception {
EthAccounts response = Mockito.mock(EthAccounts.class);
Mockito.when(mockWeb3j.ethAccounts()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getAccounts()).thenReturn(Collections.emp... |
@Override
public void accept(ICOSVisitor visitor) throws IOException
{
visitor.visitFromBoolean(this);
} | @Override
@Test
void testAccept()
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
COSWriter visitor = new COSWriter(outStream);
int index = 0;
try
{
cosBooleanTrue.accept(visitor);
testByteArrays(String.valueOf(cosBooleanTrue).... |
public int capacity()
{
return capacity;
} | @Test
void shouldCalculateCapacityForBuffer()
{
assertThat(ringBuffer.capacity(), is(CAPACITY));
} |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestStartPosition()
{
internalEncodeLogHeader(buffer, 0, 1000, 1000, () -> 500_000_000L);
final StartPositionRequestEncoder requestEncoder = new StartPositionRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
.co... |
public void logSlowQuery(final Statement statement, final long startTimeNanos, final JdbcSessionContext context) {
if ( logSlowQuery < 1 ) {
return;
}
if ( startTimeNanos <= 0 ) {
throw new IllegalArgumentException( "startTimeNanos [" + startTimeNanos + "] should be greater than 0" );
}
final long quer... | @Test
public void testLogSlowQueryFromStatementWhenLoggingEnabled() {
long logSlowQueryThresholdMillis = 300L;
SqlStatementLogger sqlStatementLogger = new SqlStatementLogger(
false,
false,
false,
logSlowQueryThresholdMillis
);
AtomicInteger callCounterToString = new AtomicInteger();
Statement... |
@Override
public String getDisplayType() {
return "Corporate EDS Login";
} | @Test
public void testGetDisplayType() {
//GIVEN
CorporateEdsLoginAuthenticatorFactory factory = new CorporateEdsLoginAuthenticatorFactory();
//WHEN
String type = factory.getDisplayType();
//THEN
assertEquals("The display type should be Corporate EDS Login", "Corpor... |
public boolean isNew(Component component, DefaultIssue issue) {
if (analysisMetadataHolder.isPullRequest()) {
return true;
}
if (periodHolder.hasPeriod()) {
if (periodHolder.hasPeriodDate()) {
return periodHolder.getPeriod().isOnPeriod(issue.creationDate());
}
if (isOnBranc... | @Test
public void isNew_returns_false_if_period_without_date() {
periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", null));
assertThat(newIssueClassifier.isNew(mock(Component.class), mock(DefaultIssue.class))).isFalse();
} |
public ServerInfo getServerInfo(URI server)
{
HttpUrl url = HttpUrl.get(server);
if (url == null) {
throw new ClientException("Invalid server URL: " + server);
}
url = url.newBuilder().encodedPath("/v1/info").build();
Request request = new Request.Builder().url(u... | @Test
public void testGetServerInfo()
throws Exception
{
ServerInfo expected = new ServerInfo(UNKNOWN, "test", true, false, Optional.of(Duration.valueOf("2m")));
server.enqueue(new MockResponse()
.addHeader(CONTENT_TYPE, "application/json")
.setBody(S... |
public static void updateKeyForBlobStore(Map<String, Object> conf, BlobStore blobStore, CuratorFramework zkClient, String key,
NimbusInfo nimbusDetails) {
try {
// Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForB... | @Test
public void testUpdateKeyForBlobStore_hostsMatch() {
zkClientBuilder.withExists(BLOBSTORE_KEY, true);
zkClientBuilder.withGetChildren(BLOBSTORE_KEY, "localhost:1111-1");
when(nimbusDetails.getHost()).thenReturn("localhost");
BlobStoreUtils.updateKeyForBlobStore(conf, blobStore,... |
public static WorkflowRuntimeOverview computeOverview(
ObjectMapper objectMapper,
WorkflowSummary summary,
WorkflowRollupOverview rollupBase,
Map<String, Task> realTaskMap) {
Map<String, StepRuntimeState> states =
realTaskMap.entrySet().stream()
.collect(
... | @Test
public void testComputeOverview() throws Exception {
WorkflowSummary workflowSummary =
loadObject("fixtures/parameters/sample-wf-summary-params.json", WorkflowSummary.class);
Task t = new Task();
t.setTaskType(Constants.MAESTRO_TASK_NAME);
t.setSeq(1);
Map<String, Object> summary = n... |
Plugin create(Options.Plugin plugin) {
try {
return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument());
} catch (IOException | URISyntaxException e) {
throw new CucumberException(e);
}
} | @Test
void fails_to_instantiates_html_plugin_with_dir_arg() {
PluginOption option = parse("html:" + tmp.toAbsolutePath());
assertThrows(IllegalArgumentException.class, () -> fc.create(option));
} |
public static Class<?> getAssistInterface(Object proxyBean)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException,
NoSuchMethodException, InvocationTargetException {
if (proxyBean == null) {
return null;
}
if (!isDubboProxyNa... | @Test
public void testGetAssistInterfaceForNull() throws NoSuchFieldException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
assertNull(DubboUtil.getAssistInterface(null));
} |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
AvroSchema schema = message.getExchange().getProperty(SchemaHelper.CONTENT_SCHEMA, AvroSchema.class);
if (schema == null) {
throw new CamelExecutionException("Missing proper avro schema for data type ... | @Test
void shouldHandlePojo() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
AvroSchema avroSchema
= Avro.mapper().schemaFrom(AvroBinaryDataTypeTransformerTest.class.getResourceAsStream("Person.avsc"));
exchange.setProperty(SchemaHelper.CONTENT_SCH... |
@Override
public Stream<FileSlice> getLatestFileSliceInRange(List<String> commitsToReturn) {
return execute(commitsToReturn, preferredView::getLatestFileSliceInRange, (commits) -> getSecondaryView().getLatestFileSliceInRange(commits));
} | @Test
public void testGetLatestFileSliceInRange() {
Stream<FileSlice> actual;
Stream<FileSlice> expected = testFileSliceStream;
List<String> commitsToReturn = Collections.singletonList("/table2");
when(primary.getLatestFileSliceInRange(commitsToReturn)).thenReturn(testFileSliceStream);
actual = f... |
@Override
public MavenArtifact searchSha1(String sha1) throws IOException {
if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) {
throw new IllegalArgumentException("Invalid SHA1 format");
}
final URL url = new URL(rootURL, String.format("identify/sha1/%s",
s... | @Test
@Ignore
public void testValidSha1() throws Exception {
MavenArtifact ma = searcher.searchSha1("9977a8d04e75609cf01badc4eb6a9c7198c4c5ea");
assertEquals("Incorrect group", "org.apache.maven.plugins", ma.getGroupId());
assertEquals("Incorrect artifact", "maven-compiler-plugin", ma.ge... |
public int getInt(Object obj) {
return Platform.UNSAFE.getInt(obj, fieldOffset);
} | @Test
public void testRepeatedFields() {
assertEquals(new UnsafeFieldAccessor(A.class, "f1").getInt(new A()), 1);
assertEquals(new UnsafeFieldAccessor(A.class, "f2").getInt(new A()), 2);
assertEquals(new UnsafeFieldAccessor(B.class, "f1").getInt(new B()), 2);
assertEquals(new UnsafeFieldAccessor(B.cla... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final StoregateApiClient client = session.getClient();
final MoveFileRequest move = new Mov... | @Test
public void testMoveOverride() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()),
... |
public static ForIteration getForIteration(EvaluationContext ctx, String name, Object start, Object end) {
validateValues(ctx, start, end);
if (start instanceof BigDecimal bigDecimal) {
return new ForIteration(name, bigDecimal, (BigDecimal) end);
}
if (start instanceof LocalD... | @Test
void getForIterationNotValidTest() {
try {
getForIteration(ctx, "iteration", "NOT", "VALID");
} catch (Exception e) {
assertTrue(e instanceof EndpointOfRangeNotValidTypeException);
final ArgumentCaptor<FEELEvent> captor = ArgumentCaptor.forClass(FEELEvent.cl... |
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filte... | @Test(description = "it should filter away internal model properties")
public void filterAwayInternalModelProperties() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final InternalModelPropertiesRemoverFilter filter = new InternalModelPropertiesRemoverFilter();
fina... |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(co... | @Test
void assertConvertDateValueError() {
assertThrows(UnsupportedDataTypeConversionException.class, () -> ResultSetUtils.convertValue(new Date(), int.class));
} |
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public KsqlConfig getKsqlConfig() {
return ksqlConfig;
} | @Test
public void shouldIgnoreRecordsWithDifferentKeyWithinPoll() {
// Given:
addPollResult(
"foo", "val".getBytes(StandardCharsets.UTF_8),
KafkaConfigStore.CONFIG_MSG_KEY, serializer.serialize("", savedProperties)
);
expectRead(consumerBefore);
// When:
getKsqlConfig();
... |
public Optional<UserDto> authenticate(HttpRequest request) {
return extractCredentialsFromHeader(request)
.flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request)));
} | @Test
public void fail_to_authenticate_when_no_login() {
when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + toBase64(":" + A_PASSWORD));
assertThatThrownBy(() -> underTest.authenticate(request))
.isInstanceOf(AuthenticationException.class)
.hasFieldOrPropertyWithValue("source", S... |
@Override
public void updateIndices(SegmentDirectory.Writer segmentWriter)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter);
if (columnOperationsMap.isEmpty()) {
return;
}
for (Map.Entry<String, List<Operation>> entry : columnOperation... | @Test
public void testDisableForwardIndexForInvertedIndexDisabledColumns()
throws Exception {
Set<String> forwardIndexDisabledColumns = new HashSet<>(SV_FORWARD_INDEX_DISABLED_COLUMNS);
forwardIndexDisabledColumns.addAll(MV_FORWARD_INDEX_DISABLED_COLUMNS);
forwardIndexDisabledColumns.addAll(MV_FORWA... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseSimpleDateRangeWithoutYearAndDay() throws ParseException {
DateRange dateRange = dateRangeParser.getRange("Jul-Aug");
assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.JUNE, 9)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.JULY, 10)));
... |
public static <I> Builder<I> foreach(Iterable<I> items) {
return new Builder<>(requireNonNull(items, "items"));
} | @Test
public void testFailSlowCallRevertSuppressed() throws Throwable {
assertFailed(builder()
.suppressExceptions()
.revertWith(reverter)
.onFailure(failures),
failingTask);
failingTask.assertInvokedAtLeast("success", FAILPOINT);
// all committed were reverted
... |
void fetchAndRunCommands() {
lastPollTime.set(clock.instant());
final List<QueuedCommand> commands = commandStore.getNewCommands(NEW_CMDS_TIMEOUT);
if (commands.isEmpty()) {
if (!commandTopicExists.get()) {
commandTopicDeleted = true;
}
return;
}
final List<QueuedCommand> ... | @Test
public void shouldRetryOnException() {
// Given:
givenQueuedCommands(queuedCommand1, queuedCommand2);
doThrow(new RuntimeException())
.doThrow(new RuntimeException())
.doNothing().when(statementExecutor).handleStatement(queuedCommand2);
// When:
commandRunner.fetchAndRunComm... |
public CompletionStage<Void> migrate(MigrationSet set) {
InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id()));
CompletionStage<Void> lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor);
return lockStage.thenCom... | @Test
public void testBasic() {
Migration m1 = () -> Arrays.asList(v1opA, v1opB);
Migration m2 = () -> Collections.singletonList(v2op);
Migration m3 = () -> Collections.singletonList(v3op);
MigrationSet migrationSet = MigrationSet.build("1", Arrays.asList(m1, m2, m3));
compl... |
void upsertSummary(CommittableSummary<CommT> summary) {
SubtaskCommittableManager<CommT> existing =
subtasksCommittableManagers.putIfAbsent(
summary.getSubtaskId(),
new SubtaskCommittableManager<>(
summary.getNumberO... | @Test
void testUpdateCommittableSummary() {
final CheckpointCommittableManagerImpl<Integer> checkpointCommittables =
new CheckpointCommittableManagerImpl<>(1, 1, 1L, METRIC_GROUP);
checkpointCommittables.upsertSummary(new CommittableSummary<>(1, 1, 1L, 1, 0, 0));
assertThatTh... |
@Override
public void run() {
doHealthCheck();
} | @Test
void testRunHealthyInstanceWithExpire() {
injectInstance(true, 0);
when(globalConfig.isExpireInstance()).thenReturn(true);
beatCheckTask.run();
assertTrue(client.getAllInstancePublishInfo().isEmpty());
} |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseReverseDateRange() throws ParseException {
DateRange dateRange = dateRangeParser.getRange("2014 Aug 14-2015 Mar 10");
assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 13)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 14)));
... |
List<CSVResult> sniff(Reader reader) throws IOException {
if (!reader.markSupported()) {
reader = new BufferedReader(reader);
}
List<CSVResult> ret = new ArrayList<>();
for (char delimiter : delimiters) {
reader.mark(markLimit);
try {
C... | @Test
public void testAllowWhiteSpacesAroundAQuote() throws Exception {
List<CSVResult> results =
sniff(DELIMITERS, ALLOW_SPACES_BEFORE_QUOTE, StandardCharsets.UTF_8);
assertEquals(4, results.size());
assertEquals(Character.valueOf(','), results.get(0).getDelimiter());
... |
private DataSource createDataSource(
SourceDef sourceDef, StreamExecutionEnvironment env, Configuration pipelineConfig) {
// Search the data source factory
DataSourceFactory sourceFactory =
FactoryDiscoveryUtils.getFactoryByIdentifier(
sourceDef.getTyp... | @Test
void testCreateDataSourceFromSourceDef() {
SourceDef sourceDef =
new SourceDef(
"data-source-factory-1",
"source-database",
Configuration.fromMap(
ImmutableMap.<String, String>builde... |
@Override
public boolean accept(Path path) {
if (engineContext == null) {
this.engineContext = new HoodieLocalEngineContext(this.conf);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Checking acceptance for path " + path);
}
Path folder = null;
try {
if (storage == null) {
... | @Test
public void testNonHoodiePaths() throws IOException {
java.nio.file.Path path1 = Paths.get(basePath, "nonhoodiefolder");
Files.createDirectories(path1);
assertTrue(pathFilter.accept(new Path(path1.toUri())));
java.nio.file.Path path2 = Paths.get(basePath, "nonhoodiefolder/somefile");
Files.... |
@Override
public TransformResultMetadata getResultMetadata() {
return _resultMetadata;
} | @Test
public void testArrayElementAtDouble() {
Random rand = new Random();
int index = rand.nextInt(MAX_NUM_MULTI_VALUES);
ExpressionContext expression = RequestContextUtils.getExpression(
String.format("array_element_at_double(%s, %d)", DOUBLE_MV_COLUMN, index + 1));
TransformFunction transfo... |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepWithBigInteger() {
Object result = Rubyfier.deep(RubyUtil.RUBY, new BigInteger("1"));
assertEquals(RubyBignum.class, result.getClass());
assertEquals(1L, ((RubyBignum)result).getLongValue());
} |
@Override
public DirectPipelineResult run(Pipeline pipeline) {
try {
options =
MAPPER
.readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class)
.as(DirectOptions.class);
} catch (IOException e) {
throw new IllegalArgumentException(
"Pipeli... | @Test
public void wordCountShouldSucceed() throws Throwable {
Pipeline p = getPipeline();
PCollection<KV<String, Long>> counts =
p.apply(Create.of("foo", "bar", "foo", "baz", "bar", "foo"))
.apply(
MapElements.via(
new SimpleFunction<String, String>() {... |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void removed_exhaustion_in_feed_block_resource_set_emits_node_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWith(
"we're c... |
@Override
public BasicTypeDefine<MysqlType> reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.<MysqlType>builder()
.name(column.getName())
.nullable(column.isNullable())
.comment... | @Test
public void testReconvertByte() {
Column column = PhysicalColumn.builder().name("test").dataType(BasicType.BYTE_TYPE).build();
BasicTypeDefine<MysqlType> typeDefine =
MySqlTypeConverter.DEFAULT_INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeD... |
static String computeDetailsAsString(SearchRequest searchRequest) {
StringBuilder message = new StringBuilder();
message.append(String.format("ES search request '%s'", searchRequest));
if (searchRequest.indices().length > 0) {
message.append(String.format(ON_INDICES_MESSAGE, Arrays.toString(searchRequ... | @Test
public void should_format_IndicesStats() {
assertThat(EsRequestDetails.computeDetailsAsString("index-1", "index-2"))
.isEqualTo("ES indices stats request on indices 'index-1,index-2'");
} |
protected static boolean isMatchingMetricName(Meter meter, String metricName) {
return meter.getId().getName().equals(metricName);
} | @Test
void matchingMetricNameReturnsTrue() {
assertTrue(MetricsUtils.isMatchingMetricName(meter, "testMetric"));
} |
@Override public final int compareTo(VirtualFile o) {
return getName().compareToIgnoreCase(o.getName());
} | @Test
public void testCompareTo_Same() throws IOException {
String parentFolder = "parentFolder";
File parentFile = tmp.newFolder(parentFolder);
String child1 = "child1";
File childFile1 = new File(parentFile, child1);
VirtualFile vf1 = new VirtualFileMinimalImplementation(ch... |
public static String encodingParams(Map<String, String> params, String encoding)
throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
if (null == params || params.isEmpty()) {
return null;
}
for (Map.Entry<String, String> entry : params.en... | @Test
void testEncodingParamsList() throws UnsupportedEncodingException {
List<String> params = new LinkedList<>();
params.add("a");
params.add("");
params.add("b");
params.add("x");
params.add("uriChar");
params.add("=");
params.add("chinese");
... |
protected String getIdentifierKey(String... params) {
String prefix = KeyTypeEnum.UNIQUE_KEY.build(serviceInterface, version, group, side);
return KeyTypeEnum.UNIQUE_KEY.build(prefix, params);
} | @Test
void getIdentifierKey() {
String identifierKey = baseServiceMetadataIdentifier.getIdentifierKey("appName");
Assertions.assertEquals(identifierKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName");
} |
@Override
public Integer doCall() throws Exception {
JsonObject pluginConfig = loadConfig();
JsonObject plugins = pluginConfig.getMap("plugins");
Optional<PluginType> camelPlugin = PluginType.findByName(name);
if (camelPlugin.isPresent()) {
if (command == null) {
... | @Test
public void shouldUseMavenGAV() throws Exception {
PluginAdd command = new PluginAdd(new CamelJBangMain().withPrinter(printer));
command.name = "foo-plugin";
command.command = "foo";
command.gav = "org.apache.camel:foo-plugin:1.0.0";
command.doCall();
Assertion... |
@SuppressWarnings("OptionalGetWithoutIsPresent")
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListConnectors> configuredStatement,
final SessionProperties sessionProperties,
final KsqlExecutionContext ksqlExecutionContext,
final ServiceContext serviceContext
) {... | @Test
public void shouldLabelConnectorsWithNoRunningTasksAsWarning() {
// Given:
when(connectClient.status("connector"))
.thenReturn(ConnectResponse.success(STATUS_WARNING, HttpStatus.SC_OK));
when(connectClient.connectors())
.thenReturn(ConnectResponse.success(ImmutableList.of("connector"... |
@Override
public Comparator<? super E> comparator() {
return underlying().comparator();
} | @Test
public void testDelegationOfComparator() {
TreePSet<Integer> testSet = TreePSet.from(Arrays.asList(3, 4, 5));
new PCollectionsTreeSetWrapperDelegationChecker<>()
.defineMockConfigurationForFunctionInvocation(TreePSet::comparator, testSet.comparator())
.defineWra... |
@Override
public Num getValue(int index) {
return values.get(index);
} | @Test
public void cashFlowValueWithTwoPositionsAndLongTimeWithoutTrades() {
BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 4d, 8d, 16d, 32d);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(1, sampleBarSeries),
Trade.sellAt(2, sampleBarSeries), Tra... |
int startReconfiguration(final String nodeType, final String address)
throws IOException, InterruptedException {
return startReconfigurationUtil(nodeType, address, System.out, System.err);
} | @Test(timeout = 30000)
public void testNameNodeGetReconfigurationStatus() throws IOException,
InterruptedException, TimeoutException {
ReconfigurationUtil ru = mock(ReconfigurationUtil.class);
namenode.setReconfigurationUtil(ru);
final String address = namenode.getHostAndPort();
List<Reconfigur... |
@Override
public void alterTable(ConnectContext context, AlterTableStmt stmt) throws UserException {
String dbName = stmt.getDbName();
String tableName = stmt.getTableName();
org.apache.iceberg.Table table = icebergCatalog.getTable(dbName, tableName);
if (table == null) {
... | @Test
public void testAlterTable(@Mocked IcebergHiveCatalog icebergHiveCatalog) throws UserException {
IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_ENVIRONMENT, icebergHiveCatalog,
Executors.newSingleThreadExecutor(), Executors.newSingleThreadExecutor(), null);
... |
public static final String getLine( LogChannelInterface log, InputStreamReader reader, int formatNr,
StringBuilder line ) throws KettleFileException {
EncodingType type = EncodingType.guessEncodingType( reader.getEncoding() );
return getLine( log, reader, type, formatNr, line );
} | @Test( timeout = 100 )
public void test_PDI695() throws KettleFileException, UnsupportedEncodingException {
String inputDOS = "col1\tcol2\tcol3\r\ndata1\tdata2\tdata3\r\n";
String inputUnix = "col1\tcol2\tcol3\ndata1\tdata2\tdata3\n";
String inputOSX = "col1\tcol2\tcol3\rdata1\tdata2\tdata3\r";
String... |
public synchronized Topology addSource(final String name,
final String... topics) {
internalTopologyBuilder.addSource(null, name, null, null, null, topics);
return this;
} | @Test
public void shouldNotAllowNullNameWhenAddingSourceWithPattern() {
assertThrows(NullPointerException.class, () -> topology.addSource(null, Pattern.compile(".*")));
} |
public void move() {
LOGGER.info("move");
} | @Test
void testMove() {
final var ballItem = new BallItem();
final var ballThread = mock(BallThread.class);
ballItem.setTwin(ballThread);
ballItem.move();
assertTrue(appender.logContains("move"));
verifyNoMoreInteractions(ballThread);
assertEquals(1, appender.getLogSize());
} |
@Override
public Future<?> submit(Runnable runnable) {
submitted.mark();
return delegate.submit(new InstrumentedRunnable(runnable));
} | @Test
@SuppressWarnings("unchecked")
public void reportsTasksInformationForThreadPoolExecutor() throws Exception {
executor = new ThreadPoolExecutor(4, 16,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32));
instrumentedExecutorService = new InstrumentedExecutorService(exe... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
locks.computeIfAbsent(msg.getOriginator(), SemaphoreWithTbMsgQueue::new)
.addToQueueAndTryProcess(msg, ctx, this::processMsgAsync);
} | @Test
public void test_sqrt_5_to_timeseries_and_metadata_and_data() {
var node = initNode(TbRuleNodeMathFunctionType.SQRT,
new TbMathResult(TbMathArgumentType.TIME_SERIES, "result", 3, true, true, DataConstants.SERVER_SCOPE),
new TbMathArgument(TbMathArgumentType.MESSAGE_BODY... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final Map<String, Object> event;
try {
event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT);
} catch (IOException e) {
... | @Test
public void decodeMessagesHandlesGenericBeatWithCloudEC2() throws Exception {
final Message message = codec.decode(messageFromJson("generic-with-cloud-ec2.json"));
assertThat(message).isNotNull();
assertThat(message.getMessage()).isEqualTo("null");
assertThat(message.getSource(... |
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString... | @Test
public void shouldThrowExceptionWhenInsertIntoReadOnlyTopic() {
// Given
final PreparedStatement<Statement> preparedStatement =
PreparedStatement.of("", new InsertInto(SourceName.of("s1"), mock(Query.class)));
final ConfiguredStatement<Statement> configured =
ConfiguredStatement.of(p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.