focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Long createPost(PostSaveReqVO createReqVO) {
// 校验正确性
validatePostForCreateOrUpdate(null, createReqVO.getName(), createReqVO.getCode());
// 插入岗位
PostDO post = BeanUtils.toBean(createReqVO, PostDO.class);
postMapper.insert(post);
return post.getId();
... | @Test
public void testCreatePost_success() {
// 准备参数
PostSaveReqVO reqVO = randomPojo(PostSaveReqVO.class,
o -> o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()))
.setId(null); // 防止 id 被设置
// 调用
Long postId = postService.createPost(reqVO);... |
public void updateConfig(DynamicConfigEvent event) {
if (!isTargetConfig(event)) {
return;
}
if (updateWithDefaultMode(event)) {
afterUpdateConfig();
}
} | @Test
public void testUpdateGraceConfig() {
try (MockedStatic<PluginConfigManager> pluginConfigManagerMockedStatic = Mockito.mockStatic(PluginConfigManager.class)) {
pluginConfigManagerMockedStatic.when(() -> PluginConfigManager.getPluginConfig(GraceConfig.class))
.thenReturn... |
private static void handleSetPrimaryIndexCacheExpireSec(long backendId, Map<Long, TTablet> backendTablets) {
List<Pair<Long, Integer>> tabletToPrimaryCacheExpireSec = Lists.newArrayList();
TabletInvertedIndex invertedIndex = GlobalStateMgr.getCurrentState().getTabletInvertedIndex();
for (TTable... | @Test
public void testHandleSetPrimaryIndexCacheExpireSec() {
Database db = GlobalStateMgr.getCurrentState().getDb("test");
long dbId = db.getId();
OlapTable olapTable = (OlapTable) db.getTable("primary_index_cache_expire_sec_test");
long backendId = 10001L;
List<Long> tablet... |
protected URI getOrigin(final Path container, final Distribution.Method method) throws BackgroundException {
return URI.create(String.format("http://%s.%s", container.getName(), bookmark.getProtocol().getDefaultHostname()));
} | @Test
public void testGetOrigin() throws Exception {
final S3Session session = new S3Session(new Host(new S3Protocol(), new S3Protocol().getDefaultHostname()));
final CloudFrontDistributionConfiguration configuration
= new CloudFrontDistributionConfiguration(session, new S3LocationFeatur... |
@Override
public @NonNull LiteralCommandNode<S> createNode(
final @NonNull String label,
final @NonNull CommandNode<C> cloudCommand,
final @NonNull Command<S> executor,
final @NonNull BrigadierPermissionChecker<C> permissionChecker
) {
final LiteralArgumen... | @Test
void testSimple() throws Exception {
// Arrange
final Command<Object> command = this.commandManager.commandBuilder("command")
.literal("literal")
.required("integer", integerParser(0, 10))
.optional("string", greedyStringParser(),
... |
public static String getFieldName(Field field) {
if (null == field) {
return null;
}
return field.getName();
} | @Test
public void getFieldNameTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
String fieldName = ReflectUtil.getFieldName(privateField);
Assert.assertNotNull(fieldName);
Field subField = ReflectUtil.getField(TestSubClass.class, "subField");
... |
public static @CheckForNull
BlueUrlTokenizer parse(@NonNull String url) {
Iterator<String> urlTokens = extractTokens(url);
//
// Yes, the following code is quite ugly, but it's easy enough to understand atm.
// Unless this gets a lot more detailed, please don't get super clever idea... | @Test
public void test_MalformedURLException() {
Assert.assertNull(BlueUrlTokenizer.parse("/a"));
} |
public int getClusterInfoFailedRetrieved() {
return numGetClusterInfoFailedRetrieved.value();
} | @Test
public void testGetClusterInfoRetrievedFailed() {
long totalBadBefore = metrics.getClusterInfoFailedRetrieved();
badSubCluster.getClusterInfoFailed();
Assert.assertEquals(totalBadBefore + 1, metrics.getClusterInfoFailedRetrieved());
} |
@Override
public Optional<NativeEntity<Collector>> findExisting(Entity entity, Map<String, ValueReference> parameters) {
if (entity instanceof EntityV1) {
return findExisting((EntityV1) entity, parameters);
} else {
throw new IllegalArgumentException("Unsupported entity versi... | @Test
@MongoDBFixtures("SidecarCollectorFacadeTest.json")
public void findExisting() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("0"))
.type(ModelTypes.SIDECAR_COLLECTOR_V1)
.data(objectMapper.convertValue(SidecarCollectorEntity.create(
... |
@Override
public GetApplicationReportResponse getApplicationReport(
GetApplicationReportRequest request) throws YarnException, IOException {
ApplicationId applicationId = request.getApplicationId();
try {
GetApplicationReportResponse response =
GetApplicationReportResponse.newInstance(hi... | @Test
void testApplicationReport() throws IOException, YarnException {
ApplicationId appId = null;
appId = ApplicationId.newInstance(0, 1);
GetApplicationReportRequest request =
GetApplicationReportRequest.newInstance(appId);
GetApplicationReportResponse response =
clientService.getApp... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertBoolean() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.BOOLEAN_TYPE).build();
BasicTypeDefine typeDefine = DB2TypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName()... |
@RequiresApi(Build.VERSION_CODES.R)
@Override
public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions();
if (inlineSuggestions.size() > 0) {
mInlineSuggestionAction.onNewSuggestions(inline... | @Test
public void testClosesInlineSuggestionsOnPick() {
simulateOnStartInputFlow();
var inlineView1 = Mockito.mock(InlineContentView.class);
var inlineView2 = Mockito.mock(InlineContentView.class);
mAnySoftKeyboardUnderTest.onInlineSuggestionsResponse(mockResponse(inlineView1, inlineView2));
var r... |
static Properties getProperties(final Arguments arguments) throws IOException {
final Properties props = new Properties();
props.put("bootstrap.servers", arguments.bootstrapServer);
props.put("client.id", "KSQLDataGenProducer");
props.put(KsqlConfig.SCHEMA_REGISTRY_URL_PROPERTY, arguments.schemaRegistry... | @Test
public void shouldPassSchemaRegistryUrl() throws Exception {
final DataGen.Arguments args = new DataGen.Arguments(
false,
"bootstrap",
null,
null,
null,
null,
"topic",
"key",
null,
0,
"srUrl",
null,
1,
... |
public static InputStream getNoticeStream() {
InputStream res = FileUtils.getInputStreamForClasspathFile(NOTICE_RESOURCE);
assert res != null;
return res;
} | @Test
public void getNoticeStreamTest() throws IOException {
Set<String> expectedStrings = Sets.newHashSet(
"Florian Schmaus"
, "Paul Schaub"
);
int maxLineLength = 0;
try (InputStream inputStream = Smack.getNoticeStream()) {
... |
@VisibleForTesting
List<String> getFuseInfo() {
return mFuseInfo;
} | @Test
public void UnderFileSystemS3() {
try (FuseUpdateChecker checker = getUpdateCheckerWithUfs("s3://alluxio-test/")) {
Assert.assertTrue(containsTargetInfo(checker.getFuseInfo(), "s3"));
}
} |
@Override
public BeamSqlTable buildBeamSqlTable(Table table) {
return new BigQueryTable(table, getConversionOptions(table.getProperties()));
} | @Test
public void testRuntimeExceptionThrown_whenAnInvalidPropertyIsSpecified() {
Table table = fakeTableWithProperties("hello", "{" + METHOD_PROPERTY + ": \"blahblah\" }");
assertThrows(
RuntimeException.class,
() -> {
provider.buildBeamSqlTable(table);
});
} |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_success() {
// 准备参数
String code = "test_code";
// mock 数据
OAuth2CodeDO codeDO = randomPojo(OAuth2CodeDO.class).setCode(code)
.setExpiresTime(LocalDateTime.now().plusDays(1));
oauth2CodeMapper.insert(codeDO);
... |
@Restricted(NoExternalUse.class)
public boolean supportIsDescendant() {
return false;
} | @Test
public void testSupportIsDescendant_AbstractBase() {
VirtualFile root = new VirtualFileMinimalImplementation();
assertFalse(root.supportIsDescendant());
} |
@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 testToResponseSerializationException() {
RestExceptionMapper mapper = new RestExceptionMapper();
Response resp = mapper.toResponse(new SerializationException());
assertEquals(resp.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} |
@Override
public Map<String, Object> batchInsertOrUpdate(List<ConfigAllInfo> configInfoList, String srcUser, String srcIp,
Map<String, Object> configAdvanceInfo, SameConfigPolicy policy) throws NacosException {
int succCount = 0;
int skipCount = 0;
List<Map<String, String>> failD... | @Test
void testBatchInsertOrUpdateAbort() throws NacosException {
List<ConfigAllInfo> configInfoList = new ArrayList<>();
//insert direct
configInfoList.add(createMockConfigAllInfo(0));
//exist config and overwrite
configInfoList.add(createMockConfigAllInfo(1));
//ins... |
@Override
public String getMessage() {
return message;
} | @Test
final void requireMixOfMessageAndNoMessageWorks() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable(t0);
final Throwable t2 = new Throwable("t2", t1);
final ExceptionWrapper e = new ExceptionWrapper(t2);
final String expected = "Throwable(\"... |
@Override
public PCollectionsImmutableNavigableSet<E> descendingSet() {
return new PCollectionsImmutableNavigableSet<>(underlying().descendingSet());
} | @Test
public void testDelegationOfDescendingSet() {
TreePSet<Integer> testSet = TreePSet.from(Arrays.asList(2, 3, 4));
new PCollectionsTreeSetWrapperDelegationChecker<>()
.defineMockConfigurationForFunctionInvocation(TreePSet::descendingSet, testSet.descendingSet())
.... |
@Override
public void collectNoValue(MetricDescriptor descriptor) {
for (MetricsCollector collector : collectors) {
collector.collectNoValue(descriptor);
}
} | @Test
public void testCollectNoValue() {
compositeCollector.collectNoValue(metricsDescriptor);
verify(collectorMock1).collectNoValue(metricsDescriptor);
verify(collectorMock2).collectNoValue(metricsDescriptor);
} |
public static Resource multiplyAndAddTo(
Resource lhs, Resource rhs, double by) {
int maxLength = ResourceUtils.getNumberOfCountableResourceTypes();
for (int i = 0; i < maxLength; i++) {
try {
ResourceInformation rhsValue = rhs.getResourceInformation(i);
ResourceInformation lhsValue ... | @Test
void testMultiplyAndAddTo() throws Exception {
unsetExtraResourceType();
setupExtraResourceType();
assertEquals(createResource(6, 4),
multiplyAndAddTo(createResource(3, 1), createResource(2, 2), 1.5));
assertEquals(createResource(6, 4, 0),
multiplyAndAddTo(createResource(3, 1), c... |
public static boolean isPopRetryTopicV2(String retryTopic) {
return retryTopic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) && retryTopic.contains(String.valueOf(POP_RETRY_SEPARATOR_V2));
} | @Test
public void testIsPopRetryTopicV2() {
String popRetryTopic = KeyBuilder.buildPopRetryTopicV2(topic, group);
assertThat(KeyBuilder.isPopRetryTopicV2(popRetryTopic)).isEqualTo(true);
String popRetryTopicV1 = KeyBuilder.buildPopRetryTopicV1(topic, group);
assertThat(KeyBuilder.isP... |
@Override
public void save(final CallContext ctx) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val requestedUrl = getRequestedUrl(webContext, sessionStore);
if (WebContextHelper.isPost(webContext)) {
LOGGER.debug("requestedUrl with data: {}... | @Test
public void testSaveGet() {
val context = MockWebContext.create().setFullRequestURL(PAC4J_URL);
val sessionStore = new MockSessionStore();
handler.save(new CallContext(context, sessionStore));
val location = (String) sessionStore.get(context, Pac4jConstants.REQUESTED_URL).get()... |
@Override
public void deleteObject(String accountName, ObjectType objectType, String objectKey) {
if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) {
sqlCanaryArchiveRepo.deleteById(objectKey);
return;
}
if (objectType.equals(ObjectType.CANARY_CONFIG)) {
sqlCanaryConfigRepo.delet... | @Test
public void testDeleteObjectWhenMetricSets() {
var testAccountName = UUID.randomUUID().toString();
var testObjectType = ObjectType.METRIC_SET_LIST;
var testObjectKey = UUID.randomUUID().toString();
sqlStorageService.deleteObject(testAccountName, testObjectType, testObjectKey);
verify(sqlMe... |
public static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length) {
// Other implementation of the same algorithm:
// int crc = 0xFFFF;
//
// for (int i = offset; i < offset + length && i < data.length; ++i) {
// crc = (((crc & 0xFFFF) >> 8) | (crc << 8));
// crc ^= data[i];
// crc ... | @Test
public void CCITT_FALSE_A() {
final byte[] data = new byte[] { 'A' };
assertEquals(0xB915, CRC16.CCITT_FALSE(data, 0, 1));
} |
public static GenericSchemaImpl of(SchemaInfo schemaInfo) {
return of(schemaInfo, true);
} | @Test
public void testKeyValueSchema() {
// configure the schema info provider
MultiVersionSchemaInfoProvider multiVersionSchemaInfoProvider = mock(MultiVersionSchemaInfoProvider.class);
List<Schema<Foo>> encodeSchemas = Lists.newArrayList(
Schema.JSON(Foo.class),
Sc... |
@Override
public Set<String> getOutputResourceFields( XMLOutputMeta meta ) {
Set<String> fields = new HashSet<>();
XMLField[] outputFields = meta.getOutputFields();
for ( int i = 0; i < outputFields.length; i++ ) {
XMLField outputField = outputFields[ i ];
fields.add( outputField.getFieldName(... | @Test
public void testGetOutputResourceFields() throws Exception {
XMLField[] outputFields = new XMLField[2];
XMLField field1 = mock( XMLField.class );
XMLField field2 = mock( XMLField.class );
outputFields[0] = field1;
outputFields[1] = field2;
when( field1.getFieldName() ).thenReturn( "fiel... |
public static String hmacSHA256(String data, String key) {
return hmacSHA256(data.getBytes(), key.getBytes());
} | @Test
public void testHmacSHA256() throws Exception {
String biezhiHmacSHA256 = "65e377c552b81d0978343e5fe7cf92bdc867d19a73d8479f0437db93b0f0b2af";
Assert.assertEquals(
biezhiHmacSHA256,
EncryptKit.hmacSHA256("biezhi", biezhiHmackey)
);
Assert.assertEq... |
public static Type fromHiveTypeToMapType(String typeStr) {
String[] kv = getKeyValueStr(typeStr);
return new MapType(fromHiveType(kv[0]), fromHiveType(kv[1]));
} | @Test
public void testMapString() {
ScalarType keyType = ScalarType.createType(PrimitiveType.TINYINT);
ScalarType valueType = ScalarType.createType(PrimitiveType.SMALLINT);
MapType mapType = new MapType(keyType, valueType);
String typeStr = "map<tinyint,smallint>";
Type resTy... |
Optional<ImageMetadataTemplate> retrieveMetadata(ImageReference imageReference)
throws IOException, CacheCorruptedException {
Path imageDirectory = cacheStorageFiles.getImageDirectory(imageReference);
Path metadataPath = imageDirectory.resolve("manifests_configs.json");
if (!Files.exists(metadataPath)... | @Test
public void testRetrieveMetadata_ociImageIndex()
throws IOException, URISyntaxException, CacheCorruptedException {
setupCachedMetadataOciImageIndex(cacheDirectory);
ImageMetadataTemplate metadata =
cacheStorageReader.retrieveMetadata(ImageReference.of("test", "image", "tag")).get();
... |
public void parse(String jsonString) {
parse(new JSONObject(jsonString));
} | @Test
public void parseTest() {
String jsonstr = "{\n" +
" \"location\": \"https://hutool.cn\",\n" +
" \"message\": \"这是一条测试消息\",\n" +
" \"requestId\": \"123456789\",\n" +
" \"traceId\": \"987654321\"\n" +
"}";
final TestBean testBean = JSONUtil.toBean(jsonstr, TestBean.class);
... |
public static boolean validateCSConfiguration(
final Configuration oldConfParam, final Configuration newConf,
final RMContext rmContext) throws IOException {
// ensure that the oldConf is deep copied
Configuration oldConf = new Configuration(oldConfParam);
QueueMetrics.setConfigurationVa... | @Test
public void testValidateCSConfigDominantRCAbsoluteModeParentMaxGPUExceeded() throws Exception {
setUpMockRM(true);
RMContext rmContext = mockRM.getRMContext();
CapacitySchedulerConfiguration oldConfiguration = cs.getConfiguration();
CapacitySchedulerConfiguration newConfiguration =
new C... |
public static boolean equivalent(
Expression left, Expression right, Types.StructType struct, boolean caseSensitive) {
return Binder.bind(struct, Expressions.rewriteNot(left), caseSensitive)
.isEquivalentTo(Binder.bind(struct, Expressions.rewriteNot(right), caseSensitive));
} | @Test
public void testInequalityEquivalence() {
String[] cols = new String[] {"id", "val", "ts", "date", "time"};
for (String col : cols) {
assertThat(
ExpressionUtil.equivalent(
Expressions.lessThan(col, 34L),
Expressions.lessThanOrEqual(col, 33L),
... |
@Override
public boolean isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType eventType) {
return true;
} | @Test
public void testIsAutoTrackEventTypeIgnored() {
Assert.assertTrue(mSensorsAPI.isAutoTrackEventTypeIgnored(SensorsAnalyticsAutoTrackEventType.APP_START));
} |
public boolean isEscapeUnicode() {
return escapeUnicode;
} | @Test
public void testEscapeUnicodeOption() {
assertThat(parse("--escape-unicode").isEscapeUnicode()).isTrue();
assertThat(parse("").isEscapeUnicode()).isFalse();
} |
private MergeSortedPages() {} | @Test
public void testEmptyStreams()
throws Exception
{
List<Type> types = ImmutableList.of(INTEGER, BIGINT, DOUBLE);
MaterializedResult actual = mergeSortedPages(
types,
ImmutableList.of(0, 1),
ImmutableList.of(ASC_NULLS_FIRST, ASC_NUL... |
public boolean intersects(Tags other) {
return this.tags.stream().anyMatch(other::contains);
} | @Test
public void testIntersects() {
Tags tags1 = new Tags(Set.of("a", "tag2", "3"));
Tags tags2 = new Tags(Set.of("a", "tag3"));
assertTrue(tags1.intersects(tags2));
assertTrue(tags2.intersects(tags1));
} |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseLaterVariadicWhenTwoVariadicsMatch() {
// Given:
givenFunctions(
function(OTHER, 1, LONG, INT_VARARGS, STRING, DOUBLE),
function(EXPECTED, 2, LONG, INT, STRING_VARARGS, DOUBLE)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Im... |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldNotLoadAPluginWhenTargetedGocdVersionIsGreaterThanCurrentGocdVersion() throws Exception {
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
copyPluginToTheDirectory(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
final GoPluginDescriptor pluginDescriptor1 = getPlug... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
List<Map<String, Object>> nodeTags = readerWay.getTag("node_tags", null);
if (nodeTags == null)
return;
for (int i = 0; i < nodeTags.size(); i++) {
... | @Test
public void testSignals() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess,
createReader(new PMap().putObject("crossing", "traffic_signals").toMap()), null);
assertEquals(Crossing.TRAFFIC_SIGNA... |
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (SelectValuesMeta) smi;
data = (SelectValuesData) sdi;
Object[] rowData = getRow(); // get row from rowset, wait for our turn, indicate busy!
if ( rowData == null ) { // no more input to be expecte... | @Test
public void testPDI16368() throws Exception {
// This tests that the fix for PDI-16388 doesn't get re-broken.
//
SelectValuesHandler step2;
Object[] inputRow2;
RowMeta inputRowMeta;
SelectValuesMeta stepMeta;
SelectValuesData stepData;
ValueMetaInterface vmi;
// First, test... |
public static <T> CompressedSerializedValue<T> fromBytes(byte[] compressedSerializedData) {
return new CompressedSerializedValue<>(compressedSerializedData);
} | @Test
void testFromNullBytes() {
assertThatThrownBy(() -> CompressedSerializedValue.fromBytes(null))
.isInstanceOf(NullPointerException.class);
} |
@Operation(summary = "queryLineageByWorkFlowName", description = "QUERY_WORKFLOW_LINEAGE_BY_NAME_NOTES")
@GetMapping(value = "/query-by-name")
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_WORKFLOW_LINEAGE_ERROR)
public Result<List<WorkFlowLineage>> queryWorkFlowLineageByName(@Parameter(hidden = tr... | @Test
public void testQueryWorkFlowLineageByName() {
long projectCode = 1L;
String searchVal = "test";
Mockito.when(workFlowLineageService.queryWorkFlowLineageByName(projectCode, searchVal))
.thenReturn(Collections.emptyList());
assertDoesNotThrow(() -> workFlowLineag... |
public static boolean hasIllegalNodeAddress(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return false;
}
Set<String> remoteAddressSet = remoteInstances.stream().map(remoteInstance ->
remoteInstance.getAddress().getHost()).col... | @Test
public void hasIllegalNodeAddressWithNull() {
boolean flag = OAPNodeChecker.hasIllegalNodeAddress(null);
Assertions.assertFalse(flag);
} |
public ThreadSafeBitSet andNot(ThreadSafeBitSet other) {
if(other.log2SegmentSize != log2SegmentSize)
throw new IllegalArgumentException("Segment sizes must be the same");
ThreadSafeBitSetSegments thisSegments = this.segments.get();
ThreadSafeBitSetSegments otherSegments = other.seg... | @Test
public void testAndNot() {
ThreadSafeBitSet tsbSet1 = new ThreadSafeBitSet();
ThreadSafeBitSet tsbSet2 = new ThreadSafeBitSet();
for (int i = 0; i < 3; i++) {
tsbSet1.set(i);
tsbSet2.set(i * 2);
}
// determine andNot
BitSet andNot_bSet =... |
public long[] decodeInt8Array(final byte[] parameterBytes, final boolean isBinary) {
ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode"));
String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8);
Collection<String> parame... | @Test
void assertParseInt8ArrayNormalTextMode() {
long[] actual = DECODER.decodeInt8Array(INT_ARRAY_STR.getBytes(), false);
assertThat(actual.length, is(2));
assertThat(actual[0], is(11L));
assertThat(actual[1], is(12L));
} |
@Override
public int choosePartition(Message<?> msg, TopicMetadata topicMetadata) {
// If the message has a key, it supersedes the round robin routing policy
if (msg.hasKey()) {
return signSafeMod(hash.makeHash(msg.getKey()), topicMetadata.numPartitions());
}
if (isBatch... | @Test
public void testChoosePartitionWithoutKey() {
Message<?> msg = mock(Message.class);
when(msg.getKey()).thenReturn(null);
RoundRobinPartitionMessageRouterImpl router = new RoundRobinPartitionMessageRouterImpl(
HashingScheme.JavaStringHash, 0, false, 0);
for (int... |
public static String getZooKeeperEnsemble(Configuration flinkConf)
throws IllegalConfigurationException {
String zkQuorum = flinkConf.getValue(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM);
if (zkQuorum == null || StringUtils.isBlank(zkQuorum)) {
throw new IllegalConfigurationEx... | @Test
void testZooKeeperEnsembleConnectStringConfiguration() throws Exception {
// ZooKeeper does not like whitespace in the quorum connect String.
String actual, expected;
Configuration conf = new Configuration();
{
expected = "localhost:2891";
setQuorum(co... |
public static TokenLocation of(final int line, final int charPositionInLine) {
return new TokenLocation(
line,
charPositionInLine,
Integer.MAX_VALUE,
Integer.MAX_VALUE
);
} | @Test
public void shouldImplementEqualsProperly() {
new EqualsTester()
.addEqualityGroup(TokenLocation.of(1, 2))
.addEqualityGroup(new TokenLocation(1, 2, 3, 4), new TokenLocation(1, 2, 3, 4))
.testEquals();
} |
@Override
public void unsubscribe(String serviceName, EventListener listener) throws NacosException {
unsubscribe(serviceName, new ArrayList<>(), listener);
} | @Test
public void testUnSubscribe5() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
EventListener listener = event -> {
};
when(changeNotifier.isSubscribed(groupName, serviceName)).thenReturn(false);
... |
public static List<ACL> parseACLs(String aclString) throws
BadAclFormatException {
List<ACL> acl = Lists.newArrayList();
if (aclString == null) {
return acl;
}
List<String> aclComps = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults()
.split(aclString)... | @Test
public void testGoodACLs() {
List<ACL> result = ZKUtil.parseACLs(
"sasl:hdfs/host1@MY.DOMAIN:cdrwa, sasl:hdfs/host2@MY.DOMAIN:ca");
ACL acl0 = result.get(0);
assertEquals(Perms.CREATE | Perms.DELETE | Perms.READ |
Perms.WRITE | Perms.ADMIN, acl0.getPerms());
assertEquals("sasl", ... |
@Override
public TimelineEvents getEntityTimelines(String entityType,
SortedSet<String> entityIds, Long limit, Long windowStart,
Long windowEnd, Set<String> eventTypes) throws IOException {
LOG.debug("getEntityTimelines type={} ids={}", entityType, entityIds);
TimelineEvents returnEvents = new Tim... | @Test
void testNullCheckGetEntityTimelines() throws Exception {
try {
store.getEntityTimelines("YARN_APPLICATION", null, null, null, null,
null);
} catch (NullPointerException e) {
fail("NPE when getEntityTimelines called with Null EntityIds");
}
} |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldAutoSetIdleSourcesFlagWithoutCheckpointing() {
// Checkpointing disabled, shut down sources immediately
FlinkPipelineOptions options = getDefaultPipelineOptions();
FlinkExecutionEnvironments.createStreamExecutionEnvironment(options);
assertThat(options.getShutdownSourcesAfterId... |
public void validate() throws TelegramApiException {
if (useHttps) {
File file = new File(keyStorePath);
if (!file.exists() || !file.canRead()) {
throw new TelegramApiException("Can't find or access server keystore file.");
}
}
} | @Test
public void testWhenHttpsEnabledKeyStoreFileMustBePresent() {
WebhookOptions webhookOptions = new WebhookOptions();
webhookOptions.setUseHttps(true);
webhookOptions.setKeyStorePath(temporaryKeyStoreFile.getAbsolutePath());
try {
webhookOptions.validate();
} ... |
static void parseAuthority(final StringReader reader, final Host host, final Consumer<HostParserException> decorator) throws HostParserException {
parseUserInfo(reader, host, decorator);
parseHostname(reader, host, decorator);
parsePath(reader, host, false, decorator);
} | @Test
public void testParseAuthorityUserPasswordDomain() throws HostParserException {
final Host host = new Host(new TestProtocol());
final String authority = "user:password@domain.tld";
final HostParser.StringReader reader = new HostParser.StringReader(authority);
HostParser.parseA... |
public Frequency floorDivision(long value) {
return new Frequency(Math.floorDiv(this.frequency, value));
} | @Test
public void testfloorDivision() {
Frequency frequency = Frequency.ofGHz(1);
long factor = 5;
Frequency expected = Frequency.ofMHz(200);
assertThat(frequency.floorDivision(factor), is(expected));
} |
public DataTable subTable(int fromRow, int fromColumn) {
return subTable(fromRow, fromColumn, height(), width());
} | @Test
void subTable_throws_for_negative_from_row() {
DataTable table = createSimpleTable();
assertThrows(IndexOutOfBoundsException.class, () -> table.subTable(-1, 0, 1, 1));
} |
@Override
public List<String> mapRow(Row element) {
List<String> res = new ArrayList<>();
Schema s = element.getSchema();
for (int i = 0; i < s.getFieldCount(); i++) {
res.add(convertFieldToString(s.getField(i).getType(), element.getValue(i)));
}
return res;
} | @Test
public void testBigNegativeNumbers() {
Schema.Builder schemaBuilder = new Schema.Builder();
schemaBuilder.addField("byte", Schema.FieldType.BYTE);
schemaBuilder.addField("int16", Schema.FieldType.INT16);
schemaBuilder.addField("int32", Schema.FieldType.INT32);
schemaBuilder.addField("int64",... |
@JsonProperty
public void setKeyStoreType(String keyStoreType) {
this.keyStoreType = keyStoreType;
} | @Test
void windowsKeyStoreValidation() {
HttpsConnectorFactory factory = new HttpsConnectorFactory();
factory.setKeyStoreType(WINDOWS_MY_KEYSTORE_NAME);
assertThat(getViolationProperties(validator.validate(factory)))
.doesNotContain("validKeyStorePassword")
.d... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testRetryByRemoteException() {
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
Collections.<Class<? extends Exception>, RetryPolicy>singletonMap(FatalException.class, TRY_ONCE_THEN_FAIL);
UnreliableInterface unreliable = (UnreliableInterface)
RetryProxy.c... |
public boolean contains(long item1, long item2) {
lock.readLock().lock();
try {
RoaringBitmap bitSet = map.get(item1);
return bitSet != null && bitSet.contains(item2, item2 + 1);
} finally {
lock.readLock().unlock();
}
} | @Test
public void testContains() {
ConcurrentBitmapSortedLongPairSet set = new ConcurrentBitmapSortedLongPairSet();
assertFalse(set.contains(1, 1));
int items = 10;
for (int i = 0; i < items; i++) {
set.add(1, i);
}
for (int i = 0; i < items; i++) {
... |
public static String pluginInfoKey(final String pluginName) {
return String.join("", pluginName, PLUGIN_INFO);
} | @Test
public void testPlugInfoKey() {
String mockPlugin = "MockPlugin";
String mokPluginInfoKey = RedisKeyConstants.pluginInfoKey(mockPlugin);
assertThat(mockPlugin, notNullValue());
assertThat(String.join("", mockPlugin, PLUGIN_INFO), equalTo(mokPluginInfoKey));
} |
static void waitUntilFinish(@Nullable StreamGobbler gobbler) {
if (gobbler != null) {
try {
gobbler.join();
} catch (InterruptedException ignored) {
// consider as finished, restore the interrupted flag
Thread.currentThread().interrupt();
}
}
} | @Test
public void forward_stream_to_log() {
InputStream stream = IOUtils.toInputStream("one\nsecond log\nthird log\n", StandardCharsets.UTF_8);
Logger logger = mock(Logger.class);
Logger startupLogger = mock(Logger.class);
StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, ... |
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found e... | @Test
public void testInterAppConstriantsByAppTag()
throws InvalidAllocationTagsQueryException {
ApplicationId application1 = BuilderUtils.newApplicationId(1000, 123);
ApplicationId application2 = BuilderUtils.newApplicationId(1001, 124);
// app1: test-tag
// app2: N/A
RMContext mockedCont... |
public static JibContainerBuilder toJibContainerBuilder(
ArtifactProcessor processor,
Jar jarOptions,
CommonCliOptions commonCliOptions,
CommonContainerConfigCliOptions commonContainerConfigCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {
Str... | @Test
public void testToJibContainerBuilder_optionalParameters()
throws IOException, InvalidImageReferenceException {
when(mockCommonContainerConfigCliOptions.getFrom()).thenReturn(Optional.of("base-image"));
when(mockCommonContainerConfigCliOptions.getExposedPorts())
.thenReturn(ImmutableSet.of... |
public List<BlameLine> blame(Path baseDir, String fileName) throws Exception {
BlameOutputProcessor outputProcessor = new BlameOutputProcessor();
try {
this.processWrapperFactory.create(
baseDir,
outputProcessor::process,
gitCommand,
GIT_DIR_FLAG, String.format(GIT_... | @Test
public void throw_exception_if_command_fails() throws Exception {
Path baseDir = temp.newFolder().toPath();
NativeGitBlameCommand blameCommand = new NativeGitBlameCommand("randomcmdthatwillneverbefound", System2.INSTANCE, processWrapperFactory);
assertThatThrownBy(() -> blameCommand.blame(baseDir, "... |
@Override
public <T extends GetWorkBudgetSpender> void distributeBudget(
ImmutableCollection<T> budgetOwners, GetWorkBudget getWorkBudget) {
if (budgetOwners.isEmpty()) {
LOG.debug("Cannot distribute budget to no owners.");
return;
}
if (getWorkBudget.equals(GetWorkBudget.noBudget())) {... | @Test
public void testDistributeBudget_adjustsStreamBudgetWhenRemainingByteBudgetTooLowNoActiveWork() {
GetWorkBudget streamRemainingBudget =
GetWorkBudget.builder().setItems(10L).setBytes(1L).build();
GetWorkBudget totalGetWorkBudget = GetWorkBudget.builder().setItems(10L).setBytes(10L).build();
... |
public static Duration parseDuration(String text) {
checkNotNull(text);
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while ... | @Test
void testParseDurationDays() {
assertThat(TimeUtils.parseDuration("987654d").toDays()).isEqualTo(987654);
assertThat(TimeUtils.parseDuration("987654day").toDays()).isEqualTo(987654);
assertThat(TimeUtils.parseDuration("987654days").toDays()).isEqualTo(987654);
assertThat(TimeUt... |
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.size() < 2) {
printInfo(err);
return 1;
}
int index = 0;
String input = args.get(index);
String option = "all";
if ("-o".equals(input)) {
option = args... | @Test
void repairAllCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "all", corruptBlockFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5 Num... |
public static void mark(Buffer buffer) {
buffer.mark();
} | @Test
public void testMark() {
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt(1);
Assertions.assertDoesNotThrow(() -> BufferUtils.mark(byteBuffer));
} |
public boolean sendEventToJS(String eventName, Bundle data, ReactContext reactContext) {
if (reactContext != null) {
sendEventToJS(eventName, Arguments.fromBundle(data), reactContext);
return true;
}
return false;
} | @Test
public void sendEventToJS_noReactContext_returnsFalse() throws Exception {
WritableMap data = mock(WritableMap.class);
final JsIOHelper uut = createUUT();
boolean result = uut.sendEventToJS("my-event", data, null);
assertFalse(result);
verify(mRCTDeviceEventEmitter, n... |
@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 shouldFindDoubleMax() {
final List<Double> input =
Arrays.asList(Double.valueOf(1.1), Double.valueOf(3.1), Double.valueOf(-1.1));
assertThat(udf.arrayMax(input), is(Double.valueOf(3.1)));
} |
public Mono<Void> createProducerAcl(KafkaCluster cluster, CreateProducerAclDTO request) {
return adminClientService.get(cluster)
.flatMap(ac -> createAclsWithLogging(ac, createProducerBindings(request)))
.then();
} | @Test
void createsProducerDependantAclsWhenTopicsAndTxIdSpecifiedByPrefix() {
ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class);
when(adminClientMock.createAcls(createdCaptor.capture()))
.thenReturn(Mono.empty());
var principal = UUID.randomUUID().to... |
public List<List<String>> getAllQueries() {
List<List<String>> result = Lists.newLinkedList();
readLock.lock();
try {
for (ProfileElement element : profileMap.values()) {
Map<String, String> infoStrings = element.infoStrings;
List<String> row = Lists.n... | @Test
public void testGetAllQueries() {
ProfileManager manager = ProfileManager.getInstance();
assertTrue(manager.getAllProfileElements().isEmpty());
RuntimeProfile profile1 = buildRuntimeProfile("123", "Query");
manager.pushProfile(null, profile1);
RuntimeProfile profile2 ... |
@Override
public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
@Nullable String projectName) {
String pat = findPersonalAccessTokenOrThrow(dbSession);
String url = requireNonNull(almSettingDto.... | @Test
void createProjectAndBindToDevOpsPlatform_whenNoKeyAndNameSpecified_generatesKeyAndUsersBitbucketRepositoryName() {
mockValidUserSession();
mockValidAlmSettingsDto();
mockValidPatForUser();
mockValidProjectDescriptor();
Repository repository = mockValidBitBucketRepository();
String gener... |
static void manageInvalidValues(final KiePMMLMiningField miningField, final ParameterInfo parameterInfo,
final List<ParameterInfo> toRemove) {
INVALID_VALUE_TREATMENT_METHOD invalidValueTreatmentMethod =
miningField.getInvalidValueTreatmentMethod() != null ?
... | @Test
void manageInvalidValuesReturnInvalid() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
final ParameterInfo parameterInfo = new ParameterInfo();
// RETURN_INVALID
KiePMMLMiningField miningField = KiePMMLMiningField.builder("FIELD", null)
... |
@Restricted(NoExternalUse.class)
public static String extractPluginNameFromIconSrc(String iconSrc) {
if (iconSrc == null) {
return "";
}
if (!iconSrc.contains("plugin-")) {
return "";
}
String[] arr = iconSrc.split(" ");
for (String element :... | @Test
public void extractPluginNameFromIconSrcExtractsPlugin() {
String result = Functions.extractPluginNameFromIconSrc("symbol-padlock plugin-design-library");
assertThat(result, is(equalTo("design-library")));
} |
public ShareSessionCache(int maxEntries, long evictionMs) {
this.maxEntries = maxEntries;
this.evictionMs = evictionMs;
} | @Test
public void testShareSessionCache() {
ShareSessionCache cache = new ShareSessionCache(3, 100);
assertEquals(0, cache.size());
ShareSessionKey key1 = cache.maybeCreateSession("grp", Uuid.randomUuid(), 0, mockedSharePartitionMap(10));
ShareSessionKey key2 = cache.maybeCreateSessi... |
public String getStaticAssets(String pluginId) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_GET_STATIC_ASSETS, new DefaultPluginInteractionCallback<>() {
@Override
public String onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVe... | @Test
public void shouldErrorOutInAbsenceOfStaticAssets() {
when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ANALYTICS_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, "{}"));
assertThatThrownBy(() -> analyticsExtension.getStaticAssets(PLUG... |
@Override
public void refreshPackages() {
throw newException();
} | @Test
void require_that_refreshPackages_throws_exception() {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().refreshPackages();
});
} |
public static Pair<String, String> decryptHandler(String dataId, String secretKey, String content) {
if (!checkCipher(dataId)) {
return Pair.with(secretKey, content);
}
Optional<String> algorithmName = parseAlgorithmName(dataId);
Optional<EncryptionPluginService> optional = a... | @Test
void testDecrypt() {
String dataId = "cipher-mockAlgo-application";
String oContent = "content";
String oSec = mockEncryptionPluginService.generateSecretKey();
String content = mockEncryptionPluginService.encrypt(oSec, oContent);
String sec = mockEncryptionPluginService... |
@Override
public Object getInitialAggregatedValue(Object rawValue) {
Union thetaUnion = _setOperationBuilder.buildUnion();
if (rawValue instanceof byte[]) { // Serialized Sketch
byte[] bytes = (byte[]) rawValue;
Sketch sketch = deserializeAggregatedValue(bytes);
thetaUnion.union(sketch);
... | @Test
public void initialShouldCreateSingleItemSketch() {
DistinctCountThetaSketchValueAggregator agg = new DistinctCountThetaSketchValueAggregator();
assertEquals(toSketch(agg.getInitialAggregatedValue("hello world")).getEstimate(), 1.0);
} |
@Udf
public <T> List<T> except(
@UdfParameter(description = "Array of values") final List<T> left,
@UdfParameter(description = "Array of exceptions") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> distinctRightValues = new HashSet<>(right);
fi... | @Test
public void shouldReturnNullForNullInputs() {
@SuppressWarnings("rawtypes")
final List result = udf.except(null, null);
assertThat(result, is(nullValue()));
} |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetFunctionVariadic() throws NoSuchMethodException {
final Type type = getClass().getDeclaredMethod("functionType", Function.class)
.getGenericParameterTypes()[0];
final ParamType schema = UdfUtil.getVarArgsSchemaFromType(type);
assertThat(schema, instanceOf(LambdaType.... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseShortAsInt16() {
Short value = Short.MAX_VALUE;
SchemaAndValue schemaAndValue = Values.parseString(
String.valueOf(value)
);
assertEquals(Schema.INT16_SCHEMA, schemaAndValue.schema());
assertInstanceOf(Short.class, schemaAndValue.value... |
@Override
public long doRemoteFunction(int value) {
long waitTime = (long) Math.floor(randomProvider.random() * 1000);
try {
sleep(waitTime);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
Thread.currentThread().interrupt();
}
return waitT... | @Test
void testSuccessfulCall() {
var remoteService = new RemoteService(new StaticRandomProvider(0.2));
var result = remoteService.doRemoteFunction(10);
assertEquals(100, result);
} |
public RegistryBuilder group(String group) {
this.group = group;
return getThis();
} | @Test
void group() {
RegistryBuilder builder = new RegistryBuilder();
builder.group("group");
Assertions.assertEquals("group", builder.build().getGroup());
} |
protected void setUpJettyOptions( Node node ) {
Map<String, String> jettyOptions = parseJettyOptions( node );
if ( jettyOptions != null && jettyOptions.size() > 0 ) {
for ( Entry<String, String> jettyOption : jettyOptions.entrySet() ) {
System.setProperty( jettyOption.getKey(), jettyOption.getVal... | @Test
public void testSetUpJettyOptionsAsSystemParameters() throws KettleXMLException {
Node configNode = getConfigNode( getConfigWithAllOptions() );
slServerConfig.setUpJettyOptions( configNode );
assertTrue( "Expected containing jetty option " + EXPECTED_ACCEPTORS_KEY, System.getProperties().containsK... |
public static Path getConfigHome() {
return getConfigHome(System.getProperties(), System.getenv());
} | @Test
public void testGetConfigHome_mac() throws IOException {
Path libraryApplicationSupport = Paths.get(fakeConfigHome, "Library", "Preferences");
Files.createDirectories(libraryApplicationSupport);
Properties fakeProperties = new Properties();
fakeProperties.setProperty("user.home", fakeConfigHome... |
public WeightedItem<T> addOrVote(T item) {
for (int i = 0; i < list.size(); i++) {
WeightedItem<T> weightedItem = list.get(i);
if (weightedItem.item.equals(item)) {
voteFor(weightedItem);
return weightedItem;
}
}
return organize... | @Test
public void testDuplicateAddIncreasesWeight() {
WeightedEvictableList<String> list = new WeightedEvictableList<>(3, 3);
list.addOrVote("a");
list.addOrVote("a");
list.addOrVote("a");
assertItemsInOrder(list, "a");
assertWeightsInOrder(list, 3);
} |
public static Matches matches(String regex) {
return matches(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testMatches() {
PCollection<String> output =
p.apply(Create.of("a", "x", "y", "z")).apply(Regex.matches("[xyz]"));
PAssert.that(output).containsInAnyOrder("x", "y", "z");
p.run();
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void endpointsWithoutNodeName() throws JsonProcessingException {
stub(String.format("/api/v1/namespaces/%s/services/hazelcast-0", NAMESPACE),
serviceLb(servicePort(32124, 5701, 31916), "35.232.226.200"));
stub(String.format("/api/v1/namespaces/%s/services/service-1", NAM... |
public static String getClientIdentify(HttpServletRequest request) {
String identify = request.getHeader(LONG_PULLING_CLIENT_IDENTIFICATION);
return StringUtil.isBlank(identify) ? "" : identify;
} | @Test
public void notExistClientIdentifyTest() {
MockHttpServletRequest request = new MockHttpServletRequest();
String clientIdentify = RequestUtil.getClientIdentify(request);
Assert.isTrue(Objects.equals(clientIdentify, ""));
} |
public Node chooseRandomWithStorageTypeTwoTrial(final String scope,
final Collection<Node> excludedNodes, StorageType type) {
netlock.readLock().lock();
try {
String searchScope;
String excludedScope;
if (scope.startsWith("~")) {
searchScope = NodeBase.ROOT;
excludedScope... | @Test
public void testChooseRandomWithStorageTypeTwoTrial() throws Exception {
Node n;
DatanodeDescriptor dd;
n = CLUSTER.chooseRandomWithStorageType("/l2/d3/r4", null, null,
StorageType.ARCHIVE);
HashSet<Node> excluded = new HashSet<>();
// exclude the host on r4 (since there is only one ... |
public long getCent() {
return cent;
} | @Test
public void yuanToCentTest() {
final Money money = new Money("1234.56");
assertEquals(123456, money.getCent());
assertEquals(123456, MathUtil.yuanToCent(1234.56));
} |
@Override
public void getClient(Request request, RequestContext requestContext, Callback<TransportClient> clientCallback)
{
URI uri = request.getURI();
debug(_log, "get client for uri: ", uri);
if (!D2_SCHEME_NAME.equalsIgnoreCase(uri.getScheme()))
{
throw new IllegalArgumentException("Unsupp... | @Test(dataProvider = "customAffinityRoutingSkippedDataProvider")
public void testCustomAffinityRoutingSkipped(boolean enableTargetHostHint, boolean enableCustomAffinityRouting,
URI expectedURI) throws Exception
{
MockStore<ServiceProperties> serviceRegistry = new MockStore<>();
MockStore<ClusterProper... |
public static <T> T convert(Class<T> type, Object value) throws ConvertException {
return convert((Type) type, value);
} | @Test
public void toStrTest3() {
final char a = 'a';
final String result = Convert.convert(String.class, a);
assertEquals("a", result);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.