focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@VisibleForTesting
protected Path maybeDownloadJars(String sName, String className, String
remoteFile, AuxServiceFile.TypeEnum type, Configuration conf)
throws IOException {
// load AuxiliaryService from remote classpath
FileContext localLFS = getLocalFileContext(conf);
// create NM aux-servic... | @Test (timeout = 15000)
public void testReuseLocalizedAuxiliaryJar() throws Exception {
File testJar = null;
AuxServices aux = null;
Configuration conf = new YarnConfiguration();
FileSystem fs = FileSystem.get(conf);
String root = "target/LocalDir";
try {
testJar = JarFinder.makeClassLoa... |
@Override
protected String query(final Path directory, final ListProgressListener listener) throws BackgroundException {
// The contains operator only performs prefix matching for a name.
return String.format("name contains '%s'", query);
} | @Test
public void testQuery() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path directory = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Pat... |
public int getDeregisterSubClusterFailedRetrieved() {
return numDeregisterSubClusterFailedRetrieved.value();
} | @Test
public void testDeregisterSubClusterRetrievedFailed() {
long totalBadBefore = metrics.getDeregisterSubClusterFailedRetrieved();
badSubCluster.getDeregisterSubClusterFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getDeregisterSubClusterFailedRetrieved());
} |
@Override
public short getTypeCode() {
return MessageType.TYPE_SEATA_MERGE_RESULT;
} | @Test
public void getTypeCode() {
MergeResultMessage mergeResultMessage = new MergeResultMessage();
assertThat(MessageType.TYPE_SEATA_MERGE_RESULT).isEqualTo(mergeResultMessage.getTypeCode());
} |
public static String join(String delimiter, String wrap, Iterable<?> objs) {
Iterator<?> iter = objs.iterator();
if (!iter.hasNext()) {
return "";
}
StringBuilder buffer = new StringBuilder();
buffer.append(wrap).append(iter.next()).append(wrap);
while (iter.h... | @Test
public void testJoin() {
ArrayList<String> strings = new ArrayList<String>();
strings.add("foo");
strings.add("bar");
strings.add("baz");
Assertions.assertEquals("foo,bar,baz", Utils.join(",", strings));
Assertions.assertEquals("", Utils.join(",", new ArrayList... |
public static FileCollection generatePathingJar(final Project project, final String taskName, final FileCollection classpath,
boolean alwaysUsePathingJar) throws IOException {
//There is a bug in the Scala nsc compiler that does not parse the dependencies of JARs in the JAR manifest
//As such, we disable pa... | @Test
public void testDoesNotCreatePathingJar() throws IOException
{
//setup
createTempDir();
Project project = ProjectBuilder.builder().withProjectDir(temp).build();
String taskName = "myTaskName";
project.getBuildDir().mkdir();
File tempFile = new File(project.getBuildDir(), "temp.class")... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public HistoryInfo get() {
return getHistoryInfo();
} | @Test
public void testInvalidAccept() throws JSONException, Exception {
WebResource r = resource();
String responseStr = "";
try {
responseStr = r.path("ws").path("v1").path("history")
.accept(MediaType.TEXT_PLAIN).get(String.class);
fail("should have thrown exception on invalid uri"... |
public static long btcToSatoshi(BigDecimal coins) throws ArithmeticException {
return coins.movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact();
} | @Test(expected = ArithmeticException.class)
public void testBtcToSatoshi_tooPrecise1() {
btcToSatoshi(new BigDecimal("0.000000001")); // More than SMALLEST_UNIT_EXPONENT precision
} |
@Operation(summary = "queryList", description = "QUERY_QUEUE_LIST_NOTES")
@GetMapping(value = "/list")
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_QUEUE_LIST_ERROR)
public Result<List<Queue>> queryList(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) {
... | @Test
public void testQueryList() throws Exception {
MvcResult mvcResult = mockMvc.perform(get("/queues/list")
.header(SESSION_ID, sessionId))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn(... |
public AMSimulator() {
this.responseQueue = new LinkedBlockingQueue<>();
} | @Test
public void testAMSimulator() throws Exception {
// Register one app
MockAMSimulator app = new MockAMSimulator();
String appId = "app1";
String queue = "default";
List<ContainerSimulator> containers = new ArrayList<>();
HashMap<ApplicationId, AMSimulator> map = new HashMap<>();
User... |
public SearchJob executeSync(String searchId, SearchUser searchUser, ExecutionState executionState) {
return searchDomain.getForUser(searchId, searchUser)
.map(s -> executeSync(s, searchUser, executionState))
.orElseThrow(() -> new NotFoundException("No search found with id <" + ... | @Test
void appliesQueryStringDecoratorsOnSearchTypes() {
final SearchUser searchUser = TestSearchUser.builder()
.allowStream("foo")
.build();
final SearchType searchType = MessageList.builder()
.id("searchType1")
.query(ElasticsearchQue... |
public void registerNodeHeartbeat(NodeStatus nodeStatus)
{
requireNonNull(nodeStatus, "nodeStatus is null");
InternalNodeState nodeState = nodeStatuses.get(nodeStatus.getNodeId());
if (nodeState == null) {
nodeStatuses.put(nodeStatus.getNodeId(), new InternalNodeState(nodeStatus)... | @Test(timeOut = 20_000)
public void testWorkerMemoryInfo()
throws Exception
{
ResourceManagerClusterStateProvider provider = new ResourceManagerClusterStateProvider(new InMemoryNodeManager(), new SessionPropertyManager(), 10, Duration.valueOf("4s"), Duration.valueOf("8s"), Duration.valueOf("... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldThrowWhenTableElementsAndValueSchemaIdPresent() {
// Given:
givenFormatsAndProps(
"protobuf",
"avro",
ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42)));
when(ct.getElements()).thenReturn(SOME_VALUE_ELEMENTS);
// When:
final Exception e = a... |
public List<JobInfo> getRecentFailures() {
return Collections.unmodifiableList(mRecentFailures);
} | @Test
public void testRecentFailures() {
Collection<JobInfo> recentFailures = mSummary.getRecentFailures();
assertEquals("Unexpected length of last activities", 3, recentFailures.size());
JobInfo[] recentFailuresArray = new JobInfo[3];
recentFailures.toArray(recentFailuresArray);
assertEquals(... |
@VisibleForTesting
public static void normalizeRequest(
ResourceRequest ask,
ResourceCalculator resourceCalculator,
Resource minimumResource,
Resource maximumResource) {
ask.setCapability(
getNormalizedResource(ask.getCapability(), resourceCalculator,
minimumResource, maximumRe... | @Test(timeout = 30000)
public void testNormalizeRequestWithDominantResourceCalculator() {
ResourceCalculator resourceCalculator = new DominantResourceCalculator();
Resource minResource = Resources.createResource(1024, 1);
Resource maxResource = Resources.createResource(10240, 10);
Resource clusterRes... |
public Config setConfigPatternMatcher(ConfigPatternMatcher configPatternMatcher) {
if (configPatternMatcher == null) {
throw new IllegalArgumentException("ConfigPatternMatcher is not allowed to be null!");
}
this.configPatternMatcher = configPatternMatcher;
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testConfigThrow_whenConfigPatternMatcherIsNull() {
config.setConfigPatternMatcher(null);
} |
public static String getContentIdentity(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
throw new IllegalArgumentException("content does not contain separator");
}
return content.substring(0, index);
} | @Test
void testGetContentIdentity() {
String content = "aa" + WORD_SEPARATOR + "bbb";
String content1 = ContentUtils.getContentIdentity(content);
assertEquals("aa", content1);
} |
protected String createTempDirString() {
return createTempDirString( System.getProperty( "java.io.tmpdir" ) );
} | @Test
public void testCreateTempDirString_TmpDir() {
String systemTmpDir = System.getProperty("java.io.tmpdir" );
String tempDir = servlet.createTempDirString();
assertTrue( tempDir.contains( systemTmpDir ) );
} |
public static ECKeyPair decrypt(String password, WalletFile walletFile) throws CipherException {
validate(walletFile);
WalletFile.Crypto crypto = walletFile.getCrypto();
byte[] mac = Numeric.hexStringToByteArray(crypto.getMac());
byte[] iv = Numeric.hexStringToByteArray(crypto.getCiph... | @Test
public void testDecryptScrypt() throws Exception {
WalletFile walletFile = load(SCRYPT);
ECKeyPair ecKeyPair = Wallet.decrypt(PASSWORD, walletFile);
assertEquals(Numeric.toHexStringNoPrefix(ecKeyPair.getPrivateKey()), (SECRET));
} |
@Override
protected CloudBlobClient connect(final ProxyFinder proxyfinder, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
try {
// Client configured with no credentials
final URI uri = new URI(String.format("%s://... | @Test
public void testConnect() throws Exception {
assertTrue(session.isConnected());
} |
@Override
public final Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
ShardingSpherePreconditions.checkNotContains(INVALID_MEMORY_TYPES, type, () -> new SQLFeatureNotSupportedException(String.format("Get value from `%s`", type.getName())));
Object result = currentR... | @Test
void assertGetValueForClob() {
assertThrows(SQLFeatureNotSupportedException.class, () -> memoryMergedResult.getValue(1, Clob.class));
} |
@Override
public void responseAvailable(SearchInvoker from) {
if (availableForProcessing != null) {
availableForProcessing.add(from);
}
} | @Test
void requireThatGroupingsAreMerged() throws IOException {
List<SearchInvoker> invokers = new ArrayList<>();
Grouping grouping1 = new Grouping(0);
grouping1.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group()
... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testStartsWith() {
StructType struct = StructType.of(required(24, "s", Types.StringType.get()));
Evaluator evaluator = new Evaluator(struct, startsWith("s", "abc"));
assertThat(evaluator.eval(TestHelpers.Row.of("abc")))
.as("abc startsWith abc should be true")
.isTrue();
... |
@Override
public void add(long key, String value) {
// fix https://github.com/crossoverJie/cim/issues/79
sortArrayMap.clear();
for (int i = 0; i < VIRTUAL_NODE_SIZE; i++) {
Long hash = super.hash("vir" + key + i);
sortArrayMap.add(hash,value);
}
sortAr... | @Test
public void getFirstNodeValue3() {
AbstractConsistentHash map = new SortArrayMapConsistentHash() ;
List<String> strings = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
strings.add("127.0.0." + i) ;
}
String process = map.process(strings,"155125389... |
@Override
public V remove(Object key) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().remove(key);
} | @Test
public void testDelegationOfUnsupportedFunctionRemoveByKey() {
new PCollectionsHashMapWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.remove(eq(this)))
.defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.remove(this))
... |
@GetMapping(
path = "/admin/namespace/{namespaceName}/members",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<NamespaceMembershipListJson> getNamespaceMembers(@PathVariable String namespaceName) {
try{
admins.checkAdminUser();
var memberships... | @Test
public void testGetNamespaceMembers() throws Exception {
mockAdminUser();
var namespace = mockNamespace();
var user = new UserData();
user.setLoginName("other_user");
var membership1 = new NamespaceMembership();
membership1.setNamespace(namespace);
membe... |
@Override
public void validateDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得科室信息
Map<Long, DeptDO> deptMap = getDeptMap(ids);
// 校验
ids.forEach(id -> {
DeptDO dept = deptMap.get(id);
if (dept == null) ... | @Test
public void testValidateDeptList_notEnable() {
// mock 数据
DeptDO deptDO = randomPojo(DeptDO.class).setStatus(CommonStatusEnum.DISABLE.getStatus());
deptMapper.insert(deptDO);
// 准备参数
List<Long> ids = singletonList(deptDO.getId());
// 调用, 并断言异常
assertSer... |
public void initialize(Configuration config) throws YarnException {
setConf(config);
this.plugin.initPlugin(config);
// Try to diagnose FPGA
LOG.info("Trying to diagnose FPGA information ...");
if (!diagnose()) {
LOG.warn("Failed to pass FPGA devices diagnose");
}
} | @Test
public void testExecutablePathWhenFileDoesNotExist()
throws YarnException {
conf.set(YarnConfiguration.NM_FPGA_PATH_TO_EXEC,
getTestParentFolder() + "/aocl");
fpgaDiscoverer.initialize(conf);
assertEquals("File doesn't exists - expected a single binary name",
"aocl", openclPl... |
@Override
public void isEqualTo(@Nullable Object expected) {
@SuppressWarnings("UndefinedEquals") // method contract requires testing iterables for equality
boolean equal = Objects.equal(actual, expected);
if (equal) {
return;
}
// Fail but with a more descriptive message:
if (actual i... | @Test
public void isEqualToNotConsistentWithEquals_failure() {
TreeSet<String> actual = new TreeSet<>(CASE_INSENSITIVE_ORDER);
TreeSet<String> expected = new TreeSet<>(CASE_INSENSITIVE_ORDER);
actual.add("one");
expected.add("ONE");
actual.add("two");
expectFailureWhenTestingThat(actual).isEqu... |
@Override
public int length() {
return 2;
} | @Test
public void testLength() {
System.out.println("length");
BetaDistribution instance = new BetaDistribution(2, 5);
instance.rand();
assertEquals(2, instance.length());
} |
public void addRequest(String requestName, long duration, int cpuTime, int allocatedKBytes,
boolean systemError, long responseSize) {
addRequest(requestName, duration, cpuTime, allocatedKBytes, systemError, null,
responseSize);
} | @Test
public void testAddRequest() {
final CounterRequest request = createCounterRequest();
// ce bindContext pour tester le cas où une requête est ajoutée avec un contexte et un contexte parent
// puis une requête ajoutée avec un contexte sans contexte parent
counter.bindContext(request.getName(), request.get... |
static void obtainTokensForNamenodesInternal(Credentials credentials,
Path[] ps, Configuration conf) throws IOException {
Set<FileSystem> fsSet = new HashSet<FileSystem>();
for(Path p: ps) {
fsSet.add(p.getFileSystem(conf));
}
String masterPrincipal = Master.getMasterPrincipal(conf);
for... | @Test
public void testObtainTokens() throws Exception {
Credentials credentials = new Credentials();
FileSystem fs = mock(FileSystem.class);
TokenCache.obtainTokensForNamenodesInternal(fs, credentials, conf, renewer);
verify(fs).addDelegationTokens(eq(renewer), eq(credentials));
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
// Load the codec by message type.
final AWSMessageType awsMessageType = AWSMessageType.valueOf(configuration.getString(CK_AWS_MESSAGE_TYPE));
final Codec.Factory<? extends Codec> codecFactory = this.availableCo... | @Test
public void testKinesisRawCodec() throws JsonProcessingException {
final HashMap<String, Object> configMap = new HashMap<>();
configMap.put(AWSCodec.CK_AWS_MESSAGE_TYPE, AWSMessageType.KINESIS_RAW.toString());
final Configuration configuration = new Configuration(configMap);
f... |
public void traverseExpression(Expression expr, Function<ExprSite, Boolean> func) {
Preconditions.checkNotNull(expr);
if (!func.apply(new ExprSite(expr))) {
return;
}
traverseChildren(expr, func);
} | @Test
public void testTraverseExpression() throws InvocationTargetException, IllegalAccessException {
Expression.Reference ref =
new Expression.Reference("a", TypeRef.of(ExpressionVisitorTest.class));
Expression e1 = new Expression.Invoke(ref, "testTraverseExpression");
Literal start = Literal.ofI... |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void fail_to_create_query_on_qualifier_when_value_is_incorrect() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("unknown").build()), emptySet());
})
.isInstanceOf(IllegalArgumentException.class)
... |
@Transactional
public Release rollbackTo(long releaseId, long toReleaseId, String operator) {
if (releaseId == toReleaseId) {
throw new BadRequestException("current release equal to target release");
}
Release release = findOne(releaseId);
Release toRelease = findOne(toReleaseId);
if (rele... | @Test
public void testRollbackTo() {
List<Release> releaseList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Release release = new Release();
release.setId(3 - i);
release.setAppId(appId);
release.setClusterName(clusterName);
release.setNamespaceName(namespaceName);
re... |
private Mono<ServerResponse> createUser(ServerRequest request) {
return request.bodyToMono(CreateUserRequest.class)
.doOnNext(createUserRequest -> {
if (StringUtils.isBlank(createUserRequest.name())) {
throw new ServerWebInputException("Name is required");
... | @Test
void createWhenNameDuplicate() {
when(userService.createUser(any(User.class), anySet()))
.thenReturn(Mono.just(new User()));
when(userService.updateWithRawPassword(anyString(), anyString()))
.thenReturn(Mono.just(new User()));
var userRequest = new UserEndpoint.... |
@Override
public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
Path target;
if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) {
// De... | @Test
public void testMoveWithDelimiter() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path placeholder = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.directory));
... |
@SuppressWarnings("unchecked")
@Override
protected synchronized void heartbeat() throws Exception {
AllocateRequest allocateRequest =
AllocateRequest.newInstance(this.lastResponseID,
super.getApplicationProgress(), new ArrayList<ResourceRequest>(),
new ArrayList<ContainerId>(), null);
... | @Test
public void testRMConnectionRetry() throws Exception {
// verify the connection exception is thrown
// if we haven't exhausted the retry interval
ApplicationMasterProtocol mockScheduler =
mock(ApplicationMasterProtocol.class);
when(mockScheduler.allocate(isA(AllocateRequest.class)))
... |
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final SelectionParameters other = (SelectionParamet... | @Test
public void testEqualsQualifiersInDifferentOrder() {
List<String> qualifyingNames = Arrays.asList( "language", "german" );
TypeMirror resultType = new TestTypeMirror( "resultType" );
List<TypeMirror> qualifiers = new ArrayList<>();
qualifiers.add( new TestTypeMirror( "org.mapst... |
public void setMaxLengthBytes(long timeout) {
kp.put("maxLengthBytes",timeout);
} | @Test
public void testMaxLengthBytes() throws Exception {
CrawlURI curi = makeCrawlURI("http://localhost:7777/200k");
fetcher().setMaxLengthBytes(50000);
fetcher().process(curi);
assertEquals(50001, curi.getRecordedSize());
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test
public void testRequestAttachmentsAndResponseAttachments() throws Exception
{
//This test verifies the server's ability to accept request attachments and send back response attachments. This is the
//main test to verify the wire protocol for streaming. We send a payload that contains the rest.li paylo... |
public static Combine.BinaryCombineDoubleFn ofDoubles() {
return new Min.MinDoubleFn();
} | @Test
public void testMinDoubleFnNan() {
testCombineFn(
Min.ofDoubles(),
Lists.newArrayList(Double.NEGATIVE_INFINITY, 2.0, 3.0, Double.NaN),
Double.NaN);
} |
@Override
public Optional<ShardingConditionValue> generate(final InExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) {
if (predicate.isNot()) {
return Optional.empty();
}
Collection<ExpressionSegment> expression... | @Test
void assertNowExpression() {
ListExpression listExpression = new ListExpression(0, 0);
listExpression.getItems().add(new CommonExpressionSegment(0, 0, "now()"));
InExpression inExpression = new InExpression(0, 0, null, listExpression, false);
Optional<ShardingConditionValue> sh... |
@Override
public AuthUser getAuthUser(Integer socialType, Integer userType, String code, String state) {
// 构建请求
AuthRequest authRequest = buildAuthRequest(socialType, userType);
AuthCallback authCallback = AuthCallback.builder().code(code).state(state).build();
// 执行请求
AuthR... | @Test
public void testAuthSocialUser_success() {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String code = randomString();
String state = randomString();
// mock 方法(AuthRequest)
... |
public static boolean safeContains(final Range<Comparable<?>> range, final Comparable<?> endpoint) {
try {
return range.contains(endpoint);
} catch (final ClassCastException ex) {
Comparable<?> rangeUpperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null;
... | @Test
void assertSafeContainsForBigInteger() {
Range<Comparable<?>> range = Range.closed(new BigInteger("123"), new BigInteger("1000"));
assertTrue(SafeNumberOperationUtils.safeContains(range, 510));
} |
public static String extractAttributeNameNameWithoutArguments(String attributeNameWithArguments) {
int start = StringUtil.lastIndexOf(attributeNameWithArguments, '[');
int end = StringUtil.lastIndexOf(attributeNameWithArguments, ']');
if (start > 0 && end > 0 && end > start) {
return... | @Test(expected = IllegalArgumentException.class)
public void extractAttributeName_wrongArguments_noArgument_noOpening() {
extractAttributeNameNameWithoutArguments("car.wheel]");
} |
public static ImmutableList<SbeField> generateFields(Ir ir, IrOptions irOptions) {
ImmutableList.Builder<SbeField> fields = ImmutableList.builder();
TokenIterator iterator = getIteratorForMessage(ir, irOptions);
while (iterator.hasNext()) {
Token token = iterator.next();
switch (token.signal())... | @Test
public void testGenerateFieldsNoSpecifiedMessage() throws Exception {
Ir ir = getIr(OnlyPrimitivesMultiMessage.RESOURCE_PATH);
assertThrows(
IllegalArgumentException.class,
() -> IrFieldGenerator.generateFields(ir, IrOptions.DEFAULT));
} |
@Override
public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize)
{
requireNonNull(outputBufferId, "outputBufferId is null");
checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte");
return partitions.get(output... | @Test
public void testAcknowledgementFreesWriters()
{
int firstPartition = 0;
int secondPartition = 1;
PartitionedOutputBuffer buffer = createPartitionedBuffer(
createInitialEmptyOutputBuffers(PARTITIONED)
.withBuffer(FIRST, firstPartition)
... |
public ExitStatus(Options options) {
this.options = options;
} | @Test
void with_ambiguous_scenarios() {
createRuntime();
bus.send(testCaseFinishedWithStatus(Status.AMBIGUOUS));
assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1)));
} |
@Override
public void process(Exchange exchange) throws Exception {
final SchematronProcessor schematronProcessor = SchematronProcessorFactory.newSchematronEngine(endpoint.getRules());
final Object payload = exchange.getIn().getBody();
final String report;
if (payload instanceof Sou... | @Test
public void testProcessValidXMLAsSource() throws Exception {
Exchange exc = new DefaultExchange(context, ExchangePattern.InOut);
exc.getIn().setBody(
new SAXSource(getXMLReader(), new InputSource(ClassLoader.getSystemResourceAsStream("xml/article-1.xml"))));
// process... |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void redberriesContractRedberriesDead()
{
// Get the bush patch
final FarmingPatch patch = farmingGuildPatches.get(Varbits.FARMING_4772);
assertNotNull(patch);
when(farmingTracker.predictPatch(patch))
.thenReturn(new PatchPrediction(Produce.REDBERRIES, CropState.DEAD, 0, 2, 3));
farmingCo... |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testTruncateFnWithHasDefaultMethodsWhenBounded() throws Exception {
class BoundedMockFn extends DoFn<String, String> {
@ProcessElement
public void processElement(
ProcessContext c,
RestrictionTracker<RestrictionWithBoundedDefaultTracker, Void> tracker,
W... |
public KnownExploitedVulnerabilitiesSchema parse(InputStream in) throws UpdateException, CorruptedDatastreamException {
final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final Module module;
if (Utils.getJavaVersion() <= 8)... | @Test
public void testParse() throws Exception {
File file = new File("./src/test/resources/update/cisa/known_exploited_vulnerabilities.json");
try (InputStream in = new FileInputStream(file)) {
KnownExploitedVulnerabilityParser instance = new KnownExploitedVulnerabilityParser();
... |
@Override
public ByteBuf copy() {
return copy(readerIndex, readableBytes());
} | @Test
public void testCopy() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
final int readerIndex = CAPACITY / 3;
final int writerIndex = CAPACITY * 2 / 3;
buffer.setIndex(readerIndex... |
@Override
public ProducerBuilder<T> batchingMaxPublishDelay(long batchDelay, @NonNull TimeUnit timeUnit) {
conf.setBatchingMaxPublishDelayMicros(batchDelay, timeUnit);
return this;
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testProducerBuilderImplWhenBatchingMaxPublishDelayPropertyIsNegative() {
producerBuilderImpl.batchingMaxPublishDelay(-1, TimeUnit.MILLISECONDS);
} |
@Override
public void close() {
} | @Test
public void shouldSucceed_forward() throws ExecutionException, InterruptedException {
// Given:
final PushRouting routing = new PushRouting();
// When:
final PushConnectionsHandle handle = handlePushRouting(routing);
context.runOnContext(v -> {
localPublisher.accept(LOCAL_ROW1);
... |
@Override
public void registerTimer(long timestamp) {
timerService.registerProcessingTimeTimer(VoidNamespace.INSTANCE, timestamp);
} | @Test
void testRegisterProcessingTimer() {
TestInternalTimerService<Integer, VoidNamespace> timerService = getTimerService();
DefaultProcessingTimeManager manager = new DefaultProcessingTimeManager(timerService);
assertThat(timerService.numProcessingTimeTimers()).isZero();
manager.re... |
Optional<CheckpointTriggerRequest> chooseRequestToExecute(
CheckpointTriggerRequest newRequest, boolean isTriggering, long lastCompletionMs) {
if (queuedRequests.size() >= maxQueuedRequests && !queuedRequests.last().isPeriodic) {
// there are only non-periodic (ie user-submitted) request... | @Test
void testForce() {
CheckpointRequestDecider decider =
decider(1, 1, Integer.MAX_VALUE, new AtomicInteger(1), new AtomicInteger(0));
CheckpointTriggerRequest request = periodicSavepoint();
assertThat(decider.chooseRequestToExecute(request, false, 123)).hasValue(request);... |
protected boolean isCore(Dependency left, Dependency right) {
final String leftName = left.getFileName().toLowerCase();
final String rightName = right.getFileName().toLowerCase();
final boolean returnVal;
//TODO - should we get rid of this merging? It removes a true BOM...
if (... | @Test
public void testIsCore() {
Dependency left = new Dependency();
Dependency right = new Dependency();
left.setFileName("axis2-kernel-1.4.1.jar");
right.setFileName("axis2-adb-1.4.1.jar");
DependencyBundlingAnalyzer instance = new DependencyBundlingAnalyzer();
boo... |
public static final String[] guessStringsFromLine( VariableSpace space, LogChannelInterface log, String line,
TextFileInputMeta inf, String delimiter, String enclosure, String escapeCharacter ) throws KettleException {
List<String> strings = new ArrayList<>();
String pol; // piece of line
try {
... | @Test
public void guessStringsFromLine() throws Exception {
TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class );
inputMeta.content = new TextFileInputMeta.Content();
inputMeta.content.fileType = "CSV";
String line = "\"\\\\valueA\"|\"valueB\\\\\"|\"val\\\\ueC\""; // "\\valueA"|"valu... |
public String getJson() {
Collection<SlowPeerJsonReport> validReports = getJsonReports(
maxNodesToReport);
try {
return WRITER.writeValueAsString(validReports);
} catch (JsonProcessingException e) {
// Failed to serialize. Don't log the exception call stack.
LOG.debug("Failed to se... | @Test
public void testGetJson() throws IOException {
OutlierMetrics outlierMetrics1 = new OutlierMetrics(0.0, 0.0, 0.0, 1.1);
tracker.addReport("node1", "node2", outlierMetrics1);
OutlierMetrics outlierMetrics2 = new OutlierMetrics(0.0, 0.0, 0.0, 1.23);
tracker.addReport("node2", "node3", outlierMetri... |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testPreemptionWithVCoreResource() {
int[][] qData = new int[][]{
// / A B
{100, 100, 100}, // maxcap
{5, 1, 1}, // apps
{2, 0, 0}, // subqueues
};
// Resources can be set like memory:vcores
String[][] resData = new String[][]{
// / A B
... |
public static OptionRule.Builder builder() {
return new OptionRule.Builder();
} | @Test
public void testVerify() {
Executable executable =
() -> {
OptionRule.builder()
.optional(TEST_NUM, TEST_MODE)
.required(TEST_PORTS, TEST_REQUIRED_HAVE_DEFAULT_VALUE)
.exclusive(TEST... |
@Override
public void save(@NonNull Session session) {
if (session.id() == null) {
throw new IllegalArgumentException("session has no ID");
}
store.put(session.id(), session);
} | @Test
void save_noId() {
var sut = new CaffeineSessionRepo(null, Duration.ofMinutes(5));
var session = new Session(null, null, null, null, null, null, null, null, null);
assertThrows(IllegalArgumentException.class, () -> sut.save(session));
} |
public Response daemonLogPage(String fileName, Integer start, Integer length, String grep, String user)
throws IOException, InvalidRequestException {
Path file = daemonLogRoot.resolve(fileName).toAbsolutePath().normalize();
if (!file.startsWith(daemonLogRoot) || Paths.get(fileName).getNameCo... | @Test
public void testDaemonLogPageOutsideLogRoot() throws Exception {
try (TmpPath rootPath = new TmpPath()) {
LogviewerLogPageHandler handler = createHandlerForTraversalTests(rootPath.getFile().toPath());
final Response returned = handler.daemonLogPage("../evil.sh", 0, 100, null, ... |
public List<String> parse(final CharSequence line) {
return this.lineParser.parse( line.toString() );
} | @Test
public void testSimpleLineParse() {
final CsvLineParser parser = new CsvLineParser();
final String s = "a,b,c";
final List<String> list = parser.parse(s);
assertThat(list).hasSize(3).containsExactly("a", "b", "c");
} |
public static LoadViewResponse fromJson(String json) {
return JsonUtil.parse(json, LoadViewResponseParser::fromJson);
} | @Test
public void missingFields() {
assertThatThrownBy(() -> LoadViewResponseParser.fromJson("{\"x\": \"val\"}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing string: metadata-location");
assertThatThrownBy(
() -> LoadViewResponseParser.fromJson(... |
@Override
public InputFile newInputFile(String path) {
return HadoopInputFile.fromLocation(path, hadoopConf.get());
} | @Test
public void testFileExists() throws IOException {
Path parent = new Path(tempDir.toURI());
Path randomFilePath = new Path(parent, "random-file-" + UUID.randomUUID());
fs.createNewFile(randomFilePath);
// check existence of the created file
assertThat(hadoopFileIO.newInputFile(randomFilePath... |
static void checkCompositeBatchVersion(final String configuredVersion, final Version batchVersion)
throws SalesforceException {
if (Version.create(configuredVersion).compareTo(batchVersion) < 0) {
throw new SalesforceException(
"Component is configured with Salesforce... | @Test
public void shouldNotAllowNewerPayloadsWhenConfiguredWithOlderVersion() throws SalesforceException {
final SObjectBatch batch = new SObjectBatch(V35_0);
assertThrows(SalesforceException.class,
() -> DefaultCompositeApiClient.checkCompositeBatchVersion(V34_0, batch.getVersion()... |
RandomTextDataGenerator(int size, int wordSize) {
this(size, DEFAULT_SEED , wordSize);
} | @Test
public void testRandomTextDataGenerator() {
RandomTextDataGenerator rtdg = new RandomTextDataGenerator(10, 0L, 5);
List<String> words = rtdg.getRandomWords();
// check the size
assertEquals("List size mismatch", 10, words.size());
// check the words
Set<String> wordsSet = new HashSet<S... |
@Override
public boolean locatorsUpdateCopy() {
return false;
} | @Test
void assertLocatorsUpdateCopy() {
assertFalse(metaData.locatorsUpdateCopy());
} |
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit)
{
if (isClosed)
{
return 0;
}
int fragmentsRead = 0;
long initialPosition = subscriberPosition.get();
int initialOffset = (int)initialPosition & termLengthMask;
... | @Test
void shouldPollOneFragmentToControlledFragmentHandlerOnContinue()
{
final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID);
position.setOrdered(initialPosition);
final Image image = createImage();
insertDataFrame(INITIAL_T... |
@Override
public String getStorageAccountKey(String accountName, Configuration rawConfig)
throws KeyProviderException {
String envelope = super.getStorageAccountKey(accountName, rawConfig);
AbfsConfiguration abfsConfig;
try {
abfsConfig = new AbfsConfiguration(rawConfig, accountName);
} c... | @Test
public void testValidScript() throws Exception {
if (!Shell.WINDOWS) {
return;
}
String expectedResult = "decretedKey";
// Create a simple script which echoes the given key plus the given
// expected result (so that we validate both script input and output)
File scriptFile = new F... |
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) {
switch (trigger.getTriggerCase()) {
case AFTER_ALL:
return AfterAllStateMachine.of(
stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList()));
case AFTER_ANY:
return AfterFirstSt... | @Test
public void testAfterWatermarkEarlyTranslation() {
RunnerApi.Trigger trigger =
RunnerApi.Trigger.newBuilder()
.setAfterEndOfWindow(
RunnerApi.Trigger.AfterEndOfWindow.newBuilder().setEarlyFirings(subtrigger1))
.build();
AfterWatermarkStateMachine.AfterWate... |
@Operation(summary = "queryUiPluginDetailById", description = "QUERY_UI_PLUGIN_DETAIL_BY_ID")
@Parameters({
@Parameter(name = "id", description = "PLUGIN_ID", required = true, schema = @Schema(implementation = int.class, example = "100")),
})
@GetMapping(value = "/{id}")
@ResponseStatus(Http... | @Test
public void testQueryUiPluginDetailById() throws Exception {
when(uiPluginService.queryUiPluginDetailById(anyInt()))
.thenReturn(uiPluginServiceResult);
final MvcResult mvcResult = mockMvc.perform(get("/ui-plugins/{id}", pluginId)
.header(SESSION_ID, sessionId)... |
public static HealthCheckRegistry getDefault() {
final HealthCheckRegistry healthCheckRegistry = tryGetDefault();
if (healthCheckRegistry != null) {
return healthCheckRegistry;
}
throw new IllegalStateException("Default registry name has not been set.");
} | @Test
public void defaultRegistryIsNotSetByDefault() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Default registry name has not been set.");
SharedHealthCheckRegistries.getDefault();
} |
public ConfigCenterBuilder cluster(String cluster) {
this.cluster = cluster;
return getThis();
} | @Test
void cluster() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.cluster("cluster");
Assertions.assertEquals("cluster", builder.build().getCluster());
} |
@VisibleForTesting
void configureCallbackInterval(Task task) {
boolean isRunningForeachStep = false;
boolean isMaestroTaskCreated = false;
boolean isFirstPollingCycle =
task != null && task.getPollCount() <= Constants.FIRST_POLLING_COUNT_LIMIT;
if (task != null && task.getOutputData().contains... | @Test
public void testConfigureCallBack() {
Task task = new Task();
// stepRuntimeSummary object
task.getOutputData()
.put(Constants.STEP_RUNTIME_SUMMARY_FIELD, StepRuntimeSummary.builder().build());
when(callbackPolicy.getCallBackDelayInSecs(any())).thenReturn(30L);
maestroWorkflowExecuto... |
List<String> liveKeysAsOrderedList() {
return new ArrayList<String>(liveMap.keySet());
} | @Test
public void destroy() {
long now = 3000;
CyclicBuffer<Object> cb = tracker.getOrCreate(key, now);
cb.add(new Object());
assertEquals(1, cb.length());
tracker.endOfLife(key);
now += CyclicBufferTracker.LINGERING_TIMEOUT + 10;
tracker.removeStaleComponents(now);
assertEquals(0, tra... |
@Override
public int length() {
return 2;
} | @Test
public void testLength() {
System.out.println("npara");
LogisticDistribution instance = new LogisticDistribution(2.0, 1.0);
instance.rand();
assertEquals(2, instance.length());
} |
@Override
public boolean wasNull() throws SQLException {
checkClosed();
return false;
} | @Test
void assertWasNull() throws SQLException {
assertFalse(databaseMetaDataResultSet.wasNull());
} |
public synchronized ResultSet fetchResults(FetchOrientation orientation, int maxFetchSize) {
long token;
switch (orientation) {
case FETCH_NEXT:
token = currentToken;
break;
case FETCH_PRIOR:
token = currentToken - 1;
... | @Test
void testFetchResultsMultipleTimesWithLimitedBufferSize() {
int bufferSize = data.size() / 2;
ResultFetcher fetcher =
buildResultFetcher(Collections.singletonList(data.iterator()), bufferSize);
int fetchSize = data.size();
runFetchMultipleTimes(
... |
public int readInt3() {
return byteBuf.readUnsignedMediumLE();
} | @Test
void assertReadInt3() {
when(byteBuf.readUnsignedMediumLE()).thenReturn(1);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt3(), is(1));
} |
Set<SourceName> analyzeExpression(
final Expression expression,
final String clauseType
) {
final Validator extractor = new Validator(clauseType);
extractor.process(expression, null);
return extractor.referencedSources;
} | @Test
public void shouldNotThrowOnPossibleSyntheticKeyColumn() {
// Given:
when(sourceSchemas.isJoin()).thenReturn(true);
// When:
analyzer.analyzeExpression(POSSIBLE_SYNTHETIC_KEY, "SELECT");
// Then: did not throw.
} |
public <T extends AbstractMessageListenerContainer> T decorateMessageListenerContainer(T container) {
Advice[] advice = prependTracingMessageContainerAdvice(container);
if (advice != null) {
container.setAdviceChain(advice);
}
return container;
} | @Test void decorateDirectMessageListenerContainer__adds_by_default() {
DirectMessageListenerContainer listenerContainer = new DirectMessageListenerContainer();
assertThat(rabbitTracing.decorateMessageListenerContainer(listenerContainer))
.extracting("adviceChain")
.asInstanceOf(array(Advice[].class... |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String returnCommand = null;
String subCommand = safeReadLine(reader, false);
if (subCommand.equals(HELP_OBJECT_SUB_COMMAND_NAME)) {
returnCommand = getHelpObject(reader);
... | @Test
public void testHelpClassPattern() {
String inputCommand = "c\n" + ExampleClass.class.getName() + "\nsm*\ntrue\ne\n";
try {
assertTrue(gateway.getBindings().containsKey(target));
command.execute("h", new BufferedReader(new StringReader(inputCommand)), writer);
String page = sWriter.toString();
Sy... |
@Override
public synchronized String toString() {
if (parameters.isEmpty()) {
return "";
}
StringBuilder b = new StringBuilder();
char sep = '?';
for (String key : parameters.keySet()) {
for (String value : parameters.get(key)) {
b.appe... | @Test
public void testKeepProtocolUpperCase() {
QueryString qs = new QueryString(
"http://site.com/page?NoEquals&WithEquals=EqualsValue");
Assert.assertTrue("Argument without equal sign was not found.",
qs.toString().contains("NoEquals"));
} |
@Udf
public <T> List<T> slice(
@UdfParameter(description = "the input array") final List<T> in,
@UdfParameter(description = "start index") final Integer from,
@UdfParameter(description = "end index") final Integer to) {
if (in == null) {
return null;
}
try {
// ... | @Test
public void shouldFullListOnNullEndpoints() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, null, null);
// Then:
assertThat(slice, is(Lists.newArrayList("a", "b", "c")));
} |
@Override
public void changeLogLevel(LoggerLevel level) {
requireNonNull(level, "level can't be null");
call(new ChangeLogLevelActionClient(level));
} | @Test
public void changeLogLevel_throws_ISE_if_http_error() {
String message = "blah";
server.enqueue(new MockResponse().setResponseCode(500).setBody(message));
// initialize registration of process
setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE);
assertThatThrownBy(() -> underTest.changeLogLevel(Log... |
static Object math(Object left, Object right, EvaluationContext ctx, BinaryOperator<BigDecimal> op) {
BigDecimal l = left instanceof String ? null : NumberEvalHelper.getBigDecimalOrNull(left);
BigDecimal r = right instanceof String ? null : NumberEvalHelper.getBigDecimalOrNull(right);
if (l == n... | @Test
void math_BothNumbers() {
final Random rnd = new Random();
MATH_OPERATORS.forEach(operator -> {
BigDecimal left = BigDecimal.valueOf(rnd.nextDouble());
BigDecimal right = BigDecimal.valueOf(rnd.nextDouble());
BigDecimal expected = operator.apply(left, right)... |
@Override
public final MetadataResolver resolve(final boolean force) {
if (force) {
this.metadataResolver = prepareServiceProviderMetadata();
}
return this.metadataResolver;
} | @Test
public void resolveServiceProviderMetadataViaFile() {
val configuration =
initializeConfiguration(new FileSystemResource("target/out.xml"), "target/keystore.jks");
final SAML2MetadataResolver metadataResolver = new SAML2ServiceProviderMetadataResolver(configuration);
assert... |
public BlockLease flatten(Block block)
{
requireNonNull(block, "block is null");
if (block instanceof DictionaryBlock) {
return flattenDictionaryBlock((DictionaryBlock) block);
}
if (block instanceof RunLengthEncodedBlock) {
return flattenRunLengthEncodedBlock... | @Test
public void testLongArrayIdentityDecode()
{
Block block = createLongArrayBlock(1, 2, 3, 4);
try (BlockLease blockLease = flattener.flatten(block)) {
Block flattenedBlock = blockLease.get();
assertSame(flattenedBlock, block);
}
} |
public IntValue increment(int increment) {
this.value += increment;
this.set = true;
return this;
} | @Test
public void multiples_calls_to_increment_int_increment_the_value() {
IntValue value = new IntValue()
.increment(10)
.increment(95);
verifySetValue(value, 105);
} |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGoMod() throws AnalysisException, InitializationException {
analyzer.prepare(engine);
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "golang/go.mod"));
analyzer.analyze(result, engine);
assertEquals(7, engine.getDependencies().length)... |
public Optional<UpdateCenter> getUpdateCenter() {
return getUpdateCenter(false);
} | @Test
public void update_center_is_null_when_property_is_false() {
settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), false);
assertThat(underTest.getUpdateCenter()).isEmpty();
} |
public static void deleteIfExists(final File file)
{
try
{
Files.deleteIfExists(file.toPath());
}
catch (final IOException ex)
{
LangUtil.rethrowUnchecked(ex);
}
} | @Test
void deleteIfExistsFile() throws IOException
{
final Path file = tempDir.resolve("delete-me.txt");
Files.createFile(file);
IoUtil.deleteIfExists(file.toFile());
assertFalse(Files.exists(file));
} |
@Override
public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) {
log.debug(
"sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}",
catalogueTree,
sortTypeEnum);
return recursionSortCatalogues... | @Test
public void sortDescTest() {
SortTypeEnum sortTypeEnum = SortTypeEnum.DESC;
List<Catalogue> catalogueTree = Lists.newArrayList();
Catalogue catalogue = new Catalogue();
catalogue.setId(1);
catalogue.setCreateTime(LocalDateTime.of(2024, 4, 28, 19, 22, 0));
Catal... |
public HealthCheckResponse checkHealth() {
final Map<String, HealthCheckResponseDetail> results = DEFAULT_CHECKS.stream()
.collect(Collectors.toMap(
Check::getName,
check -> check.check(this)
));
final boolean allHealthy = results.values().stream()
.allMatch(Healt... | @Test
public void shouldReturnUnhealthyIfMetastoreCheckFails() {
// Given:
when(ksqlClient.makeKsqlRequest(SERVER_URI, "list streams; list tables; list queries;", REQUEST_PROPERTIES))
.thenReturn(unSuccessfulResponse);
// When:
final HealthCheckResponse response = healthCheckAgent.checkHealth... |
public static Builder newBuilder() {
return new Builder();
} | @Test void spanHandlers_clearAndAdd() {
SpanHandler one = mock(SpanHandler.class);
SpanHandler two = mock(SpanHandler.class);
SpanHandler three = mock(SpanHandler.class);
Tracing.Builder builder = Tracing.newBuilder()
.addSpanHandler(one)
.addSpanHandler(two)
.addSpanHandler(thr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.