focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean shouldCopy(Path path) {
return true;
} | @Test
public void testShouldCopyWithNull() {
Assert.assertTrue(new TrueCopyFilter().shouldCopy(new Path("fake")));
} |
@Override public boolean remove(long key1, long key2) {
assert key1 != unassignedSentinel : "remove() called with key1 == nullKey1 (" + unassignedSentinel + ')';
return super.remove0(key1, key2);
} | @Test
public void testRemove() {
final long key1 = randomKey();
final long key2 = randomKey();
hsa.ensure(key1, key2);
assertTrue(hsa.remove(key1, key2));
assertFalse(hsa.remove(key1, key2));
} |
@Override
public ServerGroup servers() {
return cache.get();
} | @Test
public void unknown_endpoint_is_down() {
NginxHealthClient client = createClient("nginx-health-output.json");
assertFalse(client.servers().isHealthy("no.such.endpoint"));
} |
@GetMapping("/metrics")
public ObjectNode metrics(HttpServletRequest request) {
boolean onlyStatus = Boolean.parseBoolean(WebUtils.optional(request, "onlyStatus", "true"));
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put("status", serverStatusManager.getServerStatus().name... | @Test
void testMetrics() {
Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP);
Collection<String> clients = new HashSet<>();
clients.add("1628132208793_127.0.0.1_8080");
clients.add("127.0.0.1:8081#true");
clients.add("127.0.0.1:8082#false");
... |
public final BarcodeParameters getParams() {
return params;
} | @Test
final void testConstructorWithAll() throws IOException {
try (BarcodeDataFormat barcodeDataFormat = new BarcodeDataFormat(200, 250, BarcodeImageType.JPG, BarcodeFormat.AZTEC)) {
this.checkParams(BarcodeImageType.JPG, 200, 250, BarcodeFormat.AZTEC, barcodeDataFormat.getParams());
}
... |
public TopicMessageDTO deserialize(ConsumerRecord<Bytes, Bytes> rec) {
var message = new TopicMessageDTO();
fillKey(message, rec);
fillValue(message, rec);
fillHeaders(message, rec);
message.setPartition(rec.partition());
message.setOffset(rec.offset());
message.setTimestampType(mapToTimest... | @Test
void dataMaskingAppliedOnDeserializedMessage() {
UnaryOperator<TopicMessageDTO> maskerMock = mock();
Serde.Deserializer deser = (headers, data) -> new DeserializeResult("test", STRING, Map.of());
var recordDeser = new ConsumerRecordDeserializer("test", deser, "test", deser, "test", deser, deser, ma... |
boolean isWriteShareGroupStateSuccessful(List<PersisterStateBatch> stateBatches) {
WriteShareGroupStateResult response;
try {
response = persister.writeState(new WriteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<Partition... | @Test
public void testWriteShareGroupStateWithNullResponse() {
Persister persister = Mockito.mock(Persister.class);
mockPersisterReadStateMethod(persister);
SharePartition sharePartition = SharePartitionBuilder.builder().withPersister(persister).build();
Mockito.when(persister.write... |
public static ConfigQueryResponse buildFailResponse(int errorCode, String message) {
ConfigQueryResponse response = new ConfigQueryResponse();
response.setErrorInfo(errorCode, message);
return response;
} | @Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigQueryResponse configQueryResponse = ConfigQueryResponse.buildFailResponse(500, "Fail");
String json = mapper.writeValueAsString(configQueryResponse);
assertTrue(json.contains("\"resultCode\":" ... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertShort() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.SHORT_TYPE).build();
BasicTypeDefine typeDefine = RedshiftTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName(... |
public List<Seat> createAutoIncrementSeats(
Block block, Stadium stadium, Section section, List<BlockRow> rows) {
List<Seat> seats = new ArrayList<>();
int blockSeatNum = BLOCK_SEAT_START_NUM;
for (BlockRow row : rows) {
do {
seats.add(
... | @Test
void 블록_열_정보가_주어졌을_때_자동으로_좌석을_채번할_수_있다() {
// given
Block block = Block.builder().id(1L).build();
Stadium stadium = Stadium.builder().id(1L).build();
Section section = Section.builder().id(1L).build();
List<BlockRow> rows =
new ArrayList<>(
... |
public static List<String> getJavaOpts(Configuration conf) {
String adminOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_KEY,
YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_DEFAULT);
String userOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_KEY,
... | @Test
public void testJavaOptionsWithoutDefinedAdminOrUserOptions() throws Exception {
ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper();
ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest();
Configuration conf = new Configuration();
List<String> javaOpts = locali... |
public static String getContent(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
throw new IllegalArgumentException("The content does not contain separator!");
}
return content.substring(index + 1);
} | @Test
void testGetContent() {
String content = "abc" + Constants.WORD_SEPARATOR + "edf";
String result = ContentUtils.getContent(content);
assertEquals("edf", result);
content = "test";
try {
ContentUtils.getContent(content);
fail();
}... |
@Override
public CompletableFuture<Collection<TaskManagerInfo>> requestTaskManagerInfo(Time timeout) {
final ArrayList<TaskManagerInfo> taskManagerInfos = new ArrayList<>(taskExecutors.size());
for (Map.Entry<ResourceID, WorkerRegistration<WorkerType>> taskExecutorEntry :
taskExecu... | @Test
void testRequestTaskManagerInfo() throws Exception {
final ResourceID taskManagerId = ResourceID.generate();
final TaskExecutorGateway taskExecutorGateway =
new TestingTaskExecutorGatewayBuilder()
.setAddress(UUID.randomUUID().toString())
... |
public Expression rewrite(final Expression expression) {
return new ExpressionTreeRewriter<>(new OperatorPlugin()::process)
.rewrite(expression, null);
} | @Test
public void shouldNotReplaceArithmetic() {
// Given:
final Expression predicate = getPredicate(
"SELECT * FROM orders where '2017-01-01' + 10000 > ROWTIME;");
// When:
final Expression rewritten = rewriter.rewrite(predicate);
// Then:
verify(parser, never()).parse(any());
a... |
@Override
@SuppressWarnings("checkstyle:magicnumber")
public void process(int ordinal, @Nonnull Inbox inbox) {
try {
switch (ordinal) {
case 0:
process0(inbox);
break;
case 1:
process1(inbox);
... | @Test
public void when_processInbox3_then_tryProcess3Called() {
// When
tryProcessP.process(ORDINAL_3, inbox);
// Then
tryProcessP.validateReceptionOfItem(ORDINAL_3, MOCK_ITEM);
} |
@Override
public long getCurrentTime() {
return deploymentStart == NOT_STARTED
? 0L
: Math.max(0, clock.absoluteTimeMillis() - deploymentStart);
} | @Test
void testGetCurrentTime() {
final ManualClock clock = new ManualClock(Duration.ofMillis(5).toNanos());
final DeploymentStateTimeMetrics metrics =
new DeploymentStateTimeMetrics(JobType.BATCH, settings, clock);
final ExecutionAttemptID id1 = createExecutionAttemptId();... |
@Override
public CompletableFuture<RpcOutput> invokeRpc(RpcInput input) {
return super.invokeRpc(new RpcInput(toAbsoluteId(input.id()), input.data()));
} | @Test
public void testInvokeRpc() {
RpcInput input = new RpcInput(relIntf, null);
view.invokeRpc(input);
assertTrue(ResourceIds.isPrefix(rid, realId));
} |
@Override
public void write(MemoryBuffer buffer, T value) {
for (FieldResolver.FieldInfo fieldInfo : fieldResolver.getEmbedTypes4Fields()) {
buffer.writeInt32((int) fieldInfo.getEncodedFieldInfo());
readAndWriteFieldValue(buffer, fieldInfo, value);
}
for (FieldResolver.FieldInfo fieldInfo : fi... | @Test(dataProvider = "referenceTrackingConfig")
public void testWrite(boolean referenceTracking) {
Fury fury =
Fury.builder()
.withLanguage(Language.JAVA)
.withRefTracking(referenceTracking)
.requireClassRegistration(false)
.build();
fury.registerSeriali... |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForTableAggregate() {
// Given:
givenAggregateFunction("SUM");
final TableAggregate step = new TableAggregate(
PROPERTIES,
groupedTableSource,
formats,
ImmutableList.of(ColumnName.of("ORANGE")),
ImmutableList.of(functionCall("SUM... |
@Override
public boolean accept(final Path source, final Local local, final TransferStatus parent) {
return true;
} | @Test
public void testAcceptDirectoryExists() throws Exception {
final HashMap<Path, Path> files = new HashMap<>();
final Path source = new Path("a", EnumSet.of(Path.Type.directory));
files.put(source, new Path("a", EnumSet.of(Path.Type.directory)));
final Find find = new Find() {
... |
public GenericRow createRow(final KeyValue<List<?>, GenericRow> row) {
if (row.value() != null) {
throw new IllegalArgumentException("Not a tombstone: " + row);
}
final List<?> key = row.key();
if (key.size() < keyIndexes.size()) {
throw new IllegalArgumentException("Not enough key columns.... | @Test
public void shouldHandleSomeKeyColumnsNotInProjection() {
// Given:
givenSchema(LogicalSchema.builder()
.keyColumn(ColumnName.of("K1"), SqlTypes.INTEGER)
.keyColumn(ColumnName.of("K2"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("V0"), SqlTypes.INTEGER)
.valueColumn(Col... |
public String getValue(String template) {
StringBuilder builder = new StringBuilder();
// Just delegate parsing stuffs to Expression parser to retrieve all the expressions ordered.
Expression[] expressions = ExpressionParser.parseExpressions(template, context, expressionPrefix,
expression... | @Test
void testPostmanNotationCompatibility() {
String template = "{\"signedAt\": \"{{ now() }}\", \"fullName\": \"{{ randomFullName() }}\", \"email\": \"{{ randomEmail() }}\", \"age\": {{ randomInt(20, 99) }}} \n";
String postmanTemplate = "{\"signedAt\": \"{{ $timestamp }}\", \"fullName\": \"{{ $random... |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void test_resolveFields(boolean key, String prefix) {
Stream<MappingField> resolvedFields = INSTANCE.resolveAndValidateFields(
key,
singletonList(field("field", QueryDataType.INT, prefi... |
public boolean match(List<String> left, String right) {
if (Objects.isNull(left)) {
return false;
}
if (right.startsWith("\"") && right.endsWith("\"")) {
right = right.substring(1, right.length() - 1);
}
return !left.contains(right);
} | @Test
public void match() {
NotContainMatch notContainMatch = new NotContainMatch();
assertFalse(notContainMatch.match(null, "http.method:GET"));
assertFalse(
notContainMatch.match(Arrays.asList("http.method:GET", "http.method:POST"), "http.method:GET"));
assertTrue(notCo... |
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) {
// First check whether rpc addresses are explicitly configured.
if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) {
return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES));
}
// Fall b... | @Test
public void getMasterRpcAddresses() {
AlluxioConfiguration conf =
createConf(ImmutableMap.of(PropertyKey.MASTER_RPC_ADDRESSES, "host1:99,host2:100"));
assertEquals(
Arrays.asList(InetSocketAddress.createUnresolved("host1", 99),
InetSocketAddress.createUnresolved("host2", 100)... |
public static <T> Window<T> into(WindowFn<? super T, ?> fn) {
try {
fn.windowCoder().verifyDeterministic();
} catch (NonDeterministicException e) {
throw new IllegalArgumentException("Window coders must be deterministic.", e);
}
return Window.<T>configure().withWindowFn(fn);
} | @Test
public void testWindowIntoWindowFnAssign() {
pipeline
.apply(Create.of(1, 2, 3))
.apply(
Window.into(FixedWindows.of(Duration.standardMinutes(11L).plus(Duration.millis(1L)))));
final AtomicBoolean foundAssign = new AtomicBoolean(false);
pipeline.traverseTopologically(
... |
protected final AnyKeyboardViewBase getMiniKeyboard() {
return mMiniKeyboard;
} | @Test
public void testShortPressWhenNoPrimaryKeyAndNoPopupItemsShouldNotOutput() throws Exception {
ExternalAnyKeyboard anyKeyboard =
new ExternalAnyKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
keyboard_with_keys... |
public long acquire() {
final long currOpIndex = V_TIME_UPDATER.getAndIncrement(this);
long start = this.start;
if (start == Long.MIN_VALUE) {
start = nanoClock.get();
if (!START_UPDATER.compareAndSet(this, Long.MIN_VALUE, start)) {
start = this.start;
... | @Test
void acquireSlowSingleThread() {
Supplier<Long> mockClock = mock(Supplier.class);
when(mockClock.get()).thenReturn(SECONDS.toNanos(2));
UniformRateLimiter rateLimiter = new UniformRateLimiter(1000, mockClock);
assertThat(rateLimiter.acquire()).isEqualTo(2000000000L);
as... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testUpCastRetainsSuperInterfaceValues() throws Exception {
ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap());
SubClass extended = handler.as(SubClass.class);
extended.setString("parentValue");
Simple simple = extended.as(Simple.class);
assertEquals("... |
public Optional<DateTime> nextTime(JobTriggerDto trigger) {
return nextTime(trigger, trigger.nextTime());
} | @Test
public void nextTime() {
final JobTriggerDto trigger = JobTriggerDto.builderWithClock(clock)
.jobDefinitionId("abc-123")
.jobDefinitionType("event-processor-execution-v1")
.schedule(IntervalJobSchedule.builder()
.interval(1)
... |
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
return getDescriptionInHtml(rule)
.map(this::generateSections)
.orElse(emptySet());
} | @Test
public void parse_return_null_risk_when_desc_starts_with_ask_yourself_title() {
when(rule.htmlDescription()).thenReturn(ASKATRISK + RECOMMENTEDCODINGPRACTICE);
Set<RuleDescriptionSectionDto> results = generator.generateSections(rule);
Map<String, String> sectionKeyToContent = results.stream().coll... |
@Override
public AppSettings load() {
Properties p = loadPropertiesFile(homeDir);
Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey)
.collect(Collectors.toSet());
keysOverridableFromEnv.addAll(p.stringPropertyNames());
// 1st... | @Test
public void load_properties_from_file() throws Exception {
File homeDir = temp.newFolder();
File propsFile = new File(homeDir, "conf/sonar.properties");
FileUtils.write(propsFile, "foo=bar", UTF_8);
AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serv... |
public static final String[] convertLineToStrings( LogChannelInterface log, String line, TextFileInputMeta inf,
String delimiter, String enclosure, String escapeCharacters ) throws KettleException {
String[] strings = new String[inf.inputFields.length];
int fieldnr;
String pol; // piece of line
... | @Test
public void convertLineToStrings() throws Exception {
TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class );
inputMeta.content = new TextFileInputMeta.Content();
inputMeta.content.fileType = "CSV";
inputMeta.inputFields = new BaseFileField[ 3 ];
inputMeta.content.escapeCharac... |
@Override
protected List<MatchResult> match(List<String> specs) throws IOException {
return match(new File(".").getAbsolutePath(), specs);
} | @Test
public void testMatchWithFileThreeSlashesPrefix() throws Exception {
List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString());
temporaryFolder.newFile("aa");
temporaryFolder.newFile("ab");
String file = "file:///" + temporaryFolder.getRoot().toPath().resolve("a").toStri... |
@Override
public Optional<Listener> acquire(ContextT context) {
return tryAcquire(context).map(delegate -> new Listener() {
@Override
public void onSuccess() {
delegate.onSuccess();
unblock();
}
@Override
public voi... | @Test
public void blockWhenFullAndTimeout() {
// Acquire all 4 available tokens
for (int i = 0; i < 4; i++) {
Optional<Limiter.Listener> listener = blockingLimiter.acquire(null);
Assert.assertTrue(listener.isPresent());
}
// Next acquire will block for 1 seco... |
public static String getUserAgent(HttpServletRequest request) {
String userAgent = request.getHeader(HttpHeaderConsts.USER_AGENT_HEADER);
if (StringUtils.isEmpty(userAgent)) {
userAgent = StringUtils
.defaultIfEmpty(request.getHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER... | @Test
void testGetUserAgent() {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
String userAgent = WebUtils.getUserAgent(servletRequest);
assertEquals("", userAgent);
servletRequest.addHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER, "0");
assertE... |
public void openFile() {
openFile( false );
} | @Test
public void testLoadLastUsedRepTransNoRepository() throws Exception {
String repositoryName = null;
String fileName = "fileName";
setLoadLastUsedJobLocalWithRepository( true, repositoryName, null, fileName, false );
verify( spoon, never() ).openFile( anyString(), anyBoolean() );
} |
@Override
public void deleteGroup(Long id) {
// 校验存在
validateGroupExists(id);
// 校验分组下是否有用户
validateGroupHasUser(id);
// 删除
memberGroupMapper.deleteById(id);
} | @Test
public void testDeleteGroup_success() {
// mock 数据
MemberGroupDO dbGroup = randomPojo(MemberGroupDO.class);
groupMapper.insert(dbGroup);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbGroup.getId();
// 调用
groupService.deleteGroup(id);
// 校验数据不存在了
... |
public <T> IfrVfrStatus statusOf(Track<T> track, Instant time) {
checkNotNull(track);
checkNotNull(time);
checkArgument(
track.asTimeWindow().contains(time),
"This track does not exist at this moment in time"
);
EnumMultiset<IfrVfrStatus> counts = EnumMul... | @Test
public void testStatusOfPoint_goodBeaconAndGoodcallsign_vfr() {
String rawNop = "[RH],STARS,D21_B,03/24/2018,14:42:00.130,N518SP,C172,,5256,032,110,186,042.92704,-083.70974,3472,5256,-14.5730,42.8527,1,Y,A,D21,,POL,ARB,1446,ARB,ACT,VFR,,01500,,,,,,S,1,,0,{RH}";
Point<NopHit> point = NopHit.fro... |
@SuppressWarnings({"rawtypes", "unchecked"})
public <T extends Gauge> T gauge(String name) {
return (T) getOrAdd(name, MetricBuilder.GAUGES);
} | @Test
public void accessingAnExistingGaugeReusesIt() {
final Gauge<String> gauge1 = registry.gauge("thing", () -> () -> "string-gauge");
final Gauge<String> gauge2 = registry.gauge("thing", () -> new DefaultSettableGauge<>("settable-gauge"));
assertThat(gauge1).isSameAs(gauge2);
ass... |
ExclusivePublication addExclusivePublication(final String channel, final int streamId)
{
clientLock.lock();
try
{
ensureActive();
ensureNotReentrant();
final long registrationId = driverProxy.addExclusivePublication(channel, streamId);
stashed... | @Test
void shouldNotPreTouchLogBuffersForExclusivePublicationIfDisabled()
{
final int streamId = -53453894;
final String channel = "aeron:ipc?alias=test";
final long publicationId = 113;
final String logFileName = SESSION_ID_2 + "-log";
context.preTouchMappedMemory(false)... |
public static FactoryBuilder newFactoryBuilder() {
return new FactoryBuilder();
} | @Test void injectKindFormats_cantBeBothSingle() {
assertThatThrownBy(() -> B3Propagation.newFactoryBuilder()
.injectFormats(Span.Kind.CLIENT, Format.SINGLE, Format.SINGLE_NO_PARENT))
.isInstanceOf(IllegalArgumentException.class);
} |
static void closeStateManager(final Logger log,
final String logPrefix,
final boolean closeClean,
final boolean eosEnabled,
final ProcessorStateManager stateMgr,
... | @Test
public void testCloseStateManagerClean() {
final InOrder inOrder = inOrder(stateManager, stateDirectory);
when(stateManager.taskId()).thenReturn(taskId);
when(stateDirectory.lock(taskId)).thenReturn(true);
StateManagerUtil.closeStateManager(logger,
"logPrefix:", tr... |
@Override
public String requestMessageForLatestRevision(SCMPropertyConfiguration scmConfiguration, Map<String, String> materialData, String flyweightFolder) {
Map configuredValues = new LinkedHashMap();
configuredValues.put("scm-configuration", jsonResultMessageHandler.configurationToMap(scmConfigur... | @Test
public void shouldBuildRequestBodyForLatestRevisionRequest() throws Exception {
String requestBody = messageHandler.requestMessageForLatestRevision(scmPropertyConfiguration, materialData, "flyweight");
assertThat(requestBody, is("{\"scm-configuration\":{\"key-one\":{\"value\":\"value-one\"},\... |
@Override
public void updateNetwork(Network osNet) {
checkNotNull(osNet, ERR_NULL_NETWORK);
checkArgument(!Strings.isNullOrEmpty(osNet.getId()), ERR_NULL_NETWORK_ID);
osNetworkStore.updateNetwork(osNet);
OpenstackNetwork finalAugmentedNetwork = buildAugmentedNetworkFromType(osNet);... | @Test(expected = IllegalArgumentException.class)
public void testUpdateUnregisteredNetwork() {
target.updateNetwork(NETWORK);
} |
@Override
public int getMaxColumnsInIndex() {
return 0;
} | @Test
void assertGetMaxColumnsInIndex() {
assertThat(metaData.getMaxColumnsInIndex(), is(0));
} |
public static SourceDescription create(
final DataSource dataSource,
final boolean extended,
final List<RunningQuery> readQueries,
final List<RunningQuery> writeQueries,
final Optional<TopicDescription> topicDescription,
final List<QueryOffsetSummary> queryOffsetSummaries,
fina... | @Test
public void shouldReturnEmptyTimestampColumn() {
// Given:
final String kafkaTopicName = "kafka";
final DataSource dataSource = buildDataSource(kafkaTopicName, Optional.empty());
// When
final SourceDescription sourceDescription = SourceDescriptionFactory.create(
dataSource,
... |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenSingleSubPathsWithTrailingSlash_returnsExpectedUrl() {
assertThat(allSubPaths("http://localhost/a/"))
.containsExactly(HttpUrl.parse("http://localhost/"), HttpUrl.parse("http://localhost/a/"));
} |
@Override
public T add(K name, V value) {
validateName(nameValidator, true, name);
validateValue(valueValidator, name, value);
checkNotNull(value, "value");
int h = hashingStrategy.hashCode(name);
int i = index(h);
add0(h, i, name, value);
return thisT();
... | @Test
public void headersWithSameNamesButDifferentValuesShouldNotBeEquivalent() {
TestDefaultHeaders headers1 = newInstance();
headers1.add(of("name1"), of("value1"));
TestDefaultHeaders headers2 = newInstance();
headers1.add(of("name1"), of("value2"));
assertNotEquals(header... |
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
... | @Test
public void testInitializerInterfaceWithBuilder() {
ChannelMapping channelMapping = SingletonServiceFactory.getBean(ChannelMapping.class);
Assert.assertNotNull(channelMapping);
Assert.assertTrue(channelMapping.transform("ReplyTo").startsWith("aggregate-destination-"));
} |
@Override
public int get(PageId pageId, int bytesToRead, CacheScope cacheScope) {
mShadowCachePageRead.getAndIncrement();
mShadowCacheByteRead.getAndAdd(bytesToRead);
if (mFilter.mightContainAndResetClock(pageId)) {
mShadowCachePageHit.getAndIncrement();
mShadowCacheByteHit.getAndAdd(bytesToRe... | @Test
public void getNotExist() throws Exception {
assertEquals(0, mCacheManager.get(PAGE_ID1, PAGE1_BYTES, SCOPE1));
} |
public static JWTValidator of(String token) {
return new JWTValidator(JWT.of(token));
} | @Test
public void validateTest() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJNb0xpIiwiZXhwIjoxNjI0OTU4MDk0NTI4LCJpYXQiOjE2MjQ5NTgwMzQ1MjAsInVzZXIiOiJ1c2VyIn0.L0uB38p9sZrivbmP0VlDe--j_11YUXTu3TfHhfQhRKc";
byte[] key = "1234567890".getBytes();
boolean validate = JWT.of(token).setKey(key).vali... |
public Optional<String> retrieveTitle(final GRN itemGrn, final SearchUser searchUser) {
if (isSpecialView(itemGrn)) {
final ViewResolverDecoder decoder = new ViewResolverDecoder(itemGrn.entity());
if (decoder.isResolverViewId()) {
final ViewResolver viewResolver = viewRes... | @Test
void testReturnsIdIfTitleIsMissing() throws Exception {
doReturn(Optional.of(new Catalog.Entry("id", null))).when(catalog).getEntry(any());
assertEquals(Optional.of("id"), toTest.retrieveTitle(grn, searchUser));
} |
@ConstantFunction(name = "bitShiftLeft", argTypes = {TINYINT, BIGINT}, returnType = TINYINT)
public static ConstantOperator bitShiftLeftTinyInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createTinyInt((byte) (first.getTinyInt() << second.getBigint()));
} | @Test
public void bitShiftLeftTinyInt() {
assertEquals(80, ScalarOperatorFunctions.bitShiftLeftTinyInt(O_TI_10, O_BI_3).getTinyInt());
} |
public CellFormatter getFormatter(String columnId) {
checkId(columnId);
CellFormatter fmt = formatters.get(columnId);
return fmt == null ? DEF_FMT : fmt;
} | @Test(expected = IllegalArgumentException.class)
public void formatterBadColumn() {
tm = new TableModel(FOO);
fmt = tm.getFormatter(BAR);
} |
static Serde<List<?>> createSerde(final PersistenceSchema schema) {
final List<SimpleColumn> columns = schema.columns();
if (columns.isEmpty()) {
// No columns:
return new KsqlVoidSerde<>();
}
if (columns.size() != 1) {
throw new KsqlException("The '" + FormatFactory.KAFKA.name()
... | @Test
public void shouldThrowIfArray() {
// Given:
final PersistenceSchema schema = schemaWithFieldOfType(SqlTypes.array(SqlTypes.STRING));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> KafkaSerdeFactory.createSerde(schema)
);
// Then:
assertThat(e... |
@Udf
public List<String> items(@UdfParameter final String jsonItems) {
if (jsonItems == null) {
return null;
}
final List<JsonNode> objectList = UdfJsonMapper.readAsJsonArray(jsonItems);
final List<String> res = new ArrayList<>();
objectList.forEach(jsonObject -> {
res.add(jsonObject... | @Test
public void shouldReturnEmptyListForEmptyArray() {
assertEquals(Collections.emptyList(), udf.items("[]"));
} |
public static DeletePOptions deleteDefaults(AlluxioConfiguration conf) {
return deleteDefaults(conf, true);
} | @Test
public void deleteOptionsDefaults() {
DeletePOptions options = FileSystemOptionsUtils.deleteDefaults(mConf);
assertNotNull(options);
assertFalse(options.getRecursive());
assertFalse(options.getAlluxioOnly());
assertFalse(options.getUnchecked());
} |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void maintenance_mode_counted_as_down_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
.proposeStorageNodeWantedState(2, State.MAINTENANCE);
... |
@SuppressFBWarnings(justification = "Accepting that this is a bad practice - used a Boolean as we needed three states",
value = {"NP_BOOLEAN_RETURN_NULL"})
public Boolean getBooleanArgument(String argument) {
if (line != null && line.hasOption(argument)) {
final String value = line.g... | @Test
public void testGetBooleanArgument() throws ParseException {
String[] args = {"--scan", "missing.file", "--artifactoryUseProxy", "false", "--artifactoryParallelAnalysis", "true", "--project", "test"};
CliParser instance = new CliParser(getSettings());
try {
instance.parse(... |
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors(
ReconnaissanceReport reconnaissanceReport) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> isVulnDetector(entry.getKey()))
.map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc... | @Test
public void getVulnDetectors_whenServiceNameFilterHasMatchingService_returnsMatchedService() {
NetworkService httpService =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80))
.setTransportProtocol(TransportProtocol.TCP)
... |
@Override
public TopicCleanupPolicy getTopicCleanupPolicy(final String topicName) {
final String policy = getTopicConfig(topicName)
.getOrDefault(TopicConfig.CLEANUP_POLICY_CONFIG, "")
.toLowerCase();
if (policy.equals("compact")) {
return TopicCleanupPolicy.COMPACT;
} else if (poli... | @Test
public void shouldGetTopicCleanUpPolicyCompact() {
// Given:
givenTopicConfigs(
"foo",
overriddenConfigEntry(CLEANUP_POLICY_CONFIG, CLEANUP_POLICY_COMPACT)
);
// When / Then:
assertThat(kafkaTopicClient.getTopicCleanupPolicy("foo"),
is(TopicCleanupPolicy.COMPACT));
... |
public ClassLoader compile(CompileUnit... units) {
return compile(Arrays.asList(units), compileState -> compileState.lock.lock());
} | @Test
public void testCompile() throws Exception {
CodeGenerator codeGenerator = CodeGenerator.getSharedCodeGenerator(getClass().getClassLoader());
CompileUnit unit1 =
new CompileUnit(
"demo.pkg1",
"A",
(""
+ "package demo.pkg1;\n"
+ ... |
@Subscribe
public void onScriptCallbackEvent(ScriptCallbackEvent event)
{
String eventName = event.getEventName();
int[] intStack = client.getIntStack();
String[] stringStack = client.getStringStack();
int intStackSize = client.getIntStackSize();
int stringStackSize = client.getStringStackSize();
switch... | @Test
public void testNonExplicitSearch()
{
when(client.getIntStack()).thenReturn(new int[]{0, ABYSSAL_WHIP});
when(client.getStringStack()).thenReturn(new String[]{"whip"});
when(configManager.getConfiguration(BankTagsPlugin.CONFIG_GROUP,
TagManager.ITEM_KEY_PREFIX + ABYSSAL_WHIP)).thenReturn("herb,bossing... |
@SuppressWarnings("unchecked")
@VisibleForTesting
Schema<T> initializeSchema() throws ClassNotFoundException {
if (StringUtils.isEmpty(this.pulsarSinkConfig.getTypeClassName())) {
return (Schema<T>) Schema.BYTES;
}
Class<?> typeArg = Reflections.loadClass(this.pulsarSinkConf... | @Test
public void testVoidOutputClasses() throws Exception {
PulsarSinkConfig pulsarConfig = getPulsarConfigs();
// set type to void
pulsarConfig.setTypeClassName(Void.class.getName());
PulsarSink pulsarSink =
new PulsarSink(getPulsarClient(), pulsarConfig, new HashMa... |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
RedisClusterNode master = getFirstMaster();
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
} |
List<MappingField> resolveAndValidateFields(List<MappingField> userFields, Map<String, ?> options) {
if (options.get(OPTION_FORMAT) == null) {
throw QueryException.error("Missing '" + OPTION_FORMAT + "' option");
}
if (options.get(OPTION_PATH) == null) {
throw QueryExcept... | @Test
public void test_resolveAndValidateFields() {
// given
Map<String, String> options = Map.of(OPTION_FORMAT, FORMAT, OPTION_PATH, "/path", OPTION_GLOB, "*");
given(resolver.resolveAndValidateFields(emptyList(), options))
.willReturn(singletonList(new MappingField("field"... |
@Override
public void deleteAiVideoTemplate(Long id) {
// 校验存在
validateAiVideoTemplateExists(id);
// 删除
aiVideoTemplateMapper.deleteById(id);
} | @Test
public void testDeleteAiVideoTemplate_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> aiVideoTemplateService.deleteAiVideoTemplate(id), AI_VIDEO_TEMPLATE_NOT_EXISTS);
} |
public static PipelineIR compileSources(List<SourceWithMetadata> sourcesWithMetadata, boolean supportEscapes, ConfigVariableExpander cve) throws InvalidIRException {
Map<PluginDefinition.Type, List<Graph>> groupedPipelineSections = sourcesWithMetadata.stream()
.map(swm -> compileGraph(swm, suppo... | @Test
public void testCompileWithFullyCommentedSource() throws InvalidIRException {
List<SourceWithMetadata> sourcesWithMetadata = Arrays.asList(
new SourceWithMetadata("str", "in_plugin", 0, 0, "input { input_0 {} } "),
new SourceWithMetadata("str","commented_filter",0,0,"#f... |
public Optional<String> fetchFileIfNotModified(String url) throws IOException {
return fetchFile(url, true);
} | @Test
public void successfulRetrieve() throws Exception {
this.server.enqueue(new MockResponse()
.setResponseCode(200)
.setBody("foobar"));
server.start();
final HTTPFileRetriever httpFileRetriever = new HTTPFileRetriever(new OkHttpClient());
final O... |
public DoubleArrayAsIterable usingTolerance(double tolerance) {
return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_containsExactly_primitiveDoubleArray_inOrder_success() {
assertThat(array(1.1, TOLERABLE_2POINT2, 3.3))
.usingTolerance(DEFAULT_TOLERANCE)
.containsExactly(array(1.1, 2.2, 3.3))
.inOrder();
} |
@Override
public AppResponse process(Flow flow, ActivateAppRequest body) {
String decodedPin = ChallengeService.decodeMaskedPin(appSession.getIv(), appAuthenticator.getSymmetricKey(), body.getMaskedPincode());
if ((decodedPin == null || !Pattern.compile("\\d{5}").matcher(decodedPin).matches())) {
... | @Test
void processDigidAppNotEnabled(){
when(mockedFlow.activateApp(eq(mockedAppAuthenticator), any(AppSession.class))).thenReturn(mockedActivateAppResponse);
when(mockedFlow.setFailedStateAndReturnNOK(any(AppSession.class))).thenReturn(new NokResponse());
assertThrows(SwitchDisabledExcepti... |
@PutMapping(value = "/node/list")
@Secured(action = ActionTypes.WRITE, resource = "nacos/admin", signType = SignType.CONSOLE)
public Result<Boolean> updateNodes(@RequestBody List<Member> nodes) throws NacosApiException {
if (nodes == null || nodes.size() == 0) {
throw new NacosApiException(H... | @Test
void testUpdate() throws NacosApiException {
Member member = new Member();
member.setIp("1.1.1.1");
member.setPort(8848);
member.setAddress("test");
when(nacosClusterOperationService.updateNodes(any())).thenReturn(true);
Result<Boolean> result = nacosClusterCont... |
public static void build(Map<String, Object> argsMap, String agentPath) {
final Properties configMap = loadConfig(agentPath);
addNotNullEntries(argsMap, configMap);
addNormalEntries(argsMap, configMap);
addPathEntries(argsMap, agentPath);
} | @Test
public void testParseArgs() {
String agentArgs = "appName=test,command=INSTALL_PLUGIN:monitor/flowcontrol,server.port=9000";
Map<String, String> agentArgsMap = AgentArgsResolver.resolveAgentArgs(agentArgs);
Map<String, Object> bootArgsMap = new HashMap<>(agentArgsMap);
BootArgs... |
public static int compareVersion(final String versionA, final String versionB) {
final String[] sA = versionA.split("\\.");
final String[] sB = versionB.split("\\.");
int expectSize = 3;
if (sA.length != expectSize || sB.length != expectSize) {
throw new IllegalArgumentExcept... | @Test
void testVersionCompareLt() {
assertTrue(VersionUtils.compareVersion("1.2.0", "1.2.1") < 0);
assertTrue(VersionUtils.compareVersion("0.2.0", "1.2.0") < 0);
assertTrue(VersionUtils.compareVersion("1.2.0", "1.3.0") < 0);
} |
@Override
public String getProcessRoleConfigsResponseBody(List<PluginRoleConfig> roles) {
List<Map> list = new ArrayList<>();
for (PluginRoleConfig role : roles) {
LinkedHashMap<String, Object> e = new LinkedHashMap<>();
e.put("name", role.getName().toString());
e... | @Test
void getProcessRoleConfigsResponseBody() {
String json = converter.getProcessRoleConfigsResponseBody(List.of(new PluginRoleConfig("blackbird", "ldap", create("foo", false, "bar"))));
assertThatJson("[{\"name\":\"blackbird\",\"configuration\":{\"foo\":\"bar\"}}]").isEqualTo(json);
} |
@GetMapping(value = "/previous")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
public Result<ConfigHistoryInfo> getPreviousConfigHistoryInfo(@RequestParam("dataId") String dataId,
@RequestParam("group") String group,
@RequestParam(value = "namespaceId", required = false... | @Test
void testGetPreviousConfigHistoryInfoWhenNameSpaceIsPublic() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId(TEST_DATA_ID);
configHistoryInfo.setGroup(TEST_GROUP);
configHistoryInfo.setContent(TEST_CONTENT);... |
@Override
public void serialize(Asn1OutputStream out, String oid) throws IOException {
Asn1Utils.encodeObjectIdentifier(oid, out);
} | @Test
public void shouldSerialize() {
assertArrayEquals(
new byte[] { 0x2a, 0x03 },
serialize(new ObjectIdentifierConverter(), String.class, "1.2.3")
);
} |
protected static boolean isBeanPropertyWriteMethod(Method method) {
return method != null
&& Modifier.isPublic(method.getModifiers())
&& !Modifier.isStatic(method.getModifiers())
&& method.getDeclaringClass() != Object.class
&& method.getParameterTypes().length ==... | @Test
public void testIsBeanPropertyWriteMethod() throws Exception {
Assert.assertFalse(isBeanPropertyWriteMethod(null));
Assert.assertTrue(isBeanPropertyWriteMethod(TestReflect.class.getMethod("setS", int.class)));
Assert.assertFalse(isBeanPropertyWriteMethod(TestReflect.class.getMethod("se... |
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData,
TypeReference<T> responseFormat) {
return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null);
} | @Test
public void testIOExceptionCausesInternalServerError() throws Exception {
Request req = mock(Request.class);
ContentResponse resp = mock(ContentResponse.class);
setupHttpClient(201, req, resp);
ConnectRestException e = assertThrows(ConnectRestException.class, () -> httpRequest... |
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存
public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) {
// 1. 无数据权限
if (CollUtil.isEmpty(rules)) {
return Collections.emptyList();
}
// 2. 未配置,则默认开启
D... | @Test
public void testGetDataPermissionRule_06() {
// 准备参数
String mappedStatementId = randomString();
// mock 方法
DataPermissionContextHolder.add(AnnotationUtils.findAnnotation(TestClass06.class, DataPermission.class));
// 调用
List<DataPermissionRule> result = dataPerm... |
protected Record[] getRecords(Name name, int type) {
Record[] result = null;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Record[]> future = executor.submit(new LookupTask(name, type));
try {
result = future.get(1500, TimeUnit.MILLISECONDS);
return result;
} cat... | @Test(timeout=5000)
public void testUpstreamFault() throws Exception {
Name name = Name.fromString("19.0.17.172.in-addr.arpa.");
Record[] recs = getRegistryDNS().getRecords(name, Type.CNAME);
assertNull("Record is not null", recs);
} |
public static String getMetaDataProcessConfigPath(final String jobType) {
return String.join("/", getMetaDataRootPath(jobType), "process_config");
} | @Test
void assertGetMetaDataProcessConfigPath() {
assertThat(PipelineMetaDataNode.getMetaDataProcessConfigPath("FIXTURE"), is(migrationMetaDataRootPath + "/process_config"));
} |
private AccessLog(String logFormat, Object... args) {
Objects.requireNonNull(logFormat, "logFormat");
this.logFormat = logFormat;
this.args = args;
} | @Test
void accessLogCustomFormat() {
disposableServer = createServer()
.handle((req, resp) -> {
resp.withConnection(conn -> {
ChannelHandler handler = conn.channel().pipeline().get(NettyPipeline.AccessLogHandler);
resp.header(ACCESS_LOG_HANDLER, handler != null ? FOUND : NOT_FOUND);
});
... |
@SuppressWarnings("unchecked")
public static <T> T[] concat(Class<T> type, T[]... arrays) {
T[] result = (T[]) Array.newInstance(type, totalLength(arrays));
int currentLength = 0;
for (T[] array : arrays) {
int length = array.length;
if (length > 0) {
System.arraycopy(array, 0, resul... | @Test
public void testConcatWithEmptyArrays() {
String[] array1 = {};
String[] array2 = {"a", "b"};
String[] result = ArrayUtil.concat(String.class, array1, array2);
assertThat(result).isEqualTo(new String[] {"a", "b"});
} |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatInsertIntoPartitionBy() {
final String statementString = "INSERT INTO ADDRESS SELECT * FROM ADDRESS PARTITION BY ADDRESS;";
final Statement statement = parseSingle(statementString);
final String result = SqlFormatter.formatSql(statement);
assertThat(result, startsWith("... |
void releaseMemory(@Nonnegative long size) {
if (size == 0) {
return;
}
boolean released = false;
long currentAvailableMemorySize = 0L;
while (!released
&& totalMemorySize
>= (currentAvailableMemorySize = availableMemorySize.get... | @Test
void testReleaseMemory() throws MemoryReservationException {
UnsafeMemoryBudget budget = createUnsafeMemoryBudget();
budget.reserveMemory(50L);
budget.releaseMemory(30L);
assertThat(budget.getAvailableMemorySize()).isEqualTo(80L);
} |
public static Map<String, PartitionColumnFilter> convertColumnFilter(List<ScalarOperator> predicates) {
return convertColumnFilter(predicates, null);
} | @Test
public void convertColumnFilterNormal() {
ScalarOperator root1 = new BinaryPredicateOperator(BinaryType.EQ,
new ColumnRefOperator(1, Type.INT, "age", true),
ConstantOperator.createInt(1));
ScalarOperator root2 = new InPredicateOperator(new ColumnRefOperator(2, ... |
@Override
public Material toOldMaterial(String name, String folder, String password) {
HgMaterial hg = new HgMaterial(url, folder);
setName(name, hg);
hg.setId(id);
hg.setUserName(username);
hg.setPassword(password);
hg.setBranch(branch);
return hg;
} | @Test
void shouldCreateMaterialFromMaterialInstance() {
final HgMaterialInstance materialInstance = new HgMaterialInstance("https://example.com", "bob",
"feature", "some-flyweight");
materialInstance.setId(100L);
final HgMaterial material = (HgMaterial) materialInstance.toOl... |
public int deleteByIdAndRevision(ModelId id, int revision) {
final DBQuery.Query query = DBQuery.is(Identified.FIELD_META_ID, id).is(Revisioned.FIELD_META_REVISION, revision);
final WriteResult<ContentPack, ObjectId> writeResult = dbCollection.remove(query);
return writeResult.getN();
} | @Test
@MongoDBFixtures("ContentPackPersistenceServiceTest.json")
public void deleteByIdAndRevision() {
final int deletedContentPacks = contentPackPersistenceService.deleteByIdAndRevision(ModelId.of("dcd74ede-6832-4ef7-9f69-deadbeef0000"), 2);
final Set<ContentPack> contentPacks = contentPackPers... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldLoadQueryFile() {
// Given:
givenQueryFileContains("This statement");
// When:
standaloneExecutor.startAsync();
// Then:
verify(ksqlEngine).parse("This statement");
} |
@Override
public SchemaResult getValueSchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false);
} | @Test
public void shouldReturnErrorFromGetValueSchemaIfSchemaIsNotInExpectedFormat() {
// Given:
when(parsedSchema.schemaType()).thenReturn(ProtobufSchema.TYPE);
// When:
final SchemaResult result = supplier.getValueSchema(Optional.of(TOPIC_NAME),
Optional.empty(), expectedFormat, SerdeFeatur... |
@Override
public Optional<BlobDescriptor> handleHttpResponseException(ResponseException responseException)
throws ResponseException {
if (responseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
throw responseException;
}
if (responseException.getContent() == null) {
... | @Test
public void testHandleHttpResponseException() throws IOException {
ResponseException mockResponseException = Mockito.mock(ResponseException.class);
Mockito.when(mockResponseException.getStatusCode())
.thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
ErrorResponseTemplate emptyErrorRespons... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (scmReport.hasChangesetForLine(lineBuilder.getLine())) {
Changeset changeset = scmReport.getChangesetForLine(lineBuilder.getLine());
String author = changeset.getAuthor();
if (author != null) {
lineBui... | @Test
public void set_scm() {
ScmInfo scmInfo = new ScmInfoImpl(new Changeset[] {
Changeset.newChangesetBuilder()
.setAuthor("john")
.setDate(123_456_789L)
.setRevision("rev-1")
.build()});
ScmLineReader lineScm = new ScmLineReader(scmInfo);
DbFileSources.Line.Build... |
public <InputT, CollectionT extends PCollection<? extends InputT>>
Map<String, DataSet<?>> applyMultiOutputBeamPTransform(
DataSet<InputT> input, PTransform<CollectionT, PCollectionTuple> transform) {
return applyBeamPTransformInternal(
ImmutableMap.of("input", input),
(pipeline, map... | @Test
public void testApplyMultiOutputTransform() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.createCollectionsEnvironment();
DataSet<String> input = env.fromCollection(ImmutableList.of("a", "b", "c"));
Map<String, DataSet<?>> result =
new BeamFlinkDataSetAdapter()
... |
public T getMetaForEntry( Repository rep, IMetaStore metaStore, VariableSpace space ) throws KettleException {
try {
T theMeta = null;
if ( jobEntryBase.getParentJob() != null ) {
metaFileCache = jobEntryBase.getParentJobMeta().getMetaFileCache(); //Get the cache from the parent or create it
... | @Test
//A job getting the TransMeta from the fileSystem
public void getMetaForEntryAsTransFromFileSystemTest() throws Exception {
setupJobEntryTrans();
specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
MetaFileLoaderImpl metaFileLoader = new MetaFileLoaderImpl<TransMeta>( jobEntryBase, s... |
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 testEstimatePixelCountAllUnknown() {
assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, WIDTH_UNKNOWN), 1.0 ), 0.0);
assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, WIDTH_UNKNOWN), 12.0 ), 0.0);
assertEquals(0.0, estimatePixelCount(img(HEIGHT_UNKNOWN, ... |
@Override
public void handle(final RoutingContext routingContext) {
if (routingContext.request().isSSL()) {
final String indicatedServerName = routingContext.request().connection()
.indicatedServerName();
final String requestHost = routingContext.request().host();
if (indicatedServerNa... | @Test
public void shouldReturnMisdirectedResponse() {
// Given:
when(serverRequest.host()).thenReturn("localhost");
when(httpConnection.indicatedServerName()).thenReturn("anotherhost");
// When:
sniHandler.handle(routingContext);
// Then:
verify(routingContext, never()).next();
verif... |
@Override
public FsCompletedCheckpointStorageLocation closeAndFinalizeCheckpoint() throws IOException {
synchronized (this) {
if (!closed) {
try {
// make a best effort attempt to figure out the size
long size = 0;
try {... | @TestTemplate
void testFileExistence() throws Exception {
Path metaDataFilePath = baseFolder();
FsCheckpointMetadataOutputStream stream = createTestStream(metaDataFilePath, fileSystem);
if (fileSystem instanceof FsWithoutRecoverableWriter) {
assertThat(fileSystem.exists(metaData... |
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
... | @Test
public void testSubmitReservationInvalidDeadline() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 0, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSyst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.