focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public BrokerService getBrokerService() {
return service;
} | @Test(timeOut = 30000)
public void testProducerOnNotOwnedTopic() throws Exception {
resetChannel();
setChannelConnected();
// Force the case where the broker doesn't own any topic
doReturn(CompletableFuture.completedFuture(false)).when(namespaceService)
.isServiceUni... |
@Override
public HttpRestResult<String> httpGet(String path, Map<String, String> headers, Map<String, String> paramValues,
String encode, long readTimeoutMs) throws Exception {
final long endTime = System.currentTimeMillis() + readTimeoutMs;
String currentServerAddr = serverListMgr.getCu... | @Test
void testHttpWithRequestException() throws Exception {
assertThrows(NacosException.class, () -> {
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
any(Header.class), any(Query.class), eq(String.class))).thenThrow(new Connec... |
@SuppressWarnings("unused") // Required for automatic type inference
public static <K> Builder0<K> forClass(final Class<K> type) {
return new Builder0<>();
} | @Test
public void shouldNotThrowOnDuplicateHandlerR2() {
HandlerMaps.forClass(BaseType.class)
.withArgTypes(String.class, Integer.class)
.withReturnType(Number.class)
.put(LeafTypeA.class, handlerR2_1)
.put(LeafTypeB.class, handlerR2_1);
} |
@Override
public void linkNodes(K parentKey, K childKey, BiConsumer<TreeEntry<K, V>, TreeEntry<K, V>> consumer) {
consumer = ObjectUtil.defaultIfNull(consumer, (parent, child) -> {
});
final TreeEntryNode<K, V> parentNode = nodes.computeIfAbsent(parentKey, t -> new TreeEntryNode<>(null, t));
TreeEntryNode<K, V... | @Test
public void containsParentNodeTest() {
final ForestMap<String, String> map = new LinkedForestMap<>(false);
map.linkNodes("a", "b");
map.linkNodes("b", "c");
assertTrue(map.containsParentNode("c", "b"));
assertTrue(map.containsParentNode("c", "a"));
assertTrue(map.containsParentNode("b", "a"));
asse... |
@Override
public <R extends MessageResponse<?>> R chat(Prompt<R> prompt, ChatOptions options) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + getConfig().getApiKey());
Consumer<Map<String, Str... | @Test()
public void testChatWithImage() {
OpenAiLlmConfig config = new OpenAiLlmConfig();
config.setApiKey("sk-5gqOclb****0");
config.setModel("gpt-4-turbo");
Llm llm = new OpenAiLlm(config);
ImagePrompt prompt = new ImagePrompt("What's in this image?");
prompt.setIm... |
public static String toString(RedisCommand<?> command, Object... params) {
if (RedisCommands.AUTH.equals(command)) {
return "command: " + command + ", params: (password masked)";
}
return "command: " + command + ", params: " + LogHelper.toString(params);
} | @Test
public void toStringWithNestedPrimitives() {
Object[] input = new Object[] { "0", 1, 2L, 3.1D, 4.2F, (byte) 5, '6' };
assertThat(LogHelper.toString(input)).isEqualTo("[0, 1, 2, 3.1, 4.2, 5, 6]");
} |
static Set<Integer> parseStatusCodes(String statusCodesString) {
if (statusCodesString == null || statusCodesString.isEmpty()) {
return Collections.emptySet();
}
Set<Integer> codes = new LinkedHashSet<Integer>();
for (String codeString : statusCodesString.split(",")) {
codes.add(Integer.pars... | @Test
void parseCodes() {
assertThat(LBClient.parseStatusCodes("")).isEmpty();
assertThat(LBClient.parseStatusCodes(null)).isEmpty();
assertThat(LBClient.parseStatusCodes("504")).contains(504);
assertThat(LBClient.parseStatusCodes("503,504")).contains(503, 504);
} |
@Override
public String toString() {
return elapsed().toMillis() + " ms";
} | @Test
public void toString_() {
stopwatch.toString();
} |
@VisibleForTesting
static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) {
ImmutableSortedMap.Builder<OffsetRange, Integer> rval =
ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE);
List<OffsetRange> sortedRanges = Lists.newArrayList(ranges);
if (... | @Test
public void testMultipleOverlapsForTheSameRange() {
Iterable<OffsetRange> ranges =
Arrays.asList(
range(0, 4),
range(0, 8),
range(0, 12),
range(0, 12),
range(4, 12),
range(8, 12),
range(0, 4),
range(0, 8)... |
@Override
public Optional<ShardingConditionValue> generate(final BetweenExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) {
ConditionValue betweenConditionValue = new ConditionValue(predicate.getBetweenExpr(), params);
ConditionVal... | @Test
void assertGenerateConditionValueWithoutParameter() {
ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("id"));
ParameterMarkerExpressionSegment between = new ParameterMarkerExpressionSegment(0, 0, 0);
ParameterMarkerExpressionSegment and = new ParameterMarkerExpressionS... |
public String toLastBitString(long value, int bits) {
StringBuilder sb = new StringBuilder(bits);
long lastBit = 1L << bits - 1;
for (int i = 0; i < bits; i++) {
if ((value & lastBit) == 0)
sb.append('0');
else
sb.append('1');
... | @Test
public void testToLastBitString() {
assertEquals("1", bitUtil.toLastBitString(1L, 1));
assertEquals("01", bitUtil.toLastBitString(1L, 2));
assertEquals("001", bitUtil.toLastBitString(1L, 3));
assertEquals("010", bitUtil.toLastBitString(2L, 3));
assertEquals("011", bitUt... |
public static ServiceDescriptor genericService() {
return genericServiceDescriptor;
} | @Test
void genericService() {
Assertions.assertNotNull(ServiceDescriptorInternalCache.genericService());
Assertions.assertEquals(
GenericService.class,
ServiceDescriptorInternalCache.genericService().getServiceInterfaceClass());
} |
@PreAcquireNamespaceLock
@PutMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{itemId}")
public ItemDTO update(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName,
@PathVariable("namespaceName") String nam... | @Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testUpdate() {
this.testCreate();
String appId = "someAppId";
AppDTO app = restTemplate.get... |
@Override
public Set<String> validSiteKeys(final Action action) {
final DynamicCaptchaConfiguration config = dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration();
if (!config.isAllowHCaptcha()) {
logger.warn("Received request to verify an hCaptcha, but hCaptcha is not enabled");
... | @Test
public void badSiteKey() throws IOException {
final HCaptchaClient hc = new HCaptchaClient("fake", null, mockConfig(true, 0.5));
for (Action action : Action.values()) {
assertThat(hc.validSiteKeys(action)).contains(SITE_KEY);
assertThat(hc.validSiteKeys(action)).doesNotContain("invalid");
... |
private static ClientAuthenticationMethod getClientAuthenticationMethod(
List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
if (metadataAuthMethods == null || metadataAuthMethods
.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
// If ... | @Test
public void buildWhenPasswordGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationGrantType(AuthorizationGra... |
public static PrivateKey parsePrivateKey(String pemRepresentation, String passPhrase) throws IOException {
if (pemRepresentation == null || pemRepresentation.trim().isEmpty()) {
throw new IllegalArgumentException("Argument 'pemRepresentation' cannot be null or an empty String.");
}
... | @Test
public void testParsePrivateKey() throws Exception
{
// Setup fixture.
try ( final InputStream stream = getClass().getResourceAsStream( "/privatekey.pem" ) )
{
// Execute system under test.
final PrivateKey result = CertificateManager.parsePrivateKey( stream... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(file.attributes().getLink() != DescriptiveUrl.EMPTY) {
list.add(file.attributes().getLink());
}
list.add(new DescriptiveUrl(URI.create(String.format("%s%... | @Test
public void testRelativeDocumentRoot() {
Host host = new Host(new TestProtocol(), "localhost");
host.setDefaultPath("public_html");
Path path = new Path(
"/usr/home/dkocher/public_html/file", EnumSet.of(Path.Type.directory));
assertEquals("http://localhost/file"... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
if(!session.getClient().changeWorkingDirectory(directory.getAbsolute())) {
throw new FTPException(session.getClient().getReplyCode(), session.g... | @Test
public void testListDefault() throws Exception {
final ListService list = new FTPDefaultListService(session, new CompositeFileEntryParser(Collections.singletonList(new UnixFTPEntryParser())),
FTPListService.Command.list);
final Path directory = new FTPWorkdirService(session).find()... |
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 ... | @Test
public void testMergeCannotModifySource() {
// Don't allow to modify the source
AssertHelper.assertThrows(
"Should not allow updating source",
MaestroValidationException.class,
"Cannot modify source for parameter [tomerge]",
new Runnable() {
@SneakyThrows
... |
private <T> RestResponse<T> get(final String path, final Class<T> type) {
return executeRequestSync(HttpMethod.GET,
path,
null,
r -> deserialize(r.getBody(), type),
Optional.empty());
} | @Test
public void shouldPostQueryRequest_chunkHandler_partialMessage() {
ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST,
Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT);
executor.submit(this::expectPostQueryRequestChunkHandler);
assertThatEventual... |
public Set<ExpiredMetadataInfo> getExpiredMetadataInfos() {
return expiredMetadataInfos;
} | @Test
void testGetExpiredMetadataInfos() {
Set<ExpiredMetadataInfo> expiredMetadataInfos = namingMetadataManager.getExpiredMetadataInfos();
assertNotNull(expiredMetadataInfos);
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testSlaughterCheck1()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_BRACELET_OF_SLAUGHTER_1, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_... |
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException {
// set URL if set in authnRequest
final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL();
if (authnAcsURL != null) {
... | @Test
void resolveAcsUrlWithoutIndexInSingleAcsMetadata() throws SamlValidationException {
AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
authenticationRequest.setAuthnRequest(authnReq... |
@Override
protected String convertFromString(final String value) throws ConversionException {
final Path path = Paths.get(value);
if (path.getParent() != null) {
throw new ConversionException(
String.format("%s must be a filename only (%s)", KEY, path));
}
... | @Test
void testJarIdWithParentDir() throws Exception {
assertThatThrownBy(() -> jarIdPathParameter.convertFromString("../../test.jar"))
.isInstanceOf(ConversionException.class);
} |
public BranchesList getBranches(String serverUrl, String token, String projectSlug, String repositorySlug) {
HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s/branches", projectSlug, repositorySlug));
return doGet(token, url, body -> buildGson().fromJson(body, BranchesList.class));
... | @Test
public void getBranches_given0Branches_returnEmptyList() {
String bodyWith0Branches = "{\n" +
" \"size\": 0,\n" +
" \"limit\": 25,\n" +
" \"isLastPage\": true,\n" +
" \"values\": [],\n" +
" \"start\": 0\n" +
"}";
server.enqueue(new MockResponse()
.setHeader... |
@Override
public URL select(List<URL> urls, String serviceId, String tag, String requestKey) {
URL url = null;
if (urls.size() > 1) {
String key = tag == null ? serviceId : serviceId + "|" + tag;
url = doSelect(urls, key);
} else if (urls.size() == 1) {
ur... | @Test
public void testSelect() throws Exception {
List<URL> urls = new ArrayList<>();
urls.add(new URLImpl("http", "127.0.0.1", 8081, "v1", new HashMap<String, String>()));
urls.add(new URLImpl("http", "127.0.0.1", 8082, "v1", new HashMap<String, String>()));
urls.add(new URLImpl("h... |
protected String getUserDnForSearch(String userName) {
if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) {
// memberAttributeValuePrefix and memberAttributeValueSuffix
// were computed from memberAttributeValueTemplate
return memberDn(userName);
} else {
return ge... | @Test
void getUserDnForSearch() {
LdapRealm realm = new LdapRealm();
realm.setUserSearchAttributeName("uid");
assertEquals("foo", realm.getUserDnForSearch("foo"));
// using a template
realm.setUserSearchAttributeName(null);
realm.setMemberAttributeValueTemplate("cn={0},ou=people,dc=hadoop,dc... |
@Override
public JwtAuthenticationToken convert(Jwt jwt) {
Map<String, Map<String, Collection<String>>> resourceAccess = jwt
.getClaim(KeycloakJwtToken.RESOURCE_ACCESS_TOKEN_CLAIM);
if (resourceAccess != null) {
Map<String, Collection<String>> microcksResource = resourceAccess.get(K... | @Test
void testConvert() {
MicrocksJwtConverter converter = new MicrocksJwtConverter();
Jwt jwt = null;
try {
JWT parsedJwt = JWTParser.parse(jwtBearer);
jwt = createJwt(jwtBearer, parsedJwt);
} catch (Exception e) {
fail("Parsing Jwt bearer should not fail");
... |
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException {
final String httpSessionId = authenticationRequest.getRequest().getSession().getId();
if (authenticationRequest.getFederationName() !... | @Test
public void findSSOSessionForceAuthnInitializeTest() throws SamlSessionException, SharedServiceClientException {
authnRequest.setForceAuthn(TRUE);
authenticationRequest.setAuthnRequest(authnRequest);
samlSessionService.initializeSession(authenticationRequest, bindingContext);
... |
@Override
public ObjectNode encode(MaintenanceDomain md, CodecContext context) {
checkNotNull(md, "Maintenance Domain cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(MD_NAME, md.mdId().toString())
.put(MD_NAME_TYPE, md.mdId().nameType().... | @Test
public void testEncodeMd1() throws CfmConfigException {
MaintenanceDomain md1 = DefaultMaintenanceDomain.builder(MDID1_CHAR)
.mdLevel(MaintenanceDomain.MdLevel.LEVEL1)
.mdNumericId((short) 1)
.build();
ObjectNode node = mapper.createObjectNode()... |
@Override
public Map<String, InterpreterClient> restore() throws IOException {
Map<String, InterpreterClient> clients = new HashMap<>();
List<Path> paths = fs.list(new Path(recoveryDir + "/*.recovery"));
for (Path path : paths) {
String fileName = path.getName();
String interpreterSettingName... | @Test
void testSingleInterpreterProcess() throws InterpreterException, IOException {
InterpreterSetting interpreterSetting = interpreterSettingManager.getByName("test");
interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED);
Interpreter interpreter1 = interpreterSetting.getDefaultInterprete... |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void testToObject4() {
assertThrows(Exception.class, () -> {
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), TypeUtils.parameterize(Map.class, String.class, String.class));
});
} |
public void resetPositionsIfNeeded() {
Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp();
if (offsetResetTimestamps.isEmpty())
return;
resetPositionsAsync(offsetResetTimestamps);
} | @Test
public void testFetchOffsetErrors() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.LATEST);
// Fail with OFFSET_NOT_AVAILABLE
client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.LATEST_TIMESTAM... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void pinChatMessage() {
BaseResponse response = bot.execute(new PinChatMessage(groupId, 18).disableNotification(false));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: CHAT_NOT_MODIFIED", response.description());
... |
@Override
public <T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess(
NonKeyedPartitionStream<T_OTHER> other,
TwoInputNonBroadcastStreamProcessFunction<T, T_OTHER, OUT> processFunction) {
validateStates(
processFunction.usesStates(),
... | @Test
void testStateErrorWithConnectNonKeyedStream() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
NonKeyedPartitionStreamImpl<Integer> stream =
new NonKeyedPartitionStreamImpl<>(
env, new TestingTransformation<>("t1", Types.INT, ... |
@Override
public OAuth2AccessTokenDO getAccessToken(String accessToken) {
// 优先从 Redis 中获取
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken);
if (accessTokenDO != null) {
return accessTokenDO;
}
// 获取不到,从 MySQL 中获取
accessToken... | @Test
public void testGetAccessToken() {
// mock 数据(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class)
.setExpiresTime(LocalDateTime.now().plusDays(1));
oauth2AccessTokenMapper.insert(accessTokenDO);
// 准备参数
String accessToken = ac... |
public static String substitute(
final String string,
final Map<String, String> valueMap
) {
return StringSubstitutor.replace(
string, valueMap.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> sanitize(e.getValue())))
);
} | @Test
public void shouldSubstituteVariablesInString() {
// Given
final Map<String, String> variablesMap = new ImmutableMap.Builder<String, String>() {{
put("event", "birthday");
}}.build();
// When
final String substituted = VariableSubstitutor.substitute("Happy ${event} to you!", variables... |
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc,
long partitionId, boolean isTemp) throws DdlException {
Range<PartitionKey> range;
try {
range = checkAndCreateRang... | @Test(expected = DdlException.class)
public void testFixedRange5() throws DdlException, AnalysisException {
//add columns
int columns = 2;
Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", "");
Column k2 = new Column("k2", new ScalarType(PrimitiveType.BI... |
public static boolean hasNested(LogicalType logicalType, Predicate<LogicalType> predicate) {
final NestedTypeSearcher typeSearcher = new NestedTypeSearcher(predicate);
return logicalType.accept(typeSearcher).isPresent();
} | @Test
void testHasNested() {
final DataType dataType = ROW(FIELD("f0", INT()), FIELD("f1", STRING()));
assertThat(
LogicalTypeChecks.hasNested(
dataType.getLogicalType(), t -> t.is(LogicalTypeRoot.VARCHAR)))
.isTrue();
... |
public static Resource multiplyAndRoundDown(Resource lhs, double by) {
return multiplyAndRound(clone(lhs), by, RoundingDirection.DOWN);
} | @Test
void testMultiplyAndRoundDown() {
assertEquals(createResource(4, 1),
multiplyAndRoundDown(createResource(3, 1), 1.5),
INVALID_RESOURCE_MSG);
assertEquals(createResource(4, 1, 0),
multiplyAndRoundDown(createResource(3, 1), 1.5),
INVALID_RESOURCE_MSG);
assertEquals(crea... |
@Override public boolean remove(long key) {
return super.remove0(key, 0);
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testRemove_whenDisposed() {
hsa.dispose();
hsa.remove(1);
} |
public static BigInteger decodeQuantity(String value) {
if (isLongValue(value)) {
return BigInteger.valueOf(Long.parseLong(value));
}
if (!isValidHexQuantity(value)) {
throw new MessageDecodingException("Value must be in format 0x[0-9a-fA-F]+");
}
try {
... | @Test
public void testQuantityDecodeLong() {
assertEquals(Numeric.decodeQuantity("1234"), BigInteger.valueOf(1234));
} |
public static <T> Write<T> write() {
return new Write<>();
} | @Test
public void testWriteWithBackoff() throws Exception {
String tableName = DatabaseTestHelper.getTestTableName("UT_WRITE_BACKOFF");
DatabaseTestHelper.createTable(DATA_SOURCE, tableName);
// lock table
final Connection connection = DATA_SOURCE.getConnection();
Statement lockStatement = connec... |
public long completeSegmentByteCount() {
long result = size;
if (result == 0) return 0;
// Omit the tail if it's still writable.
Segment tail = head.prev;
if (tail.limit < Segment.SIZE && tail.owner) {
result -= tail.limit - tail.pos;
}
return result;
} | @Test public void completeSegmentByteCountOnEmptyBuffer() throws Exception {
Buffer buffer = new Buffer();
assertEquals(0, buffer.completeSegmentByteCount());
} |
ConnectorStatus.Listener wrapStatusListener(ConnectorStatus.Listener delegateListener) {
return new ConnectorStatusListener(delegateListener);
} | @Test
public void testTaskFailureAfterStartupRecordedMetrics() {
WorkerMetricsGroup workerMetricsGroup = new WorkerMetricsGroup(new HashMap<>(), new HashMap<>(), connectMetrics);
final TaskStatus.Listener taskListener = workerMetricsGroup.wrapStatusListener(delegateTaskListener);
taskListen... |
public static RedissonClient create() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return create(config);
} | @Test
public void testClusterConnectionFail() {
Awaitility.await().atLeast(Duration.ofSeconds(3)).atMost(Duration.ofSeconds(7)).untilAsserted(() -> {
Assertions.assertThrows(RedisConnectionException.class, () -> {
Config config = new Config();
config.useCluste... |
public static String ipAddressToUrlString(InetAddress address) {
if (address == null) {
throw new NullPointerException("address is null");
} else if (address instanceof Inet4Address) {
return address.getHostAddress();
} else if (address instanceof Inet6Address) {
... | @Test
void testIPv6toURL() throws UnknownHostException {
final String addressString = "2001:01db8:00:0:00:ff00:42:8329";
final String normalizedAddress = "[2001:1db8::ff00:42:8329]";
InetAddress address = InetAddress.getByName(addressString);
assertThat(NetUtils.ipAddressToUrlString... |
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
Class<OutputT> clazz) {
return to(TypeDescriptor.of(clazz));
} | @Test
@Category(NeedsRunner.class)
public void testGeneralConvert() {
PCollection<POJO2> pojos =
pipeline.apply(Create.of(new POJO1())).apply(Convert.to(POJO2.class));
PAssert.that(pojos).containsInAnyOrder(new POJO2());
pipeline.run();
} |
public void persist() throws Exception {
if (!mapping.equals(initialMapping)) {
state.update(
mapping.entrySet().stream()
.map((w) -> new Tuple2<>(w.getKey(), w.getValue()))
.collect(Collectors.toList()));
}
} | @Test
void testPersist() throws Exception {
@SuppressWarnings("unchecked")
ListState<Tuple2<TimeWindow, TimeWindow>> mockState = mock(ListState.class);
MergingWindowSet<TimeWindow> windowSet =
new MergingWindowSet<>(
EventTimeSessionWindows.withGap(Ti... |
public DdlCommandResult execute(
final String sql,
final DdlCommand ddlCommand,
final boolean withQuery,
final Set<SourceName> withQuerySources
) {
return execute(sql, ddlCommand, withQuery, withQuerySources, false);
} | @Test
public void shouldDropSource() {
// Given:
metaStore.putSource(source, false);
givenDropSourceCommand(STREAM_NAME);
// When:
final DdlCommandResult result = cmdExec.execute(SQL_TEXT, dropSource, false, NO_QUERY_SOURCES);
// Then
assertThat(result.isSuccess(), is(true));
assertT... |
public final void isLessThan(int other) {
isLessThan((double) other);
} | @Test
public void isLessThan_int_strictly() {
expectFailureWhenTestingThat(2.0).isLessThan(1);
} |
public int wrapAdjustment()
{
return wrapAdjustment;
} | @Test
void shouldExposePositionAtWhichByteArrayGetsWrapped()
{
final UnsafeBuffer wibbleBuffer = new UnsafeBuffer(
wibbleBytes, ADJUSTMENT_OFFSET, wibbleBytes.length - ADJUSTMENT_OFFSET);
wibbleBuffer.putByte(0, VALUE);
assertEquals(VALUE, wibbleBytes[wibbleBuffer.wrapAdjus... |
public ListNode2<T> add(T value) {
ListNode2<T> node = new ListNode2<T>(value);
if (size++ == 0) {
tail = node;
} else {
node.prev = head;
head.next = node;
}
head = node;
return node;
} | @Test
public void testAdd() {
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
list.add(1);
assertFalse(list.isEmpty());
assertEquals(1, list.size());
assertArrayEquals(new Integer[]{1}, list.toArray());
list.add(2);
assertFalse(list.isEmpty()... |
public static int bytesToCodePoint(ByteBuffer bytes) {
bytes.mark();
byte b = bytes.get();
bytes.reset();
int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
if (extraBytesToRead < 0) return -1; // trailing byte!
int ch = 0;
switch (extraBytesToRead) {
case 5: ch += (bytes.get() & 0xFF); ... | @Test
public void testbytesToCodePointWithInvalidUTF() {
try {
Text.bytesToCodePoint(ByteBuffer.wrap(new byte[] {-2}));
fail("testbytesToCodePointWithInvalidUTF error unexp exception !!!");
} catch (BufferUnderflowException ex) {
} catch(Exception e) {
fail("testby... |
public ExternalIssueReport parse(Path reportPath) {
try (Reader reader = Files.newBufferedReader(reportPath, StandardCharsets.UTF_8)) {
ExternalIssueReport report = gson.fromJson(reader, ExternalIssueReport.class);
externalIssueReportValidator.validate(report, reportPath);
return report;
} cat... | @Test
public void parse_whenDoesntExist_shouldFail() {
reportPath = Paths.get("unknown.json");
assertThatThrownBy(() -> externalIssueReportParser.parse(reportPath))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to read external issues report 'unknown.json'");
} |
@Override
public Optional<String> validate(String password) {
return password.matches(LOWER_CASE_REGEX)
? Optional.empty()
: Optional.of(LOWER_CASE_REASONING);
} | @Test
public void testValidateFailure() {
Optional<String> result = lowerCaseValidator.validate("PASSWORD");
Assert.assertTrue(result.isPresent());
Assert.assertEquals(result.get(), "must contain at least one lower case");
} |
protected List<Message> buildMessage(ProxyContext context, List<apache.rocketmq.v2.Message> protoMessageList,
Resource topic) {
String topicName = topic.getName();
List<Message> messageExtList = new ArrayList<>();
for (apache.rocketmq.v2.Message protoMessage : protoMessageList) {
... | @Test
public void testBuildMessage() {
long deliveryTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5);
ConfigurationManager.getProxyConfig().setMessageDelayLevel("1s 5s");
ConfigurationManager.getProxyConfig().initData();
String msgId = MessageClientIDSetter.createUniq... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
final DescriptiveUrl base = new DefaultWebUrlProvider().toUrl(host);
list.add(new DescriptiveUrl(URI.create(String.format("%s%s", base.getUrl(), URIEncoder.encode(
... | @Test
public void testCustom() {
final Host host = new Host(new TestProtocol(), "test.cyberduck.ch");
host.setWebURL("customhost");
assertEquals("http://customhost/", new DefaultWebUrlProvider().toUrl(host).getUrl());
assertEquals("http://customhost/my/documentroot/f",
ne... |
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException {
final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class);
... | @Test
void parseArtifactResolveSuccessBsn() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException {
ArtifactResponse artifactResponse = artifactResponseService.buildArtifactResponse(getArtifactResolveRequest("success", true, false,SAML_COMBICONNECT, Enc... |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
// OpenTracing aims to use low cardinality operation names. Ideally, a
// specific span decorator should be defined for all relevant Camel
// components that identify a meaningful operation name
return g... | @Test
public void testGetOperationName() {
Endpoint endpoint = Mockito.mock(Endpoint.class);
Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI);
SpanDecorator decorator = new AbstractSpanDecorator() {
@Override
public String getComponent() {
... |
public void run(String[] args) {
if (!parseArguments(args)) {
showOptions();
return;
}
if (command == null) {
System.out.println("Error: Command is empty");
System.out.println();
showOptions();
return;
}
if ... | @Test
public void testMissingPassword() {
Main main = new Main();
assertDoesNotThrow(() -> main.run("-c encrypt -i tiger".split(" ")));
} |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testEquals() {
for (Pair<String, Object> pair : FIELD_VALUE_LIST) {
UnboundPredicate<?> expected =
org.apache.iceberg.expressions.Expressions.equal(pair.first(), pair.second());
Optional<org.apache.iceberg.expressions.Expression> actual =
FlinkFilters.convert(
... |
static BigtableConfig translateToBigtableConfig(BigtableConfig config, BigtableOptions options) {
BigtableConfig.Builder builder = config.toBuilder();
if (options.getProjectId() != null && config.getProjectId() == null) {
builder.setProjectId(ValueProvider.StaticValueProvider.of(options.getProjectId()));... | @Test
public void testBigtableOptionsToBigtableConfig() throws Exception {
BigtableOptions options =
BigtableOptions.builder()
.setProjectId("project")
.setInstanceId("instance")
.setAppProfileId("app-profile")
.setDataHost("localhost")
.setPort(... |
@Nullable
public static ValueReference of(Object value) {
if (value instanceof Boolean) {
return of((Boolean) value);
} else if (value instanceof Double) {
return of((Double) value);
} else if (value instanceof Float) {
return of((Float) value);
} ... | @Test
public void deserializeInteger() throws IOException {
assertThat(objectMapper.readValue("{\"@type\":\"integer\",\"@value\":1}", ValueReference.class)).isEqualTo(ValueReference.of(1));
assertThat(objectMapper.readValue("{\"@type\":\"integer\",\"@value\":42}", ValueReference.class)).isEqualTo(Va... |
@Override
@SuppressWarnings("deprecation")
public HttpClientOperations addHandler(ChannelHandler handler) {
super.addHandler(handler);
return this;
} | @Test
void addDecoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT, ReactorNettyHttp... |
@Override
public void close() throws Exception {
if (aggregateLocalUsagePeriodicTask != null) {
aggregateLocalUsagePeriodicTask.cancel(true);
}
if (calculateQuotaPeriodicTask != null) {
calculateQuotaPeriodicTask.cancel(true);
}
resourceGroupsMap.clear... | @Test
public void testClose() throws Exception {
ResourceGroupService service = new ResourceGroupService(pulsar, TimeUnit.MILLISECONDS, null, null);
service.close();
Assert.assertTrue(service.getAggregateLocalUsagePeriodicTask().isCancelled());
Assert.assertTrue(service.getCalculateQ... |
@Draft
public ZMsg msgBinaryPicture(String picture, Object... args)
{
if (!BINARY_FORMAT.matcher(picture).matches()) {
throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(),
ZError.EPROTO);
}
ZMsg msg = new ZMsg();... | @Test
public void testValidPictureNullMsgInTheEnd()
{
String picture = "fm";
ZMsg msg = pic.msgBinaryPicture(picture, new ZFrame("My frame"), null);
assertThat(msg.getLast().size(), is(0));
} |
public String sign(RawTransaction rawTransaction) {
byte[] signedMessage = txSignService.sign(rawTransaction, chainId);
return Numeric.toHexString(signedMessage);
} | @Test
public void testSignRawTxWithHSM() throws IOException {
TransactionReceipt transactionReceipt = prepareTransfer();
prepareTransaction(transactionReceipt);
OkHttpClient okHttpClient = mock(OkHttpClient.class);
Call call = mock(Call.class);
Response hmsResponse =
... |
public MetricsBuilder enableRpc(Boolean enableRpc) {
this.enableRpc = enableRpc;
return getThis();
} | @Test
void enableRpc() {
MetricsBuilder builder = MetricsBuilder.newBuilder();
builder.enableRpc(false);
Assertions.assertFalse(builder.build().getEnableRpc());
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
attributes.find(file, listener);
return true;
}
catch(NotfoundException e) {
... | @Test
public void testFindDirectory() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path folder = new GoogleStorageDirectoryFeature(session).mkdir(
new Path(container, new AlphanumericRandomStringServ... |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void incorrectTypeIsFound() {
assertThatExceptionOfType(ConfigurationParsingException.class)
.isThrownBy(() -> factory.build(configurationSourceProvider, wrongTypeFile))
.withMessage("%s has an error:%n" +
" * Incorrect type of value at: age; is of type: String... |
@SuppressWarnings("unchecked")
@Override
public int hashCode() {
return hashCode(JAVA_HASHER);
} | @Test
public void emptyHeadersShouldBeEqual() {
TestDefaultHeaders headers1 = newInstance();
TestDefaultHeaders headers2 = newInstance();
assertNotSame(headers1, headers2);
assertEquals(headers1, headers2);
assertEquals(headers1.hashCode(), headers2.hashCode());
} |
public static String encodeCredentials(ALM alm, String pat, @Nullable String username) {
if (!alm.equals(BITBUCKET_CLOUD)) {
return pat;
}
return Base64.getEncoder().encodeToString((username + ":" + pat).getBytes(UTF_8));
} | @Test
public void encodes_credential_returns_username_and_encoded_pat_for_bitbucketcloud() {
String encodedPat = Base64.getEncoder().encodeToString((USERNAME + ":" + PAT).getBytes(UTF_8));
String encodedCredential = CredentialsEncoderHelper.encodeCredentials(ALM.BITBUCKET_CLOUD, PAT, USERNAME);
assertTha... |
public static Write<String> writeStrings() {
return Write.newBuilder(
(ValueInSingleWindow<String> stringAndWindow) ->
new PubsubMessage(
stringAndWindow.getValue().getBytes(StandardCharsets.UTF_8), ImmutableMap.of()))
.setDynamicDestinations(false)
.b... | @Test
public void testPrimitiveWriteDisplayData() {
DisplayDataEvaluator evaluator = DisplayDataEvaluator.create();
PubsubIO.Write<?> write = PubsubIO.writeStrings().to("projects/project/topics/topic");
Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms(write);
assertThat(
... |
@Override
public void filter(ContainerRequestContext requestContext) {
if (isInternalRequest(requestContext)) {
log.trace("Skipping authentication for internal request");
return;
}
try {
log.debug("Authenticating request");
BasicAuthCredential... | @Test
public void testUnknownBearer() throws IOException {
File credentialFile = setupPropertyLoginFile(true);
JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", credentialFile.getPath());
ContainerRequestContext requestContext = setMock("Unknown", "user", "password");... |
@Override
public Object getValue() {
try {
return mBeanServerConn.getAttribute(getObjectName(), attributeName);
} catch (IOException | JMException e) {
return null;
}
} | @Test
public void returnsAttributeForObjectNamePattern() throws Exception {
ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*");
JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value");
assertThat(gauge.getValue()).isInstanceOf(Long.class);... |
public static String maskRegex(String input, String key, String name) {
Map<String, Object> regexConfig = (Map<String, Object>) config.get(MASK_TYPE_REGEX);
if (regexConfig != null) {
Map<String, Object> keyConfig = (Map<String, Object>) regexConfig.get(key);
if (keyConfig != nul... | @Test
public void testMaskResponseHeader() {
String testHeader = "header";
String output = Mask.maskRegex(testHeader, "responseHeader", "header3");
System.out.println("output = " + output);
Assert.assertEquals(output, "******");
} |
@VisibleForTesting
long getJmxCacheTTL() {
return jmxCacheTTL;
} | @Test
public void testMetricCacheUpdateRace() throws Exception {
// Create test source with a single metric counter of value 1.
TestMetricsSource source = new TestMetricsSource();
MetricsSourceBuilder sourceBuilder =
MetricsAnnotations.newSourceBuilder(source);
final long JMX_CACHE_TTL = 250;... |
@Override
public QueryActionStats execute(Statement statement, QueryStage queryStage)
{
return execute(statement, queryStage, new NoResultStatementExecutor<>());
} | @Test
public void testQuerySucceededWithConverter()
{
QueryResult<Integer> result = prestoAction.execute(
sqlParser.createStatement("SELECT x FROM (VALUES (1), (2), (3)) t(x)", PARSING_OPTIONS),
QUERY_STAGE,
resultSet -> Optional.of(resultSet.getInt("x") *... |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenStatsEnabled_whenForwardingInactivityMsgToStateService_thenStatsAreRecorded() {
// GIVEN
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock);
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", true);
v... |
public static List<TypedExpression> coerceCorrectConstructorArguments(
final Class<?> type,
List<TypedExpression> arguments,
List<Integer> emptyCollectionArgumentsIndexes) {
Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from t... | @Test
public void coerceCorrectConstructorArgumentsCoerceList() {
final List<TypedExpression> arguments =
List.of(
new MapExprT(new MapCreationLiteralExpression(null, NodeList.nodeList())),
new MapExprT(new MapCreationLiteralExpression(null, No... |
public static StructType partitionType(Table table) {
Collection<PartitionSpec> specs = table.specs().values();
return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
} | @Test
public void testPartitionTypeWithRenamesInV1Table() {
PartitionSpec initialSpec = PartitionSpec.builderFor(SCHEMA).identity("data", "p1").build();
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, initialSpec, V1_FORMAT_VERSION);
table.updateSpec().addField("category"... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longLivedHelloWorldJwt() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("world.r", "world.w", "server.info.r"), "user");
claims.setExpirationTimeMinutesInTheFuture(5256000);
String jw... |
@VisibleForTesting
public static void addUserAgentEnvironments(List<String> info) {
info.add(String.format(OS_FORMAT, OSUtils.OS_NAME));
if (EnvironmentUtils.isDocker()) {
info.add(DOCKER_KEY);
}
if (EnvironmentUtils.isKubernetes()) {
info.add(KUBERNETES_KEY);
}
if (EnvironmentUtil... | @Test
public void userAgentEnvironmentStringGCP() {
Mockito.when(EnvironmentUtils.isGoogleComputeEngine()).thenReturn(true);
Mockito.when(EC2MetadataUtils.getUserData())
.thenThrow(new SdkClientException("Unable to contact EC2 metadata service."));
List<String> info = new ArrayList<>();
Update... |
@Converter(fallback = true)
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry)
throws MessagingException, IOException {
if (Multipart.class.isAssignableFrom(value.getClass())) {
TypeConverter tc = registry.lookup(type, String... | @Test
public void testMultipartToInputStream() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.send("direct:a", new Processor() {
public void process(Exchange exchange) {
exchange.getIn().setBody("Hell... |
@Override
public void onStateElection(Job job, JobState newState) {
if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job))
return;
job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String.... | @Test
void retryFilterKeepsDefaultGivenRetryFilterValueIfRetriesOnJobAnnotationIsNotProvided() {
retryFilter = new RetryFilter(0);
final Job job = aJob()
.<TestService>withJobDetails(ts -> ts.doWork())
.withState(new FailedState("a message", new RuntimeException("boom... |
public ActionResult apply(Agent agent, Map<String, String> request) {
log.debug("Searching web with query {}", request.get("query"));
String query = request.get("query");
if (query == null || query.isEmpty()) {
return ActionResult.builder()
.status(ActionResult.S... | @Test
void testApplyWithEmptyQuery() {
Map<String, String> request = new HashMap<>();
request.put("query", "");
ActionResult result = searchWebAction.apply(agent, request);
assertEquals(ActionResult.Status.FAILURE, result.getStatus());
assertEquals("The query parameter is m... |
@ConstantFunction(name = "bitor", argTypes = {BIGINT, BIGINT}, returnType = BIGINT)
public static ConstantOperator bitorBigint(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createBigint(first.getBigint() | second.getBigint());
} | @Test
public void bitorBigint() {
assertEquals(100, ScalarOperatorFunctions.bitorBigint(O_BI_100, O_BI_100).getBigint());
} |
public static <T> Read<T> readMessagesWithCoderAndParseFn(
Coder<T> coder, SimpleFunction<PubsubMessage, T> parseFn) {
return Read.newBuilder(parseFn).setCoder(coder).build();
} | @Test
public void testReadMessagesWithCoderAndParseFn() {
Coder<PubsubMessage> coder = PubsubMessagePayloadOnlyCoder.of();
List<PubsubMessage> inputs =
ImmutableList.of(
new PubsubMessage("foo".getBytes(StandardCharsets.UTF_8), new HashMap<>()),
new PubsubMessage("bar".getBytes... |
@Override
protected void respondAsLeader(
ChannelHandlerContext ctx, RoutedRequest routedRequest, T gateway) {
HttpRequest httpRequest = routedRequest.getRequest();
if (log.isTraceEnabled()) {
log.trace("Received request " + httpRequest.uri() + '.');
}
FileUp... | @Test
void testIgnoringUnknownFields() {
RestfulGateway mockRestfulGateway = new TestingRestfulGateway.Builder().build();
CompletableFuture<Void> requestProcessingCompleteFuture = new CompletableFuture<>();
TestHandler handler =
new TestHandler(requestProcessingCompleteFutur... |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
if(workdir.isRoot()) {
final AttributedList<Path> result = new AttributedList<>();
final AttributedList<Path> buckets = new Goo... | @Test
public void testSearchInBucket() throws Exception {
final String name = new AlphanumericRandomStringService().random();
final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new GoogleStorageTouchFeature(session).touch(n... |
public static Expression parseExpression(final String expressionText) {
final ParserRuleContext parseTree = GrammarParseUtil.getParseTree(
expressionText,
SqlBaseParser::singleExpression
);
return new AstBuilder(TypeRegistry.EMPTY).buildExpression(parseTree);
} | @Test
public void shouldParseExpression() {
// When:
final Expression parsed = ExpressionParser.parseExpression("1 + 2");
// Then:
assertThat(
parsed,
equalTo(new ArithmeticBinaryExpression(parsed.getLocation(), Operator.ADD, ONE, TWO))
);
} |
@Override
protected boolean doProcess(TbActorMsg msg) {
if (cantFindTenant) {
log.info("[{}] Processing missing Tenant msg: {}", tenantId, msg);
if (msg.getMsgType().equals(MsgType.QUEUE_TO_RULE_ENGINE_MSG)) {
QueueToRuleEngineMsg queueMsg = (QueueToRuleEngineMsg) msg... | @Test
public void deleteDeviceTest() {
TbActorRef deviceActorRef = mock(TbActorRef.class);
when(systemContext.resolve(ServiceType.TB_CORE, tenantId, deviceId)).thenReturn(new TopicPartitionInfo("Main", tenantId, 0,true));
when(ctx.getOrCreateChildActor(any(), any(), any(), any())).thenReturn... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testTransactionalUnknownProducerHandlingWhenRetentionLimitReached() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = new TransactionManager(logContext, "testUnresolvedSeq", 60000, 100, apiVersions);
setupWithTransactionState(trans... |
public SalesforceInputMeta() {
super(); // allocate BaseStepMeta
} | @Test
public void testSalesforceInputMeta() throws KettleException {
List<String> attributes = new ArrayList<String>();
attributes.addAll( SalesforceMetaTest.getDefaultAttributes() );
attributes.addAll( Arrays.asList( "inputFields", "condition", "query", "specifyQuery", "includeTargetURL",
"targetUR... |
@Override
public long getCreationTime() {
return creationTime;
} | @Test
public void testCreationTime() {
long beforeCreationTime = Clock.currentTimeMillis();
LocalSetStatsImpl localSetStats = createTestStats();
long afterCreationTime = Clock.currentTimeMillis();
assertBetween("creationTime", localSetStats.getCreationTime(), beforeCreationTime, aft... |
@Override
protected FileStatus[] listStatus(JobConf job) throws IOException {
FileStatus[] status = super.listStatus(job);
if (job.getBoolean(IGNORE_FILES_WITHOUT_EXTENSION_KEY, IGNORE_INPUTS_WITHOUT_EXTENSION_DEFAULT)) {
List<FileStatus> result = new ArrayList<>(status.length);
for (FileStatus fi... | @SuppressWarnings("rawtypes")
@Test
void ignoreFilesWithoutExtension() throws Exception {
fs.mkdirs(inputDir);
Path avroFile = new Path(inputDir, "somefile.avro");
Path textFile = new Path(inputDir, "someotherfile.txt");
fs.create(avroFile).close();
fs.create(textFile).close();
FileInputFor... |
@Override
public void itemDelete(String itemType, String itemId) {
} | @Test
public void itemDelete() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
@Override
public boolean checkPidPgrpidForMatch() {
return checkPidPgrpidForMatch(pid, PROCFS);
} | @Test
@Timeout(30000)
void testDestroyProcessTree() throws IOException {
// test process
String pid = "100";
// create the fake procfs root directory.
File procfsRootDir = new File(TEST_ROOT_DIR, "proc");
try {
setupProcfsRootDir(procfsRootDir);
// crank up the process tree class.
... |
@Override
public boolean next() throws SQLException {
if (skipAll) {
return false;
}
if (!paginationContext.getActualRowCount().isPresent()) {
return getMergedResult().next();
}
return rowNumber++ < paginationContext.getActualRowCount().get() && getMer... | @Test
void assertNextWithoutOffsetWithoutRowCount() throws SQLException {
ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "Oracle"));
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
Ora... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.