focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Optional<AuthProperty> inferAuth(String registry) throws InferredAuthException {
Server server = getServerFromMavenSettings(registry);
if (server == null) {
return Optional.empty();
}
SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
Setting... | @Test
public void testInferredAuth_registryWithHostWithoutPort() throws InferredAuthException {
Optional<AuthProperty> auth =
mavenSettingsServerCredentialsNoMasterPassword.inferAuth("docker.example.com");
Assert.assertTrue(auth.isPresent());
Assert.assertEquals("registryUser", auth.get().getUsern... |
@Override
public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final CreateFileUploadResponse uploadResponse = upload.start(file, status);
final String uploadUrl = uploadResponse.getUploadUrl();
... | @Test
public void testWriteZeroSingleByte() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, P... |
public Configuration getConfiguration() {
return configuration;
} | @Test
void validate_shouldValidateFetchPluggableArtifactConfigurationUniqueness() {
FetchPluggableArtifactTask task = new FetchPluggableArtifactTask(new CaseInsensitiveString("dummy"), new CaseInsensitiveString("stage"), new CaseInsensitiveString("job"), "s3", create("Foo", false, "Bar"), create("Foo", fals... |
@Override
public void open() throws Exception {
super.open();
final String operatorID = getRuntimeContext().getOperatorUniqueID();
this.workerPool =
ThreadPools.newWorkerPool("iceberg-worker-pool-" + operatorID, workerPoolSize);
} | @TestTemplate
public void testMaxContinuousEmptyCommits() throws Exception {
table.updateProperties().set(MAX_CONTINUOUS_EMPTY_COMMITS, "3").commit();
JobID jobId = new JobID();
long checkpointId = 0;
long timestamp = 0;
try (OneInputStreamOperatorTestHarness<WriteResult, Void> harness = createSt... |
public static Builder builder() {
return new Builder();
} | @Test
void testFilterInstantsWithRange() throws IOException {
Configuration conf = TestConfigurations.getDefaultConf(basePath);
conf.set(FlinkOptions.READ_STREAMING_SKIP_CLUSTERING, true);
conf.set(FlinkOptions.TABLE_TYPE, FlinkOptions.TABLE_TYPE_MERGE_ON_READ);
metaClient = HoodieTestUtils.init(baseP... |
public static String getAbsolutePath(String path, Class<?> baseClass) {
String normalPath;
if (path == null) {
normalPath = StrUtil.EMPTY;
} else {
normalPath = normalize(path);
if (isAbsolutePath(normalPath)) {
// 给定的路径已经是绝对路径了
return normalPath;
}
}
// 相对于ClassPath路径
final URL url = R... | @Test
public void getAbsolutePathTest() {
final String absolutePath = FileUtil.getAbsolutePath("LICENSE-junit.txt");
assertNotNull(absolutePath);
final String absolutePath2 = FileUtil.getAbsolutePath(absolutePath);
assertNotNull(absolutePath2);
assertEquals(absolutePath, absolutePath2);
String path = File... |
int alignment()
{
return alignment;
} | @Test
void shouldUse1KBAlignmentWhenReadingFromOldCatalogFile() throws IOException
{
final int oldRecordLength = 1024;
final File catalogFile = new File(archiveDir, CATALOG_FILE_NAME);
IoUtil.deleteIfExists(catalogFile);
Files.write(catalogFile.toPath(), new byte[oldRecordLength... |
@Deprecated
@Nonnull
public static Builder newBuilder(@Nonnull Time ttl) {
return new Builder(ttl);
} | @Test
void testStateTtlConfigBuildWithNonPositiveCleanupIncrementalSize() {
List<Integer> illegalCleanUpSizes = Arrays.asList(0, -2);
for (Integer illegalCleanUpSize : illegalCleanUpSizes) {
assertThatThrownBy(
() ->
StateT... |
@Override
public List<TransferItem> normalize(final List<TransferItem> roots) {
final List<TransferItem> normalized = new ArrayList<>();
for(TransferItem upload : roots) {
boolean duplicate = false;
for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext(); ) {
... | @Test
public void testNameClash() {
UploadRootPathsNormalizer n = new UploadRootPathsNormalizer();
final List<TransferItem> list = new ArrayList<>();
list.add(new TransferItem(new Path("/a", EnumSet.of(Path.Type.file)), new NullLocal("/f/a")));
list.add(new TransferItem(new Path("/a"... |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void invalidPropertyOk() throws IOException {
URL resource = TestsUtils.class.getClassLoader().getResource("flows/invalids/invalid-property.yaml");
assert resource != null;
File file = new File(resource.getFile());
String flowSource = Files.readString(file.toPath(), Charset.de... |
@Override
public void deletePost(Long id) {
// 校验是否存在
validatePostExists(id);
// 删除部门
postMapper.deleteById(id);
} | @Test
public void testValidatePost_notFoundForDelete() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> postService.deletePost(id), POST_NOT_FOUND);
} |
@Override
public void deleteDiscountActivity(Long id) {
// 校验存在
DiscountActivityDO activity = validateDiscountActivityExists(id);
if (CommonStatusEnum.isEnable(activity.getStatus())) { // 未关闭的活动,不能删除噢
throw exception(DISCOUNT_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED);
}
... | @Test
public void testDeleteDiscountActivity_success() {
// mock 数据
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class,
o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条... |
@Override
public Output run(RunContext runContext) throws Exception {
String renderedNamespace = runContext.render(this.namespace);
FlowService flowService = ((DefaultRunContext) runContext).getApplicationContext().getBean(FlowService.class);
flowService.checkAllowedNamespace(runContext.ten... | @Test
void shouldOutputFalseGivenNonExistingKey() throws Exception {
// Given
String namespaceId = "io.kestra." + IdUtils.create();
RunContext runContext = this.runContextFactory.of(Map.of(
"flow", Map.of("namespace", namespaceId),
"inputs", Map.of(
"k... |
public List<String> getBackends() {
List<String> backends = new ArrayList<>();
SystemInfoService infoService = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo();
try (CloseableLock ignored = CloseableLock.lock(this.rwLock.readLock())) {
for (Replica replica : replicas) {... | @Test
public void testGetBackends() throws Exception {
LocalTablet tablet = new LocalTablet();
Replica replica1 = new Replica(1L, 10001L, 8,
-1, 10, 10, ReplicaState.NORMAL, 9, 8);
Replica replica2 = new Replica(1L, 10002L, 9,
-1, 10, 10, ReplicaState.NORMAL,... |
public static String extractAttributeNameNameWithoutArguments(String attributeNameWithArguments) {
int start = StringUtil.lastIndexOf(attributeNameWithArguments, '[');
int end = StringUtil.lastIndexOf(attributeNameWithArguments, ']');
if (start > 0 && end > 0 && end > start) {
return... | @Test(expected = IllegalArgumentException.class)
public void extractAttributeName_wrongArguments_noArgument() {
extractAttributeNameNameWithoutArguments("car.wheel[");
} |
public static <T> NullableCoder<T> of(Coder<T> valueCoder) {
if (valueCoder instanceof NullableCoder) {
return (NullableCoder<T>) valueCoder;
}
return new NullableCoder<>(valueCoder);
} | @Test
public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
CoderProperties.coderSerializable(NullableCoder.of(GlobalWindow.Coder.INSTANCE));
} |
public static String execCommand(String... cmd) throws IOException {
return execCommand(cmd, -1);
} | @Test
public void testEchoHello() throws Exception {
String output = Shell.execCommand("echo", "hello");
assertEquals("hello\n", output);
} |
@Override
public Response updateSchedulerConfiguration(SchedConfUpdateInfo mutationInfo,
HttpServletRequest hsr) throws AuthorizationException, InterruptedException {
// Make Sure mutationInfo is not null.
if (mutationInfo == null) {
routerMetrics.incrUpdateSchedulerConfigurationFailedRetrieved()... | @Test
public void testUpdateSchedulerConfiguration()
throws AuthorizationException, InterruptedException {
SchedConfUpdateInfo updateInfo = new SchedConfUpdateInfo();
updateInfo.setSubClusterId("1");
Map<String, String> goodUpdateMap = new HashMap<>();
goodUpdateMap.put("goodKey", "goodVal");
... |
@Override
public boolean isEmpty() {
return items.isEmpty();
} | @Test
public void testIsEmpty() throws Exception {
//Checks empty condition
//asserts that the map starts out empty
assertTrue("Map should be empty", map.isEmpty());
map.put(1, 1);
assertFalse("Map shouldn't be empty.", map.isEmpty());
map.remove(1);
assertTru... |
static boolean containsIn(CloneGroup first, CloneGroup second) {
if (first.getCloneUnitLength() > second.getCloneUnitLength()) {
return false;
}
List<ClonePart> firstParts = first.getCloneParts();
List<ClonePart> secondParts = second.getCloneParts();
return SortedListsUtils.contains(secondPart... | @Test
public void start_index_in_C1_less_than_in_C2() {
CloneGroup c1 = newCloneGroup(1,
newClonePart("a", 1));
CloneGroup c2 = newCloneGroup(1,
newClonePart("a", 2));
assertThat(Filter.containsIn(c1, c2), is(false));
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertString() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.STRING_TYPE)
.columnLength(null)
.build();
BasicTypeDefine typeDefine ... |
@NonNull
@Override
protected AbstractFileObject<?> requireResolvedFileObject() {
return resolvedFileObject;
} | @Test
public void testRequireResolvedFileObject() {
assertEquals( resolvedFileObject, fileObject.requireResolvedFileObject() );
} |
@Override
public Page download(Request request, Task task) {
if (task == null || task.getSite() == null) {
throw new NullPointerException("task or site can not be null");
}
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = getHttpClient(task.getS... | @Test
public void testDownloader() {
HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
Html html = httpClientDownloader.download("https://www.baidu.com/");
assertTrue(!html.getFirstSourceText().isEmpty());
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() == 1) {
final int batteryLevel = data.getIntValue(Data.FORMAT_UINT8, 0);
if (batteryLevel >= 0 && batteryLevel <= 100) {
onBatteryLevelChanged(devic... | @Test
public void onInvalidDataReceived_batteryLevelOutOfRange() {
final DataReceivedCallback callback = new BatteryLevelDataCallback() {
@Override
public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) {
assertEquals("Invalid date returned Battery Level", 1, 2);
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType = null;
String colName... | @Test
public void testAggregateSingleStat() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
ColumnStatisticsData data1 = new ColStatsBuilder<>(String.class).numNulls(1).numDVs(2).avgColLen(8.5).maxColLen(13)
.hll(S_1, S_3).build();
List<ColStatsObjWithSourceIn... |
@Description("compute md5 hash")
@ScalarFunction
@SqlType(StandardTypes.VARBINARY)
public static Slice md5(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
return computeHash(Hashing.md5(), slice);
} | @Test
public void testMd5()
{
assertFunction("md5(CAST('' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("D41D8CD98F00B204E9800998ECF8427E"));
assertFunction("md5(CAST('hashme' AS VARBINARY))", VARBINARY, sqlVarbinaryHex("533F6357E0210E67D91F651BC49E1278"));
} |
public int getSchedulerConfigurationFailedRetrieved() {
return numGetSchedulerConfigurationFailedRetrieved.value();
} | @Test
public void testGetSchedulerConfigurationRetrievedFailed() {
long totalBadBefore = metrics.getSchedulerConfigurationFailedRetrieved();
badSubCluster.getSchedulerConfigurationFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getSchedulerConfigurationFailedRetrieved());
} |
@Override
public int hashCode() {
return Objects.hash( name, path, provider );
} | @Test
public void testHashCode() {
Element element2 = new Element( NAME, TYPE, PATH, LOCAL_PROVIDER );
assertEquals( element1.hashCode(), element2.hashCode() );
element2 = new Element( "diffname", TYPE, "/tmp/diffname", LOCAL_PROVIDER );
assertNotEquals( element1.hashCode(), element2.hashCode() );
... |
public void write(final Map<TopicPartition, Long> offsets) throws IOException {
// if there are no offsets, skip writing the file to save disk IOs
// but make sure to delete the existing file if one exists
if (offsets.isEmpty()) {
Utils.delete(file);
return;
}
... | @Test
public void shouldThrowIOExceptionWhenWritingToNotExistedFile() {
final Map<TopicPartition, Long> offsetsToWrite = Collections.singletonMap(new TopicPartition(topic, 0), 0L);
final File notExistedFile = new File("/not_existed_dir/not_existed_file");
final OffsetCheckpoint checkpoint =... |
public static void applyLocaleToContext(@NonNull Context context, @Nullable String localeString) {
final Locale forceLocale = LocaleTools.getLocaleForLocaleString(localeString);
final Configuration configuration = context.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.J... | @Test
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Ignore("Robolectric does not support this API")
public void testSetAndResetValueAPI17WithKnownLocale() {
Assert.assertEquals(
"English (United States)",
mContext.getResources().getConfiguration().locale.getDisplayName());
LocaleTool... |
@Override
@SuppressWarnings("nullness")
public List<Map<String, Object>> readTable(String tableName) {
LOG.info("Reading all rows from {}.{}", databaseName, tableName);
List<Map<String, Object>> result = runSQLQuery(String.format("SELECT * FROM %s", tableName));
LOG.info("Successfully loaded rows from {... | @Test
public void testReadTableShouldNotThrowErrorIfJDBCDoesNotThrowAnyError() throws SQLException {
when(container.getHost()).thenReturn(HOST);
when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT);
testManager.readTable(TABLE_NAME);
verify(driver.getConnection(any(), any(), any()).creat... |
public static ScalarOperator translate(Expr expression, ExpressionMapping expressionMapping,
ColumnRefFactory columnRefFactory) {
return translate(expression, expressionMapping, null, columnRefFactory);
} | @Test
public void testTranslateComplexFunction() {
StringLiteral test = new StringLiteral("test");
StringLiteral defaultStr = new StringLiteral("default");
BinaryPredicate predicate = new BinaryPredicate(BinaryType.EQ, defaultStr, test);
FunctionCallExpr baseFunc = new FunctionCallEx... |
public static <T> T[] checkNonEmpty(T[] array, String name) {
//No String concatenation for check
if (checkNotNull(array, name).length == 0) {
throw new IllegalArgumentException("Param '" + name + "' must not be empty");
}
return array;
} | @Test
public void testCheckNonEmptyTArrayString() {
Exception actualEx = null;
try {
ObjectUtil.checkNonEmpty((Object[]) NULL_OBJECT, NULL_NAME);
} catch (Exception e) {
actualEx = e;
}
assertNotNull(actualEx, TEST_RESULT_NULLEX_OK);
assertTru... |
@Override
public int hashCode() {
return Objects.hashCode(dataSourceName.toUpperCase(), tableName.toUpperCase(), null == schemaName ? null : schemaName.toUpperCase());
} | @Test
void assertHashCodeIncludeInstance() {
assertThat(new DataNode("ds_0.db_0.tbl_0").hashCode(), is(new DataNode("ds_0.db_0.tbl_0").hashCode()));
} |
@NonNull public static synchronized String getAllLogLines() {
ArrayList<String> lines = getAllLogLinesList();
// now to build the string
StringBuilder sb = new StringBuilder("Log contains " + lines.size() + " lines:");
while (lines.size() > 0) {
String line = lines.remove(lines.size() - 1);
... | @Test
public void testGetAllLogLines() throws Exception {
Logger.d("mTag", "Text1");
final String expectedFirstLine = "-D-[mTag] Text1";
Assert.assertTrue(Logger.getAllLogLines().endsWith(expectedFirstLine));
} |
public static KeyStore newStoreCopyContent(KeyStore originalKeyStore,
char[] currentPassword,
final char[] newPassword) throws GeneralSecurityException, IOException {
if (newPassword == null) {
throw new Il... | @Test
void testDifferentEntriesMoving() throws Exception {
final char[] oldPassword = "oldPass".toCharArray();
final char[] newPassword = "newPass".toCharArray();
KeyStore originalKeyStore = KeyStore.getInstance(PKCS12);
originalKeyStore.load(null, oldPassword);
final byte[]... |
public static CodecFactory fromHadoopString(String hadoopCodecClass) {
CodecFactory o = null;
try {
String avroCodec = HADOOP_AVRO_NAME_MAP.get(hadoopCodecClass);
if (avroCodec != null) {
o = CodecFactory.fromString(avroCodec);
}
} catch (Exception e) {
throw new AvroRuntime... | @Test
void hadoopCodecFactorySnappy() {
CodecFactory hadoopSnappyCodec = HadoopCodecFactory.fromHadoopString("org.apache.hadoop.io.compress.SnappyCodec");
CodecFactory avroSnappyCodec = CodecFactory.fromString("snappy");
assertEquals(hadoopSnappyCodec.getClass(), avroSnappyCodec.getClass());
} |
@Override
public int rpcPortOffset() {
return Integer.parseInt(System.getProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY,
String.valueOf(Constants.CLUSTER_GRPC_PORT_DEFAULT_OFFSET)));
} | @Test
void testRpcPortOffsetFromSystemProperty() {
System.setProperty(GrpcConstants.NACOS_SERVER_GRPC_PORT_OFFSET_KEY, "10001");
grpcClusterClient = new GrpcClusterClient("test", 8, 8, Collections.emptyMap());
assertEquals(10001, grpcClusterClient.rpcPortOffset());
} |
public static String get(String urlString, Charset customCharset) {
return HttpRequest.get(urlString).charset(customCharset).execute().body();
} | @Test
@Disabled
public void get12306Test() {
HttpRequest.get("https://kyfw.12306.cn/otn/")
.setFollowRedirects(true)
.then(response -> Console.log(response.body()));
} |
static void obtainTokensForNamenodesInternal(Credentials credentials,
Path[] ps, Configuration conf) throws IOException {
Set<FileSystem> fsSet = new HashSet<FileSystem>();
for(Path p: ps) {
fsSet.add(p.getFileSystem(conf));
}
String masterPrincipal = Master.getMasterPrincipal(conf);
for... | @Test
public void testSingleTokenFetch() throws Exception {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RM_PRINCIPAL, "mapred/host@REALM");
String renewer = Master.getMasterPrincipal(conf);
Credentials credentials = new Credentials();
final MockFileSystem fs = new Moc... |
@ProcessElement
public void processElement(OutputReceiver<InitialPipelineState> receiver) throws IOException {
LOG.info(daoFactory.getStreamTableDebugString());
LOG.info(daoFactory.getMetadataTableDebugString());
LOG.info("ChangeStreamName: " + daoFactory.getChangeStreamName());
boolean resume = fals... | @Test
public void testInitializeStopWithExistingPipeline() throws IOException {
metadataTableDao.updateDetectNewPartitionWatermark(Instant.now());
Instant startTime = Instant.now();
InitializeDoFn initializeDoFn =
new InitializeDoFn(
daoFactory, startTime, BigtableIO.ExistingPipelineOp... |
public boolean put(Key key, Value value) {
// retain value so that it's not released before we put it in the cache and calculate the weight
value.retain();
try {
if (!value.matchesKey(key)) {
throw new IllegalArgumentException("Value '" + value + "' does not match key... | @Test
public void testPutSameObj() {
RangeCache<Integer, RefString> cache = new RangeCache<>(value -> value.s.length(), x -> 0);
RefString s0 = new RefString("zero", 0);
assertEquals(s0.refCnt(), 1);
assertTrue(cache.put(0, s0));
assertFalse(cache.put(0, s0));
} |
@Override
public CheckForDecommissioningNodesResponse checkForDecommissioningNodes(
CheckForDecommissioningNodesRequest request) throws YarnException, IOException {
// Parameter check
if (request == null) {
RouterServerUtil.logAndThrowException("Missing checkForDecommissioningNodes request.", nul... | @Test
public void testCheckForDecommissioningNodesNormalRequest() throws Exception {
CheckForDecommissioningNodesRequest request =
CheckForDecommissioningNodesRequest.newInstance("SC-1");
CheckForDecommissioningNodesResponse response =
interceptor.checkForDecommissioningNodes(request);
ass... |
public static String substringTrimmed( String str, int beginIndex ) {
return substringTrimmed( str, beginIndex, str.length() );
} | @Test
void substringTrimmed() {
testSubstringTrimmed( "", 0 );
testSubstringTrimmed( "a", 0 );
testSubstringTrimmed( "a", 1 );
testSubstringTrimmed( "a ", 0 );
testSubstringTrimmed( " a", 0 );
testSubstringTrimmed( " a ", 0 );
testSubstringTrimmed( " a ", 1 );
testSubstringTrimmed( " a ", 0... |
public List<BlameLine> blame(Git git, String filename) {
BlameResult blameResult;
try {
blameResult = git.blame()
// Equivalent to -w command line option
.setTextComparator(RawTextComparator.WS_IGNORE_ALL)
.setFilePath(filename).call();
} catch (Exception e) {
throw new I... | @Test
public void blame_returns_all_lines() {
try (Git git = loadRepository(baseDir)) {
List<BlameLine> blameLines = jGitBlameCommand.blame(git, DUMMY_JAVA);
Date revisionDate1 = DateUtils.parseDateTime("2012-07-17T16:12:48+0200");
String revision1 = "6b3aab35a3ea32c1636fee56f996e677653c48ea"... |
public Collection<String> getCandidateEIPs(String myInstanceId, String myZone) {
if (myZone == null) {
myZone = "us-east-1d";
}
Collection<String> eipCandidates = clientConfig.shouldUseDnsForFetchingServiceUrls()
? getEIPsForZoneFromDNS(myZone)
... | @Test
public void shouldFilterNonElasticNamesInOtherRegion() {
when(config.getRegion()).thenReturn("eu-west-1");
List<String> hosts = Lists.newArrayList("example.com", "ec2-1-2-3-4.eu-west-1.compute.amazonaws.com",
"5.6.7.8", "ec2-101-202-33-44.eu-west-1.compute.amazonaws.com");
... |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void inputsBadType() {
ConstraintViolationException exception = assertThrows(
ConstraintViolationException.class,
() -> this.parse("flows/invalids/inputs-bad-type.yaml")
);
assertThat(exception.getMessage(), containsString("Invalid type: FOO"));
} |
@Nullable
public Long getLongValue(@LongFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
return switch (formatType) {
case FORMAT_UINT32_LE -> unsignedBytesToLong(
mValue[offset],
mValue[offset + 1],
mValue[... | @Test
public void getValue_UINT32_BE_big() {
final Data data = new Data(new byte[] { (byte) 0xF0, 0x00, 0x00, 0x01 });
final long value = data.getLongValue(Data.FORMAT_UINT32_BE, 0);
assertEquals(0xF0000001L, value);
} |
public static String replaceAll(CharSequence content, String regex, String replacementTemplate) {
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
return replaceAll(content, pattern, replacementTemplate);
} | @Test
public void replaceAllTest() {
//通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串
//此处把1234替换为 ->1234<-
final String replaceAll = ReUtil.replaceAll(content, "(\\d+)", "->$1<-");
assertEquals("ZZZaaabbbccc中文->1234<-", replaceAll);
} |
@Override
public ProcResult fetchResult() throws AnalysisException {
Preconditions.checkNotNull(db);
Preconditions.checkNotNull(schemaChangeHandler);
BaseProcResult result = new BaseProcResult();
result.setNames(TITLE_NAMES);
List<List<Comparable>> schemaChangeJobInfos = ge... | @Test
public void testFetchResult() throws AnalysisException {
BaseProcResult result = (BaseProcResult) optimizeProcDir.fetchResult();
List<List<String>> rows = result.getRows();
List<String> list1 = rows.get(0);
Assert.assertEquals(list1.size(), OptimizeProcDir.TITLE_NAMES.size());
... |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testOrParenAnd()
{
final Predicate parsed = PredicateExpressionParser.parse("(com.linkedin.data.it.AlwaysTruePredicate | com.linkedin.data.it.AlwaysTruePredicate) & com.linkedin.data.it.AlwaysFalsePredicate");
Assert.assertEquals(parsed.getClass(), AndPredicate.class);
final List<Pred... |
@Override
public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) {
Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:"
+ " URI path should not be null");
if (conf.getInt(PropertyKey.UNDERFS_GCS_VERSION) == GCS_VERSION_TWO) {
try {
return G... | @Test
public void createInstanceWithPath() {
UnderFileSystem ufs = mFactory.create(mPath, mConf);
Assert.assertNotNull(ufs);
Assert.assertTrue(ufs instanceof GCSUnderFileSystem);
} |
@CallSuper
protected void abortCorrectionAndResetPredictionState(boolean disabledUntilNextInputStart) {
mSuggest.resetNextWordSentence();
mLastSpaceTimeStamp = NEVER_TIME_STAMP;
mJustAutoAddedWord = false;
mKeyboardHandler.removeAllSuggestionMessages();
final InputConnection ic = getCurrentInput... | @Test
public void testStripActionNotRemovedWhenAbortingPredictionNotForever() {
Assert.assertNotNull(
mAnySoftKeyboardUnderTest
.getInputViewContainer()
.findViewById(R.id.close_suggestions_strip_text));
mAnySoftKeyboardUnderTest.abortCorrectionAndResetPredictionState(false);
... |
@Override
public String toString() {
if (!hasParameters()) return typeSubtype;
StringBuilder builder = new StringBuilder().append(typeSubtype);
String strParams = this.params.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("; "));
... | @Test
public void testToString() {
assertEquals("application/xml; q=0.9",
new MediaType("application", "xml", Map.of("q", "0.9")).toString());
assertEquals("text/csv", new MediaType("text", "csv").toString());
assertEquals("foo/bar; a=2", new MediaType("foo", "bar", Map.of("a", "2")).to... |
@Override
public List<ServiceDefinition> apply(Exchange exchange, List<ServiceDefinition> services) {
for (int i = 0; i < delegatesSize; i++) {
services = delegates.get(i).apply(exchange, services);
}
return services;
} | @Test
public void testMultiServiceFilter() throws Exception {
CombinedServiceCallServiceFilterConfiguration conf = new CombinedServiceCallServiceFilterConfiguration()
.healthy()
.custom((exchange, services) -> services.stream().filter(s -> s.getPort() < 2000).toList());
... |
public EndpointResponse getStatus(final String type, final String entity, final String action) {
final CommandId commandId = new CommandId(type, entity, action);
final Optional<CommandStatus> commandStatus = statementExecutor.getStatus(commandId);
return commandStatus.map(EndpointResponse::ok)
.or... | @Test
public void testGetStatus() throws Exception {
final StatusResource testResource = getTestStatusResource();
for (final Map.Entry<CommandId, CommandStatus> commandEntry : mockCommandStatuses.entrySet()) {
final CommandId commandId = commandEntry.getKey();
final CommandStatus expectedCommandS... |
@SuppressWarnings("FieldAccessNotGuarded")
// Note that: callWithLock ensure that code block guarded by resultPartitionReadLock and
// subpartitionLock.
public List<BufferWithIdentity> spillSubpartitionBuffers(
List<BufferIndexAndChannel> toSpill, CompletableFuture<Void> spillDoneFuture) {
... | @Test
void testSpillSubpartitionBuffers() throws Exception {
CompletableFuture<Void> spilledDoneFuture = new CompletableFuture<>();
TestingMemoryDataManagerOperation memoryDataManagerOperation =
TestingMemoryDataManagerOperation.builder()
.setRequestBufferFrom... |
public boolean containsValue(final int value)
{
boolean found = false;
final int missingValue = this.missingValue;
if (missingValue != value)
{
final int[] entries = this.entries;
@DoNotSub final int length = entries.length;
@DoNotSub int remaining... | @Test
void shouldNotContainValueForAMissingEntry()
{
assertFalse(map.containsValue(1));
} |
public void handleLoss(String loss) {
lossHandler.accept(new UnwritableMetadataException(requestedMetadataVersion, loss));
} | @Test
public void testHandleLoss() {
String expectedMessage = "stuff";
for (int i = MetadataVersion.MINIMUM_KRAFT_VERSION.ordinal();
i < MetadataVersion.VERSIONS.length;
i++) {
MetadataVersion version = MetadataVersion.VERSIONS[i];
String formattedM... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (final Thread.State state : Thread.State.values()) {
gauges.put(name(state.toString().toLowerCase(), "count"),
(Gauge<Object>) () -> getThreadCount(state));
... | @Test
public void hasAGaugeForTheNumberOfDaemonThreads() {
assertThat(((Gauge<?>) gauges.getMetrics().get("daemon.count")).getValue())
.isEqualTo(10);
} |
@Override
public Map<String, Boolean> getProjectUuidToManaged(DbSession dbSession, Set<String> projectUuids) {
return findManagedProjectService()
.map(managedProjectService -> managedProjectService.getProjectUuidToManaged(dbSession, projectUuids))
.orElse(returnNonManagedForAll(projectUuids));
} | @Test
public void getProjectUuidToManaged_delegatesToRightService_andPropagateAnswer() {
Set<String> projectUuids = Set.of("a", "b");
Map<String, Boolean> serviceResponse = Map.of("a", false, "b", true);
ManagedInstanceService anotherManagedProjectService = getManagedProjectService(projectUuids, serviceR... |
public static FormattingTuple arrayFormat(final String messagePattern,
final Object[] argArray) {
if (argArray == null || argArray.length == 0) {
return new FormattingTuple(messagePattern, null);
}
int lastArrIdx = argArray.length - 1;
... | @Test
public void testArrayThrowable() {
FormattingTuple ft;
Throwable t = new Throwable();
Object[] ia = { 1, 2, 3, t };
ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
... |
public static int[] toArray(List<Integer> list) {
if (list == null) return null;
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
} | @Test
public void testToArray() {
assertArrayEquals(new int[] {3, 2, 1}, Replicas.toArray(Arrays.asList(3, 2, 1)));
assertArrayEquals(new int[] {}, Replicas.toArray(Collections.emptyList()));
assertArrayEquals(new int[] {2}, Replicas.toArray(Collections.singletonList(2)));
} |
public boolean isNew(Component component, DefaultIssue issue) {
if (analysisMetadataHolder.isPullRequest()) {
return true;
}
if (periodHolder.hasPeriod()) {
if (periodHolder.hasPeriodDate()) {
return periodHolder.getPeriod().isOnPeriod(issue.creationDate());
}
if (isOnBranc... | @Test
public void isNew_returns_true_for_any_issue_if_pull_request() {
periodHolder.setPeriod(null);
analysisMetadataHolder.setBranch(newPr());
assertThat(newIssueClassifier.isNew(mock(Component.class), mock(DefaultIssue.class))).isTrue();
} |
@Override public HashSlotCursor8byteKey cursor() {
return new Cursor();
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testCursor_key_withoutAdvance() {
HashSlotCursor8byteKey cursor = hsa.cursor();
cursor.key();
} |
@TargetApi(21)
public String getNoBackupFilesDirectoryPath() {
return Build.VERSION.SDK_INT >= 21 &&
this.context != null
? absPath(this.context.getNoBackupFilesDir())
: "";
} | @Test
public void getNoBackupFilesDirectoryPathIsNotEmpty() {
assertThat(contextUtil.getNoBackupFilesDirectoryPath(), endsWith("/no_backup"));
} |
@Override
protected FieldValue doGet(String fieldName, EventWithContext eventWithContext) {
final ImmutableMap.Builder<String, Object> dataModelBuilder = ImmutableMap.builder();
if (eventWithContext.messageContext().isPresent()) {
dataModelBuilder.put("source", eventWithContext.messageC... | @Test
public void templateWithSyntaxError() {
final TestEvent event = new TestEvent();
final EventWithContext eventWithContext = EventWithContext.create(event, newMessage(ImmutableMap.of("hello", "world")));
final FieldValue fieldValue = newTemplate("hello: ${source.hello").doGet("test", ev... |
public MultiMap<Value, T, List<T>> search() {
if (matcher.isNegate()) {
if (map.containsKey(matcher.getValue())) {
return MultiMap.merge(map.subMap(map.firstKey(), true,
matcher.getValue(), false),
... | @Test
void testNullSearch() throws Exception {
search = new ExactMatcherSearch<>(new ExactMatcher(KeyDefinition.newKeyDefinition().withId("value").build(),
null),
map);
MultiMap<Value, Object, List<Object>> search1 = search.search();
assertTha... |
public static String name(final String path) {
if(String.valueOf(Path.DELIMITER).equals(path)) {
return path;
}
if(!StringUtils.contains(path, Path.DELIMITER)) {
return path;
}
if(StringUtils.endsWith(path, String.valueOf(Path.DELIMITER))) {
re... | @Test
public void testNormalizeNameWithBackslash() {
assertEquals("file\\name", PathNormalizer.name("/path/to/file\\name"));
} |
@Override
public void close() throws IOException {
if (mClosed.getAndSet(true)) {
LOG.warn("OBSOutputStream is already closed");
return;
}
mLocalOutputStream.close();
try {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(mFile));
ObjectMetadata o... | @Test
@PrepareForTest(OBSOutputStream.class)
public void testCloseError() throws Exception {
String errorMessage = "Invoke the createEmptyObject method error.";
BufferedInputStream inputStream = PowerMockito.mock(BufferedInputStream.class);
PowerMockito.whenNew(BufferedInputStream.class)
.withAr... |
public static <T> Collection<T> intersection(Collection<T> coll1, Collection<T> coll2) {
if (isNotEmpty(coll1) && isNotEmpty(coll2)) {
final ArrayList<T> list = new ArrayList<>(Math.min(coll1.size(), coll2.size()));
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
... | @SuppressWarnings("ConstantValue")
@Test
public void intersectionNullTest() {
final List<String> list1 = new ArrayList<>();
list1.add("aa");
final List<String> list2 = new ArrayList<>();
list2.add("aa");
final List<String> list3 = null;
final Collection<String> collection = CollUtil.intersection(list1, li... |
@VisibleForTesting
String decorateTarget(String oldTarget, PlayerIndicatorsService.Decorations decorations)
{
String newTarget = oldTarget;
if (decorations.getColor() != null && config.colorPlayerMenu())
{
String prefix = "";
int idx = oldTarget.indexOf("->");
if (idx != -1)
{
prefix = oldTarge... | @Test
public void testDecorateTarget()
{
when(playerIndicatorsConfig.colorPlayerMenu()).thenReturn(true);
String t0 = "title0";
String name = "RuneLite";
String t1 = "title1";
String t2 = "title2";
String col = "<col=ff>";
String cmbLevel = col + t0 + name + t1 + col + " (level-126)" + t2;
String ... |
public Iterator<Entry<String, Optional<MetaProperties>>> nonFailedDirectoryProps() {
return new Iterator<Entry<String, Optional<MetaProperties>>>() {
private final Iterator<String> emptyLogDirsIterator = emptyLogDirs.iterator();
private final Iterator<Entry<String, MetaProperties>> logDi... | @Test
public void testNonFailedDirectoryPropsForFoo() {
Map<String, Optional<MetaProperties>> results = new HashMap<>();
FOO.nonFailedDirectoryProps().forEachRemaining(entry ->
results.put(entry.getKey(), entry.getValue())
);
assertEquals(Optional.empty(), results.get("/t... |
public void incTopicPutNums(final String topic) {
this.statsTable.get(Stats.TOPIC_PUT_NUMS).addValue(topic, 1, 1);
} | @Test
public void testIncTopicPutNums() {
brokerStatsManager.incTopicPutNums(TOPIC);
assertThat(brokerStatsManager.getStatsItem(TOPIC_PUT_NUMS, TOPIC).getTimes().doubleValue()).isEqualTo(1L);
brokerStatsManager.incTopicPutNums(TOPIC, 2, 2);
assertThat(brokerStatsManager.getStatsItem(... |
public static java.util.Date toLogical(Schema schema, long value) {
if (!(LOGICAL_NAME.equals(schema.name())))
throw new DataException("Requested conversion of Timestamp object but the schema does not match.");
return new java.util.Date(value);
} | @Test
public void testToLogical() {
assertEquals(EPOCH.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, 0L));
assertEquals(EPOCH_PLUS_MILLIS.getTime(), Timestamp.toLogical(Timestamp.SCHEMA, TOTAL_MILLIS));
} |
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request().newBuilder().removeHeader("Accept-Encoding").build();
Response response = chain.proceed(request);
if (response.headers("Content-Encoding").contains("gzip")) {
response.close(... | @Test
public void intercept_whenGzipContentEncodingIncluded_shouldCloseTheResponse() throws IOException {
when(response.headers("Content-Encoding")).thenReturn(List.of("gzip"));
underTest.intercept(chain);
verify(response, times(1)).close();
} |
public boolean get() {
return value;
} | @Test
public void testCompareUnequalWritables() throws Exception {
DataOutputBuffer bTrue = writeWritable(new BooleanWritable(true));
DataOutputBuffer bFalse = writeWritable(new BooleanWritable(false));
WritableComparator writableComparator =
WritableComparator.get(BooleanWritable.class);
asser... |
@Override
protected CouchDbEndpoint createEndpoint(String uri, String remaining, Map<String, Object> params) throws Exception {
CouchDbEndpoint endpoint = new CouchDbEndpoint(uri, remaining, this);
setProperties(endpoint, params);
return endpoint;
} | @Test
void testPropertiesSet() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("createDatabase", true);
params.put("username", "coldplay");
params.put("password", "chrism");
params.put("heartbeat", "1000");
params.put("style", "gothic");
... |
@Override
public T get() throws PromiseException {
return _delegate.get();
} | @Test
public void testGet() {
final Promise<String> delegate = Promises.value("value");
final Promise<String> promise = new DelegatingPromise<String>(delegate);
assertEquals(delegate.get(), promise.get());
assertEquals(delegate.isDone(), promise.isDone());
} |
public JSONObject accumulate(String key, Object value) throws JSONException {
InternalJSONUtil.testValidity(value);
Object object = this.getObj(key);
if (object == null) {
this.set(key, value);
} else if (object instanceof JSONArray) {
((JSONArray) object).set(value);
} else {
this.set(key, JSONUtil.... | @Test
public void accumulateTest() {
final JSONObject jsonObject = JSONUtil.createObj().accumulate("key1", "value1");
assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
jsonObject.accumulate("key1", "value2");
assertEquals("{\"key1\":[\"value1\",\"value2\"]}", jsonObject.toString());
jsonObject.... |
@VisibleForTesting
void parseWorkflowParameter(
Map<String, Parameter> workflowParams, Parameter param, String workflowId) {
parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>());
} | @Test
public void testParseLiteralWorkflowParameter() {
StringParameter bar = StringParameter.builder().name("bar").value("test $foo-1").build();
paramEvaluator.parseWorkflowParameter(
Collections.singletonMap("foo", LongParameter.builder().expression("1+2+3;").build()),
bar,
"test-wor... |
public Input saveInput(AWSInputCreateRequest request, User user) throws Exception {
// Transpose the SaveAWSInputRequest to the needed InputCreateRequest
final HashMap<String, Object> configuration = new HashMap<>();
configuration.put(AWSCodec.CK_AWS_MESSAGE_TYPE, request.awsMessageType());
... | @Test
public void testSaveInput() throws Exception {
when(inputService.create(isA(HashMap.class))).thenCallRealMethod();
when(inputService.save(isA(Input.class))).thenReturn("input-id");
when(user.getName()).thenReturn("a-user-name");
when(messageInputFactory.create(isA(InputCreateRe... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowComputeNodesSharedData(@Mocked StarOSAgent starosAgent) throws AnalysisException, DdlException {
SystemInfoService clusterInfo = AccessTestUtil.fetchSystemInfoService();
ComputeNode node = new ComputeNode(1L, "127.0.0.1", 80);
node.setCpuCores(16);
node.set... |
public long incrementAndGet() {
return getAndAddVal(1L) + 1L;
} | @Test
public void testIncrementAndGet() {
PaddedAtomicLong counter = new PaddedAtomicLong();
long value = counter.incrementAndGet();
assertEquals(1L, value);
assertEquals(1L, counter.get());
} |
public Exchange createDbzExchange(DebeziumConsumer consumer, final SourceRecord sourceRecord) {
final Exchange exchange;
if (consumer != null) {
exchange = consumer.createExchange(false);
} else {
exchange = super.createExchange();
}
final Message message... | @Test
void testIfCreatesExchangeFromSourceDeleteRecordWithNull() {
final SourceRecord sourceRecord = createDeleteRecordWithNull();
final Exchange exchange = debeziumEndpoint.createDbzExchange(null, sourceRecord);
final Message inMessage = exchange.getIn();
assertNotNull(exchange);
... |
public Data getKeyData() {
if (keyData == null && serializationService != null) {
keyData = serializationService.toData(key);
}
return keyData;
} | @Test
public void testGetKeyData_withDataKey() {
assertEquals(toData("key"), dataEvent.getKeyData());
} |
public static ItemSpec<String> item(String key, @Nullable String value) {
return item(key, Type.STRING, value);
} | @Test
public void testCanSerializeItemSpecReference() {
DisplayData.ItemSpec<?> spec = DisplayData.item("clazz", DisplayDataTest.class);
SerializableUtils.ensureSerializable(new HoldsItemSpecReference(spec));
} |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowColumn() throws AnalysisException, DdlException {
ctx.setGlobalStateMgr(globalStateMgr);
ctx.setQualifiedUser("testUser");
ShowColumnStmt stmt = (ShowColumnStmt) com.starrocks.sql.parser.SqlParser.parse("show columns from testTbl in testDb",
ctx.get... |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldInferParallelismFromEnvironmentStreaming() throws IOException {
String confDir = extractFlinkConfig();
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(TestFlinkRunner.class);
options.setFlinkMaster("host:80");
StreamExecutionEnvironment sev =... |
void add(final long recordingId, final long recordingDescriptorOffset)
{
ensurePositive(recordingId, "recordingId");
ensurePositive(recordingDescriptorOffset, "recordingDescriptorOffset");
final int nextPosition = count << 1;
long[] index = this.index;
if (nextPosition > 0)
... | @Test
void addThrowsIllegalArgumentExceptionIfRecordingIdIsNegative()
{
assertThrows(IllegalArgumentException.class, () -> catalogIndex.add(-1, 0));
} |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testListReference() throws Exception {
MovieListReference movieListReference = new MovieListReference(1, 1999, "The Matrix", Arrays.asList("Keanu Reeves", "Laurence Fishburne", "Carrie-Anne Moss"));
objectMapper.add(movieListReference);
StateEngineRoundTripper.roundTripSnap... |
@Override
public <K, V> ICache<K, V> getCache(String name) {
checkNotNull(name, "Retrieving a cache instance with a null name is not allowed!");
return getCacheByFullName(HazelcastCacheManager.CACHE_MANAGER_PREFIX + name);
} | @Test
public void getCache_when_clientServiceNotFoundExceptionIsThrown_then_illegalStateExceptionIsThrown() {
// when ClientServiceNotFoundException was thrown by hzInstance.getDistributedObject
// (i.e. cache support is not available on the client-side)
HazelcastInstance hzInstance = mock(H... |
public Promise<Void> gracefullyShutdownClientChannels() {
return gracefullyShutdownClientChannels(ShutdownType.SHUTDOWN);
} | @Test
void connectionsNotForceClosed() throws Exception {
String configName = "server.outofservice.close.timeout";
AbstractConfiguration configuration = ConfigurationManager.getConfigInstance();
DefaultEventLoop eventLoop = spy(EVENT_LOOP);
shutdown = new ClientConnectionsShutdown(c... |
@Override
public void check(Thread currentThread) throws CeTaskInterruptedException {
super.check(currentThread);
computeTimeOutOf(taskOf(currentThread))
.ifPresent(timeout -> {
throw new CeTaskTimeoutException(format("Execution of task timed out after %s ms", timeout));
});
} | @Test
public void check_fails_with_ISE_if_thread_is_not_running_a_CeWorker() {
Thread t = newThreadWithRandomName();
assertThatThrownBy(() -> underTest.check(t))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'");
} |
public JdbcUrl parse(final String jdbcUrl) {
Matcher matcher = CONNECTION_URL_PATTERN.matcher(jdbcUrl);
ShardingSpherePreconditions.checkState(matcher.matches(), () -> new UnrecognizedDatabaseURLException(jdbcUrl, CONNECTION_URL_PATTERN.pattern().replaceAll("%", "%%")));
String authority = match... | @Test
void assertParseTestContainersJDBCUrl() {
assertThat(new StandardJdbcUrlParser().parse("jdbc:tc:mysql:5.7.34:///demo_ds").getDatabase(), is("demo_ds"));
assertThat(new StandardJdbcUrlParser().parse("jdbc:tc:postgresql:9.6.8:///demo_ds").getDatabase(), is("demo_ds"));
assertThat(new Sta... |
@Override
public int compareTo(COSObjectKey other)
{
return Long.compare(numberAndGeneration, other.numberAndGeneration);
} | @Test
void compareToInputNotNullOutputZero()
{
// Arrange
final COSObjectKey objectUnderTest = new COSObjectKey(1L, 0);
final COSObjectKey other = new COSObjectKey(1L, 0);
// Act
final int retval = objectUnderTest.compareTo(other);
// Assert result
asser... |
@Override
public AuditReplayCommand parse(Text inputLine,
Function<Long, Long> relativeToAbsolute) throws IOException {
Matcher m = logLineParseRegex.matcher(inputLine.toString());
if (!m.find()) {
throw new IOException(
"Unable to find valid message pattern from audit log line: `"
... | @Test
public void testInputWithRenameOptions() throws Exception {
Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser",
"rename (options=[TO_TRASH])", "sourcePath", "destPath");
AuditReplayCommand expected = new AuditReplayCommand(1000, "fakeUser",
"rename (options=[TO_TRASH])", "sou... |
@Override
public long getCleanTasksDelay() {
return CANCEL_WORN_OUTS_DELAY;
} | @Test
public void getCleanCeTasksDelay_returns_2() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getCleanTasksDelay())
.isEqualTo(2L);
workerCountProvider.set(1);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getCleanTasksDelay())
.isEqualTo(2L);
} |
@Override
public List<DeptDO> getDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return deptMapper.selectBatchIds(ids);
} | @Test
public void testGetDeptList_reqVO() {
// mock 数据
DeptDO dept = randomPojo(DeptDO.class, o -> { // 等会查询到
o.setName("开发部");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
deptMapper.insert(dept);
// 测试 name 不匹配
deptMapper.insert(Obje... |
@Override
void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
expectCaseSensitiveDefaultCollation(connection);
if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) {
repairColumns(connection);
}
} | @Test
public void upgrade_repairs_indexed_CI_AI_columns() throws SQLException {
answerDefaultCollation("Latin1_General_CS_AS");
answerColumnDefs(
new ColumnDef(TABLE_ISSUES, COLUMN_KEE, "Latin1_General", "Latin1_General_CS_AS", "varchar", 10, false),
new ColumnDef(TABLE_PROJECTS, COLUMN_NAME, "Lat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.