focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
} | @Test
public void testGetAnalysisPhase() {
HintAnalyzer instance = new HintAnalyzer();
AnalysisPhase expResult = AnalysisPhase.POST_INFORMATION_COLLECTION2;
AnalysisPhase result = instance.getAnalysisPhase();
assertEquals(expResult, result);
} |
public int getDeleteReservationFailedRetrieved() {
return numDeleteReservationFailedRetrieved.value();
} | @Test
public void testGetDeleteReservationRetrievedFailed() {
long totalBadBefore = metrics.getDeleteReservationFailedRetrieved();
badSubCluster.getDeleteReservationFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getDeleteReservationFailedRetrieved());
} |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariableStatement sqlStatement, final ContextManager contextManager) {
ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData();
String variableName = sqlStatement.getName();
if (isConfigur... | @Test
void assertShowCachedConnections() {
ShowDistVariableExecutor executor = new ShowDistVariableExecutor();
executor.setConnectionContext(new DistSQLConnectionContext(mock(QueryContext.class), 1,
mock(DatabaseType.class), mock(DatabaseConnectionManager.class), mock(ExecutorStateme... |
@GET
@Path("/entity-uid/{uid}/")
@Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8)
public TimelineEntity getEntity(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("uid") String uId,
@QueryParam("confstoretrieve") String confsToRetrieve,
@Q... | @Test
void testGetEntitiesBasedOnCreatedTime() throws Exception {
Client client = createClient();
try {
URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" +
"timeline/clusters/cluster1/apps/app1/entities/app?" +
"createdtimestart=1425016502030&createdtimeend=1425016502... |
@Override
public T add(K name, V value) {
throw new UnsupportedOperationException("read only");
} | @Test
public void testAddStringValues() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
HEADERS.add("name", "value1", "value2");
}
});
} |
@Override
public boolean shouldCopy(Path path) {
return true;
} | @Test
public void testShouldCopy() {
Assert.assertTrue(new TrueCopyFilter().shouldCopy(new Path("fake")));
} |
@Override
public void afterChannelInitialized(final Channel channel) {
if (eventBus == null) {
throw new IllegalStateException("Event bus must be set before channel customization can occur");
}
final ChannelCircuitBreakerHandler channelCircuitBreakerHandler = new ChannelCircuitBreakerHandler(clust... | @Test
void testAfterChannelInitialized() {
final LettuceShardCircuitBreaker lettuceShardCircuitBreaker = new LettuceShardCircuitBreaker("test",
new CircuitBreakerConfiguration().toCircuitBreakerConfig(), Schedulers.immediate());
lettuceShardCircuitBreaker.setEventBus(eventBus);
final Channel cha... |
public RegistryBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
} | @Test
void appendParameter() {
RegistryBuilder builder = new RegistryBuilder();
builder.appendParameter("default.num", "one").appendParameter("num", "ONE");
Map<String, String> parameters = builder.build().getParameters();
Assertions.assertTrue(parameters.containsKey("default.num")... |
private MergeSortedPages() {} | @Test
public void testSimpleTwoStreams()
throws Exception
{
List<Type> types = ImmutableList.of(INTEGER);
MaterializedResult actual = mergeSortedPages(
types,
ImmutableList.of(0),
ImmutableList.of(ASC_NULLS_FIRST),
Immut... |
@Override
protected SchemaTransform from(Configuration configuration) {
return new JavaFilterTransform(configuration);
} | @Test
@Category(NeedsRunner.class)
public void testFilter() {
Schema inputSchema =
Schema.of(
Schema.Field.of("a", Schema.FieldType.STRING),
Schema.Field.of("b", Schema.FieldType.INT32),
Schema.Field.of("c", Schema.FieldType.DOUBLE));
PCollection<Row> input =
... |
public boolean tryToMoveTo(State to) {
AtomicReference<State> lastFrom = new AtomicReference<>();
State newState = this.state.updateAndGet(from -> {
lastFrom.set(from);
if (TRANSITIONS.get(from).contains(to)) {
return to;
}
return from;
});
boolean updated = newState == ... | @Test
public void can_move_to_HARD_STOPPING_from_any_step_but_from_INIT_HARD_STOPPING_and_STOPPED() {
for (State state : values()) {
boolean tryToMoveTo = newLifeCycle(state).tryToMoveTo(HARD_STOPPING);
if (state == INIT || state == STOPPED || state == HARD_STOPPING) {
assertThat(tryToMoveTo).... |
@Override
public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) {
log.trace("Submitting put task configuration request {}", connName);
if (requestNotSignedProperly(requestSignature, callbac... | @Test
public void testPutTaskConfigsInvalidSignature() {
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2);
InternalRequestSignature signature = mock(InternalRequestSignature.class);
when(signature.keyAlgorithm()).thenReturn("HmacSHA256");
when(signature.isValid(... |
public Document run() throws ParserConfigurationException, IOException, SAXException, TransformerException {
DocumentBuilder docBuilder = XML.getDocumentBuilder();
Document document = docBuilder.parse(new InputSource(xmlInput));
return execute(document);
} | @Test
public void testPreProcessing() throws Exception {
String expectedDev =
"""
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
... |
static DeduplicationResult ensureSingleProducer(
QueryablePipeline pipeline,
Collection<ExecutableStage> stages,
Collection<PipelineNode.PTransformNode> unfusedTransforms) {
RunnerApi.Components.Builder unzippedComponents = pipeline.getComponents().toBuilder();
Multimap<PipelineNode.PCollecti... | @Test
public void duplicateOverStagesAndTransforms() {
/* When both a stage and a runner-executed transform produce a PCollection, all should be
* replaced with synthetic flattens.
* original graph:
* --> one -> .out \
* red -> .out | -> shared -> .out
* ... |
public static List<Endpoint> listenerListToEndPoints(
String input,
Map<ListenerName, SecurityProtocol> nameToSecurityProto
) {
return listenerListToEndPoints(input, n -> {
SecurityProtocol result = nameToSecurityProto.get(n);
if (result == null) {
thr... | @Test
public void testListenerListToEndPointsWithWildcard() {
assertEquals(Arrays.asList(
new Endpoint("PLAINTEXT", SecurityProtocol.PLAINTEXT, null, 8080)),
SocketServerConfigs.listenerListToEndPoints("PLAINTEXT://:8080",
SocketServerConfigs.DEFAULT_NAME_TO_S... |
public static List<URI> parseXrdLinkReferencesFor(XmlPullParser parser, String relation) throws IOException, XmlPullParserException, URISyntaxException {
ParserUtils.forwardToStartElement(parser);
List<URI> uriList = new ArrayList<>();
int initialDepth = parser.getDepth();
loop: while (... | @Test
public void parseXrdLinkReferencesForWebsockets() throws XmppStringprepException, IOException, XmlPullParserException, URISyntaxException {
List<URI> endpoints = new ArrayList<>();
endpoints.add(new URI("wss://xmpp.igniterealtime.org:7483/ws/"));
endpoints.add(new URI("ws://xmpp.ignite... |
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) {
in.markReaderIndex();
MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c... | @Test
void assertDecodeRotateEvent() {
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(StringUtil.decodeHexDump("000000000004010000002c0000000000000020001a9100000000000062696e6c6f672e3030303032394af65c24"));
List<Object> decodedEvents = new LinkedList<>();
binlogEventPacketDe... |
@Override
public WindowStoreIterator<V> backwardFetch(final K key,
final Instant timeFrom,
final Instant timeTo) throws IllegalArgumentException {
Objects.requireNonNull(key, "key can't be null");
final L... | @Test
public void shouldBackwardFetchKeyRangeAcrossStores() {
final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE);
stubProviderTwo.addStore(storeName, secondUnderlying);
underlyingWindowStore.put("a", "a", 0L);
secondUnderlying.... |
SyncableFileSystemView getPreferredView() {
return preferredView;
} | @Test
public void testGetPreferredView() {
assertEquals(primary, fsView.getPreferredView());
} |
@VisibleForTesting
void initializeForeachArtifactRollup(
ForeachStepOverview foreachOverview,
ForeachStepOverview prevForeachOverview,
String foreachWorkflowId) {
Set<Long> iterationsToRunInNewRun =
foreachOverview.getIterationsToRunFromDetails(prevForeachOverview);
WorkflowRollupOve... | @Test
public void testGetAggregatedRollupFromIterationsNull() {
doReturn(Collections.singletonList(new WorkflowRollupOverview()))
.when(workflowInstanceDao)
.getBatchForeachLatestRunRollupForIterations(anyString(), any());
ForeachStepOverview stepOverview = mock(ForeachStepOverview.class);
... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void editMessageReplyMarkup() {
String text = "Update" + System.currentTimeMillis();
InlineKeyboardMarkup keyboard = new InlineKeyboardMarkup(new InlineKeyboardButton(text).url("https://google.com"));
InlineKeyboardMarkup gameKeyboard = new InlineKeyboardMarkup(new InlineKeyboa... |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitSm[] submitSms = createSubmitSm(exchange);
List<String> messageIDs = new ArrayList<>(submitSms.length);
String messageID = null;
for (int i = 0; i < submitSms.length; i++) {
SubmitSm submitSm =... | @Test
public void singleDlrRequestOverridesDeliveryReceiptFlag() throws Exception {
String longSms = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
"12345678901234567890123456789012345678901234567890123456789012345678901";
Exc... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel());
... | @Test
public void return_Lines_of_Codes_from_StatisticsSupport(){
when(statisticsSupport.getLinesOfCode()).thenReturn(17752L);
ProtobufSystemInfo.Section protobuf = underTest.toProtobuf();
assertThatAttributeIs(protobuf,"Lines of Code", 17752L);
} |
public static BufferedImage fillImage(final BufferedImage image, final Color color)
{
final BufferedImage filledImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < filledImage.getWidth(); x++)
{
for (int y = 0; y < filledImage.getHeight(); y++)
{... | @Test
public void fillImage()
{
// fillImage(BufferedImage image, Color color)
assertTrue(bufferedImagesEqual(centeredPixel(GRAY), ImageUtil.fillImage(centeredPixel(BLACK), GRAY)));
assertTrue(bufferedImagesEqual(solidColor(3, 3, GREEN), ImageUtil.fillImage(solidColor(3, 3, BLACK), GREEN)));
assertTrue(buffer... |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
@Override
public JreInfoRestResponse getJreMetadata(String id) {
return jresHandler.getJreMetadata(id);
} | @Test
void getJre_shouldDownloadJre_whenHeaderIsOctetStream() throws Exception {
String anyId = "anyId";
String anyFilename = "anyFilename";
JreInfoRestResponse jreInfoRestResponse = new JreInfoRestResponse(anyId, anyFilename, "sha256", "javaPath", "os", "arch");
when(jresHandler.getJreMetadata(anyId)... |
public static int findAvailablePort(String portRange) throws IOException {
// ':' is the default value which means no constraints on the portRange
if (StringUtils.isBlank(portRange) || portRange.equals(":")) {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} ... | @Test
void testfindAvailablePort() throws IOException {
assertTrue(RemoteInterpreterUtils.findAvailablePort(":") > 0);
String portRange = ":30000";
assertTrue(RemoteInterpreterUtils.findAvailablePort(portRange) <= 30000);
portRange = "30000:";
assertTrue(RemoteInterpreterUtils.findAvailablePort(... |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsCounterValues() throws Exception {
final Counter counter = mock(Counter.class);
when(counter.getCount()).thenReturn(100L);
reporter.report(map(),
map("test.counter", counter),
map(),
map(),
map());
... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest httpRequest) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
chain.doFilter(new Servle... | @Test
public void request_used_in_chain_do_filter_is_a_servlet_wrapper_when_static_resource() throws Exception {
underTest.doFilter(request("GET", "/context/static/image.png", null), mock(HttpServletResponse.class), chain);
ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(Servlet... |
@Override
public boolean offerFirst(T t)
{
addFirstNode(t);
return true;
} | @Test
public void testOfferFirst()
{
List<Integer> control = new ArrayList<>(Arrays.asList(1, 2, 3));
LinkedDeque<Integer> q = new LinkedDeque<>(control);
control.add(0, 99);
Assert.assertTrue(q.offerFirst(99));
Assert.assertEquals(q, control);
} |
@Override
public ConnectResponse<ConfigInfos> validate(
final String plugin,
final Map<String, String> config) {
try {
final Map<String, String> maskedConfig = QueryMask.getMaskedConnectConfig(config);
LOG.debug("Issuing validate request to Kafka Connect at URI {} for plugin {} and config ... | @Test
public void testValidateWithError() throws JsonProcessingException {
// Given:
final String plugin = SAMPLE_PLUGIN.getClassName();
final String url = String.format(pathPrefix + "/connector-plugins/%s/config/validate", plugin);
WireMock.stubFor(
WireMock.put(WireMock.urlEqualTo(url))
... |
public String getKVConfigValue(final String namespace, final String key, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetKVConfigRequestHeader requestHeader = new GetKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHe... | @Test
public void assertGetKVConfigValue() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
GetKVConfigResponseHeader responseHeader = mock(GetKVConfigResponseHeader.class);
when(responseHeader.getValue()).thenReturn("value");
setResponseHeader(re... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> buckets = new AttributedList<>();
Buckets response;
String page = null;
do {
fin... | @Test
public void testListContainers() throws Exception {
final Path container = new Path("/", EnumSet.of(Path.Type.directory));
final AttributedList<Path> list = new GoogleStorageBucketListService(session).list(container, new DisabledListProgressListener());
assertFalse(list.isEmpty());
... |
@Override
public void removeLogListener(@Nonnull LogListener logListener) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testRemoveLogListener() {
loggingService.removeLogListener(logListener);
} |
@SuppressWarnings("unchecked")
public static <K, V> CowMap<K, V> emptyMap()
{
return (CowMap<K,V>) EMPTY_MAP;
} | @Test
public void testEmptyMap()
{
final CowMap<String, String> map = CowUtil.emptyMap();
Assert.assertTrue(map.isEmpty());
Assert.assertTrue(map.isReadOnly());
try
{
mutateMap(map);
Assert.fail("Should have thrown UnsupportedOperationException");
}
catch (UnsupportedOperati... |
@Override
public Map<SubClusterId, List<ResourceRequest>> splitResourceRequests(
List<ResourceRequest> resourceRequests,
Set<SubClusterId> timedOutSubClusters) throws YarnException {
// object used to accumulate statistics about the answer, initialize with
// active subclusters. Create a new inst... | @Test(timeout = 5000)
public void testStressPolicy() throws Exception {
// Tests how the headroom info are used to split based on the capacity
// each RM claims to give us.
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
initializePolicy();
addHomeSubClu... |
@Override
public boolean supportsMultipleResultSets() {
return false;
} | @Test
void assertSupportsMultipleResultSets() {
assertFalse(metaData.supportsMultipleResultSets());
} |
public static KTableHolder<GenericKey> build(
final KGroupedTableHolder groupedTable,
final TableAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedTable,
aggregate,
buildContext,
... | @Test
public void shouldBuildValueSerdeCorrectlyForAggregate() {
// When:
aggregate.build(planBuilder, planInfo);
// Then:
verify(buildContext).buildValueSerde(
VALUE_FORMAT,
PHYSICAL_AGGREGATE_SCHEMA,
MATERIALIZE_CTX
);
} |
@SuppressWarnings({"rawtypes", "unchecked"})
public <T extends Gauge> T gauge(String name) {
return (T) getOrAdd(name, MetricBuilder.GAUGES);
} | @Test
public void settableGaugeIsTreatedLikeAGauge() {
final MetricRegistry.MetricSupplier<SettableGauge<String>> supplier = () -> settableGauge;
final SettableGauge<String> gauge1 = registry.gauge("thing", supplier);
final SettableGauge<String> gauge2 = registry.gauge("thing", supplier);
... |
public static boolean arePrefixColumns(List<FieldSchema> p, List<FieldSchema> s) {
if (p == s) {
return true;
}
if (p == null || s == null || p.size() > s.size()) {
return false;
}
return areSameColumns(p, s.subList(0, p.size()));
} | @Test
public void testPrefixColumns() {
FieldSchema col1 = new FieldSchema("col1", "string", "col1 comment");
FieldSchema Col1 = new FieldSchema("Col1", "string", "col1 comment");
FieldSchema col2 = new FieldSchema("col2", "string", "col2 comment");
FieldSchema col3 = new FieldSchema("col3", "string",... |
public static org.apache.pinot.common.utils.regex.Matcher matcher(Pattern pattern, CharSequence input) {
if (pattern instanceof Re2jPattern) {
return new Re2jMatcher(pattern, input);
} else {
return new JavaUtilMatcher(pattern, input);
}
} | @Test
public void testRe2jMatcherFactory() {
Re2jPattern re2jPattern = new Re2jPattern("pattern");
Matcher matcher = MatcherFactory.matcher(re2jPattern, "");
Assert.assertTrue(matcher instanceof Re2jMatcher);
} |
@Override
protected String getFolderSuffix() {
return FOLDER_SUFFIX;
} | @Test
public void testGetFolderSuffix() {
Assert.assertEquals("/", mOBSUnderFileSystem.getFolderSuffix());
} |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldReturnWindowStoreWithPartitionWhenItExists() {
assertNotNull(storeProvider.getStore(StoreQueryParameters.fromNameAndType(windowStore, QueryableStoreTypes.windowStore()).withPartition(numStateStorePartitions - 1)));
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definitio... | @Test
void invokeArrayParamTypeHeterogenousArray() {
FunctionTestUtil.assertResultError(allFunction.invoke(new Object[]{Boolean.TRUE, 1}),
InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(allFunction.invoke(new Object[]{Boolean.FALSE, 1}),
... |
int calculatePrice(Integer basePrice, Integer percent, Integer fixedPrice) {
// 1. 优先使用固定佣金
if (fixedPrice != null && fixedPrice > 0) {
return ObjectUtil.defaultIfNull(fixedPrice, 0);
}
// 2. 根据比例计算佣金
if (basePrice != null && basePrice > 0 && percent != null && percen... | @Test
public void testCalculatePrice_useFixedPrice() {
// mock 数据
Integer payPrice = randomInteger();
Integer percent = randomInt(1, 101);
Integer fixedPrice = randomInt();
// 调用
int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice);
... |
public static boolean useGlobalDirectorySequenceId(SegmentNameGeneratorSpec spec) {
if (spec == null || spec.getConfigs() == null) {
return false;
}
String useGlobalDirectorySequenceId =
spec.getConfigs().get(SegmentGenerationTaskRunner.USE_GLOBAL_DIRECTORY_SEQUENCE_ID);
if (useGlobalDirec... | @Test
public void testUseGlobalDirectorySequenceId() {
Assert.assertFalse(SegmentGenerationJobUtils.useGlobalDirectorySequenceId(null));
SegmentNameGeneratorSpec spec = new SegmentNameGeneratorSpec();
Assert.assertFalse(SegmentGenerationJobUtils.useGlobalDirectorySequenceId(spec));
spec.setConfigs(new... |
@Override
public void failSlot(
final ResourceID taskManagerId,
final AllocationID allocationId,
final Exception cause) {
if (registeredTaskManagers.containsKey(taskManagerId)) {
internalFailAllocation(taskManagerId, allocationId, cause);
} else {
... | @Test
void testReleasingTaskExecutorIfNoMoreSlotsRegistered() throws Exception {
final JobGraph jobGraph = createSingleVertexJobWithRestartStrategy();
try (final JobMaster jobMaster =
new JobMasterBuilder(jobGraph, rpcService)
.withConfiguration(configuratio... |
public CruiseConfig deserializeConfig(String content) throws Exception {
String md5 = md5Hex(content);
Element element = parseInputStream(new ByteArrayInputStream(content.getBytes()));
LOGGER.debug("[Config Save] Updating config cache with new XML");
CruiseConfig configForEdit = classPa... | @Test
void shouldRetainArtifactSourceThatIsNotWhitespace() throws Exception {
CruiseConfig cruiseConfig = xmlLoader.deserializeConfig(goConfigMigration.upgradeIfNecessary(configWithArtifactSourceAs("t ")));
JobConfig plan = cruiseConfig.jobConfigByName("pipeline", "stage", "job", true);
asse... |
public CompletableFuture<E> subscribe(String entryName, String channelName) {
AsyncSemaphore semaphore = service.getSemaphore(new ChannelName(channelName));
CompletableFuture<E> newPromise = new CompletableFuture<>();
semaphore.acquire().thenAccept(c -> {
if (newPromise.isDone()) {
... | @Test
public void testSubscribeForRaceCondition() throws InterruptedException {
AtomicReference<CompletableFuture<PubSubConnectionEntry>> sRef = new AtomicReference<>();
new MockUp<PublishSubscribeService>() {
@Mock
AsyncSemaphore getSemaphore(ChannelName channelName) {
... |
@Override
public <VR> KTable<K, VR> aggregate(final Initializer<VR> initializer,
final Aggregator<? super K, ? super V, VR> aggregator,
final Materialized<K, VR, KeyValueStore<Bytes, byte[]>> materialized) {
return aggregate(ini... | @Test
public void shouldNotHaveNullInitializerOnAggregate() {
assertThrows(NullPointerException.class, () -> groupedStream.aggregate(null, MockAggregator.TOSTRING_ADDER, Materialized.as("store")));
} |
@Override
public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters,
final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) {
Collection<Stri... | @Test
void assertDecideWhenAllTablesIsNotBindingTables() {
SelectStatementContext select = createStatementContext();
when(select.isContainsJoinQuery()).thenReturn(true);
ShardingRule shardingRule = createShardingRule();
ShardingSphereDatabase database = createDatabase(shardingRule);
... |
@SuppressWarnings("unchecked")
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
OptionParser p = new OptionParser();
OptionSpec<Integer> count = p.accepts("count", "Record Count").withRequiredArg().ofType(Integer.class);
OptionSpec<Stri... | @Test
void defaultCodec() throws Exception {
// The default codec for random is deflate
run(Collections.emptyList());
assertTrue(err.toString().contains("Compression codec (default: deflate)"));
} |
public PrefixedConfiguration(Configuration origin, String prefix) {
this.origin = origin;
this.prefix = prefix;
} | @Test
void testPrefixedConfiguration() {
Map<String, String> props = new LinkedHashMap<>();
props.put("dubbo.protocol.name", "dubbo");
props.put("dubbo.protocol.port", "1234");
props.put("dubbo.protocols.rest.port", "2345");
InmemoryConfiguration inmemoryConfiguration = new I... |
public static String removeCRLF(String s) {
return s
.replace("\r", "")
.replace("\n", "");
} | @Test
public void testSimpleCRLF() {
String out = StringHelper.removeCRLF("hello");
assertEquals("hello", out);
boolean b6 = !out.contains("\r");
assertTrue(b6, "Should not contain : ");
boolean b5 = !out.contains("\n");
assertTrue(b5, "Should not contain : ");
... |
@Override
public boolean processArgument(final ShenyuRequest shenyuRequest, final Annotation annotation, final Object arg) {
RequestTemplate requestTemplate = shenyuRequest.getRequestTemplate();
RequestParam requestParam = ANNOTATION.cast(annotation);
String name = requestParam.value();
... | @Test
public void processArgumentNullTest() {
RequestTemplate template = new RequestTemplate(Void.class, method1, "method1", "/dev/url/param", "", "/path", ShenyuRequest.HttpMethod.GET, null, null, null);
this.request = ShenyuRequest.create(ShenyuRequest.HttpMethod.POST, "", Maps.newHashMap(), "", "... |
public String convertUnicodeCharacterRepresentation(String input) {
final char[] chars = input.toCharArray();
int nonAsciiCharCount = countNonAsciiCharacters(chars);
if(! (input.contains("\\u") || input.contains("\\U")) && nonAsciiCharCount == 0)
return input;
int replacedNonAsciiCharacterCount = 0;
final ... | @Test
public void convertsUnicodeToUpperCase(){
final FormatTranslation formatTranslation = new FormatTranslation();
assertThat(formatTranslation.convertUnicodeCharacterRepresentation("u"), CoreMatchers.equalTo("u"));
assertThat(formatTranslation.convertUnicodeCharacterRepresentation("\\Uabcde"), CoreMatchers.eq... |
public synchronized void createInstance(List<BigtableResourceManagerCluster> clusters)
throws BigtableResourceManagerException {
// Check to see if instance already exists, and throw error if it does
if (hasInstance) {
LOG.warn(
"Skipping instance creation. Instance was already created or... | @Test
public void testCreateInstanceShouldThrowErrorWhenInstanceAdminClientFailsToClose() {
BigtableInstanceAdminClient mockClient =
bigtableResourceManagerClientFactory.bigtableInstanceAdminClient();
doThrow(RuntimeException.class).when(mockClient).close();
assertThrows(BigtableResourceManagerEx... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void fail_if_components_and_components_uuid_params_are_set_at_the_same_time() {
SearchRequest request = new SearchRequest()
.setComponentKeys(singletonList("foo"))
.setComponentUuids(singletonList("bar"));
assertThatThrownBy(() -> underTest.create(request))
.isInstanceOf(Illega... |
public static <V> TimestampedValue<V> of(V value, Instant timestamp) {
return new TimestampedValue<>(value, timestamp);
} | @Test
public void testCoderEncodeDecodeEquals() throws Exception {
CoderProperties.coderDecodeEncodeEqual(
CODER, TimestampedValue.of(GlobalWindow.INSTANCE, Instant.now()));
} |
@Override
public String serialize(SarifSchema210 sarif210) {
try {
return mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(sarif210);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to serialize SARIF", e);
}
} | @Test
public void serialize() {
new Run().withResults(List.of());
SarifSchema210 sarif210 = new SarifSchema210()
.with$schema(URI.create("http://json.schemastore.org/sarif-2.1.0-rtm.4"))
.withVersion(SarifSchema210.Version._2_1_0)
.withRuns(List.of(new Run().withResults(List.of())));
St... |
public Cookie decode(String header) {
final int headerLen = checkNotNull(header, "header").length();
if (headerLen == 0) {
return null;
}
CookieBuilder cookieBuilder = null;
loop: for (int i = 0;;) {
// Skip spaces and separators.
for (;;) ... | @Test
public void testDecodingSingleCookieV1() {
String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere"
+ ";secure;comment=this is a comment;version=1;";
Cookie cookie = ClientCookieDecoder.STRICT.decode(cookieString);
assertEquals("... |
public static void validateKerberosPrincipal(
KerberosPrincipal kerberosPrincipal) throws IOException {
if (!StringUtils.isEmpty(kerberosPrincipal.getPrincipalName())) {
if (!kerberosPrincipal.getPrincipalName().contains("/")) {
throw new IllegalArgumentException(String.format(
RestA... | @Test
public void testKerberosPrincipalNameFormat() throws IOException {
Service app = createValidApplication("comp-a");
KerberosPrincipal kp = new KerberosPrincipal();
kp.setPrincipalName("user@domain.com");
app.setKerberosPrincipal(kp);
try {
ServiceApiUtil.validateKerberosPrincipal(app.g... |
@Override
public Set<String> listTopicNames() {
try {
return ExecutorUtil.executeWithRetries(
() -> adminClient.get().listTopics().names().get(),
ExecutorUtil.RetryBehaviour.ON_RETRYABLE);
} catch (final Exception e) {
throw new KafkaResponseGetFailedException("Failed to retrie... | @Test
public void shouldRetryListTopics() {
// When:
givenTopicExists("topic1", 1, 1);
givenTopicExists("topic2", 1, 2);
when(adminClient.listTopics())
.thenAnswer(listTopicResult(new NotControllerException("Not Controller")))
.thenAnswer(listTopicResult());
// When:
kafkaTop... |
void serialize(OutputStream out, TransportSecurityOptions options) {
try {
mapper.writerWithDefaultPrettyPrinter().writeValue(out, toTransportSecurityOptionsEntity(options));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | @Test
void can_serialize_options_without_authorized_peers() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
... |
public static SuccessResponse<?> noContent() {
return SuccessResponse.builder().data(Map.of()).build();
} | @Test
@DisplayName("SuccessResponse.from() - data가 존재하는 성공 응답")
public void successResponseWithNoContent() {
// When
SuccessResponse<?> response = SuccessResponse.noContent();
// Then
assertEquals("2000", response.getCode());
assertEquals(Map.of(), response.getData());
... |
public PDPageLabels getPageLabels() throws IOException
{
COSDictionary dict = root.getCOSDictionary(COSName.PAGE_LABELS);
return dict == null ? null : new PDPageLabels(document, dict);
} | @Test
void retrievePageLabelsOnMalformedPdf() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(RandomAccessReadBuffer.createBufferFromStream(
TestPDDocumentCatalog.class.getResourceAsStream("badpagelabels.pdf"))))
{
PDDocumentCatalog ... |
public static Impl join(By clause) {
return new Impl(new JoinArguments(clause));
} | @Test
@Category(NeedsRunner.class)
public void testMismatchingKeys() {
PCollection<Row> pc1 =
pipeline
.apply(
"Create1",
Create.of(Row.withSchema(CG_SCHEMA_1).addValues("user1", 1, "us").build()))
.setRowSchema(CG_SCHEMA_1);
PCollection<Row> p... |
public ArrayList<AnalysisResult<T>> getOutliers(Track<T> track) {
// the stream is wonky due to the raw type, probably could be improved
return track.points().stream()
.map(point -> analyzePoint(point, track))
.filter(analysisResult -> analysisResult.isOutlier())
.c... | @Test
public void testMissingAltitude_aka_modeCSwap_2() {
/*
* This is another mode C swap test.
*
* This test contains a much smaller change (from 1k to 0 instead of from 22k to 0).
* This test data also has a missing altitude value at the very front of the track.
... |
@Override
public Node upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("multipart", con... | @Test
public void testUploadBelowMultipartSize() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final SDSDirectS3UploadFeature feature = new SDSDirectS3UploadFeature(session, nodeid, new SDSDelegatingWriteFeature(session, nodeid, new SDSDirectS3WriteFeature(sessi... |
@Override
public Result apply(PathData item, int depth) throws IOException {
String name = getPath(item).getName();
if (!caseSensitive) {
name = StringUtils.toLowerCase(name);
}
if (globPattern.matches(name)) {
return Result.PASS;
} else {
return Result.FAIL;
}
} | @Test
public void applyMixedCase() throws IOException {
setup("name");
PathData item = new PathData("/directory/path/NaMe", mockFs.getConf());
assertEquals(Result.FAIL, name.apply(item, -1));
} |
@Override
public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception {
Map<String, WeLinkSettings> settingsMap = alarmRulesWatcher.getWeLinkSettings();
if (settingsMap == null || settingsMap.isEmpty()) {
return;
}
Map<String, List<AlarmMessage>> groupedMessage... | @Test
public void testWeLinkDoAlarm() throws Exception {
List<WeLinkSettings.WebHookUrl> webHooks = new ArrayList<>();
webHooks.add(new WeLinkSettings.WebHookUrl("clientId", "clientSecret",
"http://127.0.0.1:" + SERVER.httpPort() + "/welinkhook/api/... |
@Nullable
public Integer getIntValue(@IntFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
return switch (formatType) {
case FORMAT_UINT8 -> unsignedByteToInt(mValue[offset]);
case FORMAT_UINT16_LE -> unsignedBytesToIn... | @Test
public void getValue_SINT16() {
final Data data = new Data(new byte[] { (byte) 0xD0, (byte) 0xE7 });
final int value = data.getIntValue(Data.FORMAT_SINT16_LE, 0);
assertEquals(-6192, value);
} |
void writeInformationsDetails() throws DocumentException, IOException {
for (final JavaInformations javaInformations : javaInformationsList) {
currentTable = createJavaInformationsTable();
writeSummary(javaInformations);
writeDetails(javaInformations);
addToDocument(currentTable);
}
} | @Test
public void testTomcatInformations() throws Exception {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final PdfDocumentFactory pdfDocumentFactory = new PdfDocumentFactory(TEST_APP, null,
output);
final MBeanServer mBeanServer = MBeans.getPlatformMBeanServer();
final List<ObjectNam... |
public RowExpression extract(PlanNode node)
{
return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null);
} | @Test
public void testLeftJoinWithFalseInner()
{
List<EquiJoinClause> criteria = ImmutableList.of(new EquiJoinClause(AV, DV));
Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV)));
TableScanNode le... |
Map<ServiceId, HealthEndpoint> extractHealthEndpoints(ApplicationInfo application) {
Map<ServiceId, HealthEndpoint> endpoints = new HashMap<>();
for (HostInfo hostInfo : application.getModel().getHosts()) {
DomainName hostname = DomainName.of(hostInfo.getHostname());
for (Servic... | @Test
public void test() {
Map<ServiceId, HealthEndpoint> endpoints = model.extractHealthEndpoints(proxyHostApplicationInfo);
assertEquals(2, endpoints.size());
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "proxy-host", "default");
ClusterId clusterId = new Clust... |
@Override
public <T> ModelEnforcement<T> forBundle(
CommittedBundle<T> input, AppliedPTransform<?, ?, ?> consumer) {
if (isReadTransform(consumer)) {
return NoopReadEnforcement.INSTANCE;
}
return new ImmutabilityCheckingEnforcement<>(input, consumer);
} | @Test
public void unchangedSucceeds() {
WindowedValue<byte[]> element = WindowedValue.valueInGlobalWindow("bar".getBytes(UTF_8));
CommittedBundle<byte[]> elements =
bundleFactory.createBundle(pcollection).add(element).commit(Instant.now());
ModelEnforcement<byte[]> enforcement = factory.forBundle... |
static SVNClientManager newSvnClientManager(SvnConfiguration configuration) {
ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
final char[] passwordValue = getCharsOrNull(configuration.password());
final char[] passPhraseValue = getCharsOrNull(configuration.passPhrase());
ISVNAuthenticationMa... | @Test
public void newSvnClientManager_whenPasswordNotConfigured_shouldNotReturnNull() {
assertThat(config.password()).isNull();
assertThat(config.passPhrase()).isNull();
assertThat(newSvnClientManager(config)).isNotNull();
} |
@Override
public String description() {
return "ChronoZonedDateTime.timeLineOrder()";
} | @Test
void should_have_description() {
assertThat(comparator.description()).isEqualTo("ChronoZonedDateTime.timeLineOrder()");
} |
@Override
public Dataset<Row> apply(
final JavaSparkContext jsc,
final SparkSession sparkSession,
final Dataset<Row> rowDataset,
final TypedProperties props) {
final String sqlFile = getStringWithAltKeys(props, SqlTransformerConfig.TRANSFORMER_SQL_FILE);
final FileSystem fs = HadoopF... | @Test
public void testSqlFileBasedTransformerIncorrectConfig() {
// Test if the class throws hoodie IO exception correctly when given a incorrect config.
props.setProperty(
"hoodie.streamer.transformer.sql.file",
UtilitiesTestBase.basePath + "/non-exist-sql-file.sql");
assertThrows(
... |
public static void checkState(boolean isValid, String message) throws IllegalStateException {
if (!isValid) {
throw new IllegalStateException(message);
}
} | @Test
public void testCheckStateWithOneArgument() {
try {
Preconditions.checkState(true, "Test message %s", 12);
} catch (IllegalStateException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkState(false, "Test message %s", 12);
... |
@Override
public MaterializedTable nonWindowed() {
return new KsqlMaterializedTable(inner.nonWindowed());
} | @Test
public void shouldCallInnerNonWindowedWithCorrectParamsOnGet() {
// Given:
final MaterializedTable table = materialization.nonWindowed();
givenNoopFilter();
// When:
table.get(aKey, partition);
// Then:
verify(innerNonWindowed).get(aKey, partition, Optional.empty());
} |
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Deadline.registerIfNot(socketTimeout);
boolean isTimerStarted = Deadline.startTimer(method.getName());
try {
return method.invoke(base, args);
} finally {
if (isTimerStarted)... | @Test
public void testExceptionDispatch() throws Throwable {
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setTimeVar(conf, MetastoreConf.ConfVars.CLIENT_SOCKET_TIMEOUT, 10,
TimeUnit.MILLISECONDS);
RawStoreProxy rsp = new RawStoreProxy(conf, conf, TestStore.class);
try {... |
@Override
public GetTelemetrySubscriptionsResponse getErrorResponse(int throttleTimeMs, Throwable e) {
GetTelemetrySubscriptionsResponseData responseData = new GetTelemetrySubscriptionsResponseData()
.setErrorCode(Errors.forException(e).code())
.setThrottleTimeMs(throttleTime... | @Test
public void testGetErrorResponse() {
GetTelemetrySubscriptionsRequest req = new GetTelemetrySubscriptionsRequest(new GetTelemetrySubscriptionsRequestData(), (short) 0);
GetTelemetrySubscriptionsResponse response = req.getErrorResponse(0, Errors.CLUSTER_AUTHORIZATION_FAILED.exception());
... |
@Udf
public String extractProtocol(
@UdfParameter(description = "a valid URL to extract a protocl from") final String input) {
return UrlParser.extract(input, URI::getScheme);
} | @Test
public void shouldReturnNullIfNoProtocol() {
assertThat(
extractUdf.extractProtocol("///current/ksql/docs/syntax-reference.html#scalar-functions"),
nullValue());
} |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint,
TimeLimiter timeLimiter, String methodName) throws Throwable {
Object returnValue = proceedingJoinPoint.proceed();
if (Flux.class.isAssignableFrom(returnValue.getClass())) {
Flux<?> fluxReturnValue = (Flux<?>... | @Test
public void shouldThrowIllegalArgumentExceptionWithNotReactorType() throws Throwable{
TimeLimiter timeLimiter = TimeLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn("NOT REACTOR TYPE");
try {
reactorTimeLimiterAspectExt.handle(proceedingJoinPoint,... |
public static BDBJournalCursor getJournalCursor(BDBEnvironment env, long fromKey, long toKey)
throws JournalException, JournalInconsistentException, InterruptedException {
return getJournalCursor(env, "", fromKey, toKey);
} | @Test(expected = JournalException.class)
public void testDatabaseNamesFails(@Mocked BDBEnvironment environment) throws Exception {
new Expectations(environment) {
{
environment.getDatabaseNamesWithPrefix("");
minTimes = 0;
result = null;
... |
@Override
public void run() {
// We need to get this thread so it can be interrupted if the cached proposal has been invalidated.
_proposalPrecomputingSchedulerThread = Thread.currentThread();
LOG.info("Starting proposal candidate computation.");
while (!_shutdown && _numPrecomputingThreads > 0) {
... | @Test
public void testNoPreComputingThread() {
GoalOptimizer goalOptimizer = createGoalOptimizer();
// Should exit immediately.
goalOptimizer.run();
} |
public synchronized Topology addSink(final String name,
final String topic,
final String... parentNames) {
internalTopologyBuilder.addSink(name, topic, null, null, null, parentNames);
return this;
} | @Test
public void shouldFailWithUnknownParent() {
assertThrows(TopologyException.class, () -> topology.addSink("sink", "topic-2", "source"));
} |
@Override
public void onCreating(AbstractJob job) {
JobDetails jobDetails = job.getJobDetails();
Optional<Job> jobAnnotation = getJobAnnotation(jobDetails);
setJobName(job, jobAnnotation);
setAmountOfRetries(job, jobAnnotation);
setLabels(job, jobAnnotation);
} | @Test
void testLabelsIsUsedIfProvidedByAnnotation() {
Job job = anEnqueuedJob()
.withJobDetails(() -> testService.doWorkWithJobAnnotationAndLabels(3, "customer name"))
.build();
defaultJobFilter.onCreating(job);
assertThat(job).hasLabels(Set.of("label-3 - cu... |
public static <OutputT> Coder<OutputT> inferCoder(
SingleStoreIO.RowMapper<OutputT> rowMapper,
CoderRegistry registry,
SchemaRegistry schemaRegistry,
Logger log) {
if (rowMapper instanceof SingleStoreIO.RowMapperWithCoder) {
try {
return ((SingleStoreIO.RowMapperWithCoder<Outpu... | @Test
public void testInferCoderFromRowMapper() {
SchemaRegistry sr = SchemaRegistry.createDefault();
CoderRegistry cr = CoderRegistry.createDefault();
Coder<TestRow> c = SerializableCoder.of(TestRow.class);
assertEquals(c, SingleStoreUtil.inferCoder(new TestRowMapperWithCoder(), cr, sr, LOG));
} |
public static Node build(final List<JoinInfo> joins) {
Node root = null;
for (final JoinInfo join : joins) {
if (root == null) {
root = new Leaf(join.getLeftSource());
}
if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) {
throw new K... | @Test
public void handlesBasicTwoWayJoin() {
// Given:
when(j1.getLeftSource()).thenReturn(a);
when(j1.getRightSource()).thenReturn(b);
final List<JoinInfo> joins = ImmutableList.of(j1);
// When:
final Node root = JoinTree.build(joins);
// Then:
assertThat(root, instanceOf(Join.class... |
public static Builder custom() {
return new Builder();
} | @Test
public void shouldCreateAmountCutoff() {
HedgeConfig config = HedgeConfig.custom()
.averagePlusAmountDuration(200, false, 100).build();
HedgeDurationSupplier supplier = HedgeDurationSupplier.fromConfig(config);
then(((AverageDurationSupplier) supplier)).isInstanceOf(Avera... |
@Override
public SeekableByteChannel truncate(long size) throws IOException {
delegate.truncate(size);
return this;
} | @Test
public void testTruncate() throws IOException {
int newSize = 5;
channelUnderTest.truncate(newSize);
assertEquals(newSize, delegate.size());
assertEquals(newSize, channelUnderTest.size());
} |
@Override
public void debug(String msg) {
logger.debug(msg);
} | @Test
void testDebugWithFormat2() {
jobRunrDashboardLogger.debug("Debug with {} {}", "format1", "format2");
verify(slfLogger).debug("Debug with {} {}", "format1", "format2");
} |
@Override
public SarifSchema210 deserialize(Path reportPath) {
try {
return mapper
.enable(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION)
.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleInstantiationProblem(DeserializationContext ctxt, Clas... | @Test
public void deserialize_whenFileIsNotUtf8encoded_shouldFail() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("sarif210-nonUtf8.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstanceOf(I... |
static double toDouble(final JsonNode object) {
if (object instanceof NumericNode) {
return object.doubleValue();
}
if (object instanceof TextNode) {
try {
return Double.parseDouble(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionExc... | @Test
public void shouldConvertStringToDoubleCorrectly() {
final Double d = JsonSerdeUtils.toDouble(JsonNodeFactory.instance.textNode("1.0"));
assertThat(d, equalTo(1.0));
} |
public Future<Void> migrateFromDeploymentToStrimziPodSets(Deployment deployment, StrimziPodSet podSet) {
if (deployment == null) {
// Deployment does not exist anymore => no migration needed
return Future.succeededFuture();
} else {
int depReplicas = deployment.get... | @Test
public void testMigrationToPodSetsWithRecreateStrategy(VertxTestContext context) {
DeploymentOperator mockDepOps = mock(DeploymentOperator.class);
StrimziPodSetOperator mockPodSetOps = mock(StrimziPodSetOperator.class);
PodOperator mockPodOps = mock(PodOperator.class);
LinkedL... |
@Bean
public WebSocketPlugin webSocketPlugin(final WebSocketClient webSocketClient, final WebSocketService webSocketService) {
return new WebSocketPlugin(webSocketClient, webSocketService);
} | @Test
public void testWebSocketPlugin() {
applicationContextRunner.run(context -> {
WebSocketPlugin plugin = context.getBean("webSocketPlugin", WebSocketPlugin.class);
assertNotNull(plugin);
assertThat(plugin.named()).isEqualTo(PluginEnum.WEB_SOCKET.getName())... |
@Override
public <V1, R> KTable<K, R> leftJoin(final KTable<K, V1> other,
final ValueJoiner<? super V, ? super V1, ? extends R> joiner) {
return leftJoin(other, joiner, NamedInternal.empty());
} | @Test
public void shouldThrowNullPointerOnLeftJoinWhenMaterializedIsNull() {
assertThrows(NullPointerException.class, () -> table.leftJoin(table, MockValueJoiner.TOSTRING_JOINER, (Materialized) null));
} |
public int compare(ZonedDateTime otherDate) {
if (hasDateStamp() && otherDate != null) {
if (getDateTime().isAfter(otherDate)) return 1;
if (getDateTime().isBefore(otherDate)) return -1;
return 0;
} else {
throw new IllegalStateException("One or more DateS... | @Test
void compare() {
DateTimeStamp a = new DateTimeStamp("2018-04-04T09:10:00.586-0100");
DateTimeStamp b = new DateTimeStamp("2018-04-04T09:10:00.587-0100");
assertTrue(a.compare(b.getDateTime()) < 0);
assertTrue(b.compare(a.getDateTime()) > 0);
assertEquals(0, a.compare(n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.