focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void syncHoodieTable() {
switch (bqSyncClient.getTableType()) {
case COPY_ON_WRITE:
case MERGE_ON_READ:
syncTable(bqSyncClient);
break;
default:
throw new UnsupportedOperationException(bqSyncClient.getTableType() + " table type is not supported yet.");
... | @Test
void useBQManifestFile_newTableNonPartitioned() {
properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_USE_BQ_MANIFEST_FILE.key(), "true");
when(mockBqSyncClient.getTableType()).thenReturn(HoodieTableType.COPY_ON_WRITE);
when(mockBqSyncClient.getBasePath()).thenReturn(TEST_TABLE_BASE_PATH);
w... |
public static ThreadFactory namedThreads(String pattern) {
return new ThreadFactoryBuilder()
.setNameFormat(pattern)
.setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
.build();
} | @Test
public void namedThreads() {
ThreadFactory f = Tools.namedThreads("foo-%d");
Thread t = f.newThread(() -> TestTools.print("yo"));
assertTrue("wrong pattern", t.getName().startsWith("foo-"));
} |
private Set<ConfigKey<?>> listConfigs(Application application, ConfigKey<?> keyToMatch, boolean recursive) {
Set<ConfigKey<?>> ret = new LinkedHashSet<>();
for (ConfigKey<?> key : application.allConfigsProduced()) {
String configId = key.getConfigId();
if (recursive) {
... | @Test
public void testListConfigs() throws IOException, SAXException {
TenantApplications applications = createTenantApplications(TenantName.defaultName(), curator, configserverConfig, new MockConfigActivationListener(), new InMemoryFlagSource());
assertFalse(applications.hasApplication(ApplicationI... |
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("position") BigDecimal position,
@ParameterName("newItem") Object newItem) {
if (list == null) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", CANNO... | @Test
void invokePositionInvalid() {
FunctionTestUtil.assertResultError(listReplaceFunction.invoke(Collections.emptyList(), BigDecimal.ONE, ""), InvalidParametersEvent.class);
List list = getList();
FunctionTestUtil.assertResultError(listReplaceFunction.invoke(list, BigDecimal.ZERO, ""), Inv... |
public Map<String, String> findAliasesInSQL(String[] sqlArguments) {
Map<String, String> res = new HashMap<>();
for (int i = 0; i < sqlArguments.length - 1; i++) {
if (columnsCompleters.keySet().contains(sqlArguments[i]) &&
sqlArguments[i + 1].matches("[a-zA-Z]+")) {
res.put(sqlArgum... | @Test
void testFindAliasesInSQL_Simple() {
String sql = "select * from prod_emart.financial_account a";
Map<String, String> res = sqlCompleter.findAliasesInSQL(
delimiter.delimit(sql, 0).getArguments());
assertEquals(1, res.size());
assertEquals("prod_emart.financial_account", res.get("a")... |
public CredentialRetriever googleApplicationDefaultCredentials() {
return () -> {
try {
if (imageReference.getRegistry().endsWith("gcr.io")
|| imageReference.getRegistry().endsWith("docker.pkg.dev")) {
GoogleCredentials googleCredentials = googleCredentialsProvider.get();
... | @Test
public void testGoogleApplicationDefaultCredentials_refreshFailure()
throws CredentialRetrievalException, IOException {
Mockito.doThrow(new IOException("refresh failed"))
.when(mockGoogleCredentials)
.refreshIfExpired();
CredentialRetrieverFactory credentialRetrieverFactory =
... |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void fail_to_create_query_on_tag_using_in_operator_and_value() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(IN).setValue("java").build()), emptySet());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessa... |
@Override
public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) {
Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:"
+ " URI path should not be null");
if (checkOSSCredentials(conf)) {
try {
return OSSUnderFileSystem.createInstance(new ... | @Test
public void createInstanceWithoutCredentials() {
Configuration.unset(PropertyKey.OSS_ACCESS_KEY);
Configuration.unset(PropertyKey.OSS_SECRET_KEY);
Configuration.unset(PropertyKey.OSS_ENDPOINT_KEY);
mAlluxioConf = Configuration.global();
mConf = UnderFileSystemConfiguration.defaults(mAlluxioC... |
public void onRequest(FilterRequestContext requestContext,
RestLiFilterResponseContextFactory filterResponseContextFactory)
{
// Initiate the filter chain iterator. The RestLiCallback will be passed to the method invoker at the end of the
// filter chain.
_filterChainIterator.onReq... | @SuppressWarnings("unchecked")
@Test
public void testFilterInvocationRequestErrorOnError() throws Exception
{
_restLiFilterChain = new RestLiFilterChain(Arrays.asList(_filters),
_mockFilterChainDispatcher, _mockFilterChainCallback);
_filters[1] = new CountFilterRequestErrorOnError();
when(_res... |
public static ExecutableStage forGrpcPortRead(
QueryablePipeline pipeline,
PipelineNode.PCollectionNode inputPCollection,
Set<PipelineNode.PTransformNode> initialNodes) {
checkArgument(
!initialNodes.isEmpty(),
"%s must contain at least one %s.",
GreedyStageFuser.class.getS... | @Test
public void materializesWithStatefulConsumer() {
// (impulse.out) -> parDo -> (parDo.out)
// (parDo.out) -> stateful -> stateful.out
// stateful has a state spec which prevents it from fusing with an upstream ParDo
PTransform parDoTransform =
PTransform.newBuilder()
.putInput... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthHashrate() throws Exception {
web3j.ethHashrate().send();
verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_hashrate\",\"params\":[],\"id\":1}");
} |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testReadFieldsNestedTuples() {
String[] readFields = {"f0.f1; f0.f2; f2"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, null, null, readFields, nestedTupleType, intType);
Fie... |
public static ByteString dataMapToByteString(Map<String, String> headers, DataMap dataMap) throws MimeTypeParseException, IOException
{
return ByteString.unsafeWrap(getContentType(headers).getCodec().mapToBytes(dataMap));
} | @Test
public void testDataMapToJSONByteString() throws MimeTypeParseException, IOException
{
DataMap testDataMap = createTestDataMap();
byte[] expectedBytes = JACKSON_DATA_CODEC.mapToBytes(testDataMap);
Map<String, String> headers = Collections.singletonMap(RestConstants.HEADER_CONTENT_TYPE, "applicati... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseStruct() {
TypeInfo fieldTypeInfo1 = TypeInfoFactory.STRING;
TypeInfo fieldTypeInfo2 = TypeInfoFactory.INT;
StructTypeInfo structTypeInfo =
TypeInfoFactory.getStructTypeInfo(ImmutableList.of("fieldTypeInfo1", "fieldTypeInfo2"),
... |
public static <T> T getFirst(Iterable<T> iterable) {
return IterUtil.getFirst(iterable);
} | @Test
public void getFirstTest() {
final List<?> nullList = null;
final Object first = CollUtil.getFirst(nullList);
assertNull(first);
} |
public static ConnectorOffsets consumerGroupOffsetsToConnectorOffsets(Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets) {
List<ConnectorOffset> connectorOffsets = new ArrayList<>();
for (Map.Entry<TopicPartition, OffsetAndMetadata> topicPartitionOffset : consumerGroupOffsets.entrySet()) {
... | @Test
public void testConsumerGroupOffsetsToConnectorOffsets() {
Map<TopicPartition, OffsetAndMetadata> consumerGroupOffsets = new HashMap<>();
ConnectorOffsets connectorOffsets = SinkUtils.consumerGroupOffsetsToConnectorOffsets(consumerGroupOffsets);
assertEquals(0, connectorOffsets.offsets... |
@VisibleForTesting
static Set<AbsoluteUnixPath> getVolumesSet(RawConfiguration rawConfiguration)
throws InvalidContainerVolumeException {
Set<AbsoluteUnixPath> volumes = new HashSet<>();
for (String path : rawConfiguration.getVolumes()) {
try {
AbsoluteUnixPath absoluteUnixPath = AbsoluteU... | @Test
public void testGetValidVolumesList() throws InvalidContainerVolumeException {
when(rawConfiguration.getVolumes()).thenReturn(Collections.singletonList("/some/root"));
assertThat(PluginConfigurationProcessor.getVolumesSet(rawConfiguration))
.containsExactly(AbsoluteUnixPath.get("/some/root"));
... |
@Override
public String select(List<String> columns, List<String> where) {
StringBuilder sql = new StringBuilder();
String method = "SELECT ";
sql.append(method);
for (int i = 0; i < columns.size(); i++) {
sql.append(columns.get(i));
if (i == columns.size() - ... | @Test
void testSelectAll() {
String sql = abstractMapper.select(Arrays.asList("id", "name"), null);
assertEquals("SELECT id,name FROM tenant_info ", sql);
} |
@SneakyThrows(PSQLException.class)
@Override
public void write(final PostgreSQLPacketPayload payload, final Object value) {
byte[] binaryDate = new byte[4];
new TimestampUtils(false, null).toBinDate(null, binaryDate, (Date) value);
payload.writeBytes(binaryDate);
} | @Test
void assertWrite() throws PSQLException {
byte[] actual = new byte[4];
PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(Unpooled.wrappedBuffer(actual).writerIndex(0), StandardCharsets.UTF_8);
Date input = Date.valueOf("2023-01-30");
new PostgreSQLDateBinaryProtocol... |
public int[] findMatchingLines(List<String> left, List<String> right) {
int[] index = new int[right.size()];
int dbLine = left.size();
int reportLine = right.size();
try {
PathNode node = new MyersDiff<String>().buildPath(left, right);
while (node.prev != null) {
PathNode prevNode ... | @Test
public void shouldFindNothingWhenContentAreIdentical() {
List<String> database = new ArrayList<>();
database.add("line - 0");
database.add("line - 1");
database.add("line - 2");
database.add("line - 3");
database.add("line - 4");
List<String> report = new ArrayList<>();
report.a... |
public static BadRequestException clusterNotExists(String clusterName) {
return new BadRequestException("cluster not exists for clusterName:%s", clusterName);
} | @Test
public void testClusterNotExists(){
BadRequestException clusterNotExists = BadRequestException.clusterNotExists(clusterName);
assertEquals("cluster not exists for clusterName:test", clusterNotExists.getMessage());
} |
@Transactional
public void update(MemberDto memberDto, Long templateId, UpdateTemplateRequest updateTemplateRequest) {
Member member = memberRepository.fetchById(memberDto.id());
Category category = categoryRepository.fetchById(updateTemplateRequest.categoryId());
validateCategoryAuthorizeMe... | @Test
@DisplayName("템플릿 수정 실패: 권한 없음")
void updateTemplateFailWithUnauthorized() {
// given
MemberDto memberDto = MemberDtoFixture.getFirstMemberDto();
Member member = memberRepository.fetchById(memberDto.id());
CreateTemplateRequest createdTemplate = makeTemplateRequest("title")... |
public Response request(Request request) throws NacosException {
return request(request, rpcClientConfig.timeOutMills());
} | @Test
void testRequestWithoutAnyTry() throws NacosException {
assertThrows(NacosException.class, () -> {
when(rpcClientConfig.retryTimes()).thenReturn(-1);
rpcClient.request(null);
});
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateArithmetic() {
// Given:
final Expression expression1 = new ArithmeticBinaryExpression(
Operator.ADD, new IntegerLiteral(1), new IntegerLiteral(2)
);
final Expression expression2 = new ArithmeticBinaryExpression(
Operator.ADD, new IntegerLiteral(1), new ... |
public static <T> Patch<T> diff(List<T> original, List<T> revised, DiffAlgorithmListener progress) {
return DiffUtils.diff(original, revised, DEFAULT_DIFF.create(), progress);
} | @Test
public void testDiff_EmptyListWithNonEmpty() {
final Patch<String> patch = DiffUtils.diff(new ArrayList<>(), Arrays.asList("aaa"));
assertNotNull(patch);
assertEquals(1, patch.getDeltas().size());
final AbstractDelta<String> delta = patch.getDeltas().get(0);
assertTrue(... |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testCallFeature() {
run("call-feature.feature");
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema != null && schema.type() != Type.BOOLEAN)
throw new DataException("Invalid schema type for BooleanConverter: " + schema.type().toString());
try {
return serializer.serialize(topic... | @Test
public void testFromConnectNullSchema() {
assertArrayEquals(
TRUE,
converter.fromConnectData(TOPIC, null, Boolean.TRUE)
);
assertArrayEquals(
FALSE,
converter.fromConnectData(TOPIC, null, Boolean.FALSE)
);
} |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
if (tradingRecord != null && !tradingRecord.isClosed()) {
Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice();
Num currentPrice = this.referencePrice.getValue(index);
N... | @Test
public void testShortPositionStopLoss() {
ZonedDateTime initialEndDateTime = ZonedDateTime.now();
for (int i = 0; i < 10; i++) {
series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100);
}
AverageTrueRangeStopLossRule rule = new AverageTrueRangeStopLossRul... |
@Override
public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) {
Map<String, Object> result = newLinkedHashMap();
OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication();
result.put(ACTIVE, true);
if (... | @Test
public void shouldAssembleExpectedResultForAccessToken_withPermissions() throws ParseException {
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"),
permissions(permission(1L, "foo", "bar")),
"Bearer", oauth2AuthenticationWithUser(oauth2Request("cl... |
public AnalysisResult analysis(AnalysisResult result) {
// 1. Set sub package name by source.metrics
Class<? extends Metrics> metricsClass = MetricsHolder.find(result.getAggregationFuncStmt().getAggregationFunctionName());
String metricsClassSimpleName = metricsClass.getSimpleName();
re... | @Test
public void testEndpointAnalysis() {
AnalysisResult result = new AnalysisResult();
result.getFrom().setSourceName("Endpoint");
result.getFrom().getSourceAttribute().add("latency");
result.setMetricsName("EndpointAvg");
result.getAggregationFuncStmt().setAggregationFunct... |
static String getObjectKey(Extension extension) {
return PrimaryKeySpecUtils.getObjectPrimaryKey(extension);
} | @Test
void getObjectKey() {
var fake = createFakeExtension();
assertThat(DefaultIndexer.getObjectKey(fake)).isEqualTo("fake-extension");
} |
static CastExpr getNumericPredictorExpression(final NumericPredictor numericPredictor) {
boolean withExponent = !Objects.equals(1, numericPredictor.getExponent());
final String lambdaExpressionMethodName = withExponent ? "evaluateNumericWithExponent" :
"evaluateNumericWithoutExponent";
... | @Test
void getNumericPredictorExpressionWithoutExponent() throws IOException {
String predictorName = "predictorName";
int exponent = 1;
double coefficient = 1.23;
NumericPredictor numericPredictor = PMMLModelTestUtils.getNumericPredictor(predictorName, exponent,
coef... |
@Override
public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return leftJoin(otherStream, toValueJoinerWi... | @Test
public void shouldNotAllowNullTableOnTableLeftJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.leftJoin(null, MockValueJoiner.TOSTRING_JOINER));
assertThat(exception.getMessage(), equalTo("table can't be null"));... |
public void begin() {
databaseConnectionManager.getConnectionPostProcessors().add(target -> target.setAutoCommit(false));
} | @Test
void assertBegin() {
localTransactionManager.begin();
verify(databaseConnectionManager).getConnectionPostProcessors();
} |
public boolean sendEvents(
final Message inMessage, final Consumer<StitchResponse> resultCallback, final AsyncCallback callback) {
sendAsyncEvents(inMessage)
.subscribe(resultCallback, error -> {
// error but we continue
if (LOG.isDebugEnabled(... | @Test
void testNormalSend() {
final StitchConfiguration configuration = new StitchConfiguration();
configuration.setTableName("table_1");
configuration.setStitchSchema(StitchSchema.builder().addKeyword("field_1", "string").build());
configuration.setKeyNames("field_1");
fina... |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
if(workdir.isRoot()) {
if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(session.getHost()))) {
f... | @Test
public void testSearchInDirectory() throws Exception {
final Path bucket = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final String name = new AlphanumericRan... |
public List<MappingField> resolveAndValidateFields(
List<MappingField> userFields,
Map<String, String> options,
NodeEngine nodeEngine
) {
final InternalSerializationService serializationService = (InternalSerializationService) nodeEngine
.getSerializationS... | @Test
public void when_keyClashesWithValue_then_keyIsChosen() {
Map<String, String> options = ImmutableMap.of(
OPTION_KEY_FORMAT, JAVA_FORMAT,
OPTION_VALUE_FORMAT, JAVA_FORMAT
);
given(resolver.resolveAndValidateFields(eq(true), eq(emptyList()), eq(options), e... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.OAUTH_CLIENT,
allEntries = true) // allEntries 清空所有缓存,因为可能修改到 clientId 字段,不好清理
public void updateOAuth2Client(OAuth2ClientSaveReqVO updateReqVO) {
// 校验存在
validateOAuth2ClientExists(updateReqVO.getId());
// 校验 Client 未被占用
... | @Test
public void testUpdateOAuth2Client_success() {
// mock 数据
OAuth2ClientDO dbOAuth2Client = randomPojo(OAuth2ClientDO.class);
oauth2ClientMapper.insert(dbOAuth2Client);// @Sql: 先插入出一条存在的数据
// 准备参数
OAuth2ClientSaveReqVO reqVO = randomPojo(OAuth2ClientSaveReqVO.class, o -> ... |
@Override
@Description("The status of the Kafka and ZooKeeper clusters, and Topic Operator.")
public KafkaStatus getStatus() {
return super.getStatus();
} | @Test
public void testListenersTypeAndName() {
Kafka model = TestUtils.fromYaml("Kafka-listener-name-and-status" + ".yaml", Kafka.class);
assertThat(model.getStatus().getListeners(), is(notNullValue()));
assertThat(model.getStatus().getListeners().size(), is(2));
List<ListenerSt... |
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
} | @Test
public void testCanSerializeParcelable() {
org.robolectric.shadows.ShadowLog.stream = System.err;
BeaconManager.setDebug(true);
final Beacon original = new AltBeacon.Builder().setMfgReserved(2)
.setBluetoothAddress("aa:bb:cc:dd:ee:... |
int getMinLonForTile(double lon) {
return (int) (Math.floor((180 + lon) / lonDegree) * lonDegree) - 180;
} | @Test
public void testMinLon() {
assertEquals(-60, instance.getMinLonForTile(-59.9));
assertEquals(0, instance.getMinLonForTile(0.9));
} |
@SuppressWarnings("unchecked")
public static void validateResponse(HttpURLConnection conn,
int expectedStatus) throws IOException {
if (conn.getResponseCode() != expectedStatus) {
Exception toThrow;
InputStream es = null;
try {
es = conn.getErrorStream();
Map json = JsonSer... | @Test
public void testValidateResponseNonJsonErrorMessage() throws Exception {
String msg = "stream";
InputStream is = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
Mockito.when(conn.getErrorStream()).thenReturn(is);
... |
@Override
protected Optional<String> get(String key) {
// search for the first value available in
// 1. system properties
// 2. core property from environment variable
// 3. thread local cache (if enabled)
// 4. db
String value = systemProps.getProperty(key);
if (value != null) {
re... | @Test
public void system_settings_have_precedence_over_database() {
insertPropertyIntoDb("foo", "from db");
underTest = create(system, ImmutableMap.of("foo", "from system"));
assertThat(underTest.get("foo")).hasValue("from system");
} |
public void generate() throws IOException {
Path currentWorkingDir = Paths.get("").toAbsolutePath();
final InputStream rawDoc = Files.newInputStream(currentWorkingDir.resolve(clientParameters.inputFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(rawDoc));
long... | @Test
void testOverwriteExistingDocumentFrequencyLanguage() throws IOException {
String inputPath = "no.jsonl";
String outputPath = "output.json";
ClientParameters params1 = createParameters(inputPath, outputPath, "text", "nb", "nb", "false").build();
SignificanceModelGenerator gene... |
@Override
public boolean isEnabled(CeWorker ceWorker) {
return ceWorker.getOrdinal() < ceConfiguration.getWorkerCount();
} | @Test
public void isEnabled_returns_false_if_worker_ordinal_is_equal_to_CeConfiguration_workerCount() {
when(ceWorker.getOrdinal()).thenReturn(randomWorkerCount);
assertThat(underTest.isEnabled(ceWorker)).isFalse();
} |
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode)
throws MllpAcknowledgementGenerationException {
generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null);
} | @Test
public void testGenerateAcknowledgementPayloadWithoutEnoughFields() {
final byte[] testMessage = TEST_MESSAGE.replace("||ORM^O01|00001|D|2.3|||||||", "").getBytes();
MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
assertThrows(MllpAcknowledgementGener... |
public static void deleteDirectory(File directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
if (!directory.exists()) {
return;
}
Path path = directory.toPath();
if (Files.isSymbolicLink(path)) {
throw new IOException(format("Directory '%s' is a symboli... | @Test
public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path folder = temporaryFolder.newFolder().toPath();
Path file1 = Files.createFile(folder.resolve("file1.txt"));
Path symLink = Files.createSymbolicLink(folder.resolve("link1"... |
@Override
public void initialize(URI uri, Configuration conf)
throws IOException
{
requireNonNull(uri, "uri is null");
requireNonNull(conf, "conf is null");
super.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAut... | @Test
public void testAssumeRoleCredentials()
throws Exception
{
Configuration config = new Configuration();
config.set(S3_IAM_ROLE, "role");
config.setBoolean(S3_USE_INSTANCE_CREDENTIALS, false);
try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
f... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为操作一个部门,涉及到多个缓存
public void deleteDept(Long id) {
// 校验是否存在
validateDeptExists(id);
// 校验是否有子部门
if (deptMapper.selectCountByParentId(id) > 0) {
... | @Test
public void testDeleteDept_success() {
// mock 数据
DeptDO dbDeptDO = randomPojo(DeptDO.class);
deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbDeptDO.getId();
// 调用
deptService.deleteDept(id);
// 校验数据不存在了
assertNull(d... |
public void clearAll() {
synchronized (registeredHandlers) {
registeredHandlers.clear();
}
} | @Test
void clearAll() throws Exception {
ResultPartitionID partitionId = new ResultPartitionID();
TaskEventDispatcher ted = new TaskEventDispatcher();
ted.registerPartition(partitionId);
//noinspection unchecked
ZeroShotEventListener eventListener1 = new ZeroShotEventListene... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testNoopWithAllVersionsFromSts(VertxTestContext context) {
String kafkaVersion = VERSIONS.defaultVersion().version();
String interBrokerProtocolVersion = VERSIONS.defaultVersion().protocolVersion();
String logMessageFormatVersion = VERSIONS.defaultVersion().messageVersion()... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testZukNewPb()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your TzKal-Zuk kill count is: <col=ff0000>2</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Duration: <col=ff0000>104:31</col> (new person... |
@Override
public void uploadPart(RefCountedFSOutputStream file) throws IOException {
// this is to guarantee that nobody is
// writing to the file we are uploading.
checkState(file.isClosed());
final CompletableFuture<PartETag> future = new CompletableFuture<>();
uploadsInPr... | @Test
public void multiplePartAndObjectUploadsShouldBeReflectedInRecoverable() throws IOException {
final byte[] firstCompletePart = bytesOf("hello world");
final byte[] secondCompletePart = bytesOf("hello again");
final byte[] thirdIncompletePart = bytesOf("!!!");
uploadPart(firstC... |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testLessThanOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg = builder.startAnd().lessThan("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
UnboundPredicate expected = Expressions.lessThan("salary", 3000L);
UnboundPredicate ... |
@Override
public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws NullPointerException, IllegalArgumentException {
// check if listener has already been added through another interface/service
if (!instanceListeners.add(listener)) {
ret... | @Test
void testAddServiceInstancesChangedListener() {
List<ServiceInstance> serviceInstances = new LinkedList<>();
// Add Listener
nacosServiceDiscovery.addServiceInstancesChangedListener(
new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), nacosServiceDiscovery) {... |
@Override
public T setLong(K name, long value) {
throw new UnsupportedOperationException("read only");
} | @Test
public void testSetLong() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
HEADERS.setLong("name", 0);
}
});
} |
public static void applyLocaleToContext(@NonNull Context context, @Nullable String localeString) {
final Locale forceLocale = LocaleTools.getLocaleForLocaleString(localeString);
final Configuration configuration = context.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.J... | @Test
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Ignore("Robolectric does not support this API")
public void testSetAndResetValueAPI17WithUnknownLocale() {
Assert.assertEquals(
"English (United States)",
mContext.getResources().getConfiguration().locale.getDisplayName());
LocaleTo... |
public Result getNewName( File destDir, String newPath ) {
try {
FileProvider<File> fileProvider = providerService.get( destDir.getProvider() );
return Result.success( "", fileProvider.getNewName( destDir, newPath, space ) );
} catch ( InvalidFileProviderException | FileException e ) {
return ... | @Test
public void testGetNewName() {
TestDirectory testDirectory = new TestDirectory();
testDirectory.setPath( "/directory1" );
String newName = (String) fileController.getNewName( testDirectory, "/directory1/file1" ).getData();
Assert.assertEquals( "/directory1/file1 1", newName );
} |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testConsumerGroupOffsetCommitWithStaleMemberEpoch() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Create an empty group.
ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup(
... |
@GetMapping("")
@RequiresPermissions("system:role:list")
public ShenyuAdminResult queryRole(final String roleName,
@RequestParam @NotNull final Integer currentPage,
@RequestParam @NotNull final Integer pageSize) {
CommonPager<... | @Test
public void testQueryRole() throws Exception {
RoleVO roleVO = buildRoleVO();
PageParameter pageParameter = new PageParameter();
RoleQuery query = new RoleQuery(roleVO.getRoleName(), pageParameter);
given(roleService.listByPage(query)).willReturn(new CommonPager<>(pageParameter... |
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY);
if (registryAttr... | @Test
public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception {
final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class);
final ServletContext servletContext = mock(ServletContext.class);
final ServletConfig servletConfig = mock(Servle... |
@Override public HashSlotCursor16byteKey cursor() {
return new CursorLongKey2();
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testCursor_key1_withoutAdvance() {
HashSlotCursor16byteKey cursor = hsa.cursor();
cursor.key1();
} |
public Set<RemotingChannel> removeChannel(Channel channel) {
Set<RemotingChannel> removedChannelSet = new HashSet<>();
Set<String> groupKeySet = groupChannelMap.keySet();
for (String group : groupKeySet) {
RemotingChannel remotingChannel = removeChannel(group, channel);
i... | @Test
public void testRemoveChannel() {
String consumerGroup = "consumerGroup";
String producerGroup = "producerGroup";
String clientId = RandomStringUtils.randomAlphabetic(10);
Channel consumerChannel = createMockChannel();
RemotingChannel consumerRemotingChannel = this.rem... |
protected Date getTimeBefore(final Date targetDate) {
final Calendar cl = Calendar.getInstance(getTimeZone());
// CronTrigger does not deal with milliseconds, so truncate target
cl.setTime(targetDate);
cl.set(Calendar.MILLISECOND, 0);
final Date targetDateNoMs = cl.getTime();
// to match this
Date start... | @Test
void getTimeBefore() throws ParseException {
CronExpression cronExpression = new CronExpression("0 0 8 1 JAN ?");
Date beforeDate = cronExpression.getTimeBefore(new Date());
System.out.println(beforeDate);
assertThat(beforeDate).isNotNull();
cronExpression = new CronExpression("0 */5 * * * ?");
befo... |
static String effectiveServices(File servicesFile, ZoneId zone, CloudName cloud, InstanceName instance, Tags tags) throws Exception {
Document processedServicesXml = new XmlPreProcessor(servicesFile.getParentFile(),
servicesFile,
... | @Test
@DisplayName("when zone matches region-and-environment directive")
void prodUsEast3() throws Exception {
assertEquals(Files.readString(Paths.get("src/test/resources/effective-services/prod_us-east-3.xml")),
effectiveServices(servicesFile, ZoneId.from("prod", "us-east-3"), Clou... |
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
if (response.status() == 404 || response.status() == 204)
if (JSONObject.class.isAssignableFrom((Class<?>) type))
return new JSONObject();
else if (JSONArray.class.isAssignableFrom((Class<?>) typ... | @Test
void decodeExtendedObject() throws IOException {
String json = "{\"a\":\"b\",\"c\":1}";
Response response = Response.builder()
.status(200)
.reason("OK")
.headers(Collections.emptyMap())
.body(json, UTF_8)
.request(request)
.build();
assertThat(jsonObj... |
public void refresh(List<Pair<T>> itemsWithWeight) {
Ref<T> newRef = new Ref<>(itemsWithWeight);
newRef.refresh();
newRef.poller = this.ref.poller.refresh(newRef.items);
this.ref = newRef;
} | @Test
void testRefresh() {
Chooser<String, String> chooser = new Chooser<>("test");
assertEquals("test", chooser.getUniqueKey());
assertNull(chooser.random());
List<Pair<String>> list = new LinkedList<>();
list.add(new Pair<>("test", 1));
chooser.refresh(list);
... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if(directory.isRoot()) {
final AttributedList<Path> list = new AttributedList<>();
list.add(MYFILES_NAME);
list.add(SHARED_NAME);
... | @Test
public void testListDrives() throws Exception {
// "Drives" rather placeholders for "My Files" and "Shared".
final AttributedList<Path> list = new OneDriveListService(session, fileid).list(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener());
assertFalse(... |
public void alterTableProperties(Database db, OlapTable table, Map<String, String> properties)
throws DdlException {
Map<String, String> propertiesToPersist = new HashMap<>(properties);
Map<String, Object> results = validateToBeModifiedProps(properties, table);
TableProperty tablePr... | @Test
public void testAlterTableProperties() throws Exception {
Database db = connectContext.getGlobalStateMgr().getDb("test");
OlapTable table = (OlapTable) db.getTable("t1");
Map<String, String> properties = Maps.newHashMap();
properties.put(PropertyAnalyzer.PROPERTIES_DATACACHE_P... |
@Override
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为 permission 如果变更,涉及到新老两个 permission。直接清理,简单有效
public void updateMenu(MenuSaveVO updateReqVO) {
// 校验更新的菜单是否存在
if (menuMapper.selectById(updateReqVO.getId()) == null) {
... | @Test
public void testUpdateMenu_sonIdNotExist() {
// 准备参数
MenuSaveVO reqVO = randomPojo(MenuSaveVO.class);
// 调用,并断言异常
assertServiceException(() -> menuService.updateMenu(reqVO), MENU_NOT_EXISTS);
} |
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode =... | @Test
public void resetContextUsingZookeeperUris() throws Exception {
// Change to signle zookeeper uri
URI uri = URI.create(Constants.HEADER + "zk@zkHost:2181/");
FileSystem fs = getHadoopFilesystem(org.apache.hadoop.fs.FileSystem.get(uri, getConf()));
assertTrue(fs.mFileSystem.getConf().getBoolean(... |
@Override
protected void activate() {
move(0, 0, 20);
playSound("SKYLAUNCH_SOUND", 1);
spawnParticles("SKYLAUNCH_PARTICLE", 100);
} | @Test
void testActivate() throws Exception {
var skyLaunch = new SkyLaunch();
var logs = tapSystemOutNormalized(skyLaunch::activate)
.split("\n");
final var expectedSize = 3;
final var log1 = getLogContent(logs[0]);
final var expectedLog1 = "Move to ( 0.0, 0.0, 20.0 )";
final var log2 ... |
public static <T, E extends Throwable> CompletableFuture<T> handleException(
CompletableFuture<? extends T> completableFuture,
Class<E> exceptionClass,
Function<? super E, ? extends T> exceptionHandler) {
final CompletableFuture<T> handledFuture = new CompletableFuture<>();
... | @Test
void testHandleExceptionWithCompletedFuture() {
final CompletableFuture<String> future = CompletableFuture.completedFuture("foobar");
final CompletableFuture<String> handled =
FutureUtils.handleException(future, Exception.class, exception -> "handled");
assertThatFutur... |
public static String toHumanReadable(long size) {
if (size < 0)
return String.valueOf(size);
if (size >= EB)
return formatSize(size, EB, "EB");
if (size >= PB)
return formatSize(size, PB, "PB");
if (size >= TB)
return formatSize(size, TB, "... | @Test
public void toHumanReadableTest() {
Map<Long, String> capacityTable = new HashMap<Long, String>() {
{
put(-1L, "-1");
put(0L, "0B");
put(1023L, "1023B");
put(1024L, "1KB");
put(12_345L, "12.06KB");
... |
public synchronized long nextGtid() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
timestamp = lastTimestamp;
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
timestamp... | @Test
public void testGtidTimestampAdvancement() {
long firstGtid = gtidGenerator.nextGtid();
long secondGtid = gtidGenerator.nextGtid();
long firstTimestamp = firstGtid >> GtidGenerator.TIMESTAMP_SHIFT;
long secondTimestamp = secondGtid >> GtidGenerator.TIMESTAMP_SHIFT;
Ass... |
public void checkPAT(String serverUrl, String token) {
String url = String.format("%s/_apis/projects?%s", getTrimmedUrl(serverUrl), API_VERSION_3);
doGet(token, url);
} | @Test
public void check_pat() throws InterruptedException {
enqueueResponse(200, " { \"count\": 1,\n" +
" \"value\": [\n" +
" {\n" +
" \"id\": \"3311cd05-3f00-4a5e-b47f-df94a9982b6e\",\n" +
" \"name\": \"Project\",\n" +
" \"description\": \"Project Description\",\n... |
@Override
public BarSeries aggregate(BarSeries series, String aggregatedSeriesName) {
final List<Bar> aggregatedBars = barAggregator.aggregate(series.getBarData());
return new BaseBarSeries(aggregatedSeriesName, aggregatedBars);
} | @Test
public void testAggregateWithTheSameName() {
final List<Bar> bars = new LinkedList<>();
final ZonedDateTime time = ZonedDateTime.of(2019, 6, 12, 4, 1, 0, 0, ZoneId.systemDefault());
final Bar bar0 = new MockBar(time, 1d, 2d, 3d, 4d, 5d, 6d, 7, numFunction);
final Bar bar1 = ne... |
private KsqlScalarFunction createFunction(
final Class theClass,
final UdfDescription udfDescriptionAnnotation,
final Udf udfAnnotation,
final Method method,
final String path,
final String sensorName,
final Class<? extends Kudf> udfClass
) {
// sanity check
FunctionL... | @Test
@SuppressWarnings("unchecked")
public void shouldPassSqlInputTypesToUdafs() throws Exception {
final UdafFactoryInvoker creator
= createUdafLoader().createUdafFactoryInvoker(
TestUdaf.class.getMethod("createSumT"),
FunctionName.of("test-udf"),
"desc",
new String[]{"... |
@Override
public DiagnosticsBuilder getDiagnosticsInfo() {
return diagnostics()
.withTitle("Concurrent modified jobs:")
.with(concurrentJobModificationResolveResults, (resolveResult, diagnosticsBuilder) -> appendDiagnosticsInfo(diagnosticsBuilder, resolveResult));
} | @Test
void canGenerateCorrectDiagnosticsInfoEvenWithOnly1State() {
final Job localJob = anEnqueuedJob().build();
final Job jobFromStorage = aFailedJob().build();
final ConcurrentJobModificationResolveResult resolveResult = ConcurrentJobModificationResolveResult.failed(localJob, jobFromStora... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator361() {
UrlValidator validator = new UrlValidator();
assertTrue(validator.isValid("http://hello.tokyo/"));
} |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void formats_returns_html_message_for_single_issue_on_branch_when_analysis_change() {
String branchName = randomAlphabetic(6);
Project project = newBranch("1", branchName);
String ruleName = randomAlphabetic(8);
String host = randomAlphabetic(15);
String key = "key";
ChangedIssue ... |
public static InternalFactHandle[] orderFacts(ObjectStore objectStore) {
// this method is just needed for testing purposes, to allow round tripping
int size = objectStore.size();
InternalFactHandle[] handles = new InternalFactHandle[size];
int i = 0;
for ( Iterator<InternalFactH... | @Test
public void testOrderFacts() throws Exception {
List<InternalFactHandle> list = new ArrayList<InternalFactHandle>();
List<Integer> ids = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 30, 31, 32, -2147483640, 7, 8, 9, 10, 11, 12, 13,14, 15, 28, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27);
for(I... |
@InvokeOnHeader(Web3jConstants.ETH_GET_COMPILERS)
void ethGetCompilers(Message message) throws IOException {
Request<?, EthGetCompilers> request = web3j.ethGetCompilers();
setRequestId(message, request);
EthGetCompilers response = request.send();
boolean hasError = checkForError(mess... | @Test
public void ethGetCompilersTest() throws Exception {
EthGetCompilers response = Mockito.mock(EthGetCompilers.class);
Mockito.when(mockWeb3j.ethGetCompilers()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getCompilers()).thenRetur... |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(ur... | @Test
public void testItpcProtocol() {
final String in = "itpc://example.com";
final String out = UrlChecker.prepareUrl(in);
assertEquals("http://example.com", out);
} |
@Override
public Optional<Instant> getStartedAt() {
return Optional.ofNullable(startedAt);
} | @Test
void getStartedAt_whenComponentIsCreated_shouldNotBePresent() {
assertThat(underTest.getStartedAt()).isEmpty();
} |
public static BadRequestException create(String... errorMessages) {
return create(asList(errorMessages));
} | @Test
public void fail_when_creating_exception_with_empty_list() {
assertThatThrownBy(() -> BadRequestException.create(Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("At least one error message is required");
} |
@ScalarFunction
@SqlType(StandardTypes.BOOLEAN)
public static boolean isJsonScalar(@SqlType(StandardTypes.JSON) Slice json)
{
try (JsonParser parser = createJsonParser(JSON_FACTORY, json)) {
JsonToken nextToken = parser.nextToken();
if (nextToken == null) {
th... | @Test
public void testIsJsonScalar()
{
assertFunction("IS_JSON_SCALAR(null)", BOOLEAN, null);
assertFunction("IS_JSON_SCALAR(JSON 'null')", BOOLEAN, true);
assertFunction("IS_JSON_SCALAR(JSON 'true')", BOOLEAN, true);
assertFunction("IS_JSON_SCALAR(JSON '1')", BOOLEAN, true);
... |
@Override
public List<Port> getPorts(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_NULL);
return manager.getVirtualPorts(this.networkId, deviceId)
.stream()
.collect(Collectors.toList());
} | @Test
public void testGetPorts() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
VirtualDevice virtualDevice = manager.createVirtualDevice(virtualNetwork.id(), DID1);
manag... |
public TaskRunScheduler getTaskRunScheduler() {
return taskRunScheduler;
} | @Test
public void testTaskRunMergeTimeFirst() {
TaskRunManager taskRunManager = new TaskRunManager();
Task task = new Task("test");
task.setDefinition("select 1");
long taskId = 1;
TaskRun taskRun1 = TaskRunBuilder
.newBuilder(task)
.setExec... |
void commitOffsetsOrTransaction(final Map<Task, Map<TopicPartition, OffsetAndMetadata>> offsetsPerTask) {
log.debug("Committing task offsets {}", offsetsPerTask.entrySet().stream().collect(Collectors.toMap(t -> t.getKey().id(), Entry::getValue))); // avoid logging actual Task objects
final Set<TaskId> ... | @Test
public void testCommitWithOpenTransactionButNoOffsetsEOSV1() {
final TaskId taskId = new TaskId(0, 0);
final Task task = mock(Task.class);
when(task.id()).thenReturn(taskId);
final Tasks tasks = mock(Tasks.class);
final ConsumerGroupMetadata groupMetadata = mock(Consum... |
@Override
public Server build(Environment environment) {
printBanner(environment.getName());
final ThreadPool threadPool = createThreadPool(environment.metrics());
final Server server = buildServer(environment.lifecycle(), threadPool);
final Handler applicationHandler = createAppServ... | @Test
void doesNotDefaultExceptionMappers() {
http.setRegisterDefaultExceptionMappers(false);
assertThat(http.getRegisterDefaultExceptionMappers()).isFalse();
Environment environment = new Environment("test");
http.build(environment);
assertThat(environment.jersey().getResour... |
@Override
public boolean validateTree(ValidationContext validationContext) {
validate(validationContext);
return (onCancelConfig.validateTree(validationContext) && errors.isEmpty() && !configuration.hasErrors());
} | @Test
public void validateTreeShouldVerifyIfOnCancelTasksHasErrors() {
PluggableTask pluggableTask = new PluggableTask(new PluginConfiguration(), new Configuration());
pluggableTask.onCancelConfig = mock(OnCancelConfig.class);
com.thoughtworks.go.domain.Task cancelTask = mock(com.thoughtwork... |
@UdafFactory(description = "collect distinct values of a Bigint field into a single Array")
public static <T> Udaf<T, List<T>, List<T>> createCollectSetT() {
return new Collect<>();
} | @Test
public void shouldCollectDistinctInts() {
final Udaf<Integer, List<Integer>, List<Integer>> udaf = CollectSetUdaf.createCollectSetT();
final Integer[] values = new Integer[] {3, 4, 5, 3};
List<Integer> runningList = udaf.initialize();
for (final Integer i : values) {
runningList = udaf.agg... |
public static JSONObject checkOrSetChannelCallbackEvent(String eventName, JSONObject properties, Context context) {
if (properties == null) {
properties = new JSONObject();
}
try {
boolean isFirst = isFirstChannelEvent(eventName);
properties.put("$is_channel_c... | @Test
public void checkOrSetChannelCallbackEvent() {
final String eventName = "eventName";
JSONObject property = new JSONObject();
try {
property.put("a", "a");
property.put("b", "b");
} catch (JSONException e) {
e.printStackTrace();
}
... |
public List<Column> value() {
return byNamespace()
.get(VALUE);
} | @Test
public void shouldExposeValueColumns() {
assertThat(SOME_SCHEMA.value(), contains(
valueColumn(F0, STRING),
valueColumn(F1, BIGINT)
));
} |
T init(Object value) {
return (T) value;
} | @Test
public void testHllUnionAggregator() {
HllUnionAggregator aggregator = new HllUnionAggregator();
Hll value = aggregator.init(null);
Assert.assertEquals(Hll.HLL_DATA_EMPTY, value.getType());
} |
protected HttpUriRequest setupConnection(final String method, final String bucketName,
final String objectKey, final Map<String, String> requestParameters) throws S3ServiceException {
return this.setupConnection(HTTP_METHOD.valueOf(method), bucketName, objectKey, req... | @Test
public void testSetupConnection() throws Exception {
final RequestEntityRestStorageService service = new RequestEntityRestStorageService(session, new HttpConnectionPoolBuilder(session.getHost(),
new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManager(), session.getHo... |
public int computeIfAbsent(final int key, final IntUnaryOperator mappingFunction)
{
requireNonNull(mappingFunction);
final int missingValue = this.missingValue;
final int[] entries = this.entries;
@DoNotSub final int mask = entries.length - 1;
@DoNotSub int index = Hashing.ev... | @Test
void shouldComputeIfAbsentUsingInterface()
{
final Map<Integer, Integer> map = new Int2IntHashMap(-1);
final int key = 0;
final int result = map.computeIfAbsent(key, (k) -> k);
assertEquals(key, result);
} |
@Override
public int mkdir(String path, long mode) {
return AlluxioFuseUtils.call(LOG, () -> mkdirInternal(path, mode),
FuseConstants.FUSE_MKDIR, "path=%s,mode=%o,", path, mode);
} | @Test
@DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu")
@Ignore
public void mkDir() throws Exception {
long mode = 0755L;
mFuseFs.mkdir("/foo/bar", mode);
verify(mFileSystem).createDirectory(BASE_EXPECTED_URI.join("/foo/bar"),
CreateDirectoryPOptions.newBuilder()
... |
private <T> T newPlugin(Class<T> klass) {
// KAFKA-8340: The thread classloader is used during static initialization and must be
// set to the plugin's classloader during instantiation
try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) {
return Utils.newInstance(kl... | @Test
public void newPluginShouldServiceLoadWithPluginClassLoader() {
Converter plugin = plugins.newPlugin(
TestPlugin.SERVICE_LOADER.className(),
new AbstractConfig(new ConfigDef(), Collections.emptyMap()),
Converter.class
);
assertInstanceOf(SamplingTes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.