focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_disable() {
// mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.DISABLE.getStatus()));
tenantMapper.insert(tenant);
// 调用,并断言业务异常
assertServiceException(() -> tenantService.validTenant(1L), TEN... |
public User userDTOToUser(AdminUserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.s... | @Test
void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
User user = userMapper.userDTOToUser(userDto);
assertThat(user).isNotNull();
assertThat(user.getAuthorities()).isNotNull();
assertThat(user.getAuthorit... |
@VisibleForTesting
void scan(long streamTimeout) {
ArrayList<OpenFileCtx> ctxToRemove = new ArrayList<OpenFileCtx>();
Iterator<Entry<FileHandle, OpenFileCtx>> it = openFileMap.entrySet()
.iterator();
if (LOG.isTraceEnabled()) {
LOG.trace("openFileMap size:" + size());
}
while (it.ha... | @Test
public void testScan() throws IOException, InterruptedException {
NfsConfiguration conf = new NfsConfiguration();
// Only two entries will be in the cache
conf.setInt(NfsConfigKeys.DFS_NFS_MAX_OPEN_FILES_KEY, 2);
DFSClient dfsClient = Mockito.mock(DFSClient.class);
Nfs3FileAttributes attr ... |
public static <MSG extends Message> CloseableIterator<MSG> readStream(File file, Parser<MSG> parser) {
try {
// the input stream is closed by the CloseableIterator
BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
return readStream(input, parser);
} catch (Excepti... | @Test
public void read_empty_stream() throws Exception {
File file = temp.newFile();
CloseableIterator<Fake> it = Protobuf.readStream(file, Fake.parser());
assertThat(it).isNotNull();
assertThat(it.hasNext()).isFalse();
} |
public void setWantClientAuth(Boolean wantClientAuth) {
this.wantClientAuth = wantClientAuth;
} | @Test
public void testSetWantClientAuth() throws Exception {
configuration.setWantClientAuth(true);
configuration.configure(configurable);
assertTrue(configurable.isWantClientAuth());
} |
@SuppressWarnings("unchecked")
@SneakyThrows(ReflectiveOperationException.class)
public static <T> T invokeMethod(final Method method, final Object target, final Object... args) {
boolean accessible = method.isAccessible();
if (!accessible) {
method.setAccessible(true);
}
... | @Test
void assertInvokeMethod() throws NoSuchMethodException {
assertThat(ReflectionUtils.invokeMethod(ReflectionFixture.class.getDeclaredMethod("getInstanceValue"), new ReflectionFixture()), is("instance_value"));
} |
@Override
public long readLong() {
checkReadableBytes0(8);
long v = _getLong(readerIndex);
readerIndex += 8;
return v;
} | @Test
public void testReadLongAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readLong();
}
});
} |
public void registerNewEventDefinition(String id, User user) {
final GRN grn = grnRegistry.newGRN(GRNTypes.EVENT_DEFINITION, id);
registerNewEntity(grn, user);
} | @Test
void registerNewEventDefinition() {
final User mockUser = mock(User.class);
when(mockUser.getName()).thenReturn("mockuser");
when(mockUser.getId()).thenReturn("mockuser");
entityOwnershipService.registerNewEventDefinition("1234", mockUser);
ArgumentCaptor<GrantDTO> gr... |
public static byte[] reverseBytes(byte[] bytes) {
// We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a
// performance issue the matter can be revisited.
byte[] buf = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++)
... | @Test
public void testReverseBytes() {
assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, ByteUtils.reverseBytes(new byte[]{5, 4, 3, 2, 1}));
assertArrayEquals(new byte[]{0}, ByteUtils.reverseBytes(new byte[]{0}));
assertArrayEquals(new byte[]{}, ByteUtils.reverseBytes(new byte[]{}));
} |
@Override
public ModuleState build() {
ModuleState moduleState = new ModuleState(DistroConstants.DISTRO_MODULE);
moduleState.newState(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS_STATE,
EnvUtil.getProperty(DistroConstants.DATA_SYNC_DELAY_MILLISECONDS, Long.class,
... | @Test
void testBuild() {
ModuleState actual = new DistroModuleStateBuilder().build();
Map<String, Object> states = actual.getStates();
assertEquals(DistroConstants.DISTRO_MODULE, actual.getModuleName());
assertEquals(DistroConstants.DEFAULT_DATA_SYNC_DELAY_MILLISECONDS, states.get(Di... |
@Nullable static String normalizeIdField(String field, @Nullable String id, boolean isNullable) {
if (id == null) {
if (isNullable) return null;
throw new NullPointerException(field + " == null");
}
int length = id.length();
if (length == 0) {
if (isNullable) return null;
throw n... | @Test void normalizeIdField_badCharacters() {
assertThatThrownBy(() -> normalizeIdField("traceId", "000-0000000004d20000000ss000162e", false))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("traceId should be lower-hex encoded with no prefix");
} |
public static List<URL> parseConfigurators(String rawConfig) {
// compatible url JsonArray, such as [ "override://xxx", "override://xxx" ]
List<URL> compatibleUrls = parseJsonArray(rawConfig);
if (CollectionUtils.isNotEmpty(compatibleUrls)) {
return compatibleUrls;
}
... | @Test
void parseConfiguratorsAppNoServiceTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
Ass... |
public void insert(String data) {
this.insert(this.root, data);
} | @Test
public void prefixSearch44() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("a");
trieTree.insert("b");
trieTree.insert("c");
trieTree.insert("d");
trieTree.insert("e");
trieTree.insert("f");
trieTree.insert("g");
... |
protected void connect0(CertConfig certConfig) {
String caCertPath = certConfig.getCaCertPath();
String remoteAddress = certConfig.getRemoteAddress();
logger.info(
"Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress);
try {... | @Test
void testConnect2() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
String file =
this.getClass().getClassLoader().getResource("certs/ca.crt").getFile();
CertConfig certConfig = new Cer... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void quantifiedExpressionSome() {
String inputExpression = "some item in order.items satisfies item.price > 100";
BaseNode someBase = parse( inputExpression );
assertThat( someBase).isInstanceOf(QuantifiedExpressionNode.class);
assertThat( someBase.getText()).isEqualTo(inputEx... |
public List<StateObject> getDiscardables() {
return Stream.concat(
streamOperatorAndKeyedStates().flatMap(Collection::stream),
collectUniqueDelegates(streamChannelStates()))
.collect(Collectors.toList());
} | @Test
void testGetDiscardables() throws IOException {
Tuple2<List<StateObject>, OperatorSubtaskState> opStates =
generateSampleOperatorSubtaskState();
List<StateObject> states = opStates.f0;
OperatorSubtaskState operatorSubtaskState = opStates.f1;
List<StateObject> di... |
@Override
public short getTypeCode() {
return MessageType.TYPE_GLOBAL_BEGIN_RESULT;
} | @Test
public void testGetTypeCode() {
GlobalBeginResponse globalBeginResponse = new GlobalBeginResponse();
Assertions.assertEquals(MessageType.TYPE_GLOBAL_BEGIN_RESULT, globalBeginResponse.getTypeCode());
} |
public void set(int i) {
throw new UnsupportedOperationException("RangeSet is immutable");
} | @Test(expected = UnsupportedOperationException.class)
public void set() throws Exception {
RangeSet rs = new RangeSet(4);
rs.set(1);
} |
@Override
public AbstractUploadFilter filter(final Session<?> source, final Session<?> destination, final TransferAction action, final ProgressListener listener) {
if(log.isDebugEnabled()) {
log.debug(String.format("Filter transfer with action %s and options %s", action, options));
}
... | @Test
public void testTemporaryDisabledMultipartUpload() throws Exception {
final Host h = new Host(new TestProtocol());
final NullSession session = new NullSession(h);
final AbstractUploadFilter f = new UploadTransfer(h, Collections.emptyList())
.filter(session, null, TransferAc... |
@Override
public int[] borrowIntArray(int positionCount)
{
checkState(getBorrowedArrayCount() < maxOutstandingArrays, "Requested too many arrays: %s", getBorrowedArrayCount());
int[] array;
while (!intArrays.isEmpty() && intArrays.peek().length < positionCount) {
array = intA... | @Test
public void testOverAllocateLeases()
{
SimpleArrayAllocator allocator = new SimpleArrayAllocator(2);
allocator.borrowIntArray(10);
allocator.borrowIntArray(10);
assertThrows(IllegalStateException.class, () -> allocator.borrowIntArray(10));
} |
@Udf(description = "Returns a new string with all matches of regexp in str replaced with newStr")
public String regexpReplace(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The regexp to match."
... | @Test(expected = KsqlFunctionException.class)
public void shouldThrowExceptionOnBadPattern() {
udf.regexpReplace("foobar", "(()", "bar");
} |
@Override
protected void analyzeDependency(final Dependency dependency, final Engine engine) throws AnalysisException {
// batch request component-reports for all dependencies
synchronized (FETCH_MUTIX) {
if (reports == null) {
try {
requestDelay();
... | @Test
public void should_enrich_be_included_in_mutex_to_prevent_NPE()
throws Exception {
// Given
SproutOssIndexAnalyzer analyzer = new SproutOssIndexAnalyzer();
Identifier identifier = new PurlIdentifier("maven", "test", "test", "1.0",
Confidence.HIGHEST);
... |
@Override
@Cacheable(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, key = "#code",
unless = "#result == null")
public NotifyTemplateDO getNotifyTemplateByCodeFromCache(String code) {
return notifyTemplateMapper.selectByCode(code);
} | @Test
public void testGetNotifyTemplateByCodeFromCache() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);
// 准备参数
String code = dbNotifyTemplate.getCode();
// 调用
NotifyTemplate... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void addSimpleFields() {
Schema schema = Schema.builder().addStringField("field1").build();
PCollection<Row> added =
pipeline
.apply(
Create.of(Row.withSchema(schema).addValue("value").build()).withRowSchema(schema))
.... |
public static void injectDefaults(Configuration source, Configuration target) {
Check.notNull(source, "source");
Check.notNull(target, "target");
for (Map.Entry<String, String> entry : source) {
if (target.get(entry.getKey()) == null) {
target.set(entry.getKey(), entry.getValue());
}
... | @Test
public void injectDefaults() throws Exception {
Configuration srcConf = new Configuration(false);
Configuration targetConf = new Configuration(false);
srcConf.set("testParameter1", "valueFromSource");
srcConf.set("testParameter2", "valueFromSource");
targetConf.set("testParameter2", "origi... |
public UniqueRuleItemNodePath getUniqueItem(final String itemType) {
return uniqueItems.get(itemType);
} | @Test
void assertGetUniqueItem() {
UniqueRuleItemNodePath uniqueRulePath = ruleNodePath.getUniqueItem("tables");
assertThat(uniqueRulePath.getPath(), is("tables"));
assertTrue(uniqueRulePath.isValidatedPath("/metadata/db/rules/foo/tables/versions/1234"));
UniqueRuleItemNodePath uniqu... |
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
List<EurekaEndpoint> candidateHosts = null;
int endpointIdx = 0;
for (int retry = 0; retry < numberOfRetries; retry++) {
EurekaHttpClient currentHttpClient = delegate.get();
Eu... | @Test
public void testRequestIsRetriedOnConnectionError() throws Exception {
when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0), clusterDelegates.get(1));
when(requestExecutor.execute(clusterDelegates.get(0))).thenThrow(new TransportException("simu... |
public static Builder builder() {
return new Builder();
} | @Test
public void testRoundTripSerDe() throws JsonProcessingException {
// Full request
String fullJson = "{\"removed\":[\"foo\"],\"updated\":[\"owner\"],\"missing\":[\"bar\"]}";
assertRoundTripSerializesEquallyFrom(
fullJson,
UpdateNamespacePropertiesResponse.builder()
.addUpd... |
public synchronized boolean createIndex(String indexName)
throws ElasticsearchResourceManagerException {
LOG.info("Creating index using name '{}'.", indexName);
try {
// Check to see if the index exists
if (indexExists(indexName)) {
return false;
}
managedIndexNames.add(i... | @Test
public void testCreateCollectionShouldReturnTrueIfElasticsearchDoesNotThrowAnyError()
throws IOException {
when(elasticsearchClient
.indices()
.exists(any(GetIndexRequest.class), eq(RequestOptions.DEFAULT)))
.thenReturn(false);
when(elasticsearchClient
.... |
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
} | @Test
public void testIsErrorEnabled() {
Log mockLog = mock(Log.class);
when(mockLog.isErrorEnabled()).thenReturn(true);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
assertTrue(logger.isErrorEnabled());
verify(mockLog).isErrorEnabled();
} |
@Override
public boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionState) {
return state.tryCall(
StateWithExecutionGraph.class,
stateWithExecutionGraph ->
stateWithExecutionGraph.updateTaskExecutionStat... | @Test
void testUpdateTaskExecutionStateReturnsFalseInIllegalState() throws Exception {
final JobGraph jobGraph = createJobGraph();
final AdaptiveScheduler scheduler =
new AdaptiveSchedulerBuilder(
jobGraph, mainThreadExecutor, EXECUTOR_RESOURCE.getExec... |
protected final static List<String> splitStringPreserveDelimiter(String str, Pattern SPLIT_PATTERN) {
List<String> list = new ArrayList<>();
if (str != null) {
Matcher matcher = SPLIT_PATTERN.matcher(str);
int pos = 0;
while (matcher.find()) {
if (pos ... | @Test
public void testSplitString2() {
List<String> list = DiffRowGenerator.splitStringPreserveDelimiter("test , test2", DiffRowGenerator.SPLIT_BY_WORD_PATTERN);
System.out.println(list);
assertEquals(5, list.size());
assertEquals("[test, , ,, , test2]", list.toString());
} |
public JwtBuilder jwtBuilder() {
return new JwtBuilder();
} | @Test
void testParseWith32Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey01234567890123456789012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
assertTrue(token.startsWith(NacosSignatureAlgorithm.HS256.getHeader()));
... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path f : files.keySet()) {
try {
if(f.isDirectory()) {
new FoldersApi(new BoxApiClient(session.getClien... | @Test
public void testDeleteMultipleFiles() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
final Path folder = new BoxDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)), new Tr... |
public Iterator<Optional<Page>> process(SqlFunctionProperties properties, DriverYieldSignal yieldSignal, LocalMemoryContext memoryContext, Page page)
{
WorkProcessor<Page> processor = createWorkProcessor(properties, yieldSignal, memoryContext, page);
return processor.yieldingIterator();
} | @Test
public void testProjectLazyLoad()
{
PageProcessor pageProcessor = new PageProcessor(Optional.of(new SelectAllFilter()), ImmutableList.of(new PageProjectionWithOutputs(new LazyPagePageProjection(), new int[] {
0})), OptionalInt.of(MAX_BATCH_SIZE));
// if channel 1 is loaded... |
@InvokeOnHeader(Web3jConstants.ETH_NEW_PENDING_TRANSACTION_FILTER)
void ethNewPendingTransactionFilter(Message message) throws IOException {
Request<?, EthFilter> request = web3j.ethNewPendingTransactionFilter();
setRequestId(message, request);
EthFilter response = request.send();
bo... | @Test
public void ethNewPendingTransactionFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewPendingTransactionFilter()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilt... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetFilterLogs() throws Exception {
web3j.ethGetFilterLogs(Numeric.toBigInt("0x16")).send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_getFilterLogs\","
+ "\"params\":[\"0x16\"],\"id\":1}");
} |
@Override
protected Object getTargetObject(boolean key) {
Object targetObject;
if (key) {
// keyData is never null
if (keyData.isPortable() || keyData.isJson() || keyData.isCompact()) {
targetObject = keyData;
} else {
targetObject ... | @Test
public void testGetTargetObject_givenKeyDataIsPortable_whenKeyFlagIsTrue_thenReturnKeyData() {
Data keyData = mockPortableData();
QueryableEntry entry = createEntry(keyData, new Object(), newExtractor());
Object targetObject = entry.getTargetObject(true);
assertSame(keyData, ... |
@Udf
public <T extends Comparable<? super T>> T arrayMax(@UdfParameter(
description = "Array of values from which to find the maximum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldReturnNullForListOfNullInput() {
final List<Integer> input = Arrays.asList(null, null, null);
assertThat(udf.arrayMax(input), is(nullValue()));
} |
@Override
public boolean hasAccess( RepositoryFilePermission perm ) throws KettleException {
if ( hasAccess == null ) {
hasAccess = new HashMap<RepositoryFilePermission, Boolean>();
}
if ( hasAccess.get( perm ) == null ) {
hasAccess.put( perm, new Boolean( aclService.hasAccess( getObjectId(), ... | @Test
public void testAccess() throws Exception {
when( mockAclService.hasAccess( mockObjectId, RepositoryFilePermission.READ ) ).thenReturn( true );
when( mockAclService.hasAccess( mockObjectId, RepositoryFilePermission.WRITE ) ).thenReturn( false );
assertTrue( uiTransformation.hasAccess( RepositoryFil... |
@Description("removes whitespace from the beginning and end of a string")
@ScalarFunction
@LiteralParameters("x")
@SqlType("varchar(x)")
public static Slice trim(@SqlType("varchar(x)") Slice slice)
{
return SliceUtf8.trim(slice);
} | @Test
public void testTrim()
{
assertFunction("TRIM('')", createVarcharType(0), "");
assertFunction("TRIM(' ')", createVarcharType(3), "");
assertFunction("TRIM(' hello ')", createVarcharType(9), "hello");
assertFunction("TRIM(' hello')", createVarcharType(7), "hello");
... |
public static GenericData get() {
return INSTANCE;
} | @Test
void testEquals() {
Schema s = recordSchema();
GenericRecord r0 = new GenericData.Record(s);
GenericRecord r1 = new GenericData.Record(s);
GenericRecord r2 = new GenericData.Record(s);
Collection<CharSequence> l0 = new ArrayDeque<>();
List<CharSequence> l1 = new ArrayList<>();
Generi... |
@Udf
public int field(
@UdfParameter final String str,
@UdfParameter final String... args
) {
if (str == null || args == null) {
return 0;
}
for (int i = 0; i < args.length; i++) {
if (str.equals(args[i])) {
return i + 1;
}
}
return 0;
} | @Test
public void shouldNotFindStringInNullArray() {
// When:
String[] array = null;
final int pos = field.field("1", array);
// Then:
assertThat(pos, equalTo(0));
} |
public static <K, X, Y, V> Map<K, V> merge(Map<K, X> map1, Map<K, Y> map2, BiFunction<X, Y, V> merge) {
if (MapUtil.isEmpty(map1) && MapUtil.isEmpty(map2)) {
return MapUtil.newHashMap(0);
} else if (MapUtil.isEmpty(map1)) {
map1 = MapUtil.newHashMap(0);
} else if (MapUtil.isEmpty(map2)) {
map2 = MapUtil.... | @Test
public void testMerge() {
Map<Long, Student> map1 = null;
Map<Long, Student> map2 = Collections.emptyMap();
Map<Long, String> map = CollStreamUtil.merge(map1, map2, (s1, s2) -> s1.getName() + s2.getName());
assertEquals(map, Collections.EMPTY_MAP);
map1 = new HashMap<>();
map1.put(1L, new Student(1, ... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowCreateExternalCatalogTable() throws DdlException, AnalysisException {
new MockUp<MetadataMgr>() {
@Mock
public Database getDb(String catalogName, String dbName) {
return new Database();
}
@Mock
public Tabl... |
public boolean unblock()
{
final AtomicBuffer buffer = this.buffer;
final long headPosition = buffer.getLongVolatile(headPositionIndex);
final long tailPosition = buffer.getLongVolatile(tailPositionIndex);
if (headPosition == tailPosition)
{
return false;
... | @Test
void shouldUnblockWhenFullWithHeader()
{
final int messageLength = ALIGNMENT * 4;
when(buffer.getLongVolatile(HEAD_COUNTER_INDEX)).thenReturn((long)messageLength);
when(buffer.getLongVolatile(TAIL_COUNTER_INDEX)).thenReturn((long)messageLength + CAPACITY);
when(buffer.getIn... |
@Override
public Object convert(String value) {
if (value == null || value.isEmpty()) {
return value;
}
final CSVParser parser = getCsvParser();
final Map<String, String> fields = Maps.newHashMap();
try {
final String[] strings = parser.parseLine(value... | @Test
@SuppressWarnings("unchecked")
public void testEdgeCases() throws ConfigurationException {
Map<String, Object> configMap = Maps.newHashMap();
configMap.put("column_header", "f1,f2");
CsvConverter csvConverter = new CsvConverter(configMap);
String resultString = (String) csv... |
@Override
public int deleteUndoLogByLogCreated(Date logCreated, int limitRows, Connection conn) throws SQLException {
try (PreparedStatement deletePST = conn.prepareStatement(DELETE_UNDO_LOG_BY_CREATE_SQL)) {
deletePST.setDate(1, new java.sql.Date(logCreated.getTime()));
deletePST.se... | @Test
public void testDeleteUndoLogByLogCreated() throws SQLException {
Assertions.assertEquals(0, undoLogManager.deleteUndoLogByLogCreated(new Date(), 3000, dataSource.getConnection()));
Assertions.assertDoesNotThrow(() -> undoLogManager.deleteUndoLogByLogCreated(new Date(), 3000, connectionProxy))... |
public List<AggregationProjection> getAggregationProjections() {
List<AggregationProjection> result = new LinkedList<>();
for (Projection each : projections) {
if (each instanceof AggregationProjection) {
AggregationProjection aggregationProjection = (AggregationProjection) e... | @Test
void assertGetAggregationProjections() {
Projection projection = getAggregationProjection();
List<AggregationProjection> items = new ProjectionsContext(0, 0, true, Arrays.asList(projection, getColumnProjection())).getAggregationProjections();
assertTrue(items.contains(projection));
... |
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
return index(keyFunction, Function.identity());
} | @Test
public void index_with_valueFunction_fails_if_value_function_returns_null() {
assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(index(MyObj::getId, s -> null)))
.isInstanceOf(NullPointerException.class)
.hasMessage("Value function can't return null");
} |
@InvokeOnHeader(Web3jConstants.NET_PEER_COUNT)
void netPeerCount(Message message) throws IOException {
Request<?, NetPeerCount> request = web3j.netPeerCount();
setRequestId(message, request);
NetPeerCount response = request.send();
boolean hasError = checkForError(message, response);... | @Test
public void netPeerCountTest() throws Exception {
BigInteger peerCount = BigInteger.ONE;
NetPeerCount response = Mockito.mock(NetPeerCount.class);
Mockito.when(mockWeb3j.netPeerCount()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when... |
public DirectGraph getGraph() {
checkState(finalized, "Can't get a graph before the Pipeline has been completely traversed");
return DirectGraph.create(
producers, viewWriters, perElementConsumers, rootTransforms, stepNames);
} | @Test
public void getValueToConsumersWithDuplicateInputSucceeds() {
PCollection<String> created = p.apply(Create.of("1", "2", "3"));
PCollection<String> flattened =
PCollectionList.of(created).and(created).apply(Flatten.pCollections());
p.traverseTopologically(visitor);
DirectGraph graph = ... |
public static TypeBuilder<Schema> builder() {
return new TypeBuilder<>(new SchemaCompletion(), new NameContext());
} | @Test
void testBoolean() {
Schema.Type type = Schema.Type.BOOLEAN;
Schema simple = SchemaBuilder.builder().booleanType();
Schema expected = primitive(type, simple);
Schema built1 = SchemaBuilder.builder().booleanBuilder().prop("p", "v").endBoolean();
assertEquals(expected, built1);
} |
public TopicList getSystemTopicList() {
TopicList topicList = new TopicList();
try {
this.lock.readLock().lockInterruptibly();
for (Map.Entry<String, Set<String>> entry : clusterAddrTable.entrySet()) {
topicList.getTopicList().add(entry.getKey());
... | @Test
public void testGetSystemTopicList() {
byte[] topicList = routeInfoManager.getSystemTopicList().encode();
assertThat(topicList).isNotNull();
} |
public static BinaryOperationExpression bind(final BinaryOperationExpression segment, final SegmentType parentSegmentType, final SQLStatementBinderContext binderContext,
final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinde... | @Test
void assertBinaryOperationExpression() {
BinaryOperationExpression binaryOperationExpression = new BinaryOperationExpression(0, 0,
new LiteralExpressionSegment(0, 0, "test"),
new LiteralExpressionSegment(0, 0, "test"), "=", "test");
SQLStatementBinderContext bin... |
@Override
public int size() {
return mWidth * mHeight;
} | @Test
public void testSize() {
final MapTileArea area = new MapTileArea();
for (int zoom = 0; zoom <= TileSystem.getMaximumZoomLevel(); zoom++) {
final int mapTileUpperBound = getMapTileUpperBound(zoom);
final long size = ((long) mapTileUpperBound) * mapTileUpperBound;
... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TopicMetadata that = (TopicMetadata) o;
if (!id.equals(that.id)) return false;
if (!name.equals(that.name)) return false;
if (numPartit... | @Test
public void testEquals() {
Uuid topicId = Uuid.randomUuid();
Map<Integer, Set<String>> partitionRacks = mkMapOfPartitionRacks(15);
TopicMetadata topicMetadata = new TopicMetadata(topicId, "foo", 15, partitionRacks);
assertEquals(new TopicMetadata(topicId, "foo", 15, partitionR... |
@Override
public void createDatabaseIndexes() throws Exception {
super.createDatabaseIndexes();
log.info("Installing SQL DataBase schema PostgreSQL specific indexes part: " + SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL);
executeQueryFromFile(SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL);
} | @Test
public void givenPsqlDbSchemaService_whenCreateDatabaseIndexes_thenVerifyPsqlIndexSpecificCall() throws Exception {
SqlEntityDatabaseSchemaService service = spy(new SqlEntityDatabaseSchemaService());
willDoNothing().given(service).executeQueryFromFile(anyString());
service.createDatab... |
@Bean
@ConfigurationProperties(prefix = "shenyu.sync.websocket")
public WebsocketConfig websocketConfig() {
return new WebsocketConfig();
} | @Test
public void testWebsocketConfig() {
assertThat(websocketConfig.getUrls(), is(Lists.newArrayList("ws://localhost:9095/websocket")));
} |
public Optional<Buffer> getBuffer() {
return buffer != null ? Optional.of(buffer) : Optional.empty();
} | @Test
void testGetBuffer() {
Buffer buffer = BufferBuilderTestUtils.buildSomeBuffer(0);
NettyPayload nettyPayload = NettyPayload.newBuffer(buffer, 0, 0);
assertThat(nettyPayload.getBuffer()).isPresent();
assertThat(nettyPayload.getBuffer()).hasValue(buffer);
assertThatThrownB... |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3BulkheadAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3BulkheadAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
void compatibleCreationTime(Comment comment) {
var creationTime = comment.getSpec().getCreationTime();
if (creationTime == null) {
creationTime = defaultIfNull(comment.getSpec().getApprovedTime(),
comment.getMetadata().getCreationTimestamp());
}
comment.getSpe... | @Test
void compatibleCreationTime() {
Comment comment = new Comment();
comment.setMetadata(new Metadata());
comment.getMetadata().setName("fake-comment");
comment.setSpec(new Comment.CommentSpec());
comment.getSpec().setApprovedTime(Instant.now());
comment.getSpec().s... |
public static Context context(int ioThreads)
{
return new Context(ioThreads);
} | @Test
public void testSocketSendRecvBinaryPicture()
{
Context context = ZMQ.context(1);
Socket push = context.socket(SocketType.PUSH);
Socket pull = context.socket(SocketType.PULL);
boolean rc = pull.setReceiveTimeOut(50);
assertThat(rc, is(true));
int port = pu... |
@Override
public V get()
throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new ExecutionException(e);
}
} | @Test
public void completeDelegate_successfully_callbackAfterGet_invokeGetOnOuter_callbacksRun() throws Exception {
BiConsumer<String, Throwable> callback = getStringExecutionCallback();
delegateFuture.run();
outerFuture.get();
outerFuture.whenCompleteAsync(callback, CALLER_RUNS);
... |
@Override
public <C extends AbstractConfig> void bind(String prefix, C dubboConfig) {
DataBinder dataBinder = new DataBinder(dubboConfig);
// Set ignored*
dataBinder.setIgnoreInvalidFields(isIgnoreInvalidFields());
dataBinder.setIgnoreUnknownFields(isIgnoreUnknownFields());
/... | @Test
void testBinder() {
ApplicationConfig applicationConfig = new ApplicationConfig();
dubboConfigBinder.bind("dubbo.application", applicationConfig);
Assertions.assertEquals("hello", applicationConfig.getName());
Assertions.assertEquals("world", applicationConfig.getOwner());
... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseStepParameterWithSameName() {
LongParameter bar = LongParameter.builder().name("sample").expression("sample;").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.singletonMap(
"sample", LongParameter.builder().evaluatedResult(... |
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
writer.keyword("CREATE");
if (getReplace()) {
writer.keyword("OR REPLACE");
}
writer.keyword("EXTERNAL MAPPING");
if (ifNotExists) {
writer.keyword("IF NOT EXISTS");
... | @Test
public void test_unparse_external_name_with_schema() {
Mapping mapping = new Mapping(
"name",
new String[]{"external\"schema", "external\"name"},
null,
"Type",
null,
singletonList(new MappingField("field", ... |
public static DateTime convertToDateTime(@Nonnull Object value) {
if (value instanceof DateTime) {
return (DateTime) value;
}
if (value instanceof Date) {
return new DateTime(value, DateTimeZone.UTC);
} else if (value instanceof ZonedDateTime) {
final... | @Test
void convertFromZonedDateTimeUTC() {
final ZonedDateTime input = ZonedDateTime.of(2020, 10, 24, 10, 59, 0, 0, ZoneOffset.UTC);
final DateTime output = DateTimeConverter.convertToDateTime(input);
final DateTime expectedOutput = new DateTime(2020, 10, 24, 10, 59, DateTimeZone.UTC);
... |
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createSubnet(InputStream input) throws IOException {
log.trace(String.format(MESSAGE, "CREATE"));
String inputStr = IOUtils.toString(input, REST_UTF8);
if (!haService.isActive()
... | @Test
public void testCreateSubnetWithCreationOperation() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackNetworkAdminService.createSubnet(anyObject());
replay(mockOpenstackNetworkAdminService);
final WebTa... |
boolean openNextFile() {
try {
if ( meta.getFileInFields() ) {
data.readrow = getRow(); // Grab another row ...
if ( data.readrow == null ) { // finished processing!
if ( isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "LoadFileInput.Log.FinishedProcessing" )... | @Test
public void testOpenNextFile_010_ignoreEmpty() {
stepMetaInterface.setIgnoreEmptyFile( true );
stepInputFiles.addFile( getFile( "input0.txt" ) );
stepInputFiles.addFile( getFile( "input1.txt" ) );
stepInputFiles.addFile( getFile( "input0.txt" ) );
assertTrue( stepLoadFileInput.openNextFile... |
@Override
public Future<RestResponse> restRequest(RestRequest request)
{
return restRequest(request, new RequestContext());
} | @Test
public void testRestRetryUnlimitedClientRetryRatio() throws Exception
{
SimpleLoadBalancer balancer = prepareLoadBalancer(Arrays.asList("http://test.linkedin.com/retry1", "http://test.linkedin.com/good"),
HttpClientFactory.UNLIMITED_CLIENT_REQUEST_RETRY_RATIO);
ClockedExecutor clock = new Cloc... |
@VisibleForTesting
String[] findClassNames(AbstractConfiguration config) {
// Find individually-specified filter classes.
String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes");
Stream<String> classNameStream =
Arrays.stream(filterClassNamesStrArra... | @Test
void testClassNamesOnly() {
Class<?> expectedClass = TestZuulFilter.class;
Mockito.when(configuration.getStringArray("zuul.filters.classes"))
.thenReturn(new String[] {"com.netflix.zuul.init.TestZuulFilter"});
Mockito.when(configuration.getStringArray("zuul.filters.pa... |
@Override
public GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request)
throws YarnException, IOException {
if (request == null || request.getQueueName() == null) {
routerMetrics.incrGetQueueInfoFailedRetrieved();
String msg = "Missing getQueueInfo request or queueName.";
RouterAud... | @Test
public void testGetQueueInfo() throws Exception {
LOG.info("Test FederationClientInterceptor : Get Queue Info request.");
// null request
LambdaTestUtils.intercept(YarnException.class, "Missing getQueueInfo request or queueName.",
() -> interceptor.getQueueInfo(null));
// normal reques... |
public static Builder newBuilder(String name) {
return new Builder(name);
} | @Test
void testBuildSlotSharingGroupWithoutAllRequiredConfig() {
assertThatThrownBy(
() ->
SlotSharingGroup.newBuilder("ssg")
.setCpuCores(1)
.setTaskOffHeapMemoryMB(10)
... |
public long getTimestamp() {
if (hasTimestamp) {
return timestamp;
} else {
return Long.MIN_VALUE;
// throw new IllegalStateException(
// "Record has no timestamp. Is the time characteristic set to 'ProcessingTime', or
// " +
... | @Test
void testAllowedTimestampRange() {
assertThat(new StreamRecord<>("test", 0).getTimestamp()).isZero();
assertThat(new StreamRecord<>("test", -1).getTimestamp()).isEqualTo(-1L);
assertThat(new StreamRecord<>("test", 1).getTimestamp()).isOne();
assertThat(new StreamRecord<>("test"... |
public static Optional<CeTaskInterruptedException> isTaskInterruptedException(Throwable e) {
if (e instanceof CeTaskInterruptedException ceTaskInterruptedException) {
return Optional.of(ceTaskInterruptedException);
}
return isCauseInterruptedException(e);
} | @Test
public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass() {
String message = randomAlphabetic(50);
CeActivityDto.Status status = randomStatus();
CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) {
};
CeTaskInterruptedException e2 ... |
@Override
public Num calculate(BarSeries series, Position position) {
return criterion.calculate(series, position).dividedBy(enterAndHoldCriterion.calculate(series, position));
} | @Test
public void calculateWithNumberOfBars() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 130);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series),
Trade.buyAt(2, series), Trade.sellAt(5, series));
... |
@Override
public void updateDiyTemplate(DiyTemplateUpdateReqVO updateReqVO) {
// 校验存在
validateDiyTemplateExists(updateReqVO.getId());
// 校验名称唯一
validateNameUnique(updateReqVO.getId(), updateReqVO.getName());
// 更新
DiyTemplateDO updateObj = DiyTemplateConvert.INSTANCE.... | @Test
public void testUpdateDiyTemplate_success() {
// mock 数据
DiyTemplateDO dbDiyTemplate = randomPojo(DiyTemplateDO.class);
diyTemplateMapper.insert(dbDiyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
DiyTemplateUpdateReqVO reqVO = randomPojo(DiyTemplateUpdateReqVO.class, o -> {
... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_empty_list_of_object__using_default_converter__throws_exception() {
DataTable table = parse("",
" | firstName | lastName | birthDate |");
registry.setDefaultDataTableEntryTransformer(JACKSON_TABLE_ENTRY_BY_TYPE_CONVERTER);
registry.setDefaultDataTableCel... |
@Override
public void init(final InternalProcessorContext<Void, Void> context) {
super.init(context);
this.context = context;
try {
keySerializer = prepareKeySerializer(keySerializer, context, this.name());
} catch (ConfigException | StreamsException e) {
thro... | @Test
public void shouldThrowStreamsExceptionWithExplicitErrorMessage() {
utilsMock.when(() -> WrappingNullableUtils.prepareKeySerializer(any(), any(), any())).thenThrow(new StreamsException(""));
final Throwable exception = assertThrows(StreamsException.class, () -> sink.init(context));
a... |
private static void validateResourceRequest(ResourceRequest resReq,
Resource maximumAllocation, QueueInfo queueInfo, RMContext rmContext)
throws InvalidResourceRequestException {
final Resource requestedResource = resReq.getCapability();
checkResourceRequestAgainstAvailableResource(requestedResource... | @Test(timeout = 30000)
public void testValidateResourceRequest() throws IOException {
ResourceScheduler mockScheduler = mock(ResourceScheduler.class);
QueueInfo queueInfo = mock(QueueInfo.class);
when(queueInfo.getQueueName()).thenReturn("queue");
Resource maxResource =
Resources.createR... |
public abstract boolean isNested(); | @Test
void testIsNested() {
assertThat(Projection.of(new int[] {2, 1}).isNested()).isFalse();
assertThat(Projection.of(new int[][] {new int[] {1}, new int[] {3}}).isNested()).isFalse();
assertThat(
Projection.of(new int[][] {new int[] {1}, new int[] {1, 2}, new int[] ... |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamMa... | @Test
public void testCalculateTimezonesWithTriggers() throws IOException {
WorkflowDefinition definition =
loadObject(
"fixtures/parameters/sample-wf-with-time-triggers.json", WorkflowDefinition.class);
workflow = definition.getWorkflow();
workflowInstance.setRuntimeWorkflow(workflow)... |
@Override
protected File getFile(HandlerRequest<EmptyRequestBody> handlerRequest) {
if (logDir == null) {
return null;
}
// wrapping around another File instantiation is a simple way to remove any path information
// - we're
// solely interested in the filename
... | @Test
void testGetJobManagerCustomLogsValidFilename() throws Exception {
File actualFile = testInstance.getFile(createHandlerRequest(VALID_LOG_FILENAME));
assertThat(actualFile).isNotNull();
String actualContent = String.join("", Files.readAllLines(actualFile.toPath()));
assertThat(... |
public int getDepth(Throwable ex) {
return getDepth(ex.getClass(), 0);
} | @Test
public void ancestry() {
RollbackRule rr = new RollbackRule(java.lang.Exception.class.getName());
// Exception -> Runtime -> MyRuntimeException
assertThat(rr.getDepth(new MyRuntimeException(""))).isEqualTo(2);
} |
public BackgroundJobServerConfiguration andName(String name) {
if (isNullOrEmpty(name)) throw new IllegalArgumentException("The name can not be null or empty");
if (name.length() >= 128) throw new IllegalArgumentException("The length of the name can not exceed 128 characters");
this.name = name;... | @Test
void ifNameIsNullThenExceptionIsThrown() {
assertThatThrownBy(() -> backgroundJobServerConfiguration.andName(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The name can not be null or empty");
} |
public static MemberSelector or(MemberSelector... selectors) {
return new OrMemberSelector(selectors);
} | @Test
public void testOrMemberSelector2() {
MemberSelector selector = MemberSelectors.or(LOCAL_MEMBER_SELECTOR, LITE_MEMBER_SELECTOR);
assertFalse(selector.select(member));
verify(member).localMember();
verify(member).isLiteMember();
} |
@Override
public Response toResponse(Throwable e) {
if (log.isDebugEnabled()) {
log.debug("Uncaught exception in REST call: ", e);
} else if (log.isInfoEnabled()) {
log.info("Uncaught exception in REST call: {}", e.getMessage());
}
if (e instanceof NotFoundExc... | @Test
public void testToResponseJsonMappingException() {
RestExceptionMapper mapper = new RestExceptionMapper();
JsonParser parser = null;
Response resp = mapper.toResponse(JsonMappingException.from(parser, "dummy msg"));
assertEquals(resp.getStatus(), Response.Status.BAD_REQUEST.get... |
public static boolean sleep(long millis) {
if (millis > 0) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
return false;
}
}
return true;
} | @Test
public void testSleep() {
Assert.assertTrue(ThreadUtil.sleep(0L));
} |
public static <T> T wrap(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
} | @Test
public void testWrap2() {
boolean flag = Assert.wrap(() -> true);
org.junit.Assert.assertEquals(true, flag);
} |
public static InetSocketAddress parseAddress(String address, int defaultPort) {
return parseAddress(address, defaultPort, false);
} | @Test
void shouldParseAddressForIPv4WithPort() {
InetSocketAddress socketAddress = AddressUtils.parseAddress("127.0.0.1:8080", 80);
assertThat(socketAddress.isUnresolved()).isFalse();
assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("127.0.0.1");
assertThat(socketAddress.getPort()).isEqualTo(8... |
@Override
public int hashCode() {
return super.hashCode()
+ Long.valueOf(value).hashCode()
+ Integer.valueOf(lowerBound).hashCode()
+ Integer.valueOf(upperBound).hashCode();
} | @Test
void requireThatHashCodeIsImplemented() {
assertEquals(new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode(),
new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode());
} |
public static boolean isEnable() {
return EVENT_BUS_ENABLE;
} | @Test
public void isEnable1() throws Exception {
Assert.assertEquals(EventBus.isEnable(NullTestEvent.class), false);
} |
@Private
@VisibleForTesting
public int getPort() {
return this.getListenerAddress().getPort();
} | @Test
@Timeout(240000)
void testHostedUIs() throws Exception {
ApplicationHistoryServer historyServer = new ApplicationHistoryServer();
Configuration config = new YarnConfiguration();
config.setClass(YarnConfiguration.TIMELINE_SERVICE_STORE,
MemoryTimelineStore.class, TimelineStore.class);
... |
@Transactional
public App createNewApp(App app) {
String createBy = app.getDataChangeCreatedBy();
App createdApp = appService.save(app);
String appId = createdApp.getAppId();
appNamespaceService.createDefaultAppNamespace(appId, createBy);
clusterService.createDefaultCluster(appId, createBy);
... | @Test(expected = ServiceException.class)
public void testCreateDuplicateApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.s... |
public static int[] calcSortOrder(IntArrayList arr1, IntArrayList arr2) {
if (arr1.elementsCount != arr2.elementsCount) {
throw new IllegalArgumentException("Arrays must have equal size");
}
return calcSortOrder(arr1.buffer, arr2.buffer, arr1.elementsCount);
} | @Test
public void testCalcSortOrder() {
assertEquals(from(), from(ArrayUtil.calcSortOrder(from(), from())));
assertEquals(from(0), from(ArrayUtil.calcSortOrder(from(3), from(4))));
assertEquals(from(0, 2, 3, 1), from(ArrayUtil.calcSortOrder(from(3, 6, 3, 4), from(0, -1, 2, -6))));
as... |
public FlagSet<E> copy() {
return new FlagSet<>(enumClass, prefix, flags);
} | @Test
public void testCopy() throws Throwable {
FlagSet<SimpleEnum> s1 =
createFlagSet(SimpleEnum.class, KEYDOT, SimpleEnum.a, SimpleEnum.b);
s1.makeImmutable();
FlagSet<SimpleEnum> s2 = s1.copy();
Assertions.assertThat(s2)
.describedAs("copy of %s", s1)
.isNotSameAs(s1);
... |
public Predicate convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testBinaryString() {
ConstantOperator value = ConstantOperator.createVarchar("ttt");
ScalarOperator op = new BinaryPredicateOperator(BinaryType.EQ, F1, value);
Predicate result = CONVERTER.convert(op);
Assert.assertTrue(result instanceof LeafPredicate);
Leaf... |
@Bean
public ShenyuPlugin paramMappingPlugin(final ServerCodecConfigurer configurer) {
Map<String, Operator> operatorMap = new HashMap<>(4);
operatorMap.put(Constants.DEFAULT, new DefaultOperator());
operatorMap.put(MediaType.APPLICATION_JSON.toString(), new JsonOperator(configurer.getReader... | @Test
public void testParamMappingPlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ParamMappingPluginConfiguration.class, DefaultServerCodecConfigurer.class))
.withBean(ParamMappingPluginConfigurationTest.class)
.withPropertyValues("debug... |
public void contains(@Nullable CharSequence string) {
checkNotNull(string);
if (actual == null) {
failWithActual("expected a string that contains", string);
} else if (!actual.contains(string)) {
failWithActual("expected to contain", string);
}
} | @Test
public void stringDoesNotContainIgnoringCaseFail() {
expectFailureWhenTestingThat("äbc").ignoringCase().doesNotContain("Äb");
assertFailureValue("expected not to contain", "Äb");
assertThat(expectFailure.getFailure()).factKeys().contains("(case is ignored)");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.