focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
static InetSocketAddress parse(
final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver)
{
if (Strings.isEmpty(value))
{
throw new NullPointerException("input string must not be null or empty");
}
final String nameAndPort = nameResolver.lookup(value, uriParamName, isReResolution);
ParseResult result = tryParseIpV4(nameAndPort);
if (null == result)
{
result = tryParseIpV6(nameAndPort);
}
if (null == result)
{
throw new IllegalArgumentException("invalid format: " + nameAndPort);
}
final InetAddress inetAddress = nameResolver.resolve(result.host, uriParamName, isReResolution);
return null == inetAddress ? InetSocketAddress.createUnresolved(result.host, result.port) :
new InetSocketAddress(inetAddress, result.port);
} | @Test
void shouldRejectOnEmptyIpV6Port()
{
assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse(
"[::1]:", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER));
} |
public RemoteStorageManager storageManager() {
return remoteLogStorageManager;
} | @Test
void testGetClassLoaderAwareRemoteStorageManager() throws Exception {
ClassLoaderAwareRemoteStorageManager rsmManager = mock(ClassLoaderAwareRemoteStorageManager.class);
try (RemoteLogManager remoteLogManager =
new RemoteLogManager(config.remoteLogManagerConfig(), brokerId, logDir, clusterId, time,
t -> Optional.empty(),
(topicPartition, offset) -> { },
brokerTopicStats, metrics) {
public RemoteStorageManager createRemoteStorageManager() {
return rsmManager;
}
}
) {
assertEquals(rsmManager, remoteLogManager.storageManager());
}
} |
@Implementation
protected HttpResponse execute(
HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext)
throws HttpException, IOException {
if (FakeHttp.getFakeHttpLayer().isInterceptingHttpRequests()) {
return FakeHttp.getFakeHttpLayer()
.emulateRequest(httpHost, httpRequest, httpContext, realObject);
} else {
FakeHttp.getFakeHttpLayer()
.addRequestInfo(new HttpRequestInfo(httpRequest, httpHost, httpContext, redirector));
HttpResponse response = redirector.execute(httpHost, httpRequest, httpContext);
if (FakeHttp.getFakeHttpLayer().isInterceptingResponseContent()) {
interceptResponseContent(response);
}
FakeHttp.getFakeHttpLayer().addHttpResponse(response);
return response;
}
} | @Test
public void shouldSupportSocketTimeoutWithExceptions() throws Exception {
FakeHttp.setDefaultHttpResponse(
new TestHttpResponse() {
@Override
public HttpParams getParams() {
HttpParams httpParams = super.getParams();
HttpConnectionParams.setSoTimeout(httpParams, -1);
return httpParams;
}
});
DefaultHttpClient client = new DefaultHttpClient();
try {
client.execute(new HttpGet("http://www.nowhere.org"));
} catch (ConnectTimeoutException x) {
return;
}
fail("Exception should have been thrown");
} |
public static String computeQueryHash(String query)
{
requireNonNull(query, "query is null");
if (query.isEmpty()) {
return "";
}
byte[] queryBytes = query.getBytes(UTF_8);
long queryHash = new XxHash64().update(queryBytes).hash();
return toHexString(queryHash);
} | @Test
public void testComputeQueryHashLongQuery()
{
String longQuery = "SELECT x" + repeat(",x", 500_000) + " FROM (VALUES 1,2,3,4,5) t(x)";
assertEquals(computeQueryHash(longQuery), "26691c4d35d09c7b");
} |
@Override
public Response toResponse(final IllegalStateException exception) {
final String message = exception.getMessage();
if (LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR().equals(message)) {
/*
* If a POST request contains a Content-Type that is not application/x-www-form-urlencoded, Jersey throws
* IllegalStateException with or without @Consumes. See: https://java.net/jira/browse/JERSEY-2636
*/
// Logs exception with additional information for developers.
logger.debug("If the HTTP method is POST and using @FormParam in a resource method"
+ ", Content-Type should be application/x-www-form-urlencoded.", exception);
// Returns the same response as if NotSupportedException was thrown.
return createResponse(new NotSupportedException());
}
// LoggingExceptionMapper will log exception
return super.toResponse(exception);
} | @Test
void delegatesToParentClass() {
@SuppressWarnings("serial")
final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {
});
assertThat(reponse.getStatusInfo()).isEqualTo(INTERNAL_SERVER_ERROR);
} |
public static String generateServerId() {
return UUID.randomUUID().toString();
} | @Test
public void testGenerateServerId() {
String id = Tools.generateServerId();
/*
* Make sure it has dashes in it. We need that to build a short ID later.
* Short version: Everything falls apart if this is not an UUID-style ID.
*/
assertTrue(id.contains("-"));
} |
@Override
public Table getTable(String dbName, String tblName) {
JDBCTableName jdbcTable = new JDBCTableName(null, dbName, tblName);
return tableInstanceCache.get(jdbcTable,
k -> {
try (Connection connection = getConnection()) {
ResultSet columnSet = schemaResolver.getColumns(connection, dbName, tblName);
List<Column> fullSchema = schemaResolver.convertToSRTable(columnSet);
List<Column> partitionColumns = Lists.newArrayList();
if (schemaResolver.isSupportPartitionInformation()) {
partitionColumns = listPartitionColumns(dbName, tblName, fullSchema);
}
if (fullSchema.isEmpty()) {
return null;
}
Integer tableId = tableIdCache.getPersistentCache(jdbcTable,
j -> ConnectorTableId.CONNECTOR_ID_GENERATOR.getNextId().asInt());
return schemaResolver.getTable(tableId, tblName, fullSchema,
partitionColumns, dbName, catalogName, properties);
} catch (SQLException | DdlException e) {
LOG.warn("get table for JDBC catalog fail!", e);
return null;
}
});
} | @Test
public void testColumnTypes() {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
Table table = jdbcMetadata.getTable("test", "tbl1");
List<Column> columns = table.getColumns();
Assert.assertEquals(columns.size(), columnResult.getRowCount());
Assert.assertTrue(columns.get(0).getType().equals(ScalarType.createType(PrimitiveType.INT)));
Assert.assertTrue(columns.get(1).getType().equals(ScalarType.createUnifiedDecimalType(10, 2)));
Assert.assertTrue(columns.get(2).getType().equals(ScalarType.createCharType(10)));
Assert.assertTrue(columns.get(3).getType().equals(ScalarType.createVarcharType(10)));
Assert.assertTrue(columns.get(4).getType().equals(ScalarType.createType(PrimitiveType.SMALLINT)));
Assert.assertTrue(columns.get(5).getType().equals(ScalarType.createType(PrimitiveType.INT)));
Assert.assertTrue(columns.get(6).getType().equals(ScalarType.createType(PrimitiveType.BIGINT)));
Assert.assertTrue(columns.get(7).getType().equals(ScalarType.createType(PrimitiveType.LARGEINT)));
Assert.assertTrue(columns.get(8).getType().equals(ScalarType.createType(PrimitiveType.TINYINT)));
Assert.assertTrue(columns.get(9).getType().equals(ScalarType.createType(PrimitiveType.SMALLINT)));
Assert.assertTrue(columns.get(10).getType().equals(ScalarType.createType(PrimitiveType.INT)));
Assert.assertTrue(columns.get(11).getType().equals(ScalarType.createType(PrimitiveType.BIGINT)));
Assert.assertTrue(columns.get(12).getType().equals(ScalarType.createType(PrimitiveType.DATE)));
Assert.assertTrue(columns.get(13).getType().equals(ScalarType.createType(PrimitiveType.TIME)));
Assert.assertTrue(columns.get(14).getType().equals(ScalarType.createType(PrimitiveType.DATETIME)));
} |
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) {
IClientConfig clientConfig = getRequestClientConfig(request);
Long originTimeout = getOriginReadTimeout();
Long requestTimeout = getRequestReadTimeout(clientConfig);
long computedTimeout;
if (originTimeout == null && requestTimeout == null) {
computedTimeout = MAX_OUTBOUND_READ_TIMEOUT_MS.get();
} else if (originTimeout == null || requestTimeout == null) {
computedTimeout = originTimeout == null ? requestTimeout : originTimeout;
} else {
// return the stricter (i.e. lower) of the two timeouts
computedTimeout = Math.min(originTimeout, requestTimeout);
}
// enforce max timeout upperbound
return Duration.ofMillis(Math.min(computedTimeout, MAX_OUTBOUND_READ_TIMEOUT_MS.get()));
} | @Test
void computeReadTimeout_bolth_requestLower() {
requestConfig.set(CommonClientConfigKey.ReadTimeout, 100);
originConfig.set(CommonClientConfigKey.ReadTimeout, 1000);
Duration timeout = originTimeoutManager.computeReadTimeout(request, 1);
assertEquals(100, timeout.toMillis());
} |
public static DoFnInstanceManager cloningPool(DoFnInfo<?, ?> info, PipelineOptions options) {
return new ConcurrentQueueInstanceManager(info, options);
} | @Test
public void testCloningPoolReusesAfterComplete() throws Exception {
DoFnInfo<?, ?> info =
DoFnInfo.forFn(
initialFn,
WindowingStrategy.globalDefault(),
null /* side input views */,
null /* input coder */,
new TupleTag<>(PropertyNames.OUTPUT) /* main output id */,
DoFnSchemaInformation.create(),
Collections.emptyMap());
DoFnInstanceManager mgr = DoFnInstanceManagers.cloningPool(info, options);
DoFnInfo<?, ?> retrievedInfo = mgr.get();
assertThat(retrievedInfo, not(Matchers.<DoFnInfo<?, ?>>theInstance(info)));
assertThat(retrievedInfo.getDoFn(), not(theInstance(info.getDoFn())));
mgr.complete(retrievedInfo);
DoFnInfo<?, ?> afterCompleteInfo = mgr.get();
assertThat(afterCompleteInfo, Matchers.<DoFnInfo<?, ?>>theInstance(retrievedInfo));
assertThat(afterCompleteInfo.getDoFn(), theInstance(retrievedInfo.getDoFn()));
} |
@Override
public void onDiscoveredSplits(Collection<IcebergSourceSplit> splits) {
addSplits(splits);
} | @Test
public void testMultipleFilesInASplit() throws Exception {
SplitAssigner assigner = splitAssigner();
assigner.onDiscoveredSplits(
SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 4, 2));
assertGetNext(assigner, GetSplitResult.Status.AVAILABLE);
assertSnapshot(assigner, 1);
assertGetNext(assigner, GetSplitResult.Status.AVAILABLE);
assertGetNext(assigner, GetSplitResult.Status.UNAVAILABLE);
assertSnapshot(assigner, 0);
} |
@Override
public ValidationResult responseMessageForPluginSettingsValidation(String responseBody) {
return jsonResultMessageHandler.toValidationResult(responseBody);
} | @Test
public void shouldBuildValidationResultFromCheckSCMConfigurationValidResponse() throws Exception {
String responseBody = "[{\"key\":\"key-one\",\"message\":\"incorrect value\"},{\"message\":\"general error\"}]";
ValidationResult validationResult = messageHandler.responseMessageForPluginSettingsValidation(responseBody);
assertValidationError(validationResult.getErrors().get(0), "key-one", "incorrect value");
assertValidationError(validationResult.getErrors().get(1), "", "general error");
} |
public void start() {
commandTopicBackup.initialize();
commandConsumer.assign(Collections.singleton(commandTopicPartition));
} | @Test
public void shouldAssignCorrectPartitionToConsumer() {
// When:
commandTopic.start();
// Then:
verify(commandConsumer)
.assign(eq(Collections.singleton(new TopicPartition(COMMAND_TOPIC_NAME, 0))));
} |
public void dropMapping(String mappingName) {
StringBuilder sb = new StringBuilder()
.append("DROP MAPPING IF EXISTS ");
DIALECT.quoteIdentifier(sb, mappingName);
sqlService.execute(sb.toString()).close();
} | @Test
public void when_dropMapping_then_quoteMappingName() {
mappingHelper.dropMapping("myMapping");
verify(sqlService).execute("DROP MAPPING IF EXISTS \"myMapping\"");
} |
public String toBaseMessageIdString(Object messageId) {
if (messageId == null) {
return null;
} else if (messageId instanceof String) {
String stringId = (String) messageId;
// If the given string has a type encoding prefix,
// we need to escape it as an encoded string (even if
// the existing encoding prefix was also for string)
if (hasTypeEncodingPrefix(stringId)) {
return AMQP_STRING_PREFIX + stringId;
} else {
return stringId;
}
} else if (messageId instanceof UUID) {
return AMQP_UUID_PREFIX + messageId.toString();
} else if (messageId instanceof UnsignedLong) {
return AMQP_ULONG_PREFIX + messageId.toString();
} else if (messageId instanceof Binary) {
ByteBuffer dup = ((Binary) messageId).asByteBuffer();
byte[] bytes = new byte[dup.remaining()];
dup.get(bytes);
String hex = convertBinaryToHexString(bytes);
return AMQP_BINARY_PREFIX + hex;
} else {
throw new IllegalArgumentException("Unsupported type provided: " + messageId.getClass());
}
} | @Test
public void testToBaseMessageIdStringWithStringBeginningWithEncodingPrefixForString() {
String stringMessageId = AMQPMessageIdHelper.AMQP_STRING_PREFIX + "myStringId";
String expected = AMQPMessageIdHelper.AMQP_STRING_PREFIX + stringMessageId;
String baseMessageIdString = messageIdHelper.toBaseMessageIdString(stringMessageId);
assertNotNull("null string should not have been returned", baseMessageIdString);
assertEquals("expected base id string was not returned", expected, baseMessageIdString);
} |
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for each scope: access and default.
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry aclSpecEntry: aclSpec) {
scopeDirty.add(aclSpecEntry.getScope());
if (aclSpecEntry.getType() == MASK) {
providedMask.put(aclSpecEntry.getScope(), aclSpecEntry);
maskDirty.add(aclSpecEntry.getScope());
} else {
aclBuilder.add(aclSpecEntry);
}
}
// Copy existing entries if the scope was not replaced.
for (AclEntry existingEntry: existingAcl) {
if (!scopeDirty.contains(existingEntry.getScope())) {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
} | @Test(expected=AclException.class)
public void testReplaceAclEntriesDuplicateEntries() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
List<AclEntry> aclSpec = Lists.newArrayList(
aclEntry(ACCESS, USER, ALL),
aclEntry(ACCESS, USER, "bruce", ALL),
aclEntry(ACCESS, USER, "diana", READ_WRITE),
aclEntry(ACCESS, USER, "clark", READ),
aclEntry(ACCESS, USER, "bruce", READ_EXECUTE),
aclEntry(ACCESS, GROUP, READ),
aclEntry(ACCESS, OTHER, NONE));
replaceAclEntries(existing, aclSpec);
} |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttpEntityCallable<StorageObject>(file) {
@Override
public StorageObject call(final HttpEntity entity) throws BackgroundException {
try {
// POST /upload/storage/v1/b/myBucket/o
final StringBuilder uri = new StringBuilder(String.format("%supload/storage/v1/b/%s/o?uploadType=resumable",
session.getClient().getRootUrl(), containerService.getContainer(file).getName()));
if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) {
uri.append(String.format("&userProject=%s", session.getHost().getCredentials().getUsername()));
}
if(!Acl.EMPTY.equals(status.getAcl())) {
if(status.getAcl().isCanned()) {
uri.append("&predefinedAcl=");
if(Acl.CANNED_PRIVATE.equals(status.getAcl())) {
uri.append("private");
}
else if(Acl.CANNED_PUBLIC_READ.equals(status.getAcl())) {
uri.append("publicRead");
}
else if(Acl.CANNED_PUBLIC_READ_WRITE.equals(status.getAcl())) {
uri.append("publicReadWrite");
}
else if(Acl.CANNED_AUTHENTICATED_READ.equals(status.getAcl())) {
uri.append("authenticatedRead");
}
else if(Acl.CANNED_BUCKET_OWNER_FULLCONTROL.equals(status.getAcl())) {
uri.append("bucketOwnerFullControl");
}
else if(Acl.CANNED_BUCKET_OWNER_READ.equals(status.getAcl())) {
uri.append("bucketOwnerRead");
}
// Reset in status to skip setting ACL in upload filter already applied as canned ACL
status.setAcl(Acl.EMPTY);
}
}
final HttpEntityEnclosingRequestBase request = new HttpPost(uri.toString());
final StringBuilder metadata = new StringBuilder();
metadata.append(String.format("{\"name\": \"%s\"", containerService.getKey(file)));
metadata.append(",\"metadata\": {");
for(Iterator<Map.Entry<String, String>> iter = status.getMetadata().entrySet().iterator(); iter.hasNext(); ) {
final Map.Entry<String, String> item = iter.next();
metadata.append(String.format("\"%s\": \"%s\"", item.getKey(), item.getValue()));
if(iter.hasNext()) {
metadata.append(",");
}
}
metadata.append("}");
if(StringUtils.isNotBlank(status.getMime())) {
metadata.append(String.format(", \"contentType\": \"%s\"", status.getMime()));
}
if(StringUtils.isNotBlank(status.getStorageClass())) {
metadata.append(String.format(", \"storageClass\": \"%s\"", status.getStorageClass()));
}
if(null != status.getModified()) {
metadata.append(String.format(", \"customTime\": \"%s\"",
new ISO8601DateFormatter().format(status.getModified(), TimeZone.getTimeZone("UTC"))));
}
metadata.append("}");
request.setEntity(new StringEntity(metadata.toString(),
ContentType.create("application/json", StandardCharsets.UTF_8.name())));
if(StringUtils.isNotBlank(status.getMime())) {
// Set to the media MIME type of the upload data to be transferred in subsequent requests.
request.addHeader("X-Upload-Content-Type", status.getMime());
}
request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
final HttpClient client = session.getHttpClient();
final HttpResponse response = client.execute(request);
try {
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
break;
default:
throw new DefaultHttpResponseExceptionMappingService().map("Upload {0} failed",
new HttpResponseException(response.getStatusLine().getStatusCode(),
GoogleStorageExceptionMappingService.parse(response)), file);
}
}
finally {
EntityUtils.consume(response.getEntity());
}
if(response.containsHeader(HttpHeaders.LOCATION)) {
final String putTarget = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
// Upload the file
final HttpPut put = new HttpPut(putTarget);
put.setEntity(entity);
final HttpResponse putResponse = client.execute(put);
try {
switch(putResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
return session.getClient().getObjectParser().parseAndClose(new InputStreamReader(
putResponse.getEntity().getContent(), StandardCharsets.UTF_8), StorageObject.class);
default:
throw new DefaultHttpResponseExceptionMappingService().map("Upload {0} failed",
new HttpResponseException(putResponse.getStatusLine().getStatusCode(),
GoogleStorageExceptionMappingService.parse(putResponse)), file);
}
}
finally {
EntityUtils.consume(putResponse.getEntity());
}
}
else {
throw new DefaultHttpResponseExceptionMappingService().map("Upload {0} failed",
new HttpResponseException(response.getStatusLine().getStatusCode(),
GoogleStorageExceptionMappingService.parse(response)), file);
}
}
catch(IOException e) {
throw new GoogleStorageExceptionMappingService().map("Upload {0} failed", e, file);
}
}
@Override
public long getContentLength() {
return status.getLength();
}
};
return this.write(file, status, command);
} | @Test
public void testWritePublicReadCannedPublicAcl() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(1033);
status.setLength(content.length);
status.setAcl(Acl.CANNED_PUBLIC_READ);
final HttpResponseOutputStream<StorageObject> out = new GoogleStorageWriteFeature(session).write(test, status, new DisabledConnectionCallback());
new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
out.close();
assertNotNull(out.getStatus().getGeneration());
assertTrue(new GoogleStorageFindFeature(session).find(test));
assertTrue(new GoogleStorageAccessControlListFeature(session)
.getPermission(test).asList().contains(new Acl.UserAndRole(new Acl.GroupUser(Acl.GroupUser.EVERYONE), new Acl.Role(Acl.Role.READ))));
new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
public void verifyStatus() {
if (sequential) {
boolean unopenedIterator = responseIterator == null && !responses.isEmpty();
if (unopenedIterator || responseIterator.hasNext()) {
throw new VerificationAssertionError("More executions were expected");
}
}
} | @Test
void hitMock() {
List<Contributor> contributors = github.contributors("netflix", "feign");
assertThat(contributors).hasSize(30);
mockClient.verifyStatus();
} |
public static String[] getPathComponents(String path) throws InvalidPathException {
path = cleanPath(path);
if (isRoot(path)) {
return new String[]{""};
}
return path.split(AlluxioURI.SEPARATOR);
} | @Test
public void getPathComponentsException() throws InvalidPathException {
mException.expect(InvalidPathException.class);
PathUtils.getPathComponents("");
} |
@VisibleForTesting
AuthRequest buildAuthRequest(Integer socialType, Integer userType) {
// 1. 先查找默认的配置项,从 application-*.yaml 中读取
AuthRequest request = authRequestFactory.get(SocialTypeEnum.valueOfType(socialType).getSource());
Assert.notNull(request, String.format("社交平台(%d) 不存在", socialType));
// 2. 查询 DB 的配置项,如果存在则进行覆盖
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(socialType, userType);
if (client != null && Objects.equals(client.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
// 2.1 构造新的 AuthConfig 对象
AuthConfig authConfig = (AuthConfig) ReflectUtil.getFieldValue(request, "config");
AuthConfig newAuthConfig = ReflectUtil.newInstance(authConfig.getClass());
BeanUtil.copyProperties(authConfig, newAuthConfig);
// 2.2 修改对应的 clientId + clientSecret 密钥
newAuthConfig.setClientId(client.getClientId());
newAuthConfig.setClientSecret(client.getClientSecret());
if (client.getAgentId() != null) { // 如果有 agentId 则修改 agentId
newAuthConfig.setAgentId(client.getAgentId());
}
// 2.3 设置会 request 里,进行后续使用
ReflectUtil.setFieldValue(request, "config", newAuthConfig);
}
return request;
} | @Test
public void testBuildAuthRequest_clientDisable() {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(SocialTypeEnum.class).getType();
// mock 获得对应的 AuthRequest 实现
AuthRequest authRequest = mock(AuthDefaultRequest.class);
AuthConfig authConfig = (AuthConfig) ReflectUtil.getFieldValue(authRequest, "config");
when(authRequestFactory.get(eq("WECHAT_MP"))).thenReturn(authRequest);
// mock 数据
SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())
.setUserType(userType).setSocialType(socialType));
socialClientMapper.insert(client);
// 调用
AuthRequest result = socialClientService.buildAuthRequest(socialType, userType);
// 断言
assertSame(authRequest, result);
assertSame(authConfig, ReflectUtil.getFieldValue(authConfig, "config"));
} |
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testWriteMessageWithError() throws Exception {
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add("Message " + i);
}
WriteJmsResult<String> output =
pipeline
.apply(Create.of(data))
.apply(
JmsIO.<String>write()
.withConnectionFactory(connectionFactory)
.withValueMapper(new TextMessageMapperWithError())
.withRetryConfiguration(retryConfiguration)
.withQueue(QUEUE)
.withUsername(USERNAME)
.withPassword(PASSWORD));
PAssert.that(output.getFailedMessages()).containsInAnyOrder("Message 1", "Message 2");
pipeline.run();
assertQueueContainsMessages(98);
} |
public void validate(DataConnectionConfig dataConnectionConfig) {
int numberOfSetItems = getNumberOfSetItems(dataConnectionConfig, CLIENT_XML_PATH, CLIENT_YML_PATH, CLIENT_XML,
CLIENT_YML);
if (numberOfSetItems != 1) {
throw new HazelcastException("HazelcastDataConnection with name '" + dataConnectionConfig.getName()
+ "' could not be created, "
+ "provide either a file path with one of "
+ "\"client_xml_path\" or \"client_yml_path\" properties "
+ "or a string content with one of \"client_xml\" or \"client_yml\" properties "
+ "for the client configuration.");
}
} | @Test
public void testValidateNone() {
DataConnectionConfig dataConnectionConfig = new DataConnectionConfig();
HazelcastDataConnectionConfigValidator validator = new HazelcastDataConnectionConfigValidator();
assertThatThrownBy(() -> validator.validate(dataConnectionConfig))
.isInstanceOf(HazelcastException.class);
} |
@Override
public void execute(ComputationStep.Context context) {
VisitorsCrawler visitorsCrawler = new VisitorsCrawler(visitors, LOGGER.isDebugEnabled());
visitorsCrawler.visit(treeRootHolder.getRoot());
logVisitorExecutionDurations(visitors, visitorsCrawler);
} | @Test
public void execute_with_type_aware_visitor() {
ExecuteVisitorsStep underStep = new ExecuteVisitorsStep(treeRootHolder, singletonList(new TestTypeAwareVisitor()));
measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(1));
measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(2));
measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(3));
measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(3));
underStep.execute(new TestComputationStepContext());
assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(2);
assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(3);
assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(4);
assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(4);
} |
@Override
public void submit(Intent intent) {
checkPermission(INTENT_WRITE);
checkNotNull(intent, INTENT_NULL);
IntentData data = IntentData.submit(intent);
store.addPending(data);
} | @Ignore("skipping until we fix update ordering problem")
@Test
public void errorIntentInstallFromFlows() {
final Long id = MockIntent.nextId();
flowRuleService.setFuture(false);
MockIntent intent = new MockIntent(id);
listener.setLatch(1, Type.FAILED);
listener.setLatch(1, Type.INSTALL_REQ);
service.submit(intent);
listener.await(Type.INSTALL_REQ);
listener.await(Type.FAILED);
// FIXME the intent will be moved into INSTALLED immediately which overrides FAILED
// ... the updates come out of order
verifyState();
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
}
} | @Test
public void endpointsByNamespace() throws JsonProcessingException {
// given
stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsList(
pod("hazelcast-0", NAMESPACE, "node-name-1", "192.168.0.25", 5701),
pod("hazelcast-0", NAMESPACE, "node-name-1", "172.17.0.5", 5702),
notReadyPod("hazelcast-0", NAMESPACE, "node-name-1", "172.17.0.7")));
stub(String.format("/api/v1/namespaces/%s/pods/hazelcast-0", NAMESPACE),
pod("hazelcast-0", NAMESPACE, "node-name-1", 5701));
stub(String.format("/api/v1/namespaces/%s/pods/hazelcast-1", NAMESPACE),
pod("hazelcast-1", NAMESPACE, "node-name-2", 5701));
// when
List<Endpoint> result = kubernetesClient.endpoints();
// then
assertThat(formatPrivate(result)).containsExactlyInAnyOrder(ready("192.168.0.25", 5701), ready("172.17.0.5", 5702), notReady("172.17.0.7", null));
} |
public void createConnection() {
try {
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.initializeVariablesFrom( null );
getDatabaseDialog().setDatabaseMeta( databaseMeta );
String dbName = getDatabaseDialog().open();
if ( dbName != null ) {
dbName = dbName.trim();
databaseMeta.setName( dbName );
databaseMeta.setDisplayName( dbName );
getDatabaseDialog().setDatabaseMeta( databaseMeta );
if ( !dbName.isEmpty() ) {
// See if this user connection exists...
ObjectId idDatabase = repository.getDatabaseID( dbName );
if ( idDatabase == null ) {
repository.insertLogEntry( BaseMessages.getString(
PKG, "ConnectionsController.Message.CreatingDatabase", getDatabaseDialog()
.getDatabaseMeta().getName() ) );
repository.save( getDatabaseDialog().getDatabaseMeta(), Const.VERSION_COMMENT_INITIAL_VERSION, null );
reloadLoadedJobsAndTransformations();
} else {
showAlreadyExistsMessage();
}
}
}
// We should be able to tell the difference between a cancel and an empty database name
//
// else {
// MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
// mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Message"));
// mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Title"));
// mb.open();
// }
} catch ( KettleException e ) {
if ( mainController == null || !mainController.handleLostRepository( e ) ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Title" ),
BaseMessages.getString( PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Message" ), e );
}
} finally {
refreshConnectionList();
}
} | @Test
public void createConnection_NameExists() throws Exception {
final String dbName = "name";
when( databaseDialog.open() ).thenReturn( dbName );
when( databaseMeta.getDatabaseName() ).thenReturn( dbName );
when( repository.getDatabaseID( dbName ) ).thenReturn( new StringObjectId( "existing" ) );
controller.createConnection();
assertShowedAlreadyExistsMessage();
} |
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
final DescriptiveUrl that = (DescriptiveUrl) o;
return Objects.equals(url, that.url);
} | @Test
public void testEquals() {
assertEquals(new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.provider, "a"), new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.provider, "b"));
assertNotEquals(new DescriptiveUrl(URI.create("http://host.domainb"), DescriptiveUrl.Type.provider, "a"), new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.provider, "b"));
assertEquals(new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.http), new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.http));
assertEquals("http://host.domain", new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.http).getUrl());
} |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type = ruleFactory.getObjectRule().apply(nodeName, node, parent, jClassContainer.getPackage(), schema);
} else if (node.has("existingJavaType")) {
String typeName = node.path("existingJavaType").asText();
if (isPrimitive(typeName, jClassContainer.owner())) {
type = primitiveType(typeName, jClassContainer.owner());
} else {
type = resolveType(jClassContainer, typeName);
}
} else if (propertyTypeName.equals("string")) {
type = jClassContainer.owner().ref(String.class);
} else if (propertyTypeName.equals("number")) {
type = getNumberType(jClassContainer.owner(), ruleFactory.getGenerationConfig());
} else if (propertyTypeName.equals("integer")) {
type = getIntegerType(jClassContainer.owner(), node, ruleFactory.getGenerationConfig());
} else if (propertyTypeName.equals("boolean")) {
type = unboxIfNecessary(jClassContainer.owner().ref(Boolean.class), ruleFactory.getGenerationConfig());
} else if (propertyTypeName.equals("array")) {
type = ruleFactory.getArrayRule().apply(nodeName, node, parent, jClassContainer.getPackage(), schema);
} else {
type = jClassContainer.owner().ref(Object.class);
}
if (!node.has("javaType") && !node.has("existingJavaType") && node.has("format")) {
type = ruleFactory.getFormatRule().apply(nodeName, node.get("format"), node, type, schema);
} else if (!node.has("javaType") && !node.has("existingJavaType") && propertyTypeName.equals("string") && node.has("media")) {
type = ruleFactory.getMediaRule().apply(nodeName, node.get("media"), node, type, schema);
}
return type;
} | @Test
public void applyGeneratesIntegerUsingJavaTypeInteger() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "integer");
objectNode.put("existingJavaType", "java.lang.Integer");
when(config.isUsePrimitives()).thenReturn(true);
JType result = rule.apply("fooBar", objectNode, null, jpackage, null);
assertThat(result.fullName(), is("java.lang.Integer"));
} |
@Override
public NativeEntity<LookupTableDto> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
String username) {
if (entity instanceof EntityV1) {
return decode((EntityV1) entity, parameters, nativeEntities);
} else {
throw new IllegalArgumentException("Unsupported entity version: " + entity.getClass());
}
} | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.LOOKUP_TABLE_V1)
.data(objectMapper.convertValue(LookupTableEntity.create(
ValueReference.of(DefaultEntityScope.NAME),
ValueReference.of("http-dsv-no-cache"),
ValueReference.of("HTTP DSV without Cache"),
ValueReference.of("HTTP DSV without Cache"),
ValueReference.of("no-op-cache"),
ValueReference.of("http-dsv"),
ValueReference.of("Default single value"),
ValueReference.of(LookupDefaultValue.Type.STRING),
ValueReference.of("Default multi value"),
ValueReference.of(LookupDefaultValue.Type.OBJECT)), JsonNode.class))
.build();
final EntityDescriptor cacheDescriptor = EntityDescriptor.create("no-op-cache", ModelTypes.LOOKUP_CACHE_V1);
final CacheDto cacheDto = CacheDto.builder()
.id("5adf24b24b900a0fdb4e0001")
.name("no-op-cache")
.title("No-op cache")
.description("No-op cache")
.config(new FallbackCacheConfig())
.build();
final EntityDescriptor dataAdapterDescriptor = EntityDescriptor.create("http-dsv", ModelTypes.LOOKUP_ADAPTER_V1);
final DataAdapterDto dataAdapterDto = DataAdapterDto.builder()
.id("5adf24a04b900a0fdb4e0002")
.name("http-dsv")
.title("HTTP DSV")
.description("HTTP DSV")
.config(new FallbackAdapterConfig())
.build();
final Map<EntityDescriptor, Object> nativeEntities = ImmutableMap.of(
cacheDescriptor, cacheDto,
dataAdapterDescriptor, dataAdapterDto);
assertThat(lookupTableService.findAll()).isEmpty();
final NativeEntity<LookupTableDto> nativeEntity = facade.createNativeEntity(entity, Collections.emptyMap(), nativeEntities, "username");
assertThat(nativeEntity.descriptor().type()).isEqualTo(ModelTypes.LOOKUP_TABLE_V1);
assertThat(nativeEntity.entity().name()).isEqualTo("http-dsv-no-cache");
assertThat(nativeEntity.entity().title()).isEqualTo("HTTP DSV without Cache");
assertThat(nativeEntity.entity().description()).isEqualTo("HTTP DSV without Cache");
assertThat(nativeEntity.entity().cacheId()).isEqualTo("5adf24b24b900a0fdb4e0001");
assertThat(nativeEntity.entity().dataAdapterId()).isEqualTo("5adf24a04b900a0fdb4e0002");
assertThat(nativeEntity.entity().defaultSingleValue()).isEqualTo("Default single value");
assertThat(nativeEntity.entity().defaultSingleValueType()).isEqualTo(LookupDefaultValue.Type.STRING);
assertThat(nativeEntity.entity().defaultMultiValue()).isEqualTo("Default multi value");
assertThat(nativeEntity.entity().defaultMultiValueType()).isEqualTo(LookupDefaultValue.Type.OBJECT);
assertThat(lookupTableService.findAll()).hasSize(1);
} |
@Override
public boolean encode(
@NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = resource.get();
Transformation<Bitmap> transformation = drawable.getFrameTransformation();
boolean isTransformed = !(transformation instanceof UnitTransformation);
if (isTransformed && options.get(ENCODE_TRANSFORMATION)) {
return encodeTransformedToFile(drawable, file);
} else {
return writeDataDirect(drawable.getBuffer(), file);
}
} | @Test
public void testReturnsFalseIfFinishingFails() {
when(gifEncoder.start(any(OutputStream.class))).thenReturn(true);
when(gifEncoder.finish()).thenReturn(false);
assertFalse(encoder.encode(resource, file, options));
} |
@Override
public int hashCode()
{
if (frames.isEmpty()) {
return 0;
}
int result = 1;
for (ZFrame frame : frames) {
result = 31 * result + (frame == null ? 0 : frame.hashCode());
}
return result;
} | @Test
public void testHashcode()
{
ZMsg msg = new ZMsg();
assertThat(msg.hashCode(), is(0));
msg.add("123");
ZMsg other = ZMsg.newStringMsg("123");
assertThat(msg.hashCode(), is(other.hashCode()));
other = new ZMsg().append("2");
assertThat(msg.hashCode(), is(not(equalTo(other.hashCode()))));
} |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchMapSomeValues() {
Map<Integer, Object> data = new HashMap<>();
data.put(1, "abc");
data.put(2, "wrong".getBytes());
assertThrows(DataException.class,
() -> ConnectSchema.validateValue(MAP_INT_STRING_SCHEMA, data));
} |
@Override
public void doRun() {
final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge);
searchDbService.getExpiredSearches(findReferencedSearchIds(),
mustBeOlderThan).forEach(searchDbService::delete);
} | @Test
public void testForNonexpiredSearches() {
when(viewService.streamAll()).thenReturn(Stream.empty());
final Search search1 = Search.builder()
.createdAt(DateTime.now(DateTimeZone.UTC).minus(Duration.standardDays(1)))
.build();
final Search search2 = Search.builder()
.createdAt(DateTime.now(DateTimeZone.UTC).minus(Duration.standardHours(4)))
.build();
when(searchDbService.streamAll()).thenReturn(Stream.of(search1, search2));
this.searchesCleanUpJob.doRun();
verify(searchDbService, never()).delete(any());
} |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name -> {
ParamDefinition paramToMerge = paramsToMerge.get(name);
if (paramToMerge == null) {
return;
}
if (paramToMerge.getType() == ParamType.MAP && paramToMerge.isLiteral()) {
Map<String, ParamDefinition> baseMap = mapValueOrEmpty(params, name);
Map<String, ParamDefinition> toMergeMap = mapValueOrEmpty(paramsToMerge, name);
mergeParams(
baseMap,
toMergeMap,
MergeContext.copyWithParentMode(
context, params.getOrDefault(name, paramToMerge).getMode()));
params.put(
name,
buildMergedParamDefinition(
name, paramToMerge, params.get(name), context, baseMap));
} else if (paramToMerge.getType() == ParamType.STRING_MAP
&& paramToMerge.isLiteral()) {
Map<String, String> baseMap = stringMapValueOrEmpty(params, name);
Map<String, String> toMergeMap = stringMapValueOrEmpty(paramsToMerge, name);
baseMap.putAll(toMergeMap);
params.put(
name,
buildMergedParamDefinition(
name, paramToMerge, params.get(name), context, baseMap));
} else {
params.put(
name,
buildMergedParamDefinition(
name, paramToMerge, params.get(name), context, paramToMerge.getValue()));
}
});
} | @Test
public void testDisallowMergeModifyInternalModeNonSystem() {
// Don't allow for non system context
AssertHelper.assertThrows(
"Should not allow updating internal mode",
MaestroValidationException.class,
"Cannot modify system mode for parameter [tomerge]",
new Runnable() {
@SneakyThrows
@Override
public void run() {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'tomerge': {'type': 'LONG','value': 2, 'internal_mode': 'PROVIDED'}}");
Map<String, ParamDefinition> paramsToMerge =
parseParamDefMap(
"{'tomerge': {'type': 'LONG', 'value': 3, 'internal_mode': 'OPTIONAL'}}");
ParamsMergeHelper.mergeParams(allParams, paramsToMerge, definitionContext);
}
});
} |
@Override
public int size() {
return 0;
} | @Test
public void testIntSpliteratorSplitTryAdvance() {
Set<Integer> results = new HashSet<>();
Spliterator.OfInt spliterator = es.intSpliterator();
Spliterator.OfInt split = spliterator.trySplit();
assertNull(split);
IntConsumer consumer = results::add;
while (spliterator.tryAdvance(consumer)) { }
assertEquals(0, results.size());
} |
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
MainSettingsActivity mainSettingsActivity = (MainSettingsActivity) getActivity();
if (mainSettingsActivity == null) return super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_user_word) {
createEmptyItemForAdd();
return true;
}
return super.onOptionsItemSelected(item);
} | @Test
public void testAddNewWordFromMenuNotAtEmptyState() {
// adding a few words to the dictionary
UserDictionary userDictionary = new UserDictionary(getApplicationContext(), "en");
userDictionary.loadDictionary();
userDictionary.addWord("hello", 1);
userDictionary.addWord("you", 2);
userDictionary.close();
UserDictionaryEditorFragment fragment = startEditorFragment();
RecyclerView wordsRecyclerView = fragment.getView().findViewById(R.id.words_recycler_view);
Assert.assertNotNull(wordsRecyclerView);
Assert.assertEquals(
3 /*two words, and one AddNew*/, wordsRecyclerView.getAdapter().getItemCount());
Assert.assertEquals(
R.id.word_editor_view_type_row, wordsRecyclerView.getAdapter().getItemViewType(0));
Assert.assertEquals(
R.id.word_editor_view_type_row, wordsRecyclerView.getAdapter().getItemViewType(1));
Assert.assertEquals(
R.id.word_editor_view_type_add_new_row, wordsRecyclerView.getAdapter().getItemViewType(2));
final MenuItem menuItem = Mockito.mock(MenuItem.class);
Mockito.doReturn(R.id.add_user_word).when(menuItem).getItemId();
fragment.onOptionsItemSelected(menuItem);
TestRxSchedulers.drainAllTasks();
Assert.assertEquals(3, wordsRecyclerView.getAdapter().getItemCount());
Assert.assertEquals(
R.id.word_editor_view_type_row, wordsRecyclerView.getAdapter().getItemViewType(0));
Assert.assertEquals(
R.id.word_editor_view_type_row, wordsRecyclerView.getAdapter().getItemViewType(1));
Assert.assertEquals(
R.id.word_editor_view_type_editing_row, wordsRecyclerView.getAdapter().getItemViewType(2));
} |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithDirectorySelector() {
DiscoverySelector resource = selectDirectory("src/test/resources/io/cucumber/junit/platform/engine");
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(discoveryRequest, testDescriptor);
assertEquals(6, testDescriptor.getChildren().size());
} |
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
// 入栈
DataPermission dataPermission = this.findAnnotation(methodInvocation);
if (dataPermission != null) {
DataPermissionContextHolder.add(dataPermission);
}
try {
// 执行逻辑
return methodInvocation.proceed();
} finally {
// 出栈
if (dataPermission != null) {
DataPermissionContextHolder.remove();
}
}
} | @Test // 无 @DataPermission 注解
public void testInvoke_none() throws Throwable {
// 参数
mockMethodInvocation(TestNone.class);
// 调用
Object result = interceptor.invoke(methodInvocation);
// 断言
assertEquals("none", result);
assertEquals(1, interceptor.getDataPermissionCache().size());
assertTrue(CollUtil.getFirst(interceptor.getDataPermissionCache().values()).enable());
} |
public static HoodieIndex.IndexType getIndexType(Configuration conf) {
return HoodieIndex.IndexType.valueOf(conf.getString(FlinkOptions.INDEX_TYPE).toUpperCase());
} | @Test
void testGetIndexType() {
Configuration conf = getConf();
// set uppercase index
conf.setString(FlinkOptions.INDEX_TYPE, "BLOOM");
assertEquals(HoodieIndex.IndexType.BLOOM, OptionsResolver.getIndexType(conf));
// set lowercase index
conf.setString(FlinkOptions.INDEX_TYPE, "bloom");
assertEquals(HoodieIndex.IndexType.BLOOM, OptionsResolver.getIndexType(conf));
} |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
if(containerService.isContainer(file)) {
containers.add(file);
}
else {
callback.delete(file);
final Path bucket = containerService.getContainer(file);
if(file.getType().contains(Path.Type.upload)) {
// In-progress multipart upload
try {
multipartService.delete(new MultipartUpload(file.attributes().getVersionId(),
bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), containerService.getKey(file)));
}
catch(NotfoundException ignored) {
log.warn(String.format("Ignore failure deleting multipart upload %s", file));
}
}
else {
try {
// Always returning 204 even if the key does not exist. Does not return 404 for non-existing keys
session.getClient().deleteVersionedObject(
file.attributes().getVersionId(), bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), containerService.getKey(file));
}
catch(ServiceException e) {
throw new S3ExceptionMappingService().map("Cannot delete {0}", e, file);
}
}
}
}
for(Path file : containers) {
callback.delete(file);
try {
final String bucket = containerService.getContainer(file).getName();
session.getClient().deleteBucket(bucket);
session.getClient().getRegionEndpointCache().removeRegionForBucketName(bucket);
}
catch(ServiceException e) {
throw new S3ExceptionMappingService().map("Cannot delete {0}", e, file);
}
}
} | @Test
public void testDeleteVersionedPlaceholder() throws Exception {
final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final String name = new AlphanumericRandomStringService().random();
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path test = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl).mkdir(
new Path(container, name, EnumSet.of(Path.Type.directory)), new TransferStatus());
assertTrue(new S3FindFeature(session, acl).find(test));
assertTrue(new DefaultFindFeature(session).find(test));
new S3DefaultDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
assertFalse(new S3FindFeature(session, acl).find(test));
assertFalse(new DefaultFindFeature(session).find(test));
assertFalse(new S3FindFeature(session, acl).find(new Path(test).withAttributes(PathAttributes.EMPTY)));
assertFalse(new DefaultFindFeature(session).find(new Path(test).withAttributes(PathAttributes.EMPTY)));
} |
public Optional<RestartPlan> buildRestartPlan(RestartRequest request) {
String connectorName = request.connectorName();
ConnectorStatus connectorStatus = statusBackingStore.get(connectorName);
if (connectorStatus == null) {
return Optional.empty();
}
// If requested, mark the connector as restarting
AbstractStatus.State connectorState = request.shouldRestartConnector(connectorStatus) ? AbstractStatus.State.RESTARTING : connectorStatus.state();
ConnectorStateInfo.ConnectorState connectorInfoState = new ConnectorStateInfo.ConnectorState(
connectorState.toString(),
connectorStatus.workerId(),
connectorStatus.trace()
);
// Collect the task states, If requested, mark the task as restarting
List<ConnectorStateInfo.TaskState> taskStates = statusBackingStore.getAll(connectorName)
.stream()
.map(taskStatus -> {
AbstractStatus.State taskState = request.shouldRestartTask(taskStatus) ? AbstractStatus.State.RESTARTING : taskStatus.state();
return new ConnectorStateInfo.TaskState(
taskStatus.id().task(),
taskState.toString(),
taskStatus.workerId(),
taskStatus.trace()
);
})
.collect(Collectors.toList());
// Construct the response from the various states
Map<String, String> conf = rawConfig(connectorName);
ConnectorStateInfo stateInfo = new ConnectorStateInfo(
connectorName,
connectorInfoState,
taskStates,
connectorType(conf)
);
return Optional.of(new RestartPlan(request, stateInfo));
} | @Test
public void testBuildRestartPlanForUnknownConnector() {
String connectorName = "UnknownConnector";
RestartRequest restartRequest = new RestartRequest(connectorName, false, true);
AbstractHerder herder = testHerder();
when(statusStore.get(connectorName)).thenReturn(null);
Optional<RestartPlan> mayBeRestartPlan = herder.buildRestartPlan(restartRequest);
assertFalse(mayBeRestartPlan.isPresent());
} |
public static void executeWithRetries(
final Function function,
final RetryBehaviour retryBehaviour
) throws Exception {
executeWithRetries(() -> {
function.call();
return null;
}, retryBehaviour);
} | @Test
public void shouldReturnValue() throws Exception {
// Given:
final String expectedValue = "should return this";
// When:
final String result = ExecutorUtil.executeWithRetries(() -> expectedValue, ON_RETRYABLE);
// Then:
assertThat(result, is(expectedValue));
} |
@Override
public Collection<Long> generateKeys(final AlgorithmSQLContext context, final int keyGenerateCount) {
Collection<Long> result = new LinkedList<>();
for (int index = 0; index < keyGenerateCount; index++) {
result.add(generateKey());
}
return result;
} | @Test
void assertSetMaxVibrationOffsetFailureWhenNegative() {
assertThrows(AlgorithmInitializationException.class,
() -> TypedSPILoader.getService(KeyGenerateAlgorithm.class, "SNOWFLAKE", PropertiesBuilder.build(new Property("max-vibration-offset", "-1")))
.generateKeys(mock(AlgorithmSQLContext.class), 1));
} |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("Search State");
try {
setAttribute(protobuf, "State", getStateAsEnum().name());
completeNodeAttributes(protobuf);
} catch (Exception es) {
LoggerFactory.getLogger(EsStateSection.class).warn("Failed to retrieve ES attributes. There will be only a single \"state\" attribute.", es);
setAttribute(protobuf, "State", es.getCause() instanceof ElasticsearchException ? es.getCause().getMessage() : es.getMessage());
}
return protobuf.build();
} | @Test
public void node_attributes() {
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(attribute(section, "CPU Usage (%)")).isNotNull();
assertThat(attribute(section, "Disk Available")).isNotNull();
assertThat(attribute(section, "Store Size")).isNotNull();
assertThat(attribute(section, "Translog Size")).isNotNull();
} |
protected void preHandle(HttpServletRequest request, Object handler, SpanCustomizer customizer) {
if (WebMvcRuntime.get().isHandlerMethod(handler)) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
customizer.tag(CONTROLLER_CLASS, handlerMethod.getBeanType().getSimpleName());
customizer.tag(CONTROLLER_METHOD, handlerMethod.getMethod().getName());
} else {
customizer.tag(CONTROLLER_CLASS, handler.getClass().getSimpleName());
}
} | @Test void preHandle_HandlerMethod_addsClassAndMethodTags() throws Exception {
parser.preHandle(
request,
new HandlerMethod(controller, TestController.class.getMethod("items", String.class)),
customizer
);
verify(customizer).tag("mvc.controller.class", "TestController");
verify(customizer).tag("mvc.controller.method", "items");
verifyNoMoreInteractions(request, customizer);
} |
@Override
public Mono<Void> writeWith(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
return chain.execute(exchange).doOnError(throwable -> cleanup(exchange)).then(Mono.defer(() -> {
Connection connection = exchange.getAttribute(Constants.CLIENT_RESPONSE_CONN_ATTR);
if (Objects.isNull(connection)) {
Object error = ShenyuResultWrap.error(exchange, ShenyuResultEnum.SERVICE_RESULT_ERROR);
return WebFluxResultUtils.result(exchange, error);
}
ServerHttpResponse response = exchange.getResponse();
NettyDataBufferFactory factory = (NettyDataBufferFactory) response.bufferFactory();
final Flux<NettyDataBuffer> body = connection
.inbound()
.receive()
.retain()
.map(factory::wrap);
MediaType contentType = response.getHeaders().getContentType();
Mono<Void> responseMono = isStreamingMediaType(contentType)
? response.writeAndFlushWith(body.map(Flux::just))
: response.writeWith(body);
exchange.getAttributes().put(Constants.RESPONSE_MONO, responseMono);
// watcher httpStatus
final Consumer<HttpStatusCode> consumer = exchange.getAttribute(Constants.WATCHER_HTTP_STATUS);
Optional.ofNullable(consumer).ifPresent(c -> c.accept(response.getStatusCode()));
return responseMono.onErrorResume(error -> releaseIfNotConsumed(body, error));
})).doOnCancel(() -> cleanup(exchange));
} | @Test
public void testWriteWith() {
ServerWebExchange exchangeNoClient = MockServerWebExchange.from(MockServerHttpRequest.get("/test")
.build());
StepVerifier.create(nettyClientMessageWriter.writeWith(exchangeNoClient, chain)).expectSubscription().verifyComplete();
ServerWebExchange exchange = mock(ServerWebExchange.class);
when(exchange.getRequest()).thenReturn(mock(ServerHttpRequest.class));
when(exchange.getResponse()).thenReturn(mock(ServerHttpResponse.class));
when(exchange.getResponse().getHeaders()).thenReturn(HttpHeaders.EMPTY);
NettyDataBufferFactory factory = new NettyDataBufferFactory(mock(ByteBufAllocator.class));
when(exchange.getResponse().bufferFactory()).thenReturn(factory);
Connection connection = mock(Connection.class);
when(connection.inbound()).thenReturn(mock(NettyInbound.class));
when(connection.inbound().receive()).thenReturn(mock(ByteBufFlux.class));
when(connection.inbound().receive().retain()).thenReturn(mock(ByteBufFlux.class));
final Flux<NettyDataBuffer> body = new Flux<>() {
@Override
public void subscribe(final CoreSubscriber<? super NettyDataBuffer> coreSubscriber) {
coreSubscriber.onComplete();
}
};
when(connection.inbound().receive().retain().map(factory::wrap)).thenReturn(body);
when(exchange.getAttribute(Constants.CLIENT_RESPONSE_CONN_ATTR)).thenReturn(connection);
StepVerifier.create(nettyClientMessageWriter.writeWith(exchange, chain)).expectSubscription().verifyError();
} |
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be null");
if (dataTable.isEmpty()) {
return emptyMap();
}
DataTable keyColumn = dataTable.columns(0, 1);
DataTable valueColumns = dataTable.columns(1);
String firstHeaderCell = keyColumn.cell(0, 0);
boolean firstHeaderCellIsBlank = firstHeaderCell == null || firstHeaderCell.isEmpty();
List<K> keys = convertEntryKeys(keyType, keyColumn, valueType, firstHeaderCellIsBlank);
if (valueColumns.isEmpty()) {
return createMap(keyType, keys, valueType, nCopies(keys.size(), null));
}
boolean keysImplyTableRowTransformer = keys.size() == dataTable.height() - 1;
List<V> values = convertEntryValues(valueColumns, keyType, valueType, keysImplyTableRowTransformer);
if (keys.size() != values.size()) {
throw keyValueMismatchException(firstHeaderCellIsBlank, keys.size(), keyType, values.size(), valueType);
}
return createMap(keyType, keys, valueType, values);
} | @Test
void to_map__duplicate_keys__throws_exception() {
DataTable table = parse("",
"| | lat | lon |",
"| KMSY | 29.993333 | -90.258056 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KSFO | 37.618889 | -122.375 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KJFK | 40.639722 | -73.778889 |");
registry.defineDataTableType(new DataTableType(AirPortCode.class, AIR_PORT_CODE_TABLE_CELL_TRANSFORMER));
registry.defineDataTableType(new DataTableType(Coordinate.class, COORDINATE_TABLE_ENTRY_TRANSFORMER));
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toMap(table, AirPortCode.class, Coordinate.class));
assertThat(exception.getMessage(), startsWith(format("" +
"Can't convert DataTable to Map<%s, %s>.\n" +
"Encountered duplicate key",
typeName(AirPortCode.class), typeName(Coordinate.class))));
} |
@Override
public void registerInstance(Service service, Instance instance, String clientId) throws NacosException {
NamingUtils.checkInstanceIsLegal(instance);
Service singleton = ServiceManager.getInstance().getSingleton(service);
if (!singleton.isEphemeral()) {
throw new NacosRuntimeException(NacosException.INVALID_PARAM,
String.format("Current service %s is persistent service, can't register ephemeral instance.",
singleton.getGroupedServiceName()));
}
Client client = clientManager.getClient(clientId);
checkClientIsLegal(client, clientId);
InstancePublishInfo instanceInfo = getPublishInfo(instance);
client.addServiceInstance(singleton, instanceInfo);
client.setLastUpdatedTime();
client.recalculateRevision();
NotifyCenter.publishEvent(new ClientOperationEvent.ClientRegisterServiceEvent(singleton, clientId));
NotifyCenter
.publishEvent(new MetadataEvent.InstanceMetadataEvent(singleton, instanceInfo.getMetadataId(), false));
} | @Test
void testRegisterWhenClientPersistent() throws NacosException {
assertThrows(NacosRuntimeException.class, () -> {
Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false);
when(clientManager.getClient(anyString())).thenReturn(persistentClient);
// Excepted exception
ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedClientId);
});
} |
@Override
public Optional<String> canUpgradeTo(final DataSource other) {
final List<String> issues = PROPERTIES.stream()
.filter(prop -> !prop.isCompatible(this, other))
.map(prop -> getCompatMessage(other, prop))
.collect(Collectors.toList());
checkSchemas(getSchema(), other.getSchema())
.map(s -> getCompatMessage(other, SCHEMA_PROP) + ". (" + s + ")")
.ifPresent(issues::add);
final String err = String.join("\n\tAND ", issues);
return err.isEmpty() ? Optional.empty() : Optional.of(err);
} | @Test
public void shouldEnforceSameType() {
// Given:
final KsqlStream<String> streamA = new KsqlStream<>(
"sql",
SourceName.of("A"),
SOME_SCHEMA,
Optional.empty(),
true,
topic,
false
);
final KsqlTable<String> streamB = new KsqlTable<>(
"sql",
SourceName.of("A"),
SOME_SCHEMA,
Optional.empty(),
true,
topic,
false
);
// When:
final Optional<String> err = streamA.canUpgradeTo(streamB);
// Then:
assertThat(err.isPresent(), is(true));
assertThat(err.get(), containsString("has type = KSTREAM which is not upgradeable to KTABLE"));
} |
public String driver() {
return get(DRIVER, null);
} | @Test
public void testSetDriver() {
SW_BDC.driver(DRIVER_NEW);
assertEquals("Incorrect driver", DRIVER_NEW, SW_BDC.driver());
} |
public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException {
if (!EnvUtil.getStandaloneMode()) {
String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE);
LookupType type = chooseLookup(lookupType);
LOOK_UP = find(type);
currentLookupType = type;
} else {
LOOK_UP = new StandaloneMemberLookup();
}
LOOK_UP.injectMemberManager(memberManager);
Loggers.CLUSTER.info("Current addressing mode selection : {}", LOOK_UP.getClass().getSimpleName());
return LOOK_UP;
} | @Test
void createLookUpFileConfigMemberLookup() throws Exception {
EnvUtil.setIsStandalone(false);
mockEnvironment.setProperty(LOOKUP_MODE_TYPE, "file");
memberLookup = LookupFactory.createLookUp(memberManager);
assertEquals(FileConfigMemberLookup.class, memberLookup.getClass());
} |
public final void enter() {
if (inQueue) throw new IllegalStateException("Unbalanced enter/exit");
long timeoutNanos = timeoutNanos();
boolean hasDeadline = hasDeadline();
if (timeoutNanos == 0 && !hasDeadline) {
return; // No timeout and no deadline? Don't bother with the queue.
}
inQueue = true;
scheduleTimeout(this, timeoutNanos, hasDeadline);
} | @Test public void doubleEnter() throws Exception {
a.enter();
try {
a.enter();
fail();
} catch (IllegalStateException expected) {
}
} |
@Nullable
@Override
public Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName) {
if (null == regionName) {
regionName = "global";
} else {
regionName = regionName.trim().toLowerCase();
}
DynamicStringProperty appWhiteListProp =
configInstance.getStringProperty(namespace + "remoteRegion." + regionName + ".appWhiteList", null);
if (null == appWhiteListProp || null == appWhiteListProp.get()) {
return null;
} else {
String appWhiteListStr = appWhiteListProp.get();
String[] whitelistEntries = appWhiteListStr.split(",");
return new HashSet<String>(Arrays.asList(whitelistEntries));
}
} | @Test
public void testGetGlobalAppWhiteList() throws Exception {
String whitelistApp = "myapp";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", whitelistApp);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Set<String> globalList = config.getRemoteRegionAppWhitelist(null);
Assert.assertNotNull("Global whitelist is null.", globalList);
Assert.assertEquals("Global whitelist not as expected.", 1, globalList.size());
Assert.assertEquals("Global whitelist not as expected.", whitelistApp, globalList.iterator().next());
} |
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId,
serviceName, instance);
if (instance.isEphemeral()) {
return;
}
final Map<String, String> params = new HashMap<>(16);
params.put(CommonParams.NAMESPACE_ID, namespaceId);
params.put(CommonParams.SERVICE_NAME, NamingUtils.getGroupedName(serviceName, groupName));
params.put(CommonParams.CLUSTER_NAME, instance.getClusterName());
params.put(IP_PARAM, instance.getIp());
params.put(PORT_PARAM, String.valueOf(instance.getPort()));
params.put(EPHEMERAL_PARAM, String.valueOf(instance.isEphemeral()));
reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.DELETE);
} | @Test
void testDeregisterService() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("127.0.0.1:8848");
a.setCode(200);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
nacosRestTemplateField.set(clientProxy, nacosRestTemplate);
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
instance.setEphemeral(false);
//when
clientProxy.deregisterService(serviceName, groupName, instance);
//then
verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any());
} |
public String getQuery() throws Exception {
return getQuery(weatherConfiguration.getLocation());
} | @Test
public void testMultiIdQuery() throws Exception {
WeatherConfiguration weatherConfiguration = new WeatherConfiguration();
weatherConfiguration.setIds("524901,703448");
weatherConfiguration.setMode(WeatherMode.JSON);
weatherConfiguration.setLanguage(WeatherLanguage.nl);
weatherConfiguration.setAppid(APPID);
WeatherQuery weatherQuery = new WeatherQuery(weatherConfiguration);
weatherConfiguration.setGeoLocationProvider(geoLocationProvider);
String query = weatherQuery.getQuery();
assertThat(query, is(
"http://api.openweathermap.org/data/2.5/group?id=524901,703448&lang=nl&APPID=9162755b2efa555823cfe0451d7fff38"));
} |
@VisibleForTesting
Schema convertSchema(org.apache.avro.Schema schema) {
return Schema.of(getFields(schema));
} | @Test
void convertSchema_maps() {
Schema input = SchemaBuilder.record("testRecord")
.fields()
.name("intMap")
.type()
.map()
.values()
.intType().noDefault()
.name("recordMap")
.type()
.nullable()
.map()
.values(SchemaBuilder.record("element").fields().requiredDouble("requiredDouble").optionalString("optionalString").endRecord())
.noDefault()
.endRecord();
com.google.cloud.bigquery.Schema expected = com.google.cloud.bigquery.Schema.of(
Field.newBuilder("intMap", StandardSQLTypeName.STRUCT,
Field.newBuilder("key_value", StandardSQLTypeName.STRUCT,
Field.newBuilder("key", StandardSQLTypeName.STRING).setMode(Field.Mode.REQUIRED).build(),
Field.newBuilder("value", StandardSQLTypeName.INT64).setMode(Field.Mode.REQUIRED).build())
.setMode(Field.Mode.REPEATED).build())
.setMode(Field.Mode.NULLABLE).build(),
Field.newBuilder("recordMap", StandardSQLTypeName.STRUCT,
Field.newBuilder("key_value", StandardSQLTypeName.STRUCT,
Field.newBuilder("key", StandardSQLTypeName.STRING).setMode(Field.Mode.REQUIRED).build(),
Field.newBuilder("value", StandardSQLTypeName.STRUCT,
Field.newBuilder("requiredDouble", StandardSQLTypeName.FLOAT64).setMode(Field.Mode.REQUIRED).build(),
Field.newBuilder("optionalString", StandardSQLTypeName.STRING).setMode(Field.Mode.NULLABLE).build()
).setMode(Field.Mode.REQUIRED).build()).setMode(Field.Mode.REPEATED).build())
.setMode(Field.Mode.NULLABLE).build());
Assertions.assertEquals(expected, SCHEMA_RESOLVER.convertSchema(input));
} |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(
Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS)))
.visit(treeRootHolder.getRoot());
} | @Test
public void no_measures_for_FILE_component_without_code() {
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, null, 1)).build());
underTest.execute(new TestComputationStepContext());
assertThat(measureRepository.isEmpty()).isTrue();
} |
public int add(byte[] value) {
int offsetBufferIndex = _numValues >>> OFFSET_BUFFER_SHIFT_OFFSET;
int offsetIndex = _numValues & OFFSET_BUFFER_MASK;
PinotDataBuffer offsetBuffer;
// If this is the first entry in the offset buffer, allocate a new buffer and store the end offset of the previous
// value
if (offsetIndex == 0) {
offsetBuffer = _memoryManager.allocate(OFFSET_BUFFER_SIZE, _allocationContext);
offsetBuffer.putInt(0, _previousValueEndOffset);
_offsetBuffers.set(offsetBufferIndex, offsetBuffer);
_totalBufferSize += OFFSET_BUFFER_SIZE;
} else {
offsetBuffer = _offsetBuffers.get(offsetBufferIndex);
}
int valueLength = value.length;
if (valueLength == 0) {
offsetBuffer.putInt((offsetIndex + 1) << 2, _previousValueEndOffset);
return _numValues++;
}
int valueBufferIndex = (_previousValueEndOffset + valueLength - 1) >>> VALUE_BUFFER_SHIFT_OFFSET;
PinotDataBuffer valueBuffer;
int valueStartOffset;
// If the current value buffer does not have enough space, allocate a new buffer to store the value
if ((_previousValueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET != valueBufferIndex) {
valueBuffer = _memoryManager.allocate(VALUE_BUFFER_SIZE, _allocationContext);
_valueBuffers.set(valueBufferIndex, valueBuffer);
_totalBufferSize += VALUE_BUFFER_SIZE;
valueStartOffset = valueBufferIndex << VALUE_BUFFER_SHIFT_OFFSET;
} else {
valueBuffer = _valueBuffers.get(valueBufferIndex);
valueStartOffset = _previousValueEndOffset;
}
int valueEndOffset = valueStartOffset + valueLength;
offsetBuffer.putInt((offsetIndex + 1) << 2, valueEndOffset);
valueBuffer.readFrom(valueStartOffset & VALUE_BUFFER_MASK, value);
_previousValueEndOffset = valueEndOffset;
return _numValues++;
} | @Test
public void testAdd()
throws Exception {
try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) {
for (int i = 0; i < NUM_VALUES; i++) {
Assert.assertEquals(offHeapMutableBytesStore.add(_values[i]), i);
}
}
} |
public MailConfiguration getConfiguration() {
if (configuration == null) {
configuration = new MailConfiguration(getCamelContext());
}
return configuration;
} | @Test
public void testMailEndpointsAreConfiguredProperlyWhenUsingImap() {
MailEndpoint endpoint = checkEndpoint("imap://james@myhost:143/subject");
MailConfiguration config = endpoint.getConfiguration();
assertEquals("imap", config.getProtocol(), "getProtocol()");
assertEquals("myhost", config.getHost(), "getHost()");
assertEquals(143, config.getPort(), "getPort()");
assertEquals("james", config.getUsername(), "getUsername()");
assertEquals("james@myhost", config.getRecipients().get(Message.RecipientType.TO),
"getRecipients().get(Message.RecipientType.TO)");
assertEquals("INBOX", config.getFolderName(), "folder");
assertFalse(config.isDebugMode());
} |
@GwtIncompatible("java.util.regex.Pattern")
public void doesNotContainMatch(@Nullable Pattern regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that does not contain a match for", regex);
return;
}
Matcher matcher = regex.matcher(actual);
if (matcher.find()) {
failWithoutActual(
fact("expected not to contain a match for", regex),
fact("but contained", matcher.group()),
fact("full string", actualCustomStringRepresentationForPackageMembersToCall()));
}
} | @Test
@GwtIncompatible("Pattern")
public void stringDoesNotContainMatchPattern() {
assertThat("zzaaazz").doesNotContainMatch(Pattern.compile(".b."));
expectFailureWhenTestingThat("zzabazz").doesNotContainMatch(Pattern.compile(".b."));
assertFailureValue("expected not to contain a match for", ".b.");
assertFailureValue("but contained", "aba");
assertFailureValue("full string", "zzabazz");
} |
@Override
public double getMean() {
if (values.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < values.length; i++) {
sum += values[i] * normWeights[i];
}
return sum;
} | @Test
public void doesNotProduceNaNValues() {
WeightedSnapshot weightedSnapshot = new WeightedSnapshot(
weightedArray(new long[]{1, 2, 3}, new double[]{0, 0, 0}));
assertThat(weightedSnapshot.getMean()).isEqualTo(0);
} |
@Override
public void addTrackedResources(Key intentKey,
Collection<NetworkResource> resources) {
for (NetworkResource resource : resources) {
if (resource instanceof Link) {
intentsByLink.put(linkKey((Link) resource), intentKey);
} else if (resource instanceof ElementId) {
intentsByDevice.put((ElementId) resource, intentKey);
}
}
} | @Test
public void testEventHostAvailableMatch() throws Exception {
final Device host = device("host1");
final DeviceEvent deviceEvent =
new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, host);
reasons.add(deviceEvent);
final Key key = Key.of(0x333L, APP_ID);
Collection<NetworkResource> resources = ImmutableSet.of(host.id());
tracker.addTrackedResources(key, resources);
deviceListener.event(deviceEvent);
assertThat(
delegate.latch.await(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS),
is(true));
assertThat(delegate.intentIdsFromEvent, hasSize(1));
assertThat(delegate.compileAllFailedFromEvent, is(true));
assertThat(delegate.intentIdsFromEvent.get(0).toString(),
equalTo("0x333"));
} |
public static String generateInventoryTaskId(final InventoryDumperContext dumperContext) {
return String.format("%s.%s#%s", dumperContext.getCommonContext().getDataSourceName(), dumperContext.getActualTableName(), dumperContext.getShardingItem());
} | @Test
void assertGenerateInventoryTaskId() {
InventoryDumperContext dumperContext = new InventoryDumperContext(new DumperCommonContext("foo_ds", null, null, null));
dumperContext.setActualTableName("foo_actual_tbl");
dumperContext.setShardingItem(1);
assertThat(PipelineTaskUtils.generateInventoryTaskId(dumperContext), is("foo_ds.foo_actual_tbl#1"));
} |
@Deprecated
public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) {
return Task.callable(name, () -> callable.call());
} | @SuppressWarnings("deprecation")
@Test
public void testThrowableCallableNoError() throws InterruptedException {
final Integer magic = 0x5f3759df;
final ThrowableCallable<Integer> callable = new ThrowableCallable<Integer>() {
@Override
public Integer call() throws Throwable {
return magic;
}
};
final Task<Integer> task = Tasks.callable("magic", callable);
getEngine().run(task);
task.await(100, TimeUnit.MILLISECONDS);
assertTrue(task.isDone());
assertFalse(task.isFailed());
assertEquals(magic, task.get());
assertEquals("magic", task.getName());
} |
@Udf(description = "Returns the hyperbolic tangent of an INT value")
public Double tanh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic tangent of."
) final Integer value
) {
return tanh(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.tanh(-9.1), closeTo(-0.9999999750614947, 0.000000000000001));
assertThat(udf.tanh(-6.3), closeTo(-0.9999932559922726, 0.000000000000001));
assertThat(udf.tanh(-7), closeTo(-0.9999983369439447, 0.000000000000001));
assertThat(udf.tanh(-7L), closeTo(-0.9999983369439447, 0.000000000000001));
} |
@Override
public IdentityContext build(Request request) {
Optional<AuthPluginService> authPluginService = AuthPluginManager.getInstance()
.findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType());
IdentityContext result = new IdentityContext();
getRemoteIp(request, result);
if (!authPluginService.isPresent()) {
return result;
}
Set<String> identityNames = new HashSet<>(authPluginService.get().identityNames());
Map<String, String> map = request.getHeaders();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (identityNames.contains(entry.getKey())) {
result.setParameter(entry.getKey(), entry.getValue());
}
}
return result;
} | @Test
void testBuild() {
IdentityContext actual = identityContextBuilder.build(request);
assertEquals(IDENTITY_TEST_VALUE, actual.getParameter(IDENTITY_TEST_KEY));
assertEquals("1.1.1.1", actual.getParameter(Constants.Identity.REMOTE_IP));
} |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
JooqConfiguration conf = configuration != null ? configuration.copy() : new JooqConfiguration();
JooqEndpoint endpoint = new JooqEndpoint(uri, this, conf);
setProperties(endpoint, parameters);
initConfiguration(getCamelContext(), conf, remaining);
return endpoint;
} | @Test
public void testNonDefaultConfig() {
JooqComponent component = (JooqComponent) context().getComponent("jooq");
assertThrows(PropertyBindingException.class,
() -> component.createEndpoint(
"jooq://org.apache.camel.component.jooq.db.tables.records.BookStoreRecord?operation=unexpectedOperation"));
} |
public ZMsg dump(Appendable out)
{
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.printf("--------------------------------------\n");
for (ZFrame frame : frames) {
pw.printf("[%03d] %s\n", frame.size(), frame);
}
out.append(sw.getBuffer());
sw.close();
}
catch (IOException e) {
throw new RuntimeException("Message dump exception " + super.toString(), e);
}
return this;
} | @Test
public void testDump()
{
ZMsg msg = new ZMsg().append(new byte[0]).append(new byte[] { (byte) 0xAA });
msg.dump();
StringBuilder out = new StringBuilder();
msg.dump(out);
System.out.println(msg);
assertThat(out.toString(), endsWith("[000] \n[001] AA\n"));
} |
@Override
public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) {
log.debug(
"sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}",
catalogueTree,
sortTypeEnum);
return recursionSortCatalogues(catalogueTree, sortTypeEnum);
} | @Test
public void sortEmptyTest2() {
List<Catalogue> catalogueTree = null;
SortTypeEnum sortTypeEnum = SortTypeEnum.ASC;
List<Catalogue> resultList = catalogueTreeSortCreateTimeStrategyTest.sort(catalogueTree, sortTypeEnum);
assertEquals(Lists.newArrayList(), resultList);
} |
public List<ErasureCodingPolicy> loadPolicy(String policyFilePath) {
try {
File policyFile = getPolicyFile(policyFilePath);
if (!policyFile.exists()) {
LOG.warn("Not found any EC policy file");
return Collections.emptyList();
}
return loadECPolicies(policyFile);
} catch (ParserConfigurationException | IOException | SAXException e) {
throw new RuntimeException("Failed to load EC policy file: "
+ policyFilePath);
}
} | @Test
public void testBadECPolicy() throws Exception {
PrintWriter out = new PrintWriter(new FileWriter(POLICY_FILE));
out.println("<?xml version=\"1.0\"?>");
out.println("<configuration>");
out.println("<layoutversion>1</layoutversion>");
out.println("<schemas>");
out.println(" <schema id=\"RSk12m4\">");
out.println(" <codec>RS</codec>");
out.println(" <k>12</k>");
out.println(" <m>4</m>");
out.println(" </schema>");
out.println(" <schema id=\"RS-legacyk12m4\">");
out.println(" <codec>RS-legacy</codec>");
out.println(" <k>12</k>");
out.println(" <m>4</m>");
out.println(" </schema>");
out.println("</schemas>");
out.println("<policies>");
out.println(" <policy>");
out.println(" <schema>RSk12m4</schema>");
out.println(" <cellsize>-1025</cellsize>");
out.println(" </policy>");
out.println("</policies>");
out.println("</configuration>");
out.close();
ECPolicyLoader ecPolicyLoader = new ECPolicyLoader();
try {
ecPolicyLoader.loadPolicy(POLICY_FILE);
fail("RuntimeException should be thrown for bad policy");
} catch (RuntimeException e) {
assertExceptionContains("Bad policy is found in EC policy"
+ " configuration file", e);
}
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListInvisibleCharacter() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("us-east-1");
final Path placeholder = new GoogleStorageTouchFeature(session).touch(
new Path(container, String.format("test-\u001F-%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file)), new TransferStatus());
assertTrue(new GoogleStorageObjectListService(session).list(container, new DisabledListProgressListener()).contains(placeholder));
new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(placeholder), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
public static void addInvocationRateToSensor(final Sensor sensor,
final String group,
final Map<String, String> tags,
final String operation,
final String descriptionOfRate) {
sensor.add(
new MetricName(
operation + RATE_SUFFIX,
group,
descriptionOfRate,
tags
),
new Rate(TimeUnit.SECONDS, new WindowedCount())
);
} | @Test
public void shouldAddInvocationRateToSensor() {
final Sensor sensor = mock(Sensor.class);
final MetricName expectedMetricName = new MetricName(METRIC_NAME1 + "-rate", group, DESCRIPTION1, tags);
when(sensor.add(eq(expectedMetricName), any(Rate.class))).thenReturn(true);
StreamsMetricsImpl.addInvocationRateToSensor(sensor, group, tags, METRIC_NAME1, DESCRIPTION1);
} |
public static String translate(String src, String from, String to) {
if (isEmpty(src)) {
return src;
}
StringBuilder sb = null;
int ix;
char c;
for (int i = 0, len = src.length(); i < len; i++) {
c = src.charAt(i);
ix = from.indexOf(c);
if (ix == -1) {
if (sb != null) {
sb.append(c);
}
} else {
if (sb == null) {
sb = new StringBuilder(len);
sb.append(src, 0, i);
}
if (ix < to.length()) {
sb.append(to.charAt(ix));
}
}
}
return sb == null ? src : sb.toString();
} | @Test
void testTranslate() throws Exception {
String s = "16314";
assertEquals(StringUtils.translate(s, "123456", "abcdef"), "afcad");
assertEquals(StringUtils.translate(s, "123456", "abcd"), "acad");
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 2) {
onInvalidDataReceived(device, data);
return;
}
// Read the Op Code
final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0);
// Estimate the expected operand size based on the Op Code
int expectedOperandSize;
switch (opCode) {
case OP_CODE_COMMUNICATION_INTERVAL_RESPONSE ->
// UINT8
expectedOperandSize = 1;
case OP_CODE_CALIBRATION_VALUE_RESPONSE ->
// Calibration Value
expectedOperandSize = 10;
case OP_CODE_PATIENT_HIGH_ALERT_LEVEL_RESPONSE,
OP_CODE_PATIENT_LOW_ALERT_LEVEL_RESPONSE,
OP_CODE_HYPO_ALERT_LEVEL_RESPONSE,
OP_CODE_HYPER_ALERT_LEVEL_RESPONSE,
OP_CODE_RATE_OF_DECREASE_ALERT_LEVEL_RESPONSE,
OP_CODE_RATE_OF_INCREASE_ALERT_LEVEL_RESPONSE ->
// SFLOAT
expectedOperandSize = 2;
case OP_CODE_RESPONSE_CODE ->
// Request Op Code (UINT8), Response Code Value (UINT8)
expectedOperandSize = 2;
default -> {
onInvalidDataReceived(device, data);
return;
}
}
// Verify packet length
if (data.size() != 1 + expectedOperandSize && data.size() != 1 + expectedOperandSize + 2) {
onInvalidDataReceived(device, data);
return;
}
// Verify CRC if present
final boolean crcPresent = data.size() == 1 + expectedOperandSize + 2; // opCode + expected operand + CRC
if (crcPresent) {
final int expectedCrc = data.getIntValue(Data.FORMAT_UINT16_LE, 1 + expectedOperandSize);
final int actualCrc = CRC16.MCRF4XX(data.getValue(), 0, 1 + expectedOperandSize);
if (expectedCrc != actualCrc) {
onCGMSpecificOpsResponseReceivedWithCrcError(device, data);
return;
}
}
switch (opCode) {
case OP_CODE_COMMUNICATION_INTERVAL_RESPONSE -> {
final int interval = data.getIntValue(Data.FORMAT_UINT8, 1);
onContinuousGlucoseCommunicationIntervalReceived(device, interval, crcPresent);
return;
}
case OP_CODE_CALIBRATION_VALUE_RESPONSE -> {
final float glucoseConcentrationOfCalibration = data.getFloatValue(Data.FORMAT_SFLOAT, 1);
final int calibrationTime = data.getIntValue(Data.FORMAT_UINT16_LE, 3);
final int calibrationTypeAndSampleLocation = data.getIntValue(Data.FORMAT_UINT8, 5);
@SuppressLint("WrongConstant") final int calibrationType = calibrationTypeAndSampleLocation & 0x0F;
final int calibrationSampleLocation = calibrationTypeAndSampleLocation >> 4;
final int nextCalibrationTime = data.getIntValue(Data.FORMAT_UINT16_LE, 6);
final int calibrationDataRecordNumber = data.getIntValue(Data.FORMAT_UINT16_LE, 8);
final int calibrationStatus = data.getIntValue(Data.FORMAT_UINT8, 10);
onContinuousGlucoseCalibrationValueReceived(device, glucoseConcentrationOfCalibration,
calibrationTime, nextCalibrationTime, calibrationType, calibrationSampleLocation,
calibrationDataRecordNumber, new CGMCalibrationStatus(calibrationStatus), crcPresent);
return;
}
case OP_CODE_RESPONSE_CODE -> {
final int requestCode = data.getIntValue(Data.FORMAT_UINT8, 1); // ignore
final int responseCode = data.getIntValue(Data.FORMAT_UINT8, 2);
if (responseCode == CGM_RESPONSE_SUCCESS) {
onCGMSpecificOpsOperationCompleted(device, requestCode, crcPresent);
} else {
onCGMSpecificOpsOperationError(device, requestCode, responseCode, crcPresent);
}
return;
}
}
// Read SFLOAT value
final float value = data.getFloatValue(Data.FORMAT_SFLOAT, 1);
switch (opCode) {
case OP_CODE_PATIENT_HIGH_ALERT_LEVEL_RESPONSE ->
onContinuousGlucosePatientHighAlertReceived(device, value, crcPresent);
case OP_CODE_PATIENT_LOW_ALERT_LEVEL_RESPONSE ->
onContinuousGlucosePatientLowAlertReceived(device, value, crcPresent);
case OP_CODE_HYPO_ALERT_LEVEL_RESPONSE ->
onContinuousGlucoseHypoAlertReceived(device, value, crcPresent);
case OP_CODE_HYPER_ALERT_LEVEL_RESPONSE ->
onContinuousGlucoseHyperAlertReceived(device, value, crcPresent);
case OP_CODE_RATE_OF_DECREASE_ALERT_LEVEL_RESPONSE ->
onContinuousGlucoseRateOfDecreaseAlertReceived(device, value, crcPresent);
case OP_CODE_RATE_OF_INCREASE_ALERT_LEVEL_RESPONSE ->
onContinuousGlucoseRateOfIncreaseAlertReceived(device, value, crcPresent);
}
} | @Test
public void onContinuousGlucoseCommunicationIntervalReceived_notSecured() {
final Data data = new Data(new byte[] { 3, 11 });
callback.onDataReceived(null, data);
assertEquals("Interval", 11, interval);
assertFalse(secured);
} |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFunctionStatusStatement) sqlStatement));
}
if (sqlStatement instanceof ShowProcedureStatusStatement) {
return Optional.of(new ShowProcedureStatusExecutor((ShowProcedureStatusStatement) sqlStatement));
}
if (sqlStatement instanceof ShowTablesStatement) {
return Optional.of(new ShowTablesExecutor((ShowTablesStatement) sqlStatement, sqlStatementContext.getDatabaseType()));
}
return Optional.empty();
} | @Test
void assertCreateWithSelectStatementForTransactionIsolation() {
initProxyContext(Collections.emptyMap());
MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class);
when(selectStatement.getFrom()).thenReturn(Optional.empty());
ProjectionsSegment projectionsSegment = mock(ProjectionsSegment.class);
VariableSegment variableSegment = new VariableSegment(0, 0, "transaction_isolation");
variableSegment.setScope("SESSION");
when(projectionsSegment.getProjections()).thenReturn(Collections.singletonList(new ExpressionProjectionSegment(0, 10, "@@session.transaction_isolation", variableSegment)));
when(selectStatement.getProjections()).thenReturn(projectionsSegment);
when(sqlStatementContext.getSqlStatement()).thenReturn(selectStatement);
Optional<DatabaseAdminExecutor> actual = new MySQLAdminExecutorCreator().create(sqlStatementContext, "select @@session.transaction_isolation", "", Collections.emptyList());
assertTrue(actual.isPresent());
assertThat(actual.get(), instanceOf(MySQLSystemVariableQueryExecutor.class));
} |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testOnMergeAlreadyFinished() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
AfterEachStateMachine.inOrder(
AfterWatermarkStateMachine.pastEndOfWindow(),
RepeatedlyStateMachine.forever(AfterPaneStateMachine.elementCountAtLeast(1))),
Sessions.withGapDuration(Duration.millis(10)));
tester.injectElements(1);
tester.injectElements(5);
IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11));
IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15));
IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15));
// Finish the AfterWatermark.pastEndOfWindow() trigger in both windows
tester.advanceInputWatermark(new Instant(15));
assertTrue(tester.shouldFire(firstWindow));
assertTrue(tester.shouldFire(secondWindow));
tester.fireIfShouldFire(firstWindow);
tester.fireIfShouldFire(secondWindow);
// Confirm that we are on the second trigger by probing
assertFalse(tester.shouldFire(firstWindow));
assertFalse(tester.shouldFire(secondWindow));
tester.injectElements(1);
tester.injectElements(5);
assertTrue(tester.shouldFire(firstWindow));
assertTrue(tester.shouldFire(secondWindow));
tester.fireIfShouldFire(firstWindow);
tester.fireIfShouldFire(secondWindow);
// Merging should leave it finished
tester.mergeWindows();
// Confirm that we are on the second trigger by probing
assertFalse(tester.shouldFire(mergedWindow));
tester.injectElements(1);
assertTrue(tester.shouldFire(mergedWindow));
} |
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // TODO(b/134064106): design an alternative to no-arg check()
public final Ordered containsExactly() {
return check().about(iterableEntries()).that(checkNotNull(actual).entries()).containsExactly();
} | @Test
public void containsExactlyVararg() {
ImmutableListMultimap<Integer, String> listMultimap =
ImmutableListMultimap.of(1, "one", 3, "six", 3, "two");
assertThat(listMultimap).containsExactly(1, "one", 3, "six", 3, "two");
} |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldIdentifyAndUseCorrectSource() {
// Given:
givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE;");
// When:
injector.inject(statement, builder);
// Then:
verify(builder).withSource(argThat(supplierThatGets(sourceDescription)), any(Supplier.class));
} |
public synchronized static HealthCheckRegistry setDefault(String name) {
final HealthCheckRegistry registry = getOrCreate(name);
return setDefault(name, registry);
} | @Test
public void unableToSetDefaultRegistryTwice() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Default health check registry is already set.");
SharedHealthCheckRegistries.setDefault("default");
SharedHealthCheckRegistries.setDefault("default");
} |
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
Marshaller marshaller = getContext(clazz).createMarshaller();
setMarshallerProperties(marshaller);
if (marshallerEventHandler != null) {
marshaller.setEventHandler(marshallerEventHandler);
}
marshaller.setSchema(marshallerSchema);
return marshaller;
} | @Test
void buildsMarshallerWithDefaultEventHandler() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder().build();
Marshaller marshaller = factory.createMarshaller(Object.class);
assertThat(marshaller.getEventHandler()).isNotNull();
} |
public static void createFile(String filePath) {
Path storagePath = Paths.get(filePath);
Path parent = storagePath.getParent();
try {
if (parent != null) {
Files.createDirectories(parent);
}
Files.createFile(storagePath);
} catch (UnsupportedOperationException e) {
throw new UnimplementedRuntimeException(e, ErrorType.External);
} catch (ClassCastException e) {
throw new InvalidArgumentRuntimeException(e);
} catch (SecurityException e) {
throw new PermissionDeniedRuntimeException(e);
} catch (IOException e) {
throw new UnknownRuntimeException(e);
}
} | @Test
public void createFile() throws IOException {
File tempFile = new File(mTestFolder.getRoot(), "tmp");
FileUtils.createFile(tempFile.getAbsolutePath());
assertTrue(FileUtils.exists(tempFile.getAbsolutePath()));
assertTrue(tempFile.delete());
} |
public void setAttribute(String key, String value) {
ensureLocalMember();
if (instance != null && instance.node.clusterService.isJoined()) {
throw new UnsupportedOperationException("Attributes can not be changed after instance has started");
}
isNotNull(key, "key");
isNotNull(value, "value");
attributes.put(key, value);
} | @Test(expected = UnsupportedOperationException.class)
public void testSetAttribute_onRemoteMember() {
MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), false);
member.setAttribute("remoteMemberSet", "wontWork");
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testImplNewInstance() throws Exception {
DynConstructors.Ctor<MyClass> ctor =
DynConstructors.builder().impl(MyClass.class).buildChecked();
assertThat(ctor.newInstance()).isInstanceOf(MyClass.class);
} |
@Override
public String getName() {
return delegate().getName();
} | @Test
public void getNameDelegates() {
String name = "My_forwardingptransform-name;for!thisTest";
when(delegate.getName()).thenReturn(name);
assertThat(forwarding.getName(), equalTo(name));
} |
@Override
public Num calculate(BarSeries series, Position position) {
Num numberOfWinningPositions = numberOfWinningPositionsCriterion.calculate(series, position);
if (numberOfWinningPositions.isZero()) {
return series.zero();
}
Num grossProfit = grossProfitCriterion.calculate(series, position);
if (grossProfit.isZero()) {
return series.zero();
}
return grossProfit.dividedBy(numberOfWinningPositions);
} | @Test
public void calculateOnlyWithProfitPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series));
AnalysisCriterion avgProfit = getCriterion();
assertNumEquals(7.5, avgProfit.calculate(series, tradingRecord));
} |
public static String trimStart( final String source, char c ) {
if ( source == null ) {
return null;
}
int length = source.length();
int index = 0;
while ( index < length && source.charAt( index ) == c ) {
index++;
}
return source.substring( index );
} | @Test
public void testTrimStart_None() {
assertEquals( "file/path/", StringUtil.trimStart( "file/path/", '/' ) );
} |
@Override
public Split.Output run(RunContext runContext) throws Exception {
URI from = new URI(runContext.render(this.from));
return Split.Output.builder()
.uris(StorageService.split(runContext, this, from))
.build();
} | @Test
void partition() throws Exception {
RunContext runContext = runContextFactory.of();
URI put = storageUpload(1000);
Split result = Split.builder()
.from(put.toString())
.partitions(8)
.build();
Split.Output run = result.run(runContext);
assertThat(run.getUris().size(), is(8));
assertThat(run.getUris().getFirst().getPath(), endsWith(".yml"));
assertThat(StringUtils.countMatches(readAll(run.getUris()), "\n"), is(1000));
} |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey, metric);
} catch (Exception e) {
// catch and log to continue processing remaining metrics
log.error("Error processing Kafka metric {}", metricKey, e);
}
}
} | @Test
public void testMeasurableCounter() {
Sensor sensor = metrics.sensor("test");
sensor.add(metricName, new WindowedCount());
sensor.record();
sensor.record();
time.sleep(60 * 1000L);
// Collect metrics.
collector.collect(testEmitter);
List<SinglePointMetric> result = testEmitter.emittedMetrics();
// Should get exactly 2 Kafka measurables since Metrics always includes a count measurable.
assertEquals(2, result.size());
Metric counter = result.stream()
.flatMap(metrics -> Stream.of(metrics.builder().build()))
.filter(metric -> metric.getName().equals("test.domain.group1.name1")).findFirst().get();
assertTrue(counter.hasSum());
assertEquals(tags, getTags(counter.getSum().getDataPoints(0).getAttributesList()));
assertEquals(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE, counter.getSum().getAggregationTemporality());
assertTrue(counter.getSum().getIsMonotonic());
NumberDataPoint point = counter.getSum().getDataPoints(0);
assertEquals(2d, point.getAsDouble(), 0.0);
assertEquals(TimeUnit.SECONDS.toNanos(Instant.ofEpochSecond(61L).getEpochSecond()) +
Instant.ofEpochSecond(61L).getNano(), point.getTimeUnixNano());
assertEquals(TimeUnit.SECONDS.toNanos(Instant.ofEpochSecond(1L).getEpochSecond()) +
Instant.ofEpochSecond(1L).getNano(), point.getStartTimeUnixNano());
} |
public static <E> E get(final Iterator<E> iterator, int index) throws IndexOutOfBoundsException {
if(null == iterator){
return null;
}
Assert.isTrue(index >= 0, "[index] must be >= 0");
while (iterator.hasNext()) {
index--;
if (-1 == index) {
return iterator.next();
}
iterator.next();
}
return null;
} | @Test
public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
final String str = IterUtil.get(set.iterator(), 2);
assertEquals("C", str);
} |
private Map<String, String> appendConfig() {
Map<String, String> map = new HashMap<>(16);
map.put(INTERFACE_KEY, interfaceName);
map.put(SIDE_KEY, CONSUMER_SIDE);
ReferenceConfigBase.appendRuntimeParameters(map);
if (!ProtocolUtils.isGeneric(generic)) {
String revision = Version.getVersion(interfaceClass, version);
if (StringUtils.isNotEmpty(revision)) {
map.put(REVISION_KEY, revision);
}
String[] methods = methods(interfaceClass);
if (methods.length == 0) {
logger.warn(
CONFIG_NO_METHOD_FOUND,
"",
"",
"No method found in service interface: " + interfaceClass.getName());
map.put(METHODS_KEY, ANY_VALUE);
} else {
map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR));
}
}
AbstractConfig.appendParameters(map, getApplication());
AbstractConfig.appendParameters(map, getModule());
AbstractConfig.appendParameters(map, consumer);
AbstractConfig.appendParameters(map, this);
String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
if (StringUtils.isEmpty(hostToRegistry)) {
hostToRegistry = NetUtils.getLocalHost();
} else if (isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
}
map.put(REGISTER_IP_KEY, hostToRegistry);
if (CollectionUtils.isNotEmpty(getMethods())) {
for (MethodConfig methodConfig : getMethods()) {
AbstractConfig.appendParameters(map, methodConfig, methodConfig.getName());
String retryKey = methodConfig.getName() + ".retry";
if (map.containsKey(retryKey)) {
String retryValue = map.remove(retryKey);
if ("false".equals(retryValue)) {
map.put(methodConfig.getName() + ".retries", "0");
}
}
}
}
return map;
} | @Test
void testAppendConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
applicationConfig.setVersion("v1");
applicationConfig.setOwner("owner1");
applicationConfig.setOrganization("bu1");
applicationConfig.setArchitecture("architecture1");
applicationConfig.setEnvironment("test");
applicationConfig.setCompiler("javassist");
applicationConfig.setLogger("log4j");
applicationConfig.setDumpDirectory("/");
applicationConfig.setQosEnable(false);
applicationConfig.setQosHost("127.0.0.1");
applicationConfig.setQosPort(77777);
applicationConfig.setQosAcceptForeignIp(false);
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
applicationConfig.setShutwait("5");
applicationConfig.setMetadataType("local");
applicationConfig.setRegisterConsumer(false);
applicationConfig.setRepository("repository1");
applicationConfig.setEnableFileCache(false);
applicationConfig.setProtocol("dubbo");
applicationConfig.setMetadataServicePort(88888);
applicationConfig.setMetadataServiceProtocol("tri");
applicationConfig.setLivenessProbe("livenessProbe");
applicationConfig.setReadinessProbe("readinessProb");
applicationConfig.setStartupProbe("startupProbe");
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setClient("netty");
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
referenceConfig.setReconnect("reconnect");
referenceConfig.setSticky(false);
referenceConfig.setStub(DEFAULT_STUB_EVENT);
referenceConfig.setRouter("default");
referenceConfig.setReferAsync(true);
MonitorConfig monitorConfig = new MonitorConfig();
applicationConfig.setMonitor(monitorConfig);
ModuleConfig moduleConfig = new ModuleConfig();
moduleConfig.setMonitor("default");
moduleConfig.setName("module1");
moduleConfig.setOrganization("application1");
moduleConfig.setVersion("v1");
moduleConfig.setOwner("owner1");
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setClient("netty");
consumerConfig.setThreadpool("fixed");
consumerConfig.setCorethreads(200);
consumerConfig.setQueues(500);
consumerConfig.setThreads(300);
consumerConfig.setShareconnections(10);
consumerConfig.setUrlMergeProcessor("default");
consumerConfig.setReferThreadNum(20);
consumerConfig.setReferBackground(false);
referenceConfig.setConsumer(consumerConfig);
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
methodConfig.setStat(1);
methodConfig.setRetries(0);
methodConfig.setExecutes(10);
methodConfig.setDeprecated(false);
methodConfig.setSticky(false);
methodConfig.setReturn(false);
methodConfig.setService("service");
methodConfig.setServiceId(DemoService.class.getName());
methodConfig.setParentPrefix("demo");
referenceConfig.setMethods(Collections.singletonList(methodConfig));
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
RegistryConfig registry = new RegistryConfig();
registry.setAddress(zkUrl1);
applicationConfig.setRegistries(Collections.singletonList(registry));
applicationConfig.setRegistryIds(registry.getId());
moduleConfig.setRegistries(Collections.singletonList(registry));
referenceConfig.setRegistry(registry);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
dubboBootstrap
.application(applicationConfig)
.reference(referenceConfig)
.registry(registry)
.module(moduleConfig)
.initialize();
referenceConfig.init();
ServiceMetadata serviceMetadata = referenceConfig.getServiceMetadata();
// verify additional side parameter
Assertions.assertEquals(CONSUMER_SIDE, serviceMetadata.getAttachments().get(SIDE_KEY));
// verify additional interface parameter
Assertions.assertEquals(
DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY));
// verify additional metadata-type parameter
Assertions.assertEquals(
DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY));
// verify additional register.ip parameter
Assertions.assertEquals(
NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY));
// verify additional runtime parameters
Assertions.assertEquals(
Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY));
Assertions.assertEquals(
Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY));
Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(TIMESTAMP_KEY));
Assertions.assertEquals(
String.valueOf(ConfigUtils.getPid()),
serviceMetadata.getAttachments().get(PID_KEY));
// verify additional application config
Assertions.assertEquals(
applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY));
Assertions.assertEquals(
applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner"));
Assertions.assertEquals(
applicationConfig.getVersion(), serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY));
Assertions.assertEquals(
applicationConfig.getOrganization(),
serviceMetadata.getAttachments().get("organization"));
Assertions.assertEquals(
applicationConfig.getArchitecture(),
serviceMetadata.getAttachments().get("architecture"));
Assertions.assertEquals(
applicationConfig.getEnvironment(),
serviceMetadata.getAttachments().get("environment"));
Assertions.assertEquals(
applicationConfig.getCompiler(),
serviceMetadata.getAttachments().get("compiler"));
Assertions.assertEquals(
applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registry.ids"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor"));
Assertions.assertEquals(
applicationConfig.getDumpDirectory(),
serviceMetadata.getAttachments().get(DUMP_DIRECTORY));
Assertions.assertEquals(
applicationConfig.getQosEnable().toString(),
serviceMetadata.getAttachments().get(QOS_ENABLE));
Assertions.assertEquals(
applicationConfig.getQosHost(), serviceMetadata.getAttachments().get(QOS_HOST));
Assertions.assertEquals(
applicationConfig.getQosPort().toString(),
serviceMetadata.getAttachments().get(QOS_PORT));
Assertions.assertEquals(
applicationConfig.getQosAcceptForeignIp().toString(),
serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP));
Assertions.assertEquals(
applicationConfig.getParameters().get("key1"),
serviceMetadata.getAttachments().get("key1"));
Assertions.assertEquals(
applicationConfig.getParameters().get("key2"),
serviceMetadata.getAttachments().get("key2"));
Assertions.assertEquals(
applicationConfig.getShutwait(),
serviceMetadata.getAttachments().get("shutwait"));
Assertions.assertEquals(
applicationConfig.getMetadataType(),
serviceMetadata.getAttachments().get(METADATA_KEY));
Assertions.assertEquals(
applicationConfig.getRegisterConsumer().toString(),
serviceMetadata.getAttachments().get("register.consumer"));
Assertions.assertEquals(
applicationConfig.getRepository(),
serviceMetadata.getAttachments().get("repository"));
Assertions.assertEquals(
applicationConfig.getEnableFileCache().toString(),
serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED));
Assertions.assertEquals(
applicationConfig.getMetadataServicePort().toString(),
serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY));
Assertions.assertEquals(
applicationConfig.getMetadataServiceProtocol().toString(),
serviceMetadata.getAttachments().get(METADATA_SERVICE_PROTOCOL_KEY));
Assertions.assertEquals(
applicationConfig.getLivenessProbe(),
serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY));
Assertions.assertEquals(
applicationConfig.getReadinessProbe(),
serviceMetadata.getAttachments().get(READINESS_PROBE_KEY));
Assertions.assertEquals(
applicationConfig.getStartupProbe(),
serviceMetadata.getAttachments().get(STARTUP_PROBE));
// verify additional module config
Assertions.assertEquals(
moduleConfig.getName(), serviceMetadata.getAttachments().get("module"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor"));
Assertions.assertEquals(
moduleConfig.getOrganization(), serviceMetadata.getAttachments().get("module.organization"));
Assertions.assertEquals(
moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries"));
Assertions.assertEquals(
moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version"));
// verify additional consumer config
Assertions.assertEquals(
consumerConfig.getClient(), serviceMetadata.getAttachments().get("client"));
Assertions.assertEquals(
consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool"));
Assertions.assertEquals(
consumerConfig.getCorethreads().toString(),
serviceMetadata.getAttachments().get("corethreads"));
Assertions.assertEquals(
consumerConfig.getQueues().toString(),
serviceMetadata.getAttachments().get("queues"));
Assertions.assertEquals(
consumerConfig.getThreads().toString(),
serviceMetadata.getAttachments().get("threads"));
Assertions.assertEquals(
consumerConfig.getShareconnections().toString(),
serviceMetadata.getAttachments().get("shareconnections"));
Assertions.assertEquals(
consumerConfig.getUrlMergeProcessor(),
serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_THREAD_NUM_KEY));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_BACKGROUND_KEY));
// verify additional reference config
Assertions.assertEquals(
referenceConfig.getClient(), serviceMetadata.getAttachments().get("client"));
Assertions.assertEquals(
referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic"));
Assertions.assertEquals(
referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol"));
Assertions.assertEquals(
referenceConfig.isInit().toString(),
serviceMetadata.getAttachments().get("init"));
Assertions.assertEquals(
referenceConfig.getLazy().toString(),
serviceMetadata.getAttachments().get("lazy"));
Assertions.assertEquals(
referenceConfig.isInjvm().toString(),
serviceMetadata.getAttachments().get("injvm"));
Assertions.assertEquals(
referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect"));
Assertions.assertEquals(
referenceConfig.getSticky().toString(),
serviceMetadata.getAttachments().get("sticky"));
Assertions.assertEquals(
referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub"));
Assertions.assertEquals(
referenceConfig.getProvidedBy(),
serviceMetadata.getAttachments().get("provided-by"));
Assertions.assertEquals(
referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router"));
Assertions.assertEquals(
referenceConfig.getReferAsync().toString(),
serviceMetadata.getAttachments().get(REFER_ASYNC_KEY));
// verify additional method config
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("name"));
Assertions.assertEquals(
methodConfig.getStat().toString(),
serviceMetadata.getAttachments().get("sayName.stat"));
Assertions.assertEquals(
methodConfig.getRetries().toString(),
serviceMetadata.getAttachments().get("sayName.retries"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.reliable"));
Assertions.assertEquals(
methodConfig.getExecutes().toString(),
serviceMetadata.getAttachments().get("sayName.executes"));
Assertions.assertEquals(
methodConfig.getDeprecated().toString(),
serviceMetadata.getAttachments().get("sayName.deprecated"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.stick"));
Assertions.assertEquals(
methodConfig.isReturn().toString(),
serviceMetadata.getAttachments().get("sayName.return"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service.id"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.parent.prefix"));
// verify additional revision and methods parameter
Assertions.assertEquals(
Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()),
serviceMetadata.getAttachments().get(REVISION_KEY));
Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(METHODS_KEY));
Assertions.assertEquals(
DemoService.class.getMethods().length,
StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length);
dubboBootstrap.stop();
} |
public static <R> Mono<R> entryWith(String resourceName, Mono<R> actual) {
return entryWith(resourceName, EntryType.OUT, actual);
} | @Test
public void testReactorEntryWithBizException() {
String resourceName = createResourceName("testReactorEntryWithBizException");
StepVerifier.create(ReactorSphU.entryWith(resourceName, Mono.error(new IllegalStateException())))
.expectError(IllegalStateException.class)
.verify();
ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
assertNotNull(cn);
assertEquals(1, cn.passQps(), 0.01);
assertEquals(1, cn.totalException());
} |
public static <T extends Throwable> void checkContainsKey(final Map<?, ?> map, final Object key, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (!map.containsKey(key)) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckContainsKeyToNotThrowException() {
assertDoesNotThrow(() -> ShardingSpherePreconditions.checkContainsKey(Collections.singletonMap("foo", "value"), "foo", SQLException::new));
} |
public ModuleBuilder version(String version) {
this.version = version;
return getThis();
} | @Test
void version() {
ModuleBuilder builder = ModuleBuilder.newBuilder();
builder.version("version");
Assertions.assertEquals("version", builder.build().getVersion());
} |
public Instant toInstant() {
return instant;
} | @Test
public void testNanoPrecision() {
final String input = "2021-04-02T00:28:17.987654321Z";
final Timestamp t1 = new Timestamp(input);
assertEquals(987654321, t1.toInstant().getNano());
} |
@Override
public ByteBuf writeShort(int value) {
ensureWritable0(2);
_setShort(writerIndex, value);
writerIndex += 2;
return this;
} | @Test
public void testWriteShortAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeShort(1);
}
});
} |
@Override
public String getMessage() {
return null == message ? LocaleFactory.localizedString("Unknown") : message;
} | @Test
public void testGetMessage() {
final BackgroundException e = new BackgroundException(new LoginCanceledException());
e.setMessage("m");
assertEquals("m", e.getMessage());
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
}
} | @Test(expected = KubernetesClientException.class)
public void endpointsFailFastWhenNoPublicAccess() throws JsonProcessingException {
// given
cleanUpClient();
kubernetesClient = newKubernetesClient(ExposeExternallyMode.ENABLED, false, null, null);
stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsListResponse());
stub(String.format("/api/v1/namespaces/%s/endpoints", NAMESPACE), endpointsListResponse());
stub(String.format("/api/v1/namespaces/%s/services/service-0", NAMESPACE),
service(servicePort(0, 0, 0), servicePort(1, 1, 2)));
stub(String.format("/api/v1/namespaces/%s/services/hazelcast-0", NAMESPACE),
service(servicePort(0, 0, 0), servicePort(1, 1, 2)));
stub(String.format("/api/v1/namespaces/%s/services/service-1", NAMESPACE),
service(servicePort(0, 0, 0), servicePort(1, 1, 2)));
stub("/api/v1/nodes/node-name-1", node("node-name-1", "10.240.0.21", "35.232.226.200"));
stub("/api/v1/nodes/node-name-2", node("node-name-2", "10.240.0.22", "35.232.226.201"));
// when
List<Endpoint> result = kubernetesClient.endpoints();
// then
// exception
} |
@Override
public String getRawSourceHash(Component file) {
checkComponentArgument(file);
if (rawSourceHashesByKey.containsKey(file.getKey())) {
return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey()));
} else {
String newSourceHash = computeRawSourceHash(file);
rawSourceHashesByKey.put(file.getKey(), newSourceHash);
return checkSourceHash(file.getKey(), newSourceHash);
}
} | @Test
void getRawSourceHash_let_exception_go_through() {
IllegalArgumentException thrown = new IllegalArgumentException("this IAE will cause the hash computation to fail");
when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenThrow(thrown);
assertThatThrownBy(() -> mockedUnderTest.getRawSourceHash(FILE_COMPONENT))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(thrown.getMessage());
} |
@Override
public String convertToDatabaseColumn(Map<String, String> attribute) {
return GSON.toJson(attribute);
} | @Test
void convertToDatabaseColumn_empty() {
assertEquals("{}", this.converter.convertToDatabaseColumn(new HashMap<>(4)));
} |
public Result fetchArtifacts(String[] uris) {
checkArgument(uris != null && uris.length > 0, "At least one URI is required.");
ArtifactUtils.createMissingParents(baseDir);
List<File> artifacts =
Arrays.stream(uris)
.map(FunctionUtils.uncheckedFunction(this::fetchArtifact))
.collect(Collectors.toList());
if (artifacts.size() > 1) {
return new Result(null, artifacts);
}
if (artifacts.size() == 1) {
return new Result(artifacts.get(0), null);
}
// Should not happen.
throw new IllegalStateException("Corrupt artifact fetching state.");
} | @Test
void testMixedArtifactFetch() throws Exception {
File sourceFile = TestingUtils.getClassFile(getClass());
String uriStr = "file://" + sourceFile.toURI().getPath();
File sourceFile2 = getFlinkClientsJar();
String uriStr2 = "file://" + sourceFile2.toURI().getPath();
ArtifactFetchManager fetchMgr = new ArtifactFetchManager(configuration);
ArtifactFetchManager.Result res = fetchMgr.fetchArtifacts(new String[] {uriStr, uriStr2});
assertThat(res.getJobJar()).isNull();
assertThat(res.getArtifacts()).hasSize(2);
assertFetchedFile(res.getArtifacts().get(0), sourceFile);
assertFetchedFile(res.getArtifacts().get(1), sourceFile2);
} |
public void start(List<AlarmCallback> allCallbacks) {
LocalDateTime now = LocalDateTime.now();
lastExecuteTime = now;
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
try {
final List<AlarmMessage> alarmMessageList = new ArrayList<>(30);
LocalDateTime checkTime = LocalDateTime.now();
int minutes = Minutes.minutesBetween(lastExecuteTime, checkTime).getMinutes();
boolean[] hasExecute = new boolean[]{false};
alarmRulesWatcher.getRunningContext().values().forEach(ruleList -> ruleList.forEach(runningRule -> {
if (minutes > 0) {
runningRule.moveTo(checkTime);
/*
* Don't run in the first quarter per min, avoid to trigger false alarm.
*/
if (checkTime.getSecondOfMinute() > 15) {
hasExecute[0] = true;
alarmMessageList.addAll(runningRule.check());
}
}
}));
// Set the last execute time, and make sure the second is `00`, such as: 18:30:00
if (hasExecute[0]) {
lastExecuteTime = checkTime.withSecondOfMinute(0).withMillisOfSecond(0);
}
if (!alarmMessageList.isEmpty()) {
for (AlarmCallback callback : allCallbacks) {
try {
callback.doAlarm(alarmMessageList);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}, 10, 10, TimeUnit.SECONDS);
} | @Test
public void testTriggerTimePoint() throws InterruptedException {
String test = System.getProperty("AlarmCoreTest");
if (test == null) {
return;
}
Rules emptyRules = new Rules();
emptyRules.setRules(new ArrayList<>(0));
AlarmCore core = new AlarmCore(new AlarmRulesWatcher(emptyRules, null));
Map<String, List<RunningRule>> runningContext = Whitebox.getInternalState(core, "runningContext");
List<RunningRule> rules = new ArrayList<>(1);
RunningRule mockRule = mock(RunningRule.class);
List<LocalDateTime> checkTime = new LinkedList<>();
final boolean[] isAdd = {true};
doAnswer((Answer<Object>) mock -> {
if (isAdd[0]) {
checkTime.add(LocalDateTime.now());
}
return new ArrayList<>(0);
}).when(mockRule).check();
rules.add(mockRule);
runningContext.put("mock", rules);
core.start(new ArrayList<>(0));
for (int i = 0; i < 10; i++) {
Thread.sleep(60 * 1000L);
if (checkTime.size() >= 3) {
isAdd[0] = false;
Assertions.assertTrue(checkTimePoints(checkTime));
break;
}
if (i == 9) {
Assertions.assertTrue(false);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.