focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Set<String> getClustersByServiceName(String serviceName) {
return serviceNameMapping.getOrDefault(serviceName, Collections.EMPTY_SET);
} | @Test
public void testGetClustersByServiceName() {
Map<String, Set<String>> mapping = new HashMap<>();
Set<String> clusters = new HashSet<>();
clusters.add("cluster");
mapping.put("serviceA", clusters);
Set<String> result;
// serviceNameMapping is empty
XdsDataCache.updateServiceNameMapping(new HashMap<>());
result = XdsDataCache.getClustersByServiceName("serviceA");
Assert.assertNotNull(result);
Assert.assertEquals(0, result.size());
// serviceNameMapping is not empty, get un cached service
XdsDataCache.updateServiceNameMapping(mapping);
result = XdsDataCache.getClustersByServiceName("serviceB");
Assert.assertNotNull(result);
Assert.assertEquals(0, result.size());
// serviceNameMapping is not null, get cached service
XdsDataCache.updateServiceNameMapping(mapping);
result = XdsDataCache.getClustersByServiceName("serviceA");
Assert.assertNotNull(result);
Assert.assertEquals(1, result.size());
Assert.assertTrue(result.contains("cluster"));
} |
@Override
@Transactional(rollbackFor = Exception.class)
@LogRecord(type = SYSTEM_USER_TYPE, subType = SYSTEM_USER_CREATE_SUB_TYPE, bizNo = "{{#user.id}}",
success = SYSTEM_USER_CREATE_SUCCESS)
public Long createUser(UserSaveReqVO createReqVO) {
// 1.1 校验账户配合
tenantService.handleTenantInfo(tenant -> {
long count = userMapper.selectCount();
if (count >= tenant.getAccountCount()) {
throw exception(USER_COUNT_MAX, tenant.getAccountCount());
}
});
// 1.2 校验正确性
validateUserForCreateOrUpdate(null, createReqVO.getUsername(),
createReqVO.getMobile(), createReqVO.getEmail(), createReqVO.getDeptId(), createReqVO.getPostIds());
// 2.1 插入用户
AdminUserDO user = BeanUtils.toBean(createReqVO, AdminUserDO.class);
user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
user.setPassword(encodePassword(createReqVO.getPassword())); // 加密密码
userMapper.insert(user);
// 2.2 插入关联岗位
if (CollectionUtil.isNotEmpty(user.getPostIds())) {
userPostMapper.insertBatch(convertList(user.getPostIds(),
postId -> new UserPostDO().setUserId(user.getId()).setPostId(postId)));
}
// 3. 记录操作日志上下文
LogRecordContext.putVariable("user", user);
return user.getId();
} | @Test
public void testCreatUser_success() {
// 准备参数
UserSaveReqVO reqVO = randomPojo(UserSaveReqVO.class, o -> {
o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
o.setMobile(randomString());
o.setPostIds(asSet(1L, 2L));
}).setId(null); // 避免 id 被赋值
// mock 账户额度充足
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setAccountCount(1));
doNothing().when(tenantService).handleTenantInfo(argThat(handler -> {
handler.handle(tenant);
return true;
}));
// mock deptService 的方法
DeptDO dept = randomPojo(DeptDO.class, o -> {
o.setId(reqVO.getDeptId());
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept);
// mock postService 的方法
List<PostDO> posts = CollectionUtils.convertList(reqVO.getPostIds(), postId ->
randomPojo(PostDO.class, o -> {
o.setId(postId);
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
}));
when(postService.getPostList(eq(reqVO.getPostIds()), isNull())).thenReturn(posts);
// mock passwordEncoder 的方法
when(passwordEncoder.encode(eq(reqVO.getPassword()))).thenReturn("yudaoyuanma");
// 调用
Long userId = userService.createUser(reqVO);
// 断言
AdminUserDO user = userMapper.selectById(userId);
assertPojoEquals(reqVO, user, "password", "id");
assertEquals("yudaoyuanma", user.getPassword());
assertEquals(CommonStatusEnum.ENABLE.getStatus(), user.getStatus());
// 断言关联岗位
List<UserPostDO> userPosts = userPostMapper.selectListByUserId(user.getId());
assertEquals(1L, userPosts.get(0).getPostId());
assertEquals(2L, userPosts.get(1).getPostId());
} |
@GetMapping
@TpsControl(pointName = "NamingServiceQuery", name = "HttpNamingServiceQuery")
@Secured(action = ActionTypes.READ)
public ObjectNode detail(@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName) throws NacosException {
return getServiceOperator().queryService(namespaceId, serviceName);
} | @Test
void testDetail() {
try {
ObjectNode result = Mockito.mock(ObjectNode.class);
Mockito.when(serviceOperatorV2.queryService(Mockito.anyString(), Mockito.anyString())).thenReturn(result);
ObjectNode objectNode = serviceController.detail(TEST_NAMESPACE, TEST_SERVICE_NAME);
assertEquals(result, objectNode);
} catch (NacosException e) {
e.printStackTrace();
fail(e.getMessage());
}
} |
static String generateClassName(final OpenAPI document) {
final Info info = document.getInfo();
if (info == null) {
return DEFAULT_CLASS_NAME;
}
final String title = info.getTitle();
if (title == null) {
return DEFAULT_CLASS_NAME;
}
final String className = title.chars().filter(Character::isJavaIdentifierPart).filter(c -> c < 'z').boxed()
.collect(Collector.of(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append,
StringBuilder::toString));
if (className.isEmpty() || !Character.isJavaIdentifierStart(className.charAt(0))) {
return DEFAULT_CLASS_NAME;
}
return className;
} | @Test
public void shouldGenerateClassNameFromTitleWithNonValidJavaIdentifiers() {
final OpenAPI openapi = new OpenAPI();
final Info info = new Info();
info.setTitle("Example-API 2.0");
openapi.setInfo(info);
assertThat(RestDslSourceCodeGenerator.generateClassName(openapi)).isEqualTo("ExampleAPI20");
} |
@Override
public int positionedRead(long pos, byte[] b, int off, int len) throws IOException {
if (!CachePerThreadContext.get().getCacheEnabled()) {
MetricsSystem.meter(MetricKey.CLIENT_CACHE_BYTES_REQUESTED_EXTERNAL.getName())
.mark(len);
MetricsSystem.counter(MetricKey.CLIENT_CACHE_EXTERNAL_REQUESTS.getName()).inc();
len = getExternalFileInStream().positionedRead(pos, b, off, len);
MultiDimensionalMetricsSystem.EXTERNAL_DATA_READ.inc(len);
return len;
}
try {
return readInternal(new ByteArrayTargetBuffer(b, off), off, len,
ReadType.READ_INTO_BYTE_ARRAY, pos, true);
} catch (IOException | RuntimeException e) {
LOG.warn("Failed to read from Alluxio's page cache.", e);
if (mFallbackEnabled) {
MetricsSystem.counter(MetricKey.CLIENT_CACHE_POSITION_READ_FALLBACK.getName()).inc();
len = getExternalFileInStream().positionedRead(pos, b, off, len);
MultiDimensionalMetricsSystem.EXTERNAL_DATA_READ.inc(len);
return len;
}
throw e;
}
} | @Test
public void positionReadOversizedBuffer() throws Exception {
int fileSize = mPageSize;
byte[] testData = BufferUtils.getIncreasingByteArray(fileSize);
ByteArrayCacheManager manager = new ByteArrayCacheManager();
LocalCacheFileInStream stream = setupWithSingleFile(testData, manager);
// cache miss
byte[] cacheMiss = new byte[fileSize * 2];
Assert.assertEquals(fileSize - 1,
stream.positionedRead(1, cacheMiss, 2, fileSize * 2));
Assert.assertArrayEquals(
Arrays.copyOfRange(testData, 1, fileSize - 1),
Arrays.copyOfRange(cacheMiss, 2, fileSize));
Assert.assertEquals(0, manager.mPagesServed);
Assert.assertEquals(1, manager.mPagesCached);
// cache hit
byte[] cacheHit = new byte[fileSize * 2];
Assert.assertEquals(fileSize - 1,
stream.positionedRead(1, cacheHit, 2, fileSize * 2));
Assert.assertArrayEquals(
Arrays.copyOfRange(testData, 1, fileSize - 1),
Arrays.copyOfRange(cacheHit, 2, fileSize));
Assert.assertEquals(1, manager.mPagesServed);
} |
@Override
public int size() {
return 0;
} | @Test
public void testSize() throws Exception {
assertEquals(0, NULL_QUERY_CACHE.size());
} |
public static Instant toJoda(java.time.Instant instant) {
return Optional.ofNullable(instant).map(t -> new Instant(t.toEpochMilli())).orElse(null);
} | @Test
public void shouldConvertToJodaInstant() {
assertThat(TimeUtil.toJoda(null)).isNull();
assertThat(TimeUtil.toJoda(java.time.Instant.ofEpochMilli(0L)))
.isEqualTo(org.joda.time.Instant.ofEpochMilli(0L));
} |
public static DataMap bytesToDataMap(Map<String, String> headers, ByteString bytes) throws MimeTypeParseException, IOException
{
return getContentType(headers).getCodec().readMap(bytes);
} | @Test
public void testJSONByteStringToDataMap() throws MimeTypeParseException, IOException
{
DataMap expectedDataMap = createTestDataMap();
ByteString byteString = ByteString.copy(JACKSON_DATA_CODEC.mapToBytes(expectedDataMap));
Map<String, String> headers = Collections.singletonMap(RestConstants.HEADER_CONTENT_TYPE, "application/json");
DataMap dataMap = DataMapConverter.bytesToDataMap(headers, byteString);
Assert.assertEquals(dataMap, expectedDataMap);
} |
@Override
public String execute(CommandContext commandContext, String[] args) {
boolean http = commandContext.isHttp();
StringBuilder plainOutput = new StringBuilder();
Map<String, Object> frameworkMap = new HashMap<>();
appendFrameworkConfig(args, plainOutput, frameworkMap);
if (http) {
return JsonUtils.toJson(frameworkMap);
} else {
return plainOutput.toString();
}
} | @Test
void testFilter1() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel1 = frameworkModel.newApplication();
applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1"));
applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345));
applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
applicationModel1
.getApplicationConfigManager()
.addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181"));
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setAddress("zookeeper://127.0.0.1:2181");
applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig);
applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig());
applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig());
applicationModel1.getApplicationConfigManager().setSsl(new SslConfig());
ModuleModel moduleModel = applicationModel1.newModule();
moduleModel.getConfigManager().setModule(new ModuleConfig());
moduleModel.getConfigManager().addConsumer(new ConsumerConfig());
moduleModel.getConfigManager().addProvider(new ProviderConfig());
ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addReference(referenceConfig);
ServiceConfig<Object> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MetadataService.class);
moduleModel.getConfigManager().addService(serviceConfig);
CommandContext commandContext = new CommandContext("getConfig");
commandContext.setHttp(true);
Assertions.assertNotNull(
new GetConfig(frameworkModel).execute(commandContext, new String[] {"ApplicationConfig"}));
} |
@Nonnull
@Override
public CpcSketch getResult() {
return unionAll();
} | @Test
public void testAccumulatorWithSingleSketch() {
CpcSketch sketch = new CpcSketch(_lgNominalEntries);
IntStream.range(0, 1000).forEach(sketch::update);
CpcSketchAccumulator accumulator = new CpcSketchAccumulator(_lgNominalEntries, 2);
accumulator.apply(sketch);
Assert.assertFalse(accumulator.isEmpty());
Assert.assertEquals(accumulator.getResult().getEstimate(), sketch.getEstimate());
} |
@Override
protected boolean isSplitable(FileSystem fs, Path filename) {
return !(filename instanceof PathWithBootstrapFileStatus);
} | @Test
void pathNotSplitableForBootstrapScenario() throws IOException {
URI source = Files.createTempFile(tempDir, "source", ".parquet").toUri();
URI target = Files.createTempFile(tempDir, "target", ".parquet").toUri();
PathWithBootstrapFileStatus path = new PathWithBootstrapFileStatus(new Path(target), fs.getFileStatus(new Path(source)));
HoodieCopyOnWriteTableInputFormat cowInputFormat = new HoodieCopyOnWriteTableInputFormat();
assertFalse(cowInputFormat.isSplitable(fs, path), "Path for bootstrap should not be splitable.");
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(file.getType().contains(Path.Type.upload)) {
// Pending large file upload
final Write.Append append = new B2LargeUploadService(session, fileid, new B2WriteFeature(session, fileid)).append(file, new TransferStatus());
if(append.append) {
return new PathAttributes().withSize(append.offset);
}
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
try {
final B2BucketResponse info = session.getClient().listBucket(file.getName());
if(null == info) {
throw new NotfoundException(file.getAbsolute());
}
return this.toAttributes(info);
}
catch(B2ApiException e) {
throw new B2ExceptionMappingService(fileid).map("Failure to read attributes of {0}", e, file);
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
else {
final String id = fileid.getVersionId(file);
if(null == id) {
return PathAttributes.EMPTY;
}
B2FileResponse response;
try {
response = this.findFileInfo(file, id);
}
catch(NotfoundException e) {
// Try with reset cache after failure finding node id
response = this.findFileInfo(file, fileid.getVersionId(file));
}
final PathAttributes attr = this.toAttributes(response);
if(attr.isDuplicate()) {
// Throw failure if latest version has hide marker set and lookup was without explicit version
if(StringUtils.isBlank(file.attributes().getVersionId())) {
if(log.isDebugEnabled()) {
log.debug(String.format("Latest version of %s is duplicate", file));
}
throw new NotfoundException(file.getAbsolute());
}
}
return attr;
}
} | @Test
public void testChangedFileId() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path test = new B2TouchFeature(session, fileid).touch(new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final String latestnodeid = test.attributes().getVersionId();
assertNotNull(latestnodeid);
// Assume previously seen but changed on server
final String invalidId = String.valueOf(RandomUtils.nextLong());
test.attributes().setVersionId(invalidId);
fileid.cache(test, invalidId);
final B2AttributesFinderFeature f = new B2AttributesFinderFeature(session, fileid);
assertEquals(latestnodeid, f.find(test).getVersionId());
new B2DeleteFeature(session, fileid).delete(new B2ObjectListService(session, fileid).list(bucket, new DisabledListProgressListener()).toList(), new DisabledLoginCallback(), new Delete.DisabledCallback());
new B2DeleteFeature(session, fileid).delete(Collections.singletonList(bucket), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
public static byte[] writeUtf8(final String in) {
if (in == null) {
return null;
}
if (UnsafeUtil.hasUnsafe()) {
// Calculate the encoded length.
final int len = UnsafeUtf8Util.encodedLength(in);
final byte[] outBytes = new byte[len];
UnsafeUtf8Util.encodeUtf8(in, outBytes, 0, len);
return outBytes;
} else {
return in.getBytes(StandardCharsets.UTF_8);
}
} | @Test
public void testWriteUtf8() {
Assert.assertNull(BytesUtil.writeUtf8(null));
Assert.assertArrayEquals(new byte[] { 102, 111, 111 }, BytesUtil.writeUtf8("foo"));
} |
public PrimitiveType primitiveType()
{
return primitiveType;
} | @Test
void shouldUseAppropriatePrimitiveType() throws Exception
{
final String testXmlString =
"<types>" +
" <type name=\"testTypeChar\" primitiveType=\"char\"/>" +
" <type name=\"testTypeInt8\" primitiveType=\"int8\"/>" +
" <type name=\"testTypeInt16\" primitiveType=\"int16\"/>" +
" <type name=\"testTypeInt32\" primitiveType=\"int32\"/>" +
" <type name=\"testTypeInt64\" primitiveType=\"int64\"/>" +
" <type name=\"testTypeUInt8\" primitiveType=\"uint8\"/>" +
" <type name=\"testTypeUInt16\" primitiveType=\"uint16\"/>" +
" <type name=\"testTypeUInt32\" primitiveType=\"uint32\"/>" +
" <type name=\"testTypeUInt64\" primitiveType=\"uint64\"/>" +
" <type name=\"testTypeFloat\" primitiveType=\"float\"/>" +
" <type name=\"testTypeDouble\" primitiveType=\"double\"/>" +
"</types>";
final Map<String, Type> map = parseTestXmlWithMap("/types/type", testXmlString);
assertThat(((EncodedDataType)map.get("testTypeChar")).primitiveType(), is(PrimitiveType.CHAR));
assertThat(((EncodedDataType)map.get("testTypeInt8")).primitiveType(), is(PrimitiveType.INT8));
assertThat(((EncodedDataType)map.get("testTypeInt16")).primitiveType(), is(PrimitiveType.INT16));
assertThat(((EncodedDataType)map.get("testTypeInt32")).primitiveType(), is(PrimitiveType.INT32));
assertThat(((EncodedDataType)map.get("testTypeInt64")).primitiveType(), is(PrimitiveType.INT64));
assertThat(((EncodedDataType)map.get("testTypeUInt8")).primitiveType(), is(PrimitiveType.UINT8));
assertThat(((EncodedDataType)map.get("testTypeUInt16")).primitiveType(), is(PrimitiveType.UINT16));
assertThat(((EncodedDataType)map.get("testTypeUInt32")).primitiveType(), is(PrimitiveType.UINT32));
assertThat(((EncodedDataType)map.get("testTypeUInt64")).primitiveType(), is(PrimitiveType.UINT64));
assertThat(((EncodedDataType)map.get("testTypeFloat")).primitiveType(), is(PrimitiveType.FLOAT));
assertThat(((EncodedDataType)map.get("testTypeDouble")).primitiveType(), is(PrimitiveType.DOUBLE));
} |
public void setLocalTaskQueueCapacity(int localTaskQueueCapacity) {
this.localTaskQueueCapacity = checkPositive(localTaskQueueCapacity, "localTaskQueueCapacity");
} | @Test
public void test_setLocalTaskQueueCapacity_whenZero() {
ReactorBuilder builder = newBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setLocalTaskQueueCapacity(0));
} |
@Override
public boolean apply(Collection<Member> members) {
if (members.size() < minimumClusterSize) {
return false;
}
int count = 0;
long timestamp = Clock.currentTimeMillis();
for (Member member : members) {
if (!isAlivePerIcmp(member)) {
continue;
}
if (member.localMember() || failureDetector.isAlive(member, timestamp)) {
count++;
}
}
return count >= minimumClusterSize;
} | @Test
public void testSplitBrainProtectionPresent_whenAsManyAsSplitBrainProtectionPresent() {
splitBrainProtectionFunction = new ProbabilisticSplitBrainProtectionFunction(splitBrainProtectionSize, 10000, 10000, 200, 100, 10);
heartbeat(5, 1000);
assertTrue(splitBrainProtectionFunction.apply(subsetOfMembers(splitBrainProtectionSize)));
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (statement.getStatement() instanceof CreateSource) {
return handleCreateSource((ConfiguredStatement<CreateSource>) statement);
}
return statement;
} | @Test
public void shouldHandleExplicitFormat() {
// Given
givenConfig(ImmutableMap.of());
givenSourceProps(ImmutableMap.of(
"FORMAT", new StringLiteral("KAFKA")
));
// When
final ConfiguredStatement<?> result = injector.inject(csStatement);
// Then
assertThat(result, sameInstance(csStatement));
} |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldAddQualifierForColumnReference() {
// Given:
final Statement stmt = givenQuery("SELECT COL0 FROM TEST1;");
// When:
final Query result = (Query) AstSanitizer.sanitize(stmt, META_STORE);
// Then:
assertThat(result.getSelect(), is(new Select(ImmutableList.of(
new SingleColumn(
column(TEST1_NAME, "COL0"), Optional.of(ColumnName.of("COL0")))
))));
} |
@Override
public boolean compareAndSetSequence(long expect, long update) {
return sequence.compareAndSet(expect, update);
} | @Test
public void testCompareAndSetSequence() {
sequencer.compareAndSetSequence(23, 42);
assertEquals(0, sequencer.getSequence());
sequencer.compareAndSetSequence(0, 42);
assertEquals(42, sequencer.getSequence());
} |
protected Path search(final Path file, final ListProgressListener listener) throws BackgroundException {
final AttributedList<Path> list = session._getFeature(ListService.class).list(file.getParent(), listener);
// Try to match path only as the version might have changed in the meantime
final Path found = list.find(new ListFilteringPredicate(session.getCaseSensitivity(), file));
if(null == found) {
if(log.isWarnEnabled()) {
log.warn(String.format("File %s not found in directory listing", file));
}
}
else {
if(log.isDebugEnabled()) {
log.debug(String.format("Return attributes %s for file %s", found.attributes(), file));
}
}
return found;
} | @Test
public void testSearch() {
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))
));
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "F", EnumSet.of(Path.Type.file))
));
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v1"))
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v2"))
));
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.directory)).withAttributes(new PathAttributes().withVersionId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.directory)).withAttributes(new PathAttributes().withVersionId("v2"))
));
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withFileId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withFileId("v1"))
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withFileId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withFileId("v2"))
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.directory)).withAttributes(new PathAttributes().withFileId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.directory)).withAttributes(new PathAttributes().withFileId("v2"))
));
assertTrue(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v1"))
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes().withVersionId("v1"))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes())
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file)).withAttributes(new PathAttributes() {
@Override
public boolean isDuplicate() {
return true;
}
})
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.sensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "F", EnumSet.of(Path.Type.file))
));
assertFalse(new ListFilteringFeature.ListFilteringPredicate(Protocol.Case.insensitive, new Path(Home.ROOT, "f", EnumSet.of(Path.Type.file))).test(
new Path(Home.ROOT, "f2", EnumSet.of(Path.Type.file))
));
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testInsert()
{
assertFails(MISMATCHED_SET_COLUMN_TYPES, "Mismatch at column 1: 'a' is of type bigint but expression is of type varchar", "INSERT INTO t6 (a) SELECT b from t6");
analyze("INSERT INTO t1 SELECT * FROM t1");
analyze("INSERT INTO t3 SELECT * FROM t3");
analyze("INSERT INTO t3 SELECT a, b FROM t3");
assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t1 VALUES (1, 2)");
analyze("INSERT INTO t5 (a) VALUES(null)");
// ignore t5 hidden column
analyze("INSERT INTO t5 VALUES (1)");
// fail if hidden column provided
assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t5 VALUES (1, 2)");
// note b is VARCHAR, while a,c,d are BIGINT
analyze("INSERT INTO t6 (a) SELECT a from t6");
analyze("INSERT INTO t6 (a) SELECT c from t6");
analyze("INSERT INTO t6 (a,b,c,d) SELECT * from t6");
analyze("INSERT INTO t6 (A,B,C,D) SELECT * from t6");
analyze("INSERT INTO t6 (a,b,c,d) SELECT d,b,c,a from t6");
assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t6 (a) SELECT b from t6");
assertFails(MISSING_COLUMN, "INSERT INTO t6 (unknown) SELECT * FROM t6");
assertFails(DUPLICATE_COLUMN_NAME, "INSERT INTO t6 (a, a) SELECT * FROM t6");
assertFails(DUPLICATE_COLUMN_NAME, "INSERT INTO t6 (a, A) SELECT * FROM t6");
// b is bigint, while a is double, coercion from b to a is possible
analyze("INSERT INTO t7 (b) SELECT (a) FROM t7 ");
assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t7 (a) SELECT (b) FROM t7");
// d is array of bigints, while c is array of doubles, coercion from d to c is possible
analyze("INSERT INTO t7 (d) SELECT (c) FROM t7 ");
assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t7 (c) SELECT (d) FROM t7 ");
analyze("INSERT INTO t7 (d) VALUES (ARRAY[null])");
analyze("INSERT INTO t6 (d) VALUES (1), (2), (3)");
analyze("INSERT INTO t6 (a,b,c,d) VALUES (1, 'a', 1, 1), (2, 'b', 2, 2), (3, 'c', 3, 3), (4, 'd', 4, 4)");
} |
@Override
protected Class<ShenyuSpringWebSocketClient> getAnnotationType() {
return ShenyuSpringWebSocketClient.class;
} | @Test
public void testGetAnnotationType() {
Class<ShenyuSpringWebSocketClient> annotationType = eventListener.getAnnotationType();
assertEquals(annotationType, ShenyuSpringWebSocketClient.class);
} |
public Domain canonicalize(boolean removeConstants)
{
return new Domain(values.canonicalize(removeConstants), nullAllowed);
} | @Test
public void testCanonicalize()
throws Exception
{
assertSameDomain(Domain.onlyNull(BIGINT), Domain.onlyNull(BIGINT), false);
assertSameDomain(Domain.notNull(BIGINT), Domain.notNull(BIGINT), false);
assertDifferentDomain(Domain.onlyNull(BIGINT), Domain.notNull(BIGINT), false);
assertDifferentDomain(Domain.onlyNull(BIGINT), Domain.onlyNull(VARCHAR), false);
assertDifferentDomain(
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 1L)),
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 2L)),
false);
assertSameDomain(
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 1L)),
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 2L)),
true);
assertDifferentDomain(
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 1L)),
Domain.multipleValues(BIGINT, ImmutableList.of(0L, 1L, 2L)),
true);
} |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
List<KeyValue<String, Object>> templateParams) throws Throwable {
Assert.notBlank(properties.getSignature(), "短信签名不能为空");
// 1. 执行请求
// 参考链接 https://api.aliyun.com/document/Dysmsapi/2017-05-25/SendSms
TreeMap<String, Object> queryParam = new TreeMap<>();
queryParam.put("PhoneNumbers", mobile);
queryParam.put("SignName", properties.getSignature());
queryParam.put("TemplateCode", apiTemplateId);
queryParam.put("TemplateParam", JsonUtils.toJsonString(MapUtils.convertMap(templateParams)));
queryParam.put("OutId", sendLogId);
JSONObject response = request("SendSms", queryParam);
// 2. 解析请求
return new SmsSendRespDTO()
.setSuccess(Objects.equals(response.getStr("Code"), RESPONSE_CODE_SUCCESS))
.setSerialNo(response.getStr("BizId"))
.setApiRequestId(response.getStr("RequestId"))
.setApiCode(response.getStr("Code"))
.setApiMsg(response.getStr("Message"));
} | @Test
public void tesSendSms_success() throws Throwable {
try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("code", 1234), new KeyValue<>("op", "login"));
// mock 方法
httpUtilsMockedStatic.when(() -> HttpUtils.post(anyString(), anyMap(), anyString()))
.thenReturn("{\"Message\":\"OK\",\"RequestId\":\"30067CE9-3710-5984-8881-909B21D8DB28\",\"Code\":\"OK\",\"BizId\":\"800025323183427988\"}");
// 调用
SmsSendRespDTO result = smsClient.sendSms(sendLogId, mobile,
apiTemplateId, templateParams);
// 断言
assertTrue(result.getSuccess());
assertEquals("30067CE9-3710-5984-8881-909B21D8DB28", result.getApiRequestId());
assertEquals("OK", result.getApiCode());
assertEquals("OK", result.getApiMsg());
assertEquals("800025323183427988", result.getSerialNo());
}
} |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForTableSourceV1() {
// Given:
final TableSourceV1 step = new TableSourceV1(
PROPERTIES,
"foo",
formats,
Optional.empty(),
SCHEMA,
Optional.of(true),
OptionalInt.of(SystemColumns.CURRENT_PSEUDOCOLUMN_VERSION_NUMBER)
);
// When:
final LogicalSchema result = resolver.resolve(step, SCHEMA);
// Then:
assertThat(result, is(SCHEMA.withPseudoAndKeyColsInValue(false)));
} |
@Override
public String getName() {
return null;
} | @Test
public void testGetName() {
assertNull(NULL_QUERY_CACHE.getName());
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilder() {
ContainerBuildPlan plan = createSamplePlan();
Assert.assertEquals("base/image", plan.getBaseImage());
Assert.assertEquals(
ImmutableSet.of(new Platform("testOs", "testArchitecture")), plan.getPlatforms());
Assert.assertEquals(ImageFormat.OCI, plan.getFormat());
Assert.assertEquals(Instant.ofEpochMilli(30), plan.getCreationTime());
Assert.assertEquals(ImmutableMap.of("env", "var"), plan.getEnvironment());
Assert.assertEquals(
ImmutableSet.of(AbsoluteUnixPath.get("/mnt/foo"), AbsoluteUnixPath.get("/bar")),
plan.getVolumes());
Assert.assertEquals(ImmutableMap.of("com.example.label", "cool"), plan.getLabels());
Assert.assertEquals(ImmutableSet.of(Port.tcp(443)), plan.getExposedPorts());
Assert.assertEquals(":", plan.getUser());
Assert.assertEquals(AbsoluteUnixPath.get("/workspace"), plan.getWorkingDirectory());
Assert.assertEquals(Arrays.asList("foo", "entrypoint"), plan.getEntrypoint());
Assert.assertEquals(Arrays.asList("bar", "cmd"), plan.getCmd());
Assert.assertEquals(1, plan.getLayers().size());
MatcherAssert.assertThat(
plan.getLayers().get(0), CoreMatchers.instanceOf(FileEntriesLayer.class));
Assert.assertEquals(
Arrays.asList(
new FileEntry(
Paths.get("/src/file/foo"),
AbsoluteUnixPath.get("/path/in/container"),
FilePermissions.fromOctalString("644"),
Instant.ofEpochSecond(1))),
((FileEntriesLayer) plan.getLayers().get(0)).getEntries());
} |
static byte[] getEmptyChunk(int leastLength) {
if (emptyChunk.length >= leastLength) {
return emptyChunk; // In most time
}
synchronized (CoderUtil.class) {
emptyChunk = new byte[leastLength];
}
return emptyChunk;
} | @Test
public void testGetEmptyChunk() {
byte[] ret = CoderUtil.getEmptyChunk(chunkSize);
for (int i = 0; i < chunkSize; i++) {
assertEquals(0, ret[i]);
}
} |
public ProjectReactor execute() {
Profiler profiler = Profiler.create(LOG).startInfo("Process project properties");
Map<String, Map<String, String>> propertiesByModuleIdPath = new HashMap<>();
extractPropertiesByModule(propertiesByModuleIdPath, "", "", new HashMap<>(scannerProps.properties()));
var rootModuleProperties = propertiesByModuleIdPath.get("");
setBaseDirIfNeeded(rootModuleProperties);
ProjectDefinition rootProject = createModuleDefinition(rootModuleProperties, null);
rootProjectWorkDir = rootProject.getWorkDir();
defineChildren(rootProject, propertiesByModuleIdPath, "");
cleanAndCheckProjectDefinitions(rootProject);
profiler.stopInfo();
return new ProjectReactor(rootProject);
} | @Test
public void projectBaseDirDefaultToCurrentDirectory() {
ScannerProperties bootstrapProps = new ScannerProperties(Map.of("sonar.projectKey", "foo"));
ProjectReactor projectReactor = new ProjectReactorBuilder(bootstrapProps, mock(AnalysisWarnings.class)).execute();
var def = projectReactor.getRoot();
assertThat(def.getBaseDir()).isEqualTo(new File("").getAbsoluteFile());
} |
@Override
public Response request(Request request, long timeoutMills) throws NacosException {
DefaultRequestFuture pushFuture = sendRequestInner(request, null);
try {
return pushFuture.get(timeoutMills);
} catch (Exception e) {
throw new NacosException(NacosException.SERVER_ERROR, e);
} finally {
RpcAckCallbackSynchronizer.clearFuture(getMetaInfo().getConnectionId(), pushFuture.getRequestId());
}
} | @Test
void testBusy() {
controlManagerCenterMockedStatic = Mockito.mockStatic(ControlManagerCenter.class);
Mockito.when(ControlManagerCenter.getInstance()).thenReturn(controlManagerCenter);
Mockito.when(ControlManagerCenter.getInstance().getTpsControlManager()).thenReturn(tpsControlManager);
Mockito.when(tpsControlManager.check(Mockito.any())).thenReturn(new TpsCheckResponse(true, 200, ""));
Mockito.doReturn(false).when(streamObserver).isReady();
try {
connection.request(new NotifySubscriberRequest(), 3000L);
assertTrue(false);
} catch (Exception e) {
assertTrue(e instanceof ConnectionBusyException);
}
try {
Thread.sleep(3001);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
connection.request(new NotifySubscriberRequest(), 3000L);
assertTrue(false);
} catch (Exception e) {
assertTrue(e instanceof ConnectionBusyException);
}
assertTrue(connection.getMetaInfo().pushQueueBlockTimesLastOver(3000));
} |
@Override
public int hashCode() {
final IntIterator iterator = iterator();
int total = 0;
while (iterator.hasNext()) {
// Cast exists for substitutions
total += (int) iterator.nextValue();
}
return total;
} | @Test
public void twoEmptySetsHaveTheSameHashcode() {
final IntHashSet other = new IntHashSet(100, -1);
assertEquals(set.hashCode(), other.hashCode());
} |
public static Details create(String template, Object... args) {
return Details.builder()
.status(MaestroRuntimeException.Code.INTERNAL_ERROR)
.message(String.format(template, args))
.build();
} | @Test
public void testCreateWithoutStackTrace() {
Exception exception = new Exception(new Exception(new Exception("test")));
Details details = Details.create(exception, true, "test-msg");
assertEquals(MaestroRuntimeException.Code.INTERNAL_ERROR, details.getStatus());
assertEquals("test-msg", details.getMessage());
assertEquals(3, details.getErrors().size());
assertTrue(details.isRetryable());
} |
@Override
public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionSize, final ConnectionMode connectionMode) throws SQLException {
return getConnections(databaseName, dataSourceName, connectionSize, connectionMode,
ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(TransactionRule.class).getDefaultType());
} | @Test
void assertGetConnectionsFailed() {
assertThrows(OverallConnectionNotEnoughException.class, () -> new JDBCBackendDataSource().getConnections("schema", String.format(DATA_SOURCE_PATTERN, 1), 6, ConnectionMode.MEMORY_STRICTLY));
} |
public static CharSequence escapeForXml(CharSequence input) {
return escapeForXml(input, XmlEscapeMode.safe);
} | @Test
public void testEscapeForXml() {
assertNull(StringUtils.escapeForXml(null));
String input = "<b>";
assertCharSequenceEquals("<b>", StringUtils.escapeForXml(input));
input = "\"";
assertCharSequenceEquals(""", StringUtils.escapeForXml(input));
input = "&";
assertCharSequenceEquals("&", StringUtils.escapeForXml(input));
input = "<b>\n\t\r</b>";
assertCharSequenceEquals("<b>\n\t\r</b>", StringUtils.escapeForXml(input));
input = " & ";
assertCharSequenceEquals(" & ", StringUtils.escapeForXml(input));
input = " \" ";
assertCharSequenceEquals(" " ", StringUtils.escapeForXml(input));
input = "> of me <";
assertCharSequenceEquals("> of me <", StringUtils.escapeForXml(input));
input = "> of me & you<";
assertCharSequenceEquals("> of me & you<", StringUtils.escapeForXml(input));
input = "& <";
assertCharSequenceEquals("& <", StringUtils.escapeForXml(input));
input = "&";
assertCharSequenceEquals("&", StringUtils.escapeForXml(input));
input = "It's a good day today";
assertCharSequenceEquals("It's a good day today", StringUtils.escapeForXml(input));
} |
@Override
@Nullable
public Object convert(@Nullable String value) {
if (isNullOrEmpty(value)) {
return null;
}
LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone);
final DateTimeFormatter formatter;
if (containsTimeZone) {
formatter = DateTimeFormat
.forPattern(dateFormat)
.withDefaultYear(YearMonth.now(timeZone).getYear())
.withLocale(locale);
} else {
formatter = DateTimeFormat
.forPattern(dateFormat)
.withDefaultYear(YearMonth.now(timeZone).getYear())
.withLocale(locale)
.withZone(timeZone);
}
return DateTime.parse(value, formatter);
} | @Test
public void convertIgnoresTZIfDatePatternContainsTZ() throws Exception {
final Converter c = new DateConverter(config("YYYY-MM-dd'T'HH:mm:ss.SSSZ", "Etc/UTC", null));
final DateTime actual = (DateTime) c.convert("2014-03-12T10:00:00.000+06:00");
assertThat(actual).isEqualTo("2014-03-12T10:00:00.000+06:00");
} |
@Override
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为 permission 如果变更,涉及到新老两个 permission。直接清理,简单有效
public void updateMenu(MenuSaveVO updateReqVO) {
// 校验更新的菜单是否存在
if (menuMapper.selectById(updateReqVO.getId()) == null) {
throw exception(MENU_NOT_EXISTS);
}
// 校验父菜单存在
validateParentMenu(updateReqVO.getParentId(), updateReqVO.getId());
// 校验菜单(自己)
validateMenu(updateReqVO.getParentId(), updateReqVO.getName(), updateReqVO.getId());
// 更新到数据库
MenuDO updateObj = BeanUtils.toBean(updateReqVO, MenuDO.class);
initMenuProperty(updateObj);
menuMapper.updateById(updateObj);
} | @Test
public void testUpdateMenu_sonIdNotExist() {
// 准备参数
MenuSaveVO reqVO = randomPojo(MenuSaveVO.class);
// 调用,并断言异常
assertServiceException(() -> menuService.updateMenu(reqVO), MENU_NOT_EXISTS);
} |
public void write(WriteRequest writeRequest) {
if (!tryAcquireSemaphore()) {
return;
}
mSerializingExecutor.execute(() -> {
try {
if (mContext == null) {
LOG.debug("Received write request {}.",
RpcSensitiveConfigMask.CREDENTIAL_FIELD_MASKER.maskObjects(LOG, writeRequest));
try {
mContext = createRequestContext(writeRequest);
} catch (Exception e) {
// abort() assumes context is initialized.
// Reply with the error in order to prevent clients getting stuck.
replyError(new Error(AlluxioStatusException.fromThrowable(e), true));
throw e;
}
} else {
Preconditions.checkState(!mContext.isDoneUnsafe(),
"invalid request after write request is completed.");
}
if (mContext.isDoneUnsafe() || mContext.getError() != null) {
return;
}
validateWriteRequest(writeRequest);
if (writeRequest.hasCommand()) {
WriteRequestCommand command = writeRequest.getCommand();
if (command.getFlush()) {
flush();
} else {
handleCommand(command, mContext);
}
} else {
Preconditions.checkState(writeRequest.hasChunk(),
"write request is missing data chunk in non-command message");
ByteString data = writeRequest.getChunk().getData();
Preconditions.checkState(data != null && data.size() > 0,
"invalid data size from write request message");
writeData(new NioDataBuffer(data.asReadOnlyByteBuffer(), data.size()));
}
} catch (Exception e) {
LogUtils.warnWithException(LOG, "Exception occurred while processing write request {}.",
writeRequest, e);
abort(new Error(AlluxioStatusException.fromThrowable(e), true));
} finally {
mSemaphore.release();
}
});
} | @Test
public void writeInvalidOffsetFirstRequest() throws Exception {
// The write request contains an invalid offset
mWriteHandler.write(newWriteRequestCommand(1));
waitForResponses();
checkErrorCode(mResponseObserver, Status.Code.INVALID_ARGUMENT);
} |
public static ConfigChangeBatchListenResponse buildFailResponse(String errorMessage) {
ConfigChangeBatchListenResponse response = new ConfigChangeBatchListenResponse();
response.setResultCode(ResponseCode.FAIL.getCode());
response.setMessage(errorMessage);
return response;
} | @Override
@Test
public void testSerializeFailResponse() throws JsonProcessingException {
ConfigChangeBatchListenResponse configChangeBatchListenResponse = ConfigChangeBatchListenResponse.buildFailResponse(
"Fail");
String json = mapper.writeValueAsString(configChangeBatchListenResponse);
assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode()));
assertTrue(json.contains("\"errorCode\":0"));
assertTrue(json.contains("\"message\":\"Fail\""));
assertTrue(json.contains("\"success\":false"));
} |
@ApiOperation(value = "Delete a comment on a historic process instance", tags = { "History Process" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the historic process instance and comment were found and the comment is deleted. Response body is left empty intentionally."),
@ApiResponse(code = 404, message = "Indicates the requested historic process instance was not found or the historic process instance does not have a comment with the given ID.") })
@DeleteMapping(value = "/history/historic-process-instances/{processInstanceId}/comments/{commentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteComment(@ApiParam(name = "processInstanceId") @PathVariable("processInstanceId") String processInstanceId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId) {
HistoricProcessInstance instance = getHistoricProcessInstanceFromRequest(processInstanceId);
Comment comment = taskService.getComment(commentId);
if (comment == null || comment.getProcessInstanceId() == null || !comment.getProcessInstanceId().equals(instance.getId())) {
throw new FlowableObjectNotFoundException("Process instance '" + instance.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class);
}
taskService.deleteComment(commentId);
} | @Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testCreateComment() throws Exception {
ProcessInstance pi = null;
try {
pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");
HttpPost httpPost = new HttpPost(
SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT_COLLECTION, pi.getId()));
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("message", "This is a comment...");
httpPost.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
List<Comment> commentsOnProcess = taskService.getProcessInstanceComments(pi.getId());
assertThat(commentsOnProcess).hasSize(1);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThat(responseNode).isNotNull();
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo(" {"
+ " id: '" + commentsOnProcess.get(0).getId() + "',"
+ " author: 'kermit',"
+ " message: 'This is a comment...',"
+ " taskId: null,"
+ " taskUrl: null,"
+ " processInstanceId: '" + pi.getProcessInstanceId() + "',"
+ " processInstanceUrl: '" + SERVER_URL_PREFIX + RestUrls
.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, pi.getId(), commentsOnProcess.get(0).getId()) + "'"
+ "}");
} finally {
if (pi != null) {
List<Comment> comments = taskService.getProcessInstanceComments(pi.getId());
for (Comment c : comments) {
taskService.deleteComment(c.getId());
}
}
}
} |
@Override
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
liquibase.dropAll();
} | @Test
void testRun() throws Exception {
final String databaseUrl = MigrationTestSupport.getDatabaseUrl();
final TestMigrationConfiguration conf = MigrationTestSupport.createConfiguration(databaseUrl);
// Create some data
new DbMigrateCommand<>(
TestMigrationConfiguration::getDataSource, TestMigrationConfiguration.class, "migrations.xml")
.run(null, new Namespace(Collections.emptyMap()), conf);
try (Handle handle = Jdbi.create(databaseUrl, "sa", "").open()) {
assertThat(MigrationTestSupport.tableExists(handle, "PERSONS"))
.isTrue();
}
// Drop it
dropAllCommand.run(null, new Namespace(Collections.emptyMap()), conf);
try (Handle handle = Jdbi.create(databaseUrl, "sa", "").open()) {
assertThat(MigrationTestSupport.tableExists(handle, "PERSONS"))
.isFalse();
}
} |
@Udf(description = "Returns a masked version of the input string. The last n characters"
+ " will be replaced according to the default masking rules.")
@SuppressWarnings("MethodMayBeStatic") // Invoked via reflection
public String mask(
@UdfParameter("input STRING to be masked") final String input,
@UdfParameter("number of characters to mask before the end") final int numChars
) {
return doMask(new Masker(), input, numChars);
} | @Test
public void shouldReturnNullForNullInput() {
final String result = udf.mask(null, 5);
assertThat(result, is(nullValue()));
} |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void issueI60UOPTest() {
final String uaStr = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 dingtalk-win/1.0.0 nw(0.14.7) DingTalk(6.5.40-Release.9059101) Mojo/1.0.0 Native AppType(release) Channel/201200";
final UserAgent ua = UserAgentUtil.parse(uaStr);
assertEquals("DingTalk-win", ua.getBrowser().toString());
assertEquals("6.5.40-Release.9059101", ua.getVersion());
assertEquals("Webkit", ua.getEngine().toString());
assertEquals("537.36", ua.getEngineVersion());
assertEquals("Windows 10 or Windows Server 2016", ua.getOs().toString());
assertEquals("10.0", ua.getOsVersion());
assertEquals("Windows", ua.getPlatform().toString());
assertFalse(ua.isMobile());
} |
public void addBasicProperty(String name, String strValue) {
if (strValue == null) {
return;
}
name = capitalizeFirstLetter(name);
Method adderMethod = findAdderMethod(name);
if (adderMethod == null) {
addError("No adder for property [" + name + "].");
return;
}
Class<?>[] paramTypes = adderMethod.getParameterTypes();
isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue);
Object arg;
try {
arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]);
} catch (Throwable t) {
addError("Conversion to type [" + paramTypes[0] + "] failed. ", t);
return;
}
if (arg != null) {
invokeMethodWithSingleParameterOnThisObject(adderMethod, strValue);
}
} | @Test
public void testPropertyCollection() {
setter.addBasicProperty("adjective", "nice");
setter.addBasicProperty("adjective", "big");
assertEquals(2, house.adjectiveList.size());
assertEquals("nice", house.adjectiveList.get(0));
assertEquals("big", house.adjectiveList.get(1));
} |
public Optional<String> extract(final String uri) {
if (uri.startsWith(this.target) && uri.length() != this.target.length()) {
return Optional.of(uri.replaceFirst(this.target, ""));
}
return empty();
} | @Test
public void should_return_null_if_uri_does_not_match() {
MountTo to = new MountTo("/dir");
assertThat(to.extract("/target/filename").isPresent(), is(false));
} |
@Override
protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException {
if(null == digest) {
log.warn("Checksum calculation disabled");
return super.decorate(in, null);
}
else {
return new DigestInputStream(in, digest);
}
} | @Test
public void testDecorate() throws Exception {
final NullInputStream n = new NullInputStream(1L);
assertSame(NullInputStream.class, new DropboxUploadFeature(session, new DropboxWriteFeature(session)).decorate(n, null).getClass());
} |
public List<Event> log() { return log; } | @Test
public void truncate_log() {
assertEquals(0, new History(List.of(), List.of()).log().size());
assertEquals(1, new History(ImmutableMap.of(), shuffledEvents(1), 2).log().size());
assertEquals(2, new History(ImmutableMap.of(), shuffledEvents(2), 2).log().size());
History history = new History(ImmutableMap.of(), shuffledEvents(5), 3);
assertEquals(3, history.log().size());
assertEquals("Most recent events are kept",
List.of(2L, 3L, 4L),
history.log().stream().map(e -> e.at().toEpochMilli()).toList());
} |
public static SimpleTableSegment bind(final SimpleTableSegment segment, final SQLStatementBinderContext binderContext, final Map<String, TableSegmentBinderContext> tableBinderContexts) {
fillPivotColumnNamesInBinderContext(segment, binderContext);
IdentifierValue databaseName = getDatabaseName(segment, binderContext);
ShardingSpherePreconditions.checkNotNull(databaseName.getValue(), NoDatabaseSelectedException::new);
IdentifierValue schemaName = getSchemaName(segment, binderContext);
IdentifierValue tableName = segment.getTableName().getIdentifier();
checkTableExists(binderContext, databaseName.getValue(), schemaName.getValue(), tableName.getValue());
ShardingSphereSchema schema = binderContext.getMetaData().getDatabase(databaseName.getValue()).getSchema(schemaName.getValue());
tableBinderContexts.putIfAbsent(
(segment.getAliasName().orElseGet(tableName::getValue)).toLowerCase(), createSimpleTableBinderContext(segment, schema, databaseName, schemaName, binderContext));
TableNameSegment tableNameSegment = new TableNameSegment(segment.getTableName().getStartIndex(), segment.getTableName().getStopIndex(), tableName);
SimpleTableSegment result = new SimpleTableSegment(tableNameSegment);
segment.getOwner().ifPresent(result::setOwner);
segment.getAliasSegment().ifPresent(result::setAlias);
return result;
} | @Test
void assertBindTableNotExists() {
SimpleTableSegment simpleTableSegment = new SimpleTableSegment(new TableNameSegment(0, 10, new IdentifierValue("t_not_exists")));
ShardingSphereMetaData metaData = createMetaData();
Map<String, TableSegmentBinderContext> tableBinderContexts = new LinkedHashMap<>();
assertThrows(TableNotFoundException.class, () -> SimpleTableSegmentBinder.bind(
simpleTableSegment, new SQLStatementBinderContext(metaData, DefaultDatabase.LOGIC_NAME, databaseType, Collections.emptySet()), tableBinderContexts));
} |
public NioAsyncSocketBuilder setWriteQueueCapacity(int writeQueueCapacity) {
verifyNotBuilt();
this.writeQueueCapacity = checkPositive(writeQueueCapacity, "writeQueueCapacity");
return this;
} | @Test
public void test_setWriteQueueCapacity_whenZero() {
NioReactor reactor = (NioReactor) newReactor();
NioAsyncSocketBuilder builder = reactor.newAsyncSocketBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setWriteQueueCapacity(0));
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testAbsoluteMemoryNegative() throws Exception {
expectNegativeValueOfResource("memory");
parseResourceConfigValue("2 vcores,-5120 mb");
} |
public static boolean isPathPresent(MaskTree filter, PathSpec path)
{
return !getPresentPaths(filter, Collections.singleton(path)).isEmpty();
} | @Test
public void testEmptyFilter()
{
final MaskTree filter = new MaskTree();
Assert.assertFalse(ProjectionUtil.isPathPresent(filter, new PathSpec("foo")));
} |
public String getKafkaTopicName() {
return _kafkaTopicName;
} | @Test
public void testGetKafkaTopicName() {
KafkaPartitionLevelStreamConfig config = getStreamConfig("topic", "", "", "");
Assert.assertEquals("topic", config.getKafkaTopicName());
} |
public void begin(InterpretationContext ec, String localName,
Attributes attributes) {
if ("substitutionProperty".equals(localName)) {
addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead.");
}
String name = attributes.getValue(NAME_ATTRIBUTE);
String value = attributes.getValue(VALUE_ATTRIBUTE);
String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE);
Scope scope = ActionUtil.stringToScope(scopeStr);
if (checkFileAttributeSanity(attributes)) {
String file = attributes.getValue(FILE_ATTRIBUTE);
file = ec.subst(file);
try {
FileInputStream istream = new FileInputStream(file);
loadAndSetProperties(ec, istream, scope);
} catch (FileNotFoundException e) {
addError("Could not find properties file [" + file + "].", e);
} catch (IOException e1) {
addError("Could not read properties file [" + file + "].", e1);
}
} else if (checkResourceAttributeSanity(attributes)) {
String resource = attributes.getValue(RESOURCE_ATTRIBUTE);
resource = ec.subst(resource);
URL resourceURL = Loader.getResourceBySelfClassLoader(resource);
if (resourceURL == null) {
addError("Could not find resource [" + resource + "].");
} else {
try {
InputStream istream = resourceURL.openStream();
loadAndSetProperties(ec, istream, scope);
} catch (IOException e) {
addError("Could not read resource file [" + resource + "].", e);
}
}
} else if (checkValueNameAttributesSanity(attributes)) {
value = RegularEscapeUtil.basicEscape(value);
// now remove both leading and trailing spaces
value = value.trim();
value = ec.subst(value);
ActionUtil.setProperty(ec, name, value, scope);
} else {
addError(INVALID_ATTRIBUTES);
}
} | @Test
public void testLoadResource() {
atts.setValue("resource", "asResource/joran/propertyActionTest.properties");
propertyAction.begin(ec, null, atts);
assertEquals("tata", ec.getProperty("r1"));
assertEquals("toto", ec.getProperty("r2"));
} |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
SendMessageContext sendMessageContext;
switch (request.getCode()) {
case RequestCode.CONSUMER_SEND_MSG_BACK:
return this.consumerSendMsgBack(ctx, request);
default:
SendMessageRequestHeader requestHeader = parseRequestHeader(request);
if (requestHeader == null) {
return null;
}
TopicQueueMappingContext mappingContext = this.brokerController.getTopicQueueMappingManager().buildTopicQueueMappingContext(requestHeader, true);
RemotingCommand rewriteResult = this.brokerController.getTopicQueueMappingManager().rewriteRequestForStaticTopic(requestHeader, mappingContext);
if (rewriteResult != null) {
return rewriteResult;
}
sendMessageContext = buildMsgContext(ctx, requestHeader, request);
try {
this.executeSendMessageHookBefore(sendMessageContext);
} catch (AbortProcessException e) {
final RemotingCommand errorResponse = RemotingCommand.createResponseCommand(e.getResponseCode(), e.getErrorMessage());
errorResponse.setOpaque(request.getOpaque());
return errorResponse;
}
RemotingCommand response;
clearReservedProperties(requestHeader);
if (requestHeader.isBatch()) {
response = this.sendBatchMessage(ctx, request, sendMessageContext, requestHeader, mappingContext,
(ctx1, response1) -> executeSendMessageHookAfter(response1, ctx1));
} else {
response = this.sendMessage(ctx, request, sendMessageContext, requestHeader, mappingContext,
(ctx12, response12) -> executeSendMessageHookAfter(response12, ctx12));
}
return response;
}
} | @Test
public void testProcessRequest_WithMsgBackWithConsumeMessageAfterHook() throws Exception {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).
thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
final RemotingCommand request = createSendMsgBackCommand(RequestCode.CONSUMER_SEND_MSG_BACK);
sendMessageProcessor = new SendMessageProcessor(brokerController);
List<ConsumeMessageHook> consumeMessageHookList = new ArrayList<>();
final ConsumeMessageContext[] messageContext = new ConsumeMessageContext[1];
ConsumeMessageHook consumeMessageHook = new ConsumeMessageHook() {
@Override
public String hookName() {
return "TestHook";
}
@Override
public void consumeMessageBefore(ConsumeMessageContext context) {
}
@Override
public void consumeMessageAfter(ConsumeMessageContext context) {
messageContext[0] = context;
throw new AbortProcessException(ResponseCode.FLOW_CONTROL, "flow control test");
}
};
consumeMessageHookList.add(consumeMessageHook);
sendMessageProcessor.registerConsumeMessageHook(consumeMessageHookList);
final RemotingCommand response = sendMessageProcessor.processRequest(handlerContext, request);
assertThat(response).isNotNull();
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
} |
Map<String, String> removeSelfReferences(final Map<String, String> vars) {
final Map<String, String> resolvedVars = new HashMap<>();
vars.forEach((key, value) -> {
if (!isVariableSelfReferencing(vars, key)) {
resolvedVars.put(key, value);
}
});
return resolvedVars;
} | @Test
public void testRemoveSelfReferences2() {
// Given
Map<String, String> input = new HashMap<>();
input.put("FLTK2_DIR", "${FLTK2_INCLUDE_DIR}");
input.put("FLTK2_LIBRARY_SEARCH_PATH", "");
input.put("FLTK2_INCLUDE_DIR", "${FLTK2_DIR}");
input.put("FLTK2_IMAGES_LIBS", "");
input.put("FLTK2_DIR_SEARCH", "");
input.put("FLTK2_WRAP_UI", "1");
input.put("FLTK2_FOUND", "0");
input.put("FLTK2_IMAGES_LIBRARY", "fltk2_images");
input.put("FLTK2_PLATFORM_DEPENDENT_LIBS", "import32");
input.put("FLTK_FLUID_EXECUTABLE", "${FLTK2_FLUID_EXECUTABLE}");
input.put("FLTK2_INCLUDE_SEARCH_PATH", "");
input.put("FLTK2_LIBRARY", "${FLTK2_LIBRARIES}");
input.put("FLTK2_BUILT_WITH_CMAKE", "1");
input.put("FLTK2_INCLUDE_PATH", "${FLTK2_INCLUDE_DIR}");
input.put("FLTK2_GL_LIBRARY", "fltk2_gl");
input.put("FLTK2_FLUID_EXE", "${FLTK2_FLUID_EXECUTABLE}");
input.put("HAS_FLTK2", "${FLTK2_FOUND}");
input.put("FLTK2_BASE_LIBRARY", "fltk2");
Map<String, String> expectedOutput = new HashMap<>();
expectedOutput.put("FLTK2_LIBRARY_SEARCH_PATH", "");
expectedOutput.put("FLTK2_IMAGES_LIBS", "");
expectedOutput.put("FLTK2_DIR_SEARCH", "");
expectedOutput.put("FLTK2_WRAP_UI", "1");
expectedOutput.put("FLTK2_FOUND", "0");
expectedOutput.put("FLTK2_IMAGES_LIBRARY", "fltk2_images");
expectedOutput.put("FLTK2_PLATFORM_DEPENDENT_LIBS", "import32");
expectedOutput.put("FLTK_FLUID_EXECUTABLE", "${FLTK2_FLUID_EXECUTABLE}");
expectedOutput.put("FLTK2_INCLUDE_SEARCH_PATH", "");
expectedOutput.put("FLTK2_LIBRARY", "${FLTK2_LIBRARIES}");
expectedOutput.put("FLTK2_BUILT_WITH_CMAKE", "1");
expectedOutput.put("FLTK2_GL_LIBRARY", "fltk2_gl");
expectedOutput.put("FLTK2_FLUID_EXE", "${FLTK2_FLUID_EXECUTABLE}");
expectedOutput.put("HAS_FLTK2", "${FLTK2_FOUND}");
expectedOutput.put("FLTK2_BASE_LIBRARY", "fltk2");
// When
Map<String, String> output = analyzer.removeSelfReferences(input);
// Then
assertEquals(expectedOutput, output);
} |
public static void createTopics(
Logger log, String bootstrapServers, Map<String, String> commonClientConf,
Map<String, String> adminClientConf,
Map<String, NewTopic> topics, boolean failOnExisting) throws Throwable {
// this method wraps the call to createTopics() that takes admin client, so that we can
// unit test the functionality with MockAdminClient. The exception is caught and
// re-thrown so that admin client is closed when the method returns.
try (Admin adminClient
= createAdminClient(bootstrapServers, commonClientConf, adminClientConf)) {
createTopics(log, adminClient, topics, failOnExisting);
} catch (Exception e) {
log.warn("Failed to create or verify topics {}", topics, e);
throw e;
}
} | @Test
public void testExistingTopicsMustHaveRequestedNumberOfPartitions() {
List<TopicPartitionInfo> tpInfo = new ArrayList<>();
tpInfo.add(new TopicPartitionInfo(0, broker1, singleReplica, Collections.emptyList()));
tpInfo.add(new TopicPartitionInfo(1, broker2, singleReplica, Collections.emptyList()));
adminClient.addTopic(
false,
TEST_TOPIC,
tpInfo,
null);
assertThrows(RuntimeException.class, () -> WorkerUtils.createTopics(
log, adminClient, Collections.singletonMap(TEST_TOPIC, NEW_TEST_TOPIC), false));
} |
public static SessionWindows ofInactivityGapWithNoGrace(final Duration inactivityGap) {
return ofInactivityGapAndGrace(inactivityGap, ofMillis(NO_GRACE_PERIOD));
} | @Test
public void windowSizeMustNotBeNegative() {
assertThrows(IllegalArgumentException.class, () -> SessionWindows.ofInactivityGapWithNoGrace(ofMillis(-1)));
} |
@Override
public synchronized void close() {
this.length = 0L;
if(temporary.exists()) {
try {
if(file != null) {
file.close();
}
}
catch(IOException e) {
log.error(String.format("Failure closing buffer %s", this));
}
finally {
try {
temporary.delete();
file = null;
}
catch(AccessDeniedException | NotfoundException e) {
log.warn(String.format("Failure removing temporary file %s for buffer %s. Schedule for delete on exit.", temporary, this));
Paths.get(temporary.getAbsolute()).toFile().deleteOnExit();
}
}
}
} | @Test
public void testClose() throws Exception {
final FileBuffer buffer = new FileBuffer();
assertEquals(0L, buffer.length(), 0L);
final byte[] chunk = RandomUtils.nextBytes(100);
buffer.write(chunk, 0L);
assertEquals(100L, buffer.length(), 0L);
buffer.close();
assertEquals(0L, buffer.length(), 0L);
buffer.write(chunk, 0L);
assertEquals(100L, buffer.length(), 0L);
} |
@Override
public E computeIfAbsent(String key, Function<? super String, ? extends E> mappingFunction) {
try {
return cacheStore.invoke(key, new AtomicComputeProcessor<>(), mappingFunction);
} catch (EntryProcessorException e) {
throw new RuntimeException(e.getCause());
}
} | @Test
public void computeIfAbsent_cacheMiss_mappingFunctionReturnsNull_returnOldValue() {
Function<String, Integer> mappingFunction = k -> null;
doReturn(null).when(mutableEntryMock).getValue();
entryProcessorMock = new CacheRegistryStore.AtomicComputeProcessor<>();
entryProcessorArgMock = mappingFunction;
Integer cacheResult = classUnderTest.computeIfAbsent(CACHE_KEY, mappingFunction);
verify(mutableEntryMock, never()).setValue(any());
assertNull(cacheResult);
} |
public Collection<SQLException> closeConnections(final boolean forceRollback) {
Collection<SQLException> result = new LinkedList<>();
synchronized (cachedConnections) {
resetSessionVariablesIfNecessary(cachedConnections.values(), result);
for (Connection each : cachedConnections.values()) {
try {
if (forceRollback && connectionSession.getTransactionStatus().isInTransaction()) {
each.rollback();
}
each.close();
} catch (final SQLException ex) {
result.add(ex);
}
}
cachedConnections.clear();
}
if (!forceRollback) {
connectionPostProcessors.clear();
}
return result;
} | @SuppressWarnings("unchecked")
@Test
void assertCloseConnectionsCorrectlyWhenNotForceRollback() throws ReflectiveOperationException, SQLException {
Multimap<String, Connection> cachedConnections = (Multimap<String, Connection>) Plugins.getMemberAccessor()
.get(ProxyDatabaseConnectionManager.class.getDeclaredField("cachedConnections"), databaseConnectionManager);
Connection connection = prepareCachedConnections();
cachedConnections.put("ignoredDataSourceName", connection);
databaseConnectionManager.closeConnections(false);
verify(connection).close();
assertTrue(cachedConnections.isEmpty());
verifyConnectionPostProcessorsEmpty();
} |
@Override
public List<DataSourceConfigDO> getDataSourceConfigList() {
List<DataSourceConfigDO> result = dataSourceConfigMapper.selectList();
// 补充 master 数据源
result.add(0, buildMasterDataSourceConfig());
return result;
} | @Test
public void testGetDataSourceConfigList() {
// mock 数据
DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class);
dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
// 调用
List<DataSourceConfigDO> dataSourceConfigList = dataSourceConfigService.getDataSourceConfigList();
// 断言
assertEquals(2, dataSourceConfigList.size());
// master
assertEquals(0L, dataSourceConfigList.get(0).getId());
assertEquals("primary", dataSourceConfigList.get(0).getName());
assertEquals("http://localhost:3306", dataSourceConfigList.get(0).getUrl());
assertEquals("yunai", dataSourceConfigList.get(0).getUsername());
assertEquals("tudou", dataSourceConfigList.get(0).getPassword());
// normal
assertPojoEquals(dbDataSourceConfig, dataSourceConfigList.get(1));
} |
@Override
public NodeToLabelsInfo getNodeToLabels(HttpServletRequest hsr)
throws IOException {
try {
long startTime = clock.getTime();
Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters();
final HttpServletRequest hsrCopy = clone(hsr);
Class[] argsClasses = new Class[]{HttpServletRequest.class};
Object[] args = new Object[]{hsrCopy};
ClientMethod remoteMethod = new ClientMethod("getNodeToLabels", argsClasses, args);
Map<SubClusterInfo, NodeToLabelsInfo> nodeToLabelsInfoMap =
invokeConcurrent(subClustersActive, remoteMethod, NodeToLabelsInfo.class);
NodeToLabelsInfo nodeToLabelsInfo =
RouterWebServiceUtil.mergeNodeToLabels(nodeToLabelsInfoMap);
if (nodeToLabelsInfo != null) {
long stopTime = clock.getTime();
routerMetrics.succeededGetNodeToLabelsRetrieved(stopTime - startTime);
RouterAuditLogger.logSuccess(getUser().getShortUserName(), GET_NODETOLABELS,
TARGET_WEB_SERVICE);
return nodeToLabelsInfo;
}
} catch (NotFoundException e) {
routerMetrics.incrNodeToLabelsFailedRetrieved();
RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN,
TARGET_WEB_SERVICE, e.getLocalizedMessage());
RouterServerUtil.logAndThrowIOException("get all active sub cluster(s) error.", e);
} catch (YarnException e) {
routerMetrics.incrNodeToLabelsFailedRetrieved();
RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN,
TARGET_WEB_SERVICE, e.getLocalizedMessage());
RouterServerUtil.logAndThrowIOException("getNodeToLabels error.", e);
}
routerMetrics.incrNodeToLabelsFailedRetrieved();
RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_NODETOLABELS, UNKNOWN,
TARGET_WEB_SERVICE, "getNodeToLabels Failed.");
throw new RuntimeException("getNodeToLabels Failed.");
} | @Test
public void testGetNodeToLabels() throws IOException {
NodeToLabelsInfo info = interceptor.getNodeToLabels(null);
HashMap<String, NodeLabelsInfo> map = info.getNodeToLabels();
Assert.assertNotNull(map);
Assert.assertEquals(2, map.size());
NodeLabelsInfo node1Value = map.getOrDefault("node1", null);
Assert.assertNotNull(node1Value);
Assert.assertEquals(1, node1Value.getNodeLabelsName().size());
Assert.assertEquals("CPU", node1Value.getNodeLabelsName().get(0));
NodeLabelsInfo node2Value = map.getOrDefault("node2", null);
Assert.assertNotNull(node2Value);
Assert.assertEquals(1, node2Value.getNodeLabelsName().size());
Assert.assertEquals("GPU", node2Value.getNodeLabelsName().get(0));
} |
public DefaultSwitcher(String name, String type) {
this.name = "DefaultSwitcher.".concat(name);
this.defaultId = name.concat(".").concat("_default");
this.type = type;
} | @Test
public void DefaultSwitcher() {
DefaultSwitcher switcher = new DefaultSwitcher("test", "schema");
assertFalse(switcher.current().isPresent());
switcher.use("test");
assertEquals(switcher.current().orElse(null), "test");
switcher.use("test2");
assertEquals(switcher.current().orElse(null), "test2");
switcher.useLast();
assertEquals(switcher.current().orElse(null), "test");
switcher.reset();
assertFalse(switcher.current().isPresent());
} |
@Override
public void updateCommentVisible(ProductCommentUpdateVisibleReqVO updateReqVO) {
// 校验评论是否存在
validateCommentExists(updateReqVO.getId());
// 更新可见状态
productCommentMapper.updateById(new ProductCommentDO().setId(updateReqVO.getId())
.setVisible(updateReqVO.getVisible()));
} | @Test
public void testUpdateCommentVisible_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
o.setVisible(Boolean.TRUE);
});
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId();
ProductCommentUpdateVisibleReqVO updateReqVO = new ProductCommentUpdateVisibleReqVO();
updateReqVO.setId(productCommentId);
updateReqVO.setVisible(Boolean.FALSE);
productCommentService.updateCommentVisible(updateReqVO);
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
assertFalse(productCommentDO.getVisible());
} |
@ApiOperation(value = "Create or update Alarm Comment ",
notes = "Creates or Updates the Alarm Comment. " +
"When creating comment, platform generates Alarm Comment Id as " + UUID_WIKI_LINK +
"The newly created Alarm Comment id will be present in the response. Specify existing Alarm Comment id to update the alarm. " +
"Referencing non-existing Alarm Comment Id will cause 'Not Found' error. " +
"\n\n To create new Alarm comment entity it is enough to specify 'comment' json element with 'text' node, for example: {\"comment\": { \"text\": \"my comment\"}}. " +
"\n\n If comment type is not specified the default value 'OTHER' will be saved. If 'alarmId' or 'userId' specified in body it will be ignored." +
TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}/comment", method = RequestMethod.POST)
@ResponseBody
public AlarmComment saveAlarmComment(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "A JSON value representing the comment.") @RequestBody AlarmComment alarmComment) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId);
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
Alarm alarm = checkAlarmInfoId(alarmId, Operation.WRITE);
alarmComment.setAlarmId(alarmId);
return tbAlarmCommentService.saveAlarmComment(alarm, alarmComment, getCurrentUser());
} | @Test
public void testUpdateAlarmCommentViaCustomer() throws Exception {
loginCustomerUser();
AlarmComment savedComment = createAlarmComment(alarm.getId());
Mockito.reset(tbClusterService, auditLogService);
JsonNode newComment = JacksonUtil.newObjectNode().set("text", new TextNode("Updated comment"));
savedComment.setComment(newComment);
AlarmComment updatedAlarmComment = saveAlarmComment(alarm.getId(), savedComment);
Assert.assertNotNull(updatedAlarmComment);
Assert.assertEquals(newComment.get("text"), updatedAlarmComment.getComment().get("text"));
Assert.assertEquals("true", updatedAlarmComment.getComment().get("edited").asText());
Assert.assertNotNull(updatedAlarmComment.getComment().get("editedOn"));
testLogEntityActionEntityEqClass(alarm, alarm.getId(), tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.UPDATED_COMMENT, 1, updatedAlarmComment);
} |
public String ofClass(Class<?> clazz) {
return clazz.getClassLoader() + "-" + clazz.getCanonicalName();
} | @Test
public void generate_key_of_class() {
assertThat(keys.ofClass(FakeComponent.class)).endsWith("-org.sonar.core.platform.ComponentKeysTest.FakeComponent");
} |
@Override
public Response toResponse(Throwable exception) {
debugLog(exception);
if (exception instanceof WebApplicationException w) {
var res = w.getResponse();
if (res.getStatus() >= 500) {
log(w);
}
return res;
}
if (exception instanceof AuthenticationException) {
return Response.status(Status.UNAUTHORIZED).build();
}
if (exception instanceof ValidationException ve) {
if (ve.seeOther() != null) {
return Response.seeOther(ve.seeOther()).build();
}
return buildContentNegotiatedErrorResponse(ve.localizedMessage(), Status.BAD_REQUEST);
}
// the remaining exceptions are unexpected, let's log them
log(exception);
if (exception instanceof FederationException fe) {
var errorMessage = new Message(FEDERATION_ERROR_MESSAGE, fe.reason().name());
return buildContentNegotiatedErrorResponse(errorMessage, Status.INTERNAL_SERVER_ERROR);
}
var status = Status.INTERNAL_SERVER_ERROR;
var errorMessage = new Message(SERVER_ERROR_MESSAGE, (String) null);
return buildContentNegotiatedErrorResponse(errorMessage, status);
} | @Test
void toResponse_propagateWebApplicationException() {
var ex = new NotFoundException();
// when
var res = mapper.toResponse(ex);
// then
assertEquals(404, res.getStatus());
} |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(distance, edgeState, reverse);
if (Double.isInfinite(seconds)) return Double.POSITIVE_INFINITY;
// add penalty at start/stop/via points
if (edgeState.get(EdgeIteratorState.UNFAVORED_EDGE)) seconds += headingPenaltySeconds;
double distanceCosts = distance * distanceInfluence;
if (Double.isInfinite(distanceCosts)) return Double.POSITIVE_INFINITY;
return seconds / priority + distanceCosts;
} | @Test
public void testSpeedFactorAndPriority() {
EdgeIteratorState primary = graph.edge(0, 1).setDistance(10).
set(roadClassEnc, PRIMARY).set(avSpeedEnc, 80);
EdgeIteratorState secondary = graph.edge(1, 2).setDistance(10).
set(roadClassEnc, SECONDARY).set(avSpeedEnc, 70);
CustomModel customModel = createSpeedCustomModel(avSpeedEnc).setDistanceInfluence(70d).
addToPriority(If("road_class != PRIMARY", MULTIPLY, "0.5")).
addToSpeed(If("road_class != PRIMARY", MULTIPLY, "0.9"));
Weighting weighting = createWeighting(customModel);
assertEquals(1.15, weighting.calcEdgeWeight(primary, false), 0.01);
assertEquals(1.84, weighting.calcEdgeWeight(secondary, false), 0.01);
customModel = createSpeedCustomModel(avSpeedEnc).setDistanceInfluence(70d).
addToPriority(If("road_class == PRIMARY", MULTIPLY, "1.0")).
addToPriority(Else(MULTIPLY, "0.5")).
addToSpeed(If("road_class != PRIMARY", MULTIPLY, "0.9"));
weighting = createWeighting(customModel);
assertEquals(1.15, weighting.calcEdgeWeight(primary, false), 0.01);
assertEquals(1.84, weighting.calcEdgeWeight(secondary, false), 0.01);
} |
public static Set<String> getNBServiceList() {
Set<String> permString = new HashSet<>();
for (Permission perm : getAdminDefaultPerms()) {
permString.add(perm.getName());
}
return permString;
} | @Test
public void testGetNBServiceList() {
Set<String> permString = new HashSet<>();
permString.add(new ServicePermission(ApplicationAdminService.class.getName(), ServicePermission.GET).getName());
assertEquals(1, permString.size());
assertEquals("org.onosproject.app.ApplicationAdminService", permString.toArray()[0]);
} |
@Override
public void updateApiConfig(K8sApiConfig config) {
checkNotNull(config, ERR_NULL_CONFIG);
configStore.updateApiConfig(config);
log.info(String.format(MSG_CONFIG, endpoint(config), MSG_UPDATED));
} | @Test(expected = NullPointerException.class)
public void testUpdateNullConfig() {
target.updateApiConfig(null);
} |
public Single<Boolean> addAll(Publisher<? extends V> c) {
return new PublisherAdder<V>() {
@Override
public RFuture<Boolean> add(Object o) {
return instance.addAsync((V) o);
}
}.addAll(c);
} | @Test
public void testAddAllIndex() {
RListRx<Integer> list = redisson.getList("list");
sync(list.add(1));
sync(list.add(2));
sync(list.add(3));
sync(list.add(4));
sync(list.add(5));
Assertions.assertEquals(true, sync(list.addAll(2, Arrays.asList(7, 8, 9))));
assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 5);
sync(list.addAll(sync(list.size())-1, Arrays.asList(9, 1, 9)));
assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5);
sync(list.addAll(sync(list.size()), Arrays.asList(0, 5)));
assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5, 0, 5);
Assertions.assertEquals(true, sync(list.addAll(0, Arrays.asList(6, 7))));
assertThat(sync(list)).containsExactly(6,7,1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5, 0, 5);
} |
public void ensureCapacity(@NonNegative long maximumSize) {
requireArgument(maximumSize >= 0);
int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1);
if ((table != null) && (table.length >= maximum)) {
return;
}
table = new long[Math.max(Caffeine.ceilingPowerOfTwo(maximum), 8)];
sampleSize = (maximumSize == 0) ? 10 : (10 * maximum);
blockMask = (table.length >>> 3) - 1;
if (sampleSize <= 0) {
sampleSize = Integer.MAX_VALUE;
}
size = 0;
} | @Test(dataProvider = "sketch")
public void ensureCapacity_smaller(FrequencySketch<Integer> sketch) {
int size = sketch.table.length;
sketch.ensureCapacity(size / 2);
assertThat(sketch.table).hasLength(size);
assertThat(sketch.sampleSize).isEqualTo(10 * size);
assertThat(sketch.blockMask).isEqualTo((size >> 3) - 1);
} |
@Override
public UserCredentials findByResetToken(TenantId tenantId, String resetToken) {
return DaoUtil.getData(userCredentialsRepository.findByResetToken(resetToken));
} | @Test
public void testFindByResetToken() {
UserCredentials foundedUserCredentials = userCredentialsDao.findByResetToken(SYSTEM_TENANT_ID, RESET_TOKEN);
assertNotNull(foundedUserCredentials);
assertEquals(neededUserCredentials.getId(), foundedUserCredentials.getId());
} |
public Range(T start, Stepper<T> stepper) {
this(start, null, stepper);
} | @Test
public void rangeContains() {
// 开始区间
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-31");
DateRange startRange = DateUtil.range(start, end, DateField.DAY_OF_YEAR);
// 结束区间
DateTime start1 = DateUtil.parse("2017-01-31");
DateTime end1 = DateUtil.parse("2017-02-02");
DateRange endRange = DateUtil.range(start1, end1, DateField.DAY_OF_YEAR);
// 交集
List<DateTime> dateTimes = DateUtil.rangeContains(startRange, endRange);
assertEquals(1, dateTimes.size());
assertEquals(DateUtil.parse("2017-01-31"), dateTimes.get(0));
} |
@GET
@Path("/{entityType}/{entityId}")
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8
/* , MediaType.APPLICATION_XML */})
public TimelineEntity getEntity(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("entityType") String entityType,
@PathParam("entityId") String entityId,
@QueryParam("fields") String fields) {
init(res);
TimelineEntity entity = null;
try {
entity = timelineDataManager.getEntity(
parseStr(entityType),
parseStr(entityId),
parseFieldsStr(fields, ","),
getUser(req));
} catch (YarnException e) {
// The user doesn't have the access to override the existing domain.
LOG.info(e.getMessage(), e);
throw new ForbiddenException(e);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
} catch (Exception e) {
LOG.error("Error getting entity", e);
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
}
if (entity == null) {
throw new NotFoundException("Timeline entity "
+ new EntityIdentifier(parseStr(entityId), parseStr(entityType))
+ " is not found");
}
return entity;
} | @Test
void testPrimaryFilterLong() {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("timeline")
.path("type_1").queryParam("primaryFilter",
"long:" + Long.toString((long) Integer.MAX_VALUE + 1L))
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
response.getType().toString());
verifyEntities(response.getEntity(TimelineEntities.class));
} |
@Override
public DataflowMapTaskExecutor create(
MutableNetwork<Node, Edge> network,
PipelineOptions options,
String stageName,
ReaderFactory readerFactory,
SinkFactory sinkFactory,
DataflowExecutionContext<?> executionContext,
CounterSet counterSet,
IdGenerator idGenerator) {
// Swap out all the InstructionOutput nodes with OutputReceiver nodes
Networks.replaceDirectedNetworkNodes(
network, createOutputReceiversTransform(stageName, counterSet));
// Swap out all the ParallelInstruction nodes with Operation nodes
Networks.replaceDirectedNetworkNodes(
network,
createOperationTransformForParallelInstructionNodes(
stageName, network, options, readerFactory, sinkFactory, executionContext));
// Collect all the operations within the network and attach all the operations as receivers
// to preceding output receivers.
List<Operation> topoSortedOperations = new ArrayList<>();
for (OperationNode node :
Iterables.filter(Networks.topologicalOrder(network), OperationNode.class)) {
topoSortedOperations.add(node.getOperation());
for (Node predecessor :
Iterables.filter(network.predecessors(node), OutputReceiverNode.class)) {
((OutputReceiverNode) predecessor)
.getOutputReceiver()
.addOutput((Receiver) node.getOperation());
}
}
if (LOG.isDebugEnabled()) {
LOG.info("Map task network: {}", Networks.toDot(network));
}
return IntrinsicMapTaskExecutor.withSharedCounterSet(
topoSortedOperations, counterSet, executionContext.getExecutionStateTracker());
} | @Test
public void testCreateMapTaskExecutor() throws Exception {
List<ParallelInstruction> instructions =
Arrays.asList(
createReadInstruction("Read"),
createParDoInstruction(0, 0, "DoFn1"),
createParDoInstruction(0, 0, "DoFnWithContext"),
createFlattenInstruction(1, 0, 2, 0, "Flatten"),
createWriteInstruction(3, 0, "Write"));
MapTask mapTask = new MapTask();
mapTask.setStageName(STAGE);
mapTask.setSystemName("systemName");
mapTask.setInstructions(instructions);
mapTask.setFactory(Transport.getJsonFactory());
try (DataflowMapTaskExecutor executor =
mapTaskExecutorFactory.create(
mapTaskToNetwork.apply(mapTask),
options,
STAGE,
readerRegistry,
sinkRegistry,
BatchModeExecutionContext.forTesting(options, counterSet, "testStage"),
counterSet,
idGenerator)) {
// Safe covariant cast not expressible without rawtypes.
@SuppressWarnings({
"rawtypes", // TODO(https://github.com/apache/beam/issues/20447)
"unchecked"
})
List<Object> operations = (List) executor.operations;
assertThat(
operations,
hasItems(
instanceOf(ReadOperation.class),
instanceOf(ParDoOperation.class),
instanceOf(ParDoOperation.class),
instanceOf(FlattenOperation.class),
instanceOf(WriteOperation.class)));
// Verify that the inputs are attached.
ReadOperation readOperation =
Iterables.getOnlyElement(Iterables.filter(operations, ReadOperation.class));
assertEquals(2, readOperation.receivers[0].getReceiverCount());
FlattenOperation flattenOperation =
Iterables.getOnlyElement(Iterables.filter(operations, FlattenOperation.class));
for (ParDoOperation operation : Iterables.filter(operations, ParDoOperation.class)) {
assertSame(flattenOperation, operation.receivers[0].getOnlyReceiver());
}
WriteOperation writeOperation =
Iterables.getOnlyElement(Iterables.filter(operations, WriteOperation.class));
assertSame(writeOperation, flattenOperation.receivers[0].getOnlyReceiver());
}
@SuppressWarnings("unchecked")
Counter<Long, ?> otherMsecCounter =
(Counter<Long, ?>) counterSet.getExistingCounter("test-other-msecs");
// "other" state only got created upon MapTaskExecutor.execute().
assertNull(otherMsecCounter);
counterSet.extractUpdates(false, updateExtractor);
verifyOutputCounters(
updateExtractor,
"read_output_name",
"DoFn1_output",
"DoFnWithContext_output",
"flatten_output_name");
verify(updateExtractor).longSum(eq(named("Read-ByteCount")), anyBoolean(), anyLong());
verify(updateExtractor).longSum(eq(named("Write-ByteCount")), anyBoolean(), anyLong());
verifyNoMoreInteractions(updateExtractor);
} |
protected void recordClientElapseTime() {
if (context != null) {
Long startTime = (Long) context.removeAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME);
if (startTime != null) {
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, RpcRuntimeContext.now() - startTime);
}
}
} | @Test
public void testRecordClientElapseTime() {
BoltInvokerCallback invokerCallback = new BoltInvokerCallback(null, null,
null, null, null, null);
invokerCallback.recordClientElapseTime();
Long elapse = (Long) RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
Assert.assertNull(elapse);
RpcInternalContext context = RpcInternalContext.getContext();
invokerCallback = new BoltInvokerCallback(null, null,
null, null, context, null);
invokerCallback.recordClientElapseTime();
elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
Assert.assertNull(elapse);
context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now() - 1000);
invokerCallback.recordClientElapseTime();
elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
Assert.assertNotNull(elapse);
} |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final CopyFileRequest copy = new CopyFileRequest()
.name(target.getName())
.parentID(fileid.getFileId(target.getParent()))
.mode(1); // Overwrite
final File file = new FilesApi(session.getClient()).filesCopy(
fileid.getFileId(source), copy);
listener.sent(status.getLength());
fileid.cache(target, file.getId());
return target.withAttributes(new StoregateAttributesFinderFeature(session, fileid).toAttributes(file));
}
catch(ApiException e) {
throw new StoregateExceptionMappingService(fileid).map("Cannot copy {0}", e, source);
}
} | @Test
public void testCopyFileWithRename() throws Exception {
final StoregateIdProvider fileid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, fileid).mkdir(new Path(
String.format("/My files/%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path test = new StoregateTouchFeature(session, fileid).touch(new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final Path copy = new Path(new StoregateDirectoryFeature(session, fileid).mkdir(new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
assertNotEquals(test.attributes().getFileId(), new StoregateCopyFeature(session, fileid).copy(test, copy, new TransferStatus(), new DisabledConnectionCallback(), new DisabledStreamListener()).attributes().getFileId());
assertTrue(new DefaultFindFeature(session).find(test));
assertTrue(new DefaultFindFeature(session).find(copy));
new StoregateDeleteFeature(session, fileid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException {
return loadKey(readPemFile(f), passwd);
} | @Test
public void loadKeyOpenSSHMultipleKeys() throws IOException, GeneralSecurityException {
File file = new File(this.getClass().getResource("openssh-multiple-keys").getFile());
String password = "password";
assertThrows(InvalidKeySpecException.class, () -> PrivateKeyProvider.loadKey(file, password));
} |
protected Object createAndFillObject(ObjectNode json, Object toReturn, String className, List<String> genericClasses) {
Iterator<Map.Entry<String, JsonNode>> fields = json.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> element = fields.next();
String key = element.getKey();
JsonNode jsonNode = element.getValue();
if (isSimpleTypeNode(jsonNode)) {
Map.Entry<String, List<String>> fieldDescriptor = getFieldClassNameAndGenerics(toReturn, key, className, genericClasses);
setField(toReturn, key, internalLiteralEvaluation(getSimpleTypeNodeTextValue(jsonNode), fieldDescriptor.getKey()));
} else if (jsonNode.isArray()) {
List<Object> nestedList = new ArrayList<>();
Map.Entry<String, List<String>> fieldDescriptor = getFieldClassNameAndGenerics(toReturn, key, className, genericClasses);
List<Object> returnedList = createAndFillList((ArrayNode) jsonNode, nestedList, fieldDescriptor.getKey(), fieldDescriptor.getValue());
setField(toReturn, key, returnedList);
} else if (jsonNode.isObject()) {
Map.Entry<String, List<String>> fieldDescriptor = getFieldClassNameAndGenerics(toReturn, key, className, genericClasses);
Object nestedObject = createObject(fieldDescriptor.getKey(), fieldDescriptor.getValue());
Object returnedObject = createAndFillObject((ObjectNode) jsonNode, nestedObject, fieldDescriptor.getKey(), fieldDescriptor.getValue());
setField(toReturn, key, returnedObject);
} else if (!isEmptyText(jsonNode)) {
Map.Entry<String, List<String>> fieldDescriptor = getFieldClassNameAndGenerics(toReturn, key, className, genericClasses);
setField(toReturn, key, internalLiteralEvaluation(jsonNode.textValue(), fieldDescriptor.getKey()));
} else {
// empty strings are skipped
}
}
return toReturn;
} | @Test
public void convertObject_nestedList() {
ObjectNode objectNode = new ObjectNode(factory);
ArrayNode jsonNodes = new ArrayNode(factory);
objectNode.set("listField", jsonNodes);
ObjectNode nestedObject = new ObjectNode(factory);
nestedObject.put("field", "fieldValue");
jsonNodes.add(nestedObject);
Object result = expressionEvaluator.createAndFillObject(objectNode, new HashMap<>(), String.class.getCanonicalName(), List.of());
assertThat(result).isInstanceOf(Map.class);
Map<String, Object> resultMap = (Map<String, Object>) result;
assertThat(resultMap).hasSize(1);
List<Map<String, Object>> nestedList = (List<Map<String, Object>>) resultMap.get("listField");
assertThat(nestedList).hasSize(1);
assertThat(nestedList.get(0)).containsEntry("field", "fieldValue");
} |
@Override
public int size() {
int count = 0;
for (PipelineConfigs part : this.parts) {
count += part.size();
}
return count;
} | @Test
public void shouldReturnSizeSummedFrom2ConfigParts() {
PipelineConfigs group = new MergePipelineConfigs(
new BasicPipelineConfigs(PipelineConfigMother.pipelineConfig("pipeline1")),
new BasicPipelineConfigs(PipelineConfigMother.pipelineConfig("pipeline2")));
assertThat(group.size(), is(2));
} |
@Override
public ByteBuffer[] nioBuffers() {
return nioBuffers(readerIndex, readableBytes());
} | @Test
public void testNioBuffersAfterRelease2() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().nioBuffers(0, 1);
}
});
} |
@Override
public void destroy() {
super.destroy();
cache.clear();
listener.remove();
} | @Test
public void testMapLoaderGet() {
Map<String, String> cache = new HashMap<>();
cache.put("1", "11");
cache.put("2", "22");
cache.put("3", "33");
LocalCachedMapOptions<String, String> options = LocalCachedMapOptions.<String, String>name("test")
.storeMode(LocalCachedMapOptions.StoreMode.LOCALCACHE).loader(createMapLoader(cache));
RMap<String, String> map = redisson.getLocalCachedMap(options);
assertThat(map.size()).isEqualTo(0);
assertThat(map.get("1")).isEqualTo("11");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("0")).isNull();
map.put("0", "00");
assertThat(map.get("0")).isEqualTo("00");
assertThat(map.size()).isEqualTo(2);
assertThat(map.containsKey("2")).isTrue();
assertThat(map.size()).isEqualTo(3);
Map<String, String> s = map.getAll(new HashSet<>(Arrays.asList("1", "2", "9", "3")));
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("1", "11");
expectedMap.put("2", "22");
expectedMap.put("3", "33");
assertThat(s).isEqualTo(expectedMap);
assertThat(map.size()).isEqualTo(4);
destroy(map);
} |
public boolean isKeyColumn(final ColumnName columnName) {
return findColumnMatching(withNamespace(Namespace.KEY).and(withName(columnName)))
.isPresent();
} | @Test
public void shouldMatchRowPartitionAndOffsetColumnNames() {
assertThat(SystemColumns.isPseudoColumn(ROWPARTITION_NAME), is(true));
assertThat(SystemColumns.isPseudoColumn(ROWOFFSET_NAME), is(true));
assertThat(SOME_SCHEMA.isKeyColumn(ROWPARTITION_NAME), is(false));
assertThat(SOME_SCHEMA.isKeyColumn(ROWOFFSET_NAME), is(false));
} |
@Override
protected void write(final MySQLPacketPayload payload) {
for (Object each : data) {
if (null == each) {
payload.writeInt1(NULL);
continue;
}
writeDataIntoPayload(payload, each);
}
} | @Test
void assertTimestampWithoutNanos() {
long now = System.currentTimeMillis() / 1000L * 1000L;
Timestamp timestamp = new Timestamp(now);
MySQLTextResultSetRowPacket actual = new MySQLTextResultSetRowPacket(Arrays.asList(null, "value", BigDecimal.ONE, new byte[]{}, timestamp));
actual.write(payload);
verify(payload).writeInt1(0xfb);
verify(payload).writeStringLenenc("value");
verify(payload).writeStringLenenc("1");
verify(payload).writeStringLenenc(timestamp.toString().split("\\.")[0]);
} |
public EndpointResponse checkHealth() {
return EndpointResponse.ok(getResponse());
} | @Test
public void shouldGetCachedResponse() {
// Given:
healthCheckResource.checkHealth();
// When:
final EndpointResponse response = healthCheckResource.checkHealth();
// Then:
assertThat(response.getEntity(), sameInstance(response1));
} |
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) {
if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) {
throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'.");
}
return loadManagerWrapper.get();
} | @Test(timeOut = 30 * 1000)
public void testCheckOwnershipPresentWithSystemNamespace() throws Exception {
NamespaceBundle namespaceBundle =
getBundleAsync(pulsar1, TopicName.get(NamespaceName.SYSTEM_NAMESPACE + "/test")).get();
try {
pulsar1.getNamespaceService().checkOwnershipPresent(namespaceBundle);
} catch (Exception ex) {
log.info("Got exception", ex);
assertTrue(ex.getCause() instanceof UnsupportedOperationException);
}
} |
@Override
public boolean hasNext() {
return !pathStack.isEmpty();
} | @Test
void hasNextForEmptyTree() {
var iter = new BstIterator<>(emptyRoot);
assertFalse(iter.hasNext(), "hasNext() should return false for empty tree.");
} |
public static <E> Stream<E> toStream(Iterable<E> iterable) {
checkNotNull(iterable);
return iterable instanceof Collection
? ((Collection<E>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
} | @Test
void testToStream() {
Queue<Integer> deque = new ArrayDeque<>();
testIterable.forEach(deque::add);
Stream<Integer> stream = IterableUtils.toStream(testIterable);
assertThat(stream.allMatch(value -> deque.poll().equals(value))).isTrue();
} |
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] issuers = EMPTY;
X509TrustManager tm = trustManagerRef.get();
if (tm != null) {
issuers = tm.getAcceptedIssuers();
}
return issuers;
} | @Test (timeout = 30000)
public void testReload() throws Exception {
KeyPair kp = generateKeyPair("RSA");
cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
String truststoreLocation = BASEDIR + "/testreload.jks";
createTrustStore(truststoreLocation, "password", "cert1", cert1);
long reloadInterval = 10;
Timer fileMonitoringTimer = new Timer(FileBasedKeyStoresFactory.SSL_MONITORING_THREAD_NAME, true);
final ReloadingX509TrustManager tm =
new ReloadingX509TrustManager("jks", truststoreLocation, "password");
try {
fileMonitoringTimer.schedule(new FileMonitoringTimerTask(
Paths.get(truststoreLocation), tm::loadFrom,null), reloadInterval, reloadInterval);
assertEquals(1, tm.getAcceptedIssuers().length);
// Wait so that the file modification time is different
Thread.sleep((reloadInterval+ 1000));
// Add another cert
Map<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
certs.put("cert1", cert1);
certs.put("cert2", cert2);
createTrustStore(truststoreLocation, "password", certs);
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return tm.getAcceptedIssuers().length == 2;
}
}, (int) reloadInterval, 100000);
} finally {
fileMonitoringTimer.cancel();
}
} |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testDecimalType() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder
.startAnd()
.equals("decimal", PredicateLeaf.Type.DECIMAL, new HiveDecimalWritable("20.12"))
.end()
.build();
UnboundPredicate expected = Expressions.equal("decimal", new BigDecimal("20.12"));
UnboundPredicate actual =
(UnboundPredicate) HiveIcebergFilterFactory.generateFilterExpression(arg);
assertPredicatesMatch(expected, actual);
} |
@Override
public void write(final MySQLPacketPayload payload, final Object value) {
LocalDateTime dateTime = value instanceof LocalDateTime ? (LocalDateTime) value : new Timestamp(((Date) value).getTime()).toLocalDateTime();
int year = dateTime.getYear();
int month = dateTime.getMonthValue();
int dayOfMonth = dateTime.getDayOfMonth();
int hours = dateTime.getHour();
int minutes = dateTime.getMinute();
int seconds = dateTime.getSecond();
int nanos = dateTime.getNano();
boolean isTimeAbsent = 0 == hours && 0 == minutes && 0 == seconds;
boolean isNanosAbsent = 0 == nanos;
if (isTimeAbsent && isNanosAbsent) {
payload.writeInt1(4);
writeDate(payload, year, month, dayOfMonth);
return;
}
if (isNanosAbsent) {
payload.writeInt1(7);
writeDate(payload, year, month, dayOfMonth);
writeTime(payload, hours, minutes, seconds);
return;
}
payload.writeInt1(11);
writeDate(payload, year, month, dayOfMonth);
writeTime(payload, hours, minutes, seconds);
writeNanos(payload, nanos);
} | @Test
void assertWriteWithElevenBytes() {
MySQLDateBinaryProtocolValue actual = new MySQLDateBinaryProtocolValue();
actual.write(payload, Timestamp.valueOf("1970-01-14 12:10:30.1"));
verify(payload).writeInt1(11);
verify(payload).writeInt2(1970);
verify(payload).writeInt1(1);
verify(payload).writeInt1(14);
verify(payload).writeInt1(12);
verify(payload).writeInt1(10);
verify(payload).writeInt1(30);
verify(payload).writeInt4(100000000);
} |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testRequiredColumn() {
boolean shouldRead = new StrictMetricsEvaluator(SCHEMA, notNull("required")).eval(FILE);
assertThat(shouldRead).as("Should match: required columns are always non-null").isTrue();
shouldRead = new StrictMetricsEvaluator(SCHEMA, isNull("required")).eval(FILE);
assertThat(shouldRead).as("Should not match: required columns never contain null").isFalse();
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final String prefix = containerService.isContainer(directory) ? StringUtils.EMPTY : containerService.getKey(directory) + Path.DELIMITER;
return this.list(directory, listener, prefix);
} | @Test
public void testListNotFoundFolder() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final String name = new AlphanumericRandomStringService().random();
try {
new SwiftObjectListService(session).list(new Path(container, name, EnumSet.of(Path.Type.directory)), new DisabledListProgressListener());
fail();
}
catch(NotfoundException e) {
// Expected
}
final Path file = new SwiftTouchFeature(session, new SwiftRegionService(session)).touch(new Path(container, String.format("%s-", name), EnumSet.of(Path.Type.file)), new TransferStatus());
try {
new SwiftObjectListService(session).list(new Path(container, name, EnumSet.of(Path.Type.directory)), new DisabledListProgressListener());
fail();
}
catch(NotfoundException e) {
// Expected
}
new SwiftDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
@Override
public Iterable<GenericRow> transform(
final K readOnlyKey,
final GenericRow value,
final KsqlProcessingContext ctx
) {
if (value == null) {
return null;
}
final List<Iterator<?>> iters = new ArrayList<>(tableFunctionAppliers.size());
int maxLength = 0;
for (final TableFunctionApplier applier : tableFunctionAppliers) {
final List<?> exploded = applier.apply(value, processingLogger);
iters.add(exploded.iterator());
maxLength = Math.max(maxLength, exploded.size());
}
final List<GenericRow> rows = new ArrayList<>(maxLength);
for (int i = 0; i < maxLength; i++) {
final GenericRow newRow = new GenericRow(value.values().size() + iters.size());
newRow.appendAll(value.values());
for (final Iterator<?> iter : iters) {
if (iter.hasNext()) {
newRow.append(iter.next());
} else {
newRow.append(null);
}
}
rows.add(newRow);
}
return rows;
} | @Test
public void shouldPassCorrectParamsToTableFunctionAppliers() {
// Given:
final TableFunctionApplier applier = createApplier(Arrays.asList(10, 10, 10));
final KudtfFlatMapper<String> flatMapper =
new KudtfFlatMapper<>(ImmutableList.of(applier), processingLogger);
// When:
flatMapper.transform(KEY, VALUE, ctx);
// Then:
verify(applier).apply(VALUE, processingLogger);
} |
public int maxPayloadSize() {
return maxPayloadSize;
} | @Test
void maxPayloadSize() {
assertThat(builder.build().maxPayloadSize()).isEqualTo(DEFAULT_MAX_PAYLOAD_SIZE);
builder.maxPayloadSize(1024);
assertThat(builder.build().maxPayloadSize()).isEqualTo(1024);
} |
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
checkArgument(b.signum() >= 0, () -> "b must be positive or zero: " + b);
checkArgument(numBytes > 0, () -> "numBytes must be positive: " + numBytes);
byte[] src = b.toByteArray();
byte[] dest = new byte[numBytes];
boolean isFirstByteOnlyForSign = src[0] == 0;
int length = isFirstByteOnlyForSign ? src.length - 1 : src.length;
checkArgument(length <= numBytes, () -> "The given number does not fit in " + numBytes);
int srcPos = isFirstByteOnlyForSign ? 1 : 0;
int destPos = numBytes - length;
System.arraycopy(src, srcPos, dest, destPos, length);
return dest;
} | @Test
public void bigIntegerToBytes_paddedSingleByte() {
BigInteger b = BigInteger.valueOf(0b0000_1111);
byte[] expected = new byte[]{0, 0b0000_1111};
byte[] actual = ByteUtils.bigIntegerToBytes(b, 2);
assertArrayEquals(expected, actual);
} |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_empty_optional_object() {
registry.setDefaultDataTableEntryTransformer(TABLE_ENTRY_BY_TYPE_CONVERTER_SHOULD_NOT_BE_USED);
registry.setDefaultDataTableCellTransformer(TABLE_CELL_BY_TYPE_CONVERTER_SHOULD_NOT_BE_USED);
DataTable table = parse("");
registry.defineDataTableType(new DataTableType(ChessBoard.class, CHESS_BOARD_TABLE_TRANSFORMER));
assertEquals(Optional.empty(), converter.convert(table, OPTIONAL_CHESS_BOARD_TYPE));
} |
protected String getTag(ILoggingEvent event) {
// format tag based on encoder layout; truncate if max length
// exceeded (only necessary for isLoggable(), which throws
// IllegalArgumentException)
String tag = (this.tagEncoder != null) ? this.tagEncoder.getLayout().doLayout(event) : event.getLoggerName();
if (checkLoggable && (tag.length() > MAX_TAG_LENGTH)) {
tag = tag.substring(0, MAX_TAG_LENGTH - 1) + "*";
}
return tag;
} | @Test
public void longTagTruncatedIfCheckLoggable() {
LoggingEvent event = new LoggingEvent();
event.setMessage(TAG);
boolean checkLoggable = true;
setTagPattern(TAG, checkLoggable);
String actualTag = logcatAppender.getTag(event);
assertThat(TRUNCATED_TAG, is(actualTag));
assertThat(TAG, is(not(actualTag)));
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testWeb3ClientVersion() throws Exception {
web3j.web3ClientVersion().send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\",\"params\":[],\"id\":1}");
} |
@Override
public String getWelcomeMessage(final User user) {
if (isEnhanced()) {
return "Welcome " + user + ". You're using the enhanced welcome message.";
}
return "Welcome to the application.";
} | @Test
void testFeatureTurnedOff() {
final var properties = new Properties();
properties.put("enhancedWelcome", false);
var service = new PropertiesFeatureToggleVersion(properties);
assertFalse(service.isEnhanced());
final var welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code"));
assertEquals("Welcome to the application.", welcomeMessage);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.