focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Query query() {
return query;
} | @Test
void testQuery() {
Query query = Query.parse("foo=bar&baz", Name::of);
Map<String, String> expected = new LinkedHashMap<>();
expected.put("foo", "bar");
expected.put("baz", null);
assertEquals(expected, query.lastEntries());
expected.remove("baz");
asse... |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
void mdcIsAlsoAvailableDuringLoggingOfJobSuccess() throws Exception {
// GIVEN
Job job = anEnqueuedJob().build();
MDC.put("testKey", "testValue");
MDCMapper.saveMDCContextToJob(job);
BackgroundJobRunner runner = mock(BackgroundJobRunner.class);
when(backgroundJ... |
@Override
public Map<Errors, Integer> errorCounts() {
HashMap<Errors, Integer> counts = new HashMap<>();
updateErrorCounts(counts, Errors.forCode(data.errorCode()));
return counts;
} | @Test
public void testErrorCountsReturnsOneError() {
PushTelemetryResponseData data = new PushTelemetryResponseData()
.setErrorCode(Errors.CLUSTER_AUTHORIZATION_FAILED.code());
data.setErrorCode(Errors.INVALID_CONFIG.code());
PushTelemetryResponse response = new PushTelemetry... |
@VisibleForTesting
CommandReturn getRawDiskInfo() throws IOException {
return ShellUtils.execCommandWithOutput("df", "-k", "-P", "-T", mJournalPath);
} | @Test
public void testFailedInfo() throws IOException {
JournalSpaceMonitor monitor = Mockito.spy(
new JournalSpaceMonitor(Paths.get(".").toAbsolutePath().toString(), 10));
doThrow(new IOException("couldnt run")).when(monitor).getRawDiskInfo();
assertThrows(IOException.class, monitor::getDiskInfo... |
public static String execCommand(String... cmd) throws IOException {
return execCommand(cmd, -1);
} | @Test
public void testHeadDevZero() throws Exception {
final int length = 100000;
String output = Shell.execCommand("head", "-c", Integer.toString(length), "/dev/zero");
assertEquals(length, output.length());
} |
public FEELFnResult<List<Object>> invoke(@ParameterName( "list" ) Object list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = new... | @Test
void invokeParamNotCollection() {
FunctionTestUtil.assertResultList(
distinctValuesFunction.invoke(BigDecimal.valueOf(10.1)),
Collections.singletonList(BigDecimal.valueOf(10.1)));
} |
public static String getHippo4jHome() {
if (StringUtil.isBlank(hippo4jHomePath)) {
hippo4jHomePath = System.getProperty(HIPPO4J_HOME_KEY);
if (StringUtil.isBlank(hippo4jHomePath)) {
hippo4jHomePath = Paths.get(System.getProperty("user.home"), "hippo4j").toString();
... | @Test
public void getHippo4jHomeTest() {
String hippo4jHome = EnvUtil.getHippo4jHome();
Assert.isTrue(StringUtil.isNotBlank(hippo4jHome));
} |
public static boolean overlapsOrdered(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) {
assert left.isDescending() == right.isDescending() : "Cannot compare pointer with different directions";
assert left.lastEntryKeyData == null && right.lastEntryKeyData == null : "Can m... | @Test
void overlapsIsNull() {
assertTrue(overlapsOrdered(IS_NULL, IS_NULL,
OrderedIndexStore.SPECIAL_AWARE_COMPARATOR), "IS NULL should overlap with itself");
assertTrue(overlapsOrdered(IS_NULL_DESC, IS_NULL_DESC,
OrderedIndexStore.SPECIAL_AWARE_COMPARATOR), "IS NULL ... |
public AdditionalServletWithClassLoader load(
AdditionalServletMetadata metadata, String narExtractionDirectory) throws IOException {
final File narFile = metadata.getArchivePath().toAbsolutePath().toFile();
NarClassLoader ncl = NarClassLoaderBuilder.builder()
.narFile(narFi... | @Test(expectedExceptions = IOException.class)
public void testLoadEventListenerWithWrongListenerClass() throws Exception {
AdditionalServletDefinition def = new AdditionalServletDefinition();
def.setAdditionalServletClass(Runnable.class.getName());
def.setDescription("test-proxy-listener");
... |
public static BigDecimal round(double v, int scale) {
return round(v, scale, RoundingMode.HALF_UP);
} | @Test
public void roundTest() {
// 四舍
final String round1 = NumberUtil.roundStr(2.674, 2);
final String round2 = NumberUtil.roundStr("2.674", 2);
assertEquals("2.67", round1);
assertEquals("2.67", round2);
// 五入
final String round3 = NumberUtil.roundStr(2.675, 2);
final String round4 = NumberUtil.rou... |
@Override
public PlanNode optimize(
PlanNode maxSubplan,
ConnectorSession session,
VariableAllocator variableAllocator,
PlanNodeIdAllocator idAllocator)
{
return rewriteWith(new Rewriter(session, idAllocator), maxSubplan);
} | @Test
public void testJdbcComputePushdownAll()
{
String table = "test_table";
String schema = "test_schema";
String expression = "(c1 + c2) - c2";
TypeProvider typeProvider = TypeProvider.copyOf(ImmutableMap.of("c1", BIGINT, "c2", BIGINT));
RowExpression rowExpression = ... |
public static String getServiceName(NetworkService networkService) {
if (isWebService(networkService) && networkService.hasSoftware()) {
return Ascii.toLowerCase(networkService.getSoftware().getName());
}
return Ascii.toLowerCase(networkService.getServiceName());
} | @Test
public void getServiceName_whenWebServiceWithSoftware_returnsServiceName() {
assertThat(
NetworkServiceUtils.getServiceName(
NetworkService.newBuilder()
.setNetworkEndpoint(forIpAndPort("127.0.0.1", 22))
.setServiceName("http")
... |
@Udf
public <T> List<T> except(
@UdfParameter(description = "Array of values") final List<T> left,
@UdfParameter(description = "Array of exceptions") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> distinctRightValues = new HashSet<>(right);
fi... | @Test
public void shouldReturnEmptyArrayIfAllExcepted() {
final List<String> input1 = Arrays.asList("foo", " ", "foo", "bar");
final List<String> input2 = Arrays.asList("bar", " ", "foo", "extra");
final List<String> result = udf.except(input1, input2);
assertThat(result.isEmpty(), is(true));
} |
public String getFullUrl() {
if (StrUtils.isNotEmpty(fullUrl)) {
return fullUrl;
}
return fullUrl = createFullUrl();
} | @Test
public void testFullUrlWithoutProtocol() {
HttpRequest req0 = new HttpRequest.Builder()
.url("localhost:8086/write")
.params(MapUtils.of("k1", singletonList("v1")))
.get()
.build();
Assert.assertEquals("http://localhost:8086/write... |
@Override
public boolean isIndexed(QueryContext queryContext) {
Index index = queryContext.matchIndex(attributeName, QueryContext.IndexMatchHint.PREFER_ORDERED);
return index != null && index.isOrdered() && expressionCanBeUsedAsIndexPrefix();
} | @Test
public void likePredicateIsNotIndexed_whenUnderscoreWildcardIsUsed() {
QueryContext queryContext = mock(QueryContext.class);
when(queryContext.matchIndex("this", QueryContext.IndexMatchHint.PREFER_ORDERED)).thenReturn(createIndex(IndexType.SORTED));
assertFalse(new LikePredicate("this... |
public static <F extends Future<Void>> Mono<Void> from(F future) {
Objects.requireNonNull(future, "future");
if (future.isDone()) {
if (!future.isSuccess()) {
return Mono.error(FutureSubscription.wrapError(future.cause()));
}
return Mono.empty();
}
return new ImmediateFutureMono<>(future);
} | @Test
void raceTestImmediateFutureMonoWithSuccess() {
for (int i = 0; i < 1000; i++) {
final TestSubscriber subscriber = new TestSubscriber();
final ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE;
final Promise<Void> promise = eventExecutor.newPromise();
RaceTestUtils.race(() -> ... |
public String getEmail() {
return email;
} | @Test
public void should_have_no_arg_constructor() {
assertThat(new GsonEmail().getEmail()).isEmpty();
} |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testMultipleSettersAnnotatedWithDefault() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Found setters marked with @Default:");
expectedException.expectMessage(
"property [other] should not be marked with @Default on ... |
@Udf(description = "Returns a new string encoded using the outputEncoding ")
public String encode(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The input encoding."
+ " If null, the... | @Test
public void shouldEncodeUtf8ToBase64() {
assertThat(udf.encode("Example!", "utf8", "base64"), is("RXhhbXBsZSE="));
assertThat(udf.encode("Plant trees", "utf8", "base64"), is("UGxhbnQgdHJlZXM="));
assertThat(udf.encode("1 + 1 = 1", "utf8", "base64"), is("MSArIDEgPSAx"));
assertThat(udf.encode("Ελ... |
@Override
public List<GrantedAuthority> getAuthorities(JsonObject introspectionResponse) {
List<GrantedAuthority> auth = new ArrayList<>(getAuthorities());
if (introspectionResponse.has("scope") && introspectionResponse.get("scope").isJsonPrimitive()) {
String scopeString = introspectionResponse.get("scope").g... | @Test
public void testGetAuthoritiesJsonObject_withoutScopes() {
List<GrantedAuthority> expected = new ArrayList<>();
expected.add(new SimpleGrantedAuthority("ROLE_API"));
List<GrantedAuthority> authorities = granter.getAuthorities(introspectionResponse);
assertTrue(authorities.containsAll(expected));
ass... |
public static String getName(Class cls) {
Objects.requireNonNull(cls, "cls");
return cls.getName();
} | @Test
void testGetName() {
final String name = "java.lang.Integer";
Integer val = 1;
assertEquals(name, ClassUtils.getName(val));
assertEquals(name, ClassUtils.getName(Integer.class));
assertEquals(name, ClassUtils.getCanonicalName(val));
assertEquals(name, C... |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testFloatingPoingLiteralFromJLS() {
// The largest positive finite literal of type float is 3.4028235e38f.
assertThat( getLiteral( float.class.getCanonicalName(), "3.4028235e38f" ) ).isNotNull();
// The smallest positive finite non-zero literal of type float is 1.40e-45f.
... |
public static Key of(String key, ApplicationId appId) {
return new StringKey(key, appId);
} | @Test
public void keysAreImmutable() {
assertThatClassIsImmutableBaseClass(Key.class);
// Will be a long based key, class is private so cannot be
// accessed directly
Key longKey = Key.of(0xabcdefL, NetTestTools.APP_ID);
assertThatClassIsImmutable(longKey.getClass());
... |
MetricsType getMetricsType(String remaining) {
String name = StringHelper.before(remaining, ":");
MetricsType type;
if (name == null) {
type = DEFAULT_METRICS_TYPE;
} else {
type = MetricsType.getByName(name);
}
if (type == null) {
thro... | @Test
public void testGetMetricsType() {
for (MetricsType type : EnumSet.allOf(MetricsType.class)) {
assertThat(component.getMetricsType(type.toString() + ":metrics-name"), is(type));
}
} |
public static byte[] compress(String urlString) throws MalformedURLException {
byte[] compressedBytes = null;
if (urlString != null) {
// Figure the compressed bytes can't be longer than the original string.
byte[] byteBuffer = new byte[urlString.length()];
int byteBu... | @Test
public void testCompressHttpsAndWWWInCaps() throws MalformedURLException {
String testURL = "HTTPS://WWW.radiusnetworks.com";
byte[] expectedBytes = {0x01, 'r', 'a', 'd', 'i', 'u', 's', 'n', 'e', 't', 'w', 'o', 'r', 'k', 's', 0x07};
assertTrue(Arrays.equals(expectedBytes, UrlBeaconUrlC... |
@Override
public void close() throws IOException {
boolean triedToClose = false, success = false;
try {
flush();
((FileOutputStream)out).getChannel().force(true);
triedToClose = true;
super.close();
success = true;
} finally {
if (success) {
boolean renamed = t... | @Test
public void testFailToRename() throws IOException {
assumeWindows();
OutputStream fos = null;
try {
fos = new AtomicFileOutputStream(DST_FILE);
fos.write(TEST_STRING.getBytes());
FileUtil.setWritable(TEST_DIR, false);
exception.expect(IOException.class);
exception.expec... |
public void mirrorKeys() {
/* how to mirror?
width = 55
[0..15] [20..35] [40..55]
phase 1: multiple by -1
[0] [-20] [-40]
phase 2: add keyboard width
[55] [35] [15]
phase 3: subtracting the key's width
[40] [20] [0]
cool?
*/
final int keyboardWidth = getMinWidth();
f... | @Test
public void testKeyboardPopupSupportsMirrorOneRow() throws Exception {
String popupCharacters = "qwert";
AnyPopupKeyboard keyboard =
new AnyPopupKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
popupCharact... |
public String cleanURL(String entry) {
String url = entry;
if (entry.contains("\"") && checkMethod(entry)) {
// we tokenize using double quotes. this means
// for tomcat we should have 3 tokens if there
// isn't any additional information in the logs
Strin... | @Test
public void testcleanURL() throws Exception {
String res = tclp.cleanURL(URL1);
assertEquals("/addrbook/", res);
assertNull(tclp.stripFile(res, new HTTPNullSampler()));
} |
public void validate(final Metric metric) {
if (metric == null) {
throw new ValidationException("Metric cannot be null");
}
if (!isValidFunction(metric.functionName())) {
throw new ValidationException("Unrecognized metric : " + metric.functionName() + ", valid metrics : "... | @Test
void throwsExceptionOnMetricMissingFieldName() {
//check count metric is fine with no field
toTest.validate(new Metric("count", null, SortSpec.Direction.Ascending, null));
//check other metrics throw exception on missing field
assertThrows(ValidationException.class, () -> toTes... |
public static S3SignRequest fromJson(String json) {
return JsonUtil.parse(json, S3SignRequestParser::fromJson);
} | @Test
public void missingFields() {
assertThatThrownBy(() -> S3SignRequestParser.fromJson("{}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing string: region");
assertThatThrownBy(() -> S3SignRequestParser.fromJson("{\"region\":\"us-west-2\"}"))
.isIn... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldEvaluateLambdaArgsToType() {
// Given:
givenUdfWithNameAndReturnType("TRANSFORM", SqlTypes.STRING);
when(function.parameters()).thenReturn(
ImmutableList.of(
ArrayType.of(DoubleType.INSTANCE),
StringType.INSTANCE,
LambdaType.of(
... |
@PostMapping("/token")
@PermitAll
@Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@Parameters({
@Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"),
@Parameter(name = "code", description = "授权... | @Test
public void testPostAccessToken_password() {
// 准备参数
String granType = OAuth2GrantTypeEnum.PASSWORD.getGrantType();
String username = randomString();
String password = randomString();
String scope = "write read";
HttpServletRequest request = mockRequest("test_cl... |
@Override
public String toString() {
return messageListener.toString();
} | @Test
public void test_toString() {
MessageListener<String> listener = createMessageListenerMock();
when(listener.toString()).thenReturn("foobar");
ReliableMessageListenerAdapter<String> adapter = new ReliableMessageListenerAdapter<>(listener);
assertEquals("foobar", adapter.toStrin... |
public String hash() {
try (LockResource r = new LockResource(mLock.readLock())) {
return mHash.get();
}
} | @Test
public void hash() {
PathProperties properties = new PathProperties();
String hash0 = properties.hash();
properties.add(NoopJournalContext.INSTANCE, ROOT, READ_CACHE);
String hash1 = properties.hash();
Assert.assertNotEquals(hash0, hash1);
properties.add(NoopJournalContext.INSTANCE, DI... |
@Override
public Message request(final Message msg, final long timeout) throws RequestTimeoutException, MQClientException,
RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
return this.defaultMQProducerImpl.request(msg, timeout);
} | @Test
public void assertRequest() throws MQBrokerException, RemotingException, InterruptedException, MQClientException, NoSuchFieldException, IllegalAccessException, RequestTimeoutException {
setDefaultMQProducerImpl();
MessageQueueSelector selector = mock(MessageQueueSelector.class);
Messag... |
@Bean
@ConditionalOnMissingBean(EtcdDataChangedInit.class)
public DataChangedInit etcdDataChangedInit(final EtcdClient etcdClient) {
return new EtcdDataChangedInit(etcdClient);
} | @Test
public void testEtcdDataInit() {
EtcdSyncConfiguration etcdListener = new EtcdSyncConfiguration();
EtcdClient client = mock(EtcdClient.class);
assertNotNull(etcdListener.etcdDataChangedInit(client));
} |
@Override
public boolean canPass(Node node, int acquireCount) {
return canPass(node, acquireCount, false);
} | @Test
public void testThrottlingControllerQueueTimeout() throws InterruptedException {
final ThrottlingController paceController = new ThrottlingController(500, 10d);
final Node node = mock(Node.class);
final AtomicInteger passCount = new AtomicInteger();
final AtomicInteger blockCo... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 7) {
onInvalidDataReceived(device, data);
return;
}
// First byte: flags
int offset = 0;
final int flags = data.getIntValue(Data.FORMAT_UINT8,... | @Test
public void onIntermediateCuffPressureReceived_minimal() {
final DataReceivedCallback callback = new IntermediateCuffPressureDataCallback() {
@Override
public void onIntermediateCuffPressureReceived(@NonNull final BluetoothDevice device,
final float cuffPressure, final int unit,
... |
protected final static List<String> splitStringPreserveDelimiter(String str, Pattern SPLIT_PATTERN) {
List<String> list = new ArrayList<>();
if (str != null) {
Matcher matcher = SPLIT_PATTERN.matcher(str);
int pos = 0;
while (matcher.find()) {
if (pos ... | @Test
public void testSplitString() {
List<String> list = DiffRowGenerator.splitStringPreserveDelimiter("test,test2", DiffRowGenerator.SPLIT_BY_WORD_PATTERN);
assertEquals(3, list.size());
assertEquals("[test, ,, test2]", list.toString());
} |
@Override
public void getConfig(StorServerConfig.Builder builder) {
super.getConfig(builder);
provider.getConfig(builder);
} | @Test
void testThatGroupsAreCountedInWhenComputingSplitBits() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
ContentCluster cluster = parseCluster("<cluster id=\"storage\">\n" +
" <redundancy>3</redundancy>" +
" <documen... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForCreateResourceGroup() {
MySQLCreateResourceGroupStatement resourceGroupStatement = mock(MySQLCreateResourceGroupStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(resourceGroupStatement);
QueryContext queryContext = new QueryContext(sqlSta... |
@Override
public void launch() throws IOException {
type.assertFull();
String numaId = SupervisorUtils.getNumaIdForPort(port, conf);
if (numaId == null) {
LOG.info("Launching worker with assignment {} for this supervisor {} on port {} with id {}",
assignment, ... | @Test
public void testLaunchStorm1version() throws Exception {
final String topoId = "test_topology_storm_1.x";
final int supervisorPort = 6628;
final int port = 8080;
final String stormHome = ContainerTest.asAbsPath("tmp", "storm-home");
final String stormLogDir = ContainerT... |
public static String extractCharset(String line, String defaultValue) {
if (line == null) {
return defaultValue;
}
final String[] parts = line.split(" ");
String charsetInfo = "";
for (var part : parts) {
if (part.startsWith("charset")) {
... | @DisplayName("default charset information")
@Test
void testExtractCharset() {
assertEquals("UTF-8", TelegramAsyncHandler.extractCharset("Content-Type: text/plain; charset=UTF-8",
StandardCharsets.US_ASCII.name()));
} |
@Override
public ReservationListResponse listReservations(
ReservationListRequest requestInfo) throws YarnException, IOException {
// Check if reservation system is enabled
checkReservationSystem();
ReservationListResponse response =
recordFactory.newRecordInstance(ReservationListRespo... | @Test
public void testListReservationsByTimeInterval() {
resourceManager = setupResourceManager();
ClientRMService clientService = resourceManager.getClientRMService();
Clock clock = new UTCClock();
long arrival = clock.getTime();
long duration = 60000;
long deadline = (long) (arrival + 1.05 *... |
@Private
@VisibleForTesting
static void checkResourceRequestAgainstAvailableResource(Resource reqResource,
Resource availableResource) throws InvalidResourceRequestException {
for (int i = 0; i < ResourceUtils.getNumberOfCountableResourceTypes(); i++) {
final ResourceInformation requestedRI =
... | @Test
public void testCustomResourceRequestedUnitIsSmallerThanAvailableUnit()
throws InvalidResourceRequestException {
Resource requestedResource =
ResourceTypesTestHelper.newResource(1, 1,
ImmutableMap.of("custom-resource-1", "11"));
Resource availableResource =
... |
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 filter_no_data() {
List<Criterion> criteria = singletonList(Criterion.builder().setKey("duplicated_lines_density").setOperator(EQ).setValue("NO_DATA").build());
ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet());
assertThat(underTest.getMetricCriteria())
... |
public Map<String, byte[]> getXAttrs(Path path) throws IOException {
return retrieveHeaders(path, INVOCATION_XATTR_GET_MAP);
} | @Test
public void testFilterEmptyXAttrs() throws Throwable {
Map<String, byte[]> xAttrs = headerProcessing.getXAttrs(MAGIC_PATH,
Lists.list());
Assertions.assertThat(xAttrs.keySet())
.describedAs("Attribute keys")
.isEmpty();
} |
@VisibleForTesting
String generateBody(EventNotificationContext ctx, TeamsEventNotificationConfigV2 config) throws PermanentEventNotificationException {
final List<MessageSummary> backlog = getMessageBacklog(ctx, config);
Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog,... | @Test(expected = PermanentEventNotificationException.class)
public void buildCustomMessageWithInvalidTemplate() throws EventNotificationException {
notificationConfig = buildInvalidTemplate();
teamsEventNotification.generateBody(eventNotificationContext, notificationConfig);
} |
public void joinChannels() {
for (IrcChannel channel : configuration.getChannelList()) {
joinChannel(channel);
}
} | @Test
public void doJoinChannels() {
endpoint.joinChannels();
verify(connection).doJoin("#chan1");
verify(connection).doJoin("#chan2", "chan2key");
} |
@PostMapping("/status")
@Operation(summary = "Get the email status of an account")
public DEmailStatusResult getEmailStatus(@RequestBody DAccountRequest deprecatedRequest) {
AppSession appSession = validate(deprecatedRequest);
var result = accountService.getEmailStatus(appSession.getAccountId()... | @Test
public void validEmailStatusNotVerified() {
DAccountRequest request = new DAccountRequest();
request.setAppSessionId("id");
EmailStatusResult result = new EmailStatusResult();
result.setStatus(Status.OK);
result.setError("error");
result.setEmailStatus(EmailSta... |
public static double regularizedUpperIncompleteGamma(double s, double x) {
if (s < 0.0) {
throw new IllegalArgumentException("Invalid s: " + s);
}
if (x < 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
double igf = 0.0;
if (x !=... | @Test
public void testUpperIncompleteGamma() {
System.out.println("incompleteGamma");
assertEquals(0.2193, Gamma.regularizedUpperIncompleteGamma(2.1, 3), 1E-4);
assertEquals(0.6496, Gamma.regularizedUpperIncompleteGamma(3, 2.1), 1E-4);
} |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyDefaultsToTypeAnyObject() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
JType result = rule.apply("fooBar", objectNode, null, jpackage, null);
assertThat(re... |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testMissingSourceInfo() {
try {
OptionsParser.parse(new String[] {
"hdfs://localhost:8020/target/"});
Assert.fail("Neither source listing not source paths present");
} catch (IllegalArgumentException ignore) {}
} |
@Override
public String toString()
{
return (this._key == null)? "" : this._key.toString();
} | @Test
public void testToString()
{
IdResponse<Long> longIdResponse = new IdResponse<>(6L);
longIdResponse.toString();
IdResponse<Long> nullIdResponse = new IdResponse<>(null);
nullIdResponse.toString();
} |
@Override
public City find(Long id) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id);
return cityRepository.find(id)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
} | @Test
void find() throws ElementNotFoundException {
City expected = createCity();
Mockito.when(cityRepository.find(expected.getId()))
.thenReturn(Optional.of(expected));
City actual = cityService.find(expected.getId());
ReflectionAssert.assertReflectionEquals(expected... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
ret... | @Test
void invokeArrayParamTypeHeterogenousArray() {
FunctionTestUtil.assertResultError(nnAllFunction.invoke(new Object[]{Boolean.TRUE, 1}), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(nnAllFunction.invoke(new Object[]{Boolean.FALSE, 1}), InvalidParametersEvent.class);
... |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
RedisClusterNode master = getFirstMaster();
connection.setConfig(master, "timeout", "10");
} |
@Override
public ParameterByTypeTransformer parameterByTypeTransformer() {
return transformer;
} | @Test
void can_transform_string_to_type() throws Throwable {
Method method = JavaDefaultParameterTransformerDefinitionTest.class.getMethod("transform_string_to_type",
String.class, Type.class);
JavaDefaultParameterTransformerDefinition definition = new JavaDefaultParameterTransformerDefi... |
List<MappingField> resolveFields(
@Nonnull String[] externalName,
@Nullable String dataConnectionName,
@Nonnull Map<String, String> options,
@Nonnull List<MappingField> userFields,
boolean stream
) {
Predicate<MappingField> pkColumnName = Options.g... | @Test
public void testResolvesMappingFieldsViaSample_withUserFields() {
try (MongoClient client = MongoClients.create(mongoContainer.getConnectionString())) {
String databaseName = "testDatabase";
String collectionName = "people_3";
MongoDatabase testDatabase = client.get... |
@Override
public FileAttributes getFileAttributes() {
checkState(this.type == Component.Type.FILE, "Only component of type FILE have a FileAttributes object");
return fileAttributes;
} | @Test
public void fail_with_ISE_when_calling_get_file_attributes_on_not_file() {
assertThatThrownBy(() -> {
ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null);
component.getFileAttributes();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("On... |
@Override
public List<ConfigKeyInfo> connectorPluginConfig(String pluginName) {
Plugins p = plugins();
Class<?> pluginClass;
try {
pluginClass = p.pluginClass(pluginName);
} catch (ClassNotFoundException cnfe) {
throw new NotFoundException("Unknown plugin " + ... | @Test
public void testGetConnectorConfigDefWithBadName() throws Exception {
String connName = "AnotherPlugin";
AbstractHerder herder = testHerder();
when(worker.getPlugins()).thenReturn(plugins);
when(plugins.pluginClass(anyString())).thenThrow(new ClassNotFoundException());
... |
public static <T, K, U> AggregateOperation1<T, Map<K, U>, Map<K, U>> toMap(
FunctionEx<? super T, ? extends K> keyFn,
FunctionEx<? super T, ? extends U> valueFn
) {
checkSerializable(keyFn, "keyFn");
checkSerializable(valueFn, "valueFn");
return toMap(keyFn, valueFn,
... | @Test
public void when_toMapCombinesDuplicates_then_exception() {
// Given
AggregateOperation1<Entry<Integer, Integer>, Map<Integer, Integer>, Map<Integer, Integer>> op =
toMap(Entry::getKey, Entry::getValue);
BiConsumerEx<? super Map<Integer, Integer>, ? super Map<Integer, I... |
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.koraAppElement = this.elements.getTypeElement(CommonClassNames.koraApp.canonicalName());
if (this.koraAppElement == null) {
return;
}
this.moduleElement ... | @Test
void appWithProxies() throws Throwable {
var graphDraw = testClass(AppWithValueOfComponents.class);
var node1 = graphDraw.getNodes().get(0);
var node2 = graphDraw.getNodes().get(1);
var node3 = graphDraw.getNodes().get(2);
var graph = graphDraw.init();
var value... |
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
} | @Test
public void finalCase() {
assertThat(
bind(
"Test",
"lock",
forSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Test {",
" final Object lock = ne... |
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// Do not allow framing; OF-997
... | @Test
public void nonExcludedUrlWillErrorWhenMatchingCIDROnBlocklist() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(AdminUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
final String cidr ... |
private native static boolean isSupportedSuite(int alg, int padding); | @Test(timeout=120000)
public void testIsSupportedSuite() throws Exception {
Assume.assumeTrue("Skipping due to falilure of loading OpensslCipher.",
OpensslCipher.getLoadingFailureReason() == null);
Assert.assertFalse("Unknown suite must not be supported.",
OpensslCipher.isSupported(CipherSuite... |
public static String resolveRegistryContract(String chainId) {
final Long chainIdLong = Long.parseLong(chainId);
if (chainIdLong.equals(ChainIdLong.MAINNET)) {
return MAINNET;
} else if (chainIdLong.equals(ChainIdLong.ROPSTEN)) {
return ROPSTEN;
} else if (chainId... | @Test
public void testResolveRegistryContractInvalid() {
assertThrows(
EnsResolutionException.class, () -> resolveRegistryContract(ChainIdLong.NONE + ""));
} |
public Page<Instance> findInstancesByNamespace(String appId, String clusterName, String
namespaceName, Pageable pageable) {
Page<InstanceConfig> instanceConfigs = instanceConfigRepository.
findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfter(appId, clusterName,... | @Test
@Rollback
public void testFindInstancesByNamespace() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
Date someValidDa... |
public static boolean isParentAncestorOf(
Table table, long snapshotId, long ancestorParentSnapshotId) {
for (Snapshot snapshot : ancestorsOf(snapshotId, table::snapshot)) {
if (snapshot.parentId() != null && snapshot.parentId() == ancestorParentSnapshotId) {
return true;
}
}
retu... | @Test
public void isParentAncestorOf() {
assertThat(SnapshotUtil.isParentAncestorOf(table, snapshotMain1Id, snapshotBaseId)).isTrue();
assertThat(SnapshotUtil.isParentAncestorOf(table, snapshotBranchId, snapshotMain1Id)).isFalse();
assertThat(SnapshotUtil.isParentAncestorOf(table, snapshotFork2Id, snapsho... |
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {
final long now = System.cur... | @Test
public void reportsCounters() throws Exception {
final Counter counter = mock(Counter.class);
Mockito.when(counter.getCount()).thenReturn(100L);
reporter.report(this.map(), this.map("counter", counter), this.map(), this.map(), this.map());
final ArgumentCaptor<InfluxDbPoint> i... |
@VisibleForTesting
static Resource getUnitResource(YarnConfiguration yarnConfig) {
final int unitMemMB, unitVcore;
final String yarnRmSchedulerClazzName = yarnConfig.get(YarnConfiguration.RM_SCHEDULER);
if (Objects.equals(yarnRmSchedulerClazzName, YARN_RM_FAIR_SCHEDULER_CLAZZ)
... | @Test
void testGetUnitResource() {
final int minMem = 64;
final int minVcore = 1;
final int incMem = 512;
final int incVcore = 2;
final int incMemLegacy = 1024;
final int incVcoreLegacy = 4;
YarnConfiguration yarnConfig = new YarnConfiguration();
yarn... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatStruct() {
final SqlStruct struct = SqlStruct.builder()
.field("field1", SqlTypes.INTEGER)
.field("field2", SqlTypes.STRING)
.build();
assertThat(
ExpressionFormatter.formatExpression(new Type(struct)),
equalTo("STRUCT<field1 INTEGER, fiel... |
public static <T extends CharSequence> T[] removeBlank(T[] array) {
return filter(array, StrUtil::isNotBlank);
} | @Test
public void removeBlankTest() {
String[] a = {"a", "b", "", null, " ", "c"};
String[] resultA = {"a", "b", "c"};
assertArrayEquals(ArrayUtil.removeBlank(a), resultA);
} |
@Override
public ValidationResult validate(Object value) {
if ((allowMissing && value == null) || value instanceof List) {
return new ValidationResult.ValidationPassed();
} else {
return new ValidationResult.ValidationFailed("Value is not a list!");
}
} | @Test
public void testValidate() throws Exception {
final ListValidator v = new ListValidator();
assertFalse(v.validate(null).passed());
assertFalse(v.validate(Maps.newHashMap()).passed());
assertTrue(v.validate(Lists.newArrayList()).passed());
assertTrue(v.validate(Lists.ne... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testClusterSchedulerFifo() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("scheduler").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION... |
public static void setRuleMechanism(String ruleMech) {
if (ruleMech != null
&& (!ruleMech.equalsIgnoreCase(MECHANISM_HADOOP)
&& !ruleMech.equalsIgnoreCase(MECHANISM_MIT))) {
throw new IllegalArgumentException("Invalid rule mechanism: " + ruleMech);
}
ruleMechanism = ruleMech;
... | @Test
public void testAntiPatterns() throws Exception {
KerberosName.setRuleMechanism(KerberosName.MECHANISM_HADOOP);
checkBadName("owen/owen/owen@FOO.COM");
checkBadName("owen@foo/bar.com");
checkBadTranslation("foo@ACME.COM");
checkBadTranslation("root/joe@FOO.COM");
KerberosName.setRuleMe... |
@Override
public ManageSnapshots removeTag(String name) {
updateSnapshotReferencesOperation().removeTag(name);
return this;
} | @TestTemplate
public void testRemoveTag() {
table.newAppend().appendFile(FILE_A).commit();
long snapshotId = table.currentSnapshot().snapshotId();
// Test a basic case of creating and then removing a branch and tag
table.manageSnapshots().createTag("tag1", snapshotId).commit();
table.manageSnapsho... |
public final void setSpin(boolean spin) {
this.spin = spin;
} | @Test
public void test_setSpin() {
ReactorBuilder builder = newBuilder();
builder.setSpin(true);
assertTrue(builder.spin);
} |
@Udf
public <T> List<T> mapValues(final Map<String, T> input) {
if (input == null) {
return null;
}
return Lists.newArrayList(input.values());
} | @Test
public void shouldReturnNullForNullInput() {
List<Long> result = udf.mapValues((Map<String, Long>) null);
assertThat(result, is(nullValue()));
} |
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
if (varbitChanged.getVarbitId() == Varbits.WINTERTODT_TIMER)
{
int timeToNotify = config.roundNotification();
// Sometimes wt var updates are sent to players even after leaving wt.
// So only notify if in wt or after just having left.
... | @Test
public void matchStartingNotification_shouldNotify_when10SecondsOptionSelected()
{
when(config.roundNotification()).thenReturn(10);
VarbitChanged varbitChanged = new VarbitChanged();
varbitChanged.setVarbitId(Varbits.WINTERTODT_TIMER);
varbitChanged.setValue(20);
wintertodtPlugin.onVarbitChanged(var... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("list", concurrency);
try {
final String prefix = this.createPrefix(directory);
if(log.isDebugEnabl... | @Test
public void testListFile() throws Exception {
final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final String name = new AlphanumericRandomStringService().random();
final Path file = new S3TouchFeature(session, ... |
public static <K, V> StateSerdes<K, V> withBuiltinTypes(
final String topic,
final Class<K> keyClass,
final Class<V> valueClass) {
return new StateSerdes<>(topic, Serdes.serdeFrom(keyClass), Serdes.serdeFrom(valueClass));
} | @Test
public void shouldThrowForUnknownKeyTypeForBuiltinTypes() {
assertThrows(IllegalArgumentException.class, () -> StateSerdes.withBuiltinTypes("anyName", Class.class, byte[].class));
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDecodeStaticStruct() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000001"
+ "0000000000000000000000000000000000000000000000000000000000000064";
assertEquals(
FunctionReturnDecoder.decod... |
@SuppressWarnings("checkstyle:NestedIfDepth")
@Nullable
public PartitioningStrategy getPartitioningStrategy(
String mapName,
PartitioningStrategyConfig config,
final List<PartitioningAttributeConfig> attributeConfigs
) {
if (attributeConfigs != null && !attributeC... | @Test
public void whenPartitioningStrategyClassDefined_getPartitioningStrategy_returnsNewInstance() {
PartitioningStrategyConfig cfg = new PartitioningStrategyConfig();
cfg.setPartitioningStrategyClass("com.hazelcast.partition.strategy.StringPartitioningStrategy");
PartitioningStrategy parti... |
@Override
public String getSQLQueryFields( String tableName ) {
return "SELECT * FROM " + tableName + getLimitClause( 0 );
} | @Test
public void testQuerySchema() {
DatabricksDatabaseMeta db = new DatabricksDatabaseMeta();
assertEquals( "SELECT * FROM thetable LIMIT 0", db.getSQLQueryFields( "thetable" ) );
} |
@Override
public void onWorkflowFinalized(Workflow workflow) {
WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput());
WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow);
String reason = workflow.getReasonForIncompletion();
LOG.inf... | @Test
public void testWorkflowFinalizedNotCreatedTasks() {
Task task = new Task();
task.setReferenceTaskName("bar");
Map<String, Object> summary = new HashMap<>();
summary.put("runtime_state", Collections.singletonMap("status", "CREATED"));
summary.put("type", "NOOP");
task.setOutputData(Coll... |
public int getCacheVersion() throws KettleException {
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder( 17, 31 )
// info
.append( this.getName() )
.append( this.getTransformationType() )
.append( this.getSizeRowset() )
.append( this.getSleepTimeEmpty() )
.append... | @Test
public void testGetCacheVersion() throws Exception {
TransMeta transMeta = new TransMeta( getClass().getResource( "one-step-trans.ktr" ).getPath() );
int oldCacheVersion = transMeta.getCacheVersion();
transMeta.setSizeRowset( 10 );
int currCacheVersion = transMeta.getCacheVersion();
assertNo... |
@ApiOperation(value = "Query for historic variable instances", tags = { "History", "Query" },
notes = "All supported JSON parameter fields allowed are exactly the same as the parameters found for getting a collection of historic process instances,"
+ " but passed in as JSON-body arguments rather... | @Test
@Deployment
public void testQueryVariableInstances() throws Exception {
HashMap<String, Object> processVariables = new HashMap<>();
processVariables.put("stringVar", "Azerty");
processVariables.put("intVar", 67890);
processVariables.put("booleanVar", false);
Proces... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testBagClearBeforeRead() throws Exception {
StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of());
BagState<String> bag = underTest.state(NAMESPACE, addr);
bag.clear();
bag.add("hello");
assertThat(bag.read(), Matchers.containsInAnyOrder("hello"));
//... |
public ChannelFuture writeOneInbound(Object msg) {
return writeOneInbound(msg, newPromise());
} | @Test
public void testWriteOneInbound() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger flushCount = new AtomicInteger(0);
EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
@Override
... |
@SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops"})
public void validate(Workflow workflow, User caller) {
try {
RunProperties runProperties = new RunProperties();
runProperties.setOwner(caller);
Map<String, ParamDefinition> workflowParams = workflow.getParams();
Map<String, ParamD... | @Test
public void testValidateDefaultRunParams() {
definition
.getWorkflow()
.getParams()
.put("FROM_DATE", ParamDefinition.buildParamDefinition("FROM_DATE", "YYYYMMDD"));
definition
.getWorkflow()
.getParams()
.put("DIFFERENT_TYPE", ParamDefinition.buildParamDe... |
@VisibleForTesting
WxMaService getWxMaService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMaService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MINI_APP.getType(), userType);
if (client != null && Objects.equals(client.... | @Test
public void testGetWxMaService_clientNull() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 方法
// 调用
WxMaService result = socialClientService.getWxMaService(userType);
// 断言
assertSame(wxMaService, result);
} |
protected void validateTopic(Resource topic) {
GrpcValidator.getInstance().validateTopic(topic);
} | @Test
public void testValidateTopic() {
assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().build()));
assertThrows(GrpcProxyException.class, () -> messingActivity.validateTopic(Resource.newBuilder().setName(TopicValidator.RMQ_SYS_TRACE_TOPIC).build()));
... |
public StreamPullQueryMetadata createStreamPullQuery(
final ServiceContext serviceContext,
final ImmutableAnalysis analysis,
final ConfiguredStatement<Query> statementOrig,
final boolean excludeTombstones
) {
final boolean streamPullQueriesEnabled =
statementOrig
.getSe... | @Test
public void shouldCheckStreamPullQueryEnabledFlag() {
setupKsqlEngineWithSharedRuntimeEnabled();
@SuppressWarnings("unchecked") final ConfiguredStatement<Query> statementOrig =
mock(ConfiguredStatement.class);
when(statementOrig.getMaskedStatementText()).thenReturn("TEXT");
final Sessio... |
@Override
public boolean isTemplateAvailable(ThemeContext themeContext, String viewName) {
var suffix = thymeleafProperties.getSuffix();
// Currently, we only support Path here.
var path = themeContext.getPath().resolve("templates").resolve(viewName + suffix);
return Files.exists(pat... | @Test
void templateAvailableTest() throws FileNotFoundException, URISyntaxException {
var themeUrl = ResourceUtils.getURL("classpath:themes/default");
var themePath = Path.of(themeUrl.toURI());
when(thymeleafProperties.getSuffix()).thenReturn(".html");
var themeContext = ThemeContex... |
public String getName() {
return name;
} | @Test
public void getName() {
assertEquals(fn, cs.getName());
} |
@GetMapping("/readiness")
public ResponseEntity<String> readiness(HttpServletRequest request) {
ReadinessResult result = ModuleHealthCheckerHolder.getInstance().checkReadiness();
if (result.isSuccess()) {
return ResponseEntity.ok().body("OK");
}
return ResponseEntity.stat... | @Test
void testReadinessSuccess() throws Exception {
Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0);
Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP);
ResponseEntity<String> response = healthController.readiness... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowOnSchemaInferenceMismatchForKey() throws Exception {
// Given:
when(srClient.getLatestSchemaMetadata(Mockito.any()))
.thenReturn(new SchemaMetadata(1, 1, ""));
when(srClient.getSchemaById(1))
.thenReturn(new AvroSchema(RAW_SCHEMA));
givenDataSourceWithSchem... |
public TopicList getUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_UNIT_TOPIC_LIST, null);
RemotingCommand response = this.remot... | @Test
public void assertGetUnitTopicList() throws RemotingException, InterruptedException, MQClientException {
mockInvokeSync();
TopicList responseBody = new TopicList();
responseBody.getTopicList().add(defaultTopic);
setResponseBody(responseBody);
TopicList actual = mqClient... |
static Entry<String, String> splitTrimmedConfigStringComponent(String input) {
int i;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == '=') {
break;
}
}
if (i == input.length()) {
throw new FormatterException("No equals sig... | @Test
public void testSplitTrimmedConfigStringComponentOnNameEqualsEmpty() {
assertEquals(new AbstractMap.SimpleImmutableEntry<>("name", ""),
ScramParser.splitTrimmedConfigStringComponent("name="));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.