focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
protected Object getContent(ScmGetRequest request) {
GithubScm.validateUserHasPushPermission(request.getApiUrl(), request.getCredentials().getPassword().getPlainText(), request.getOwner(), request.getRepo());
String url = String.format("%s/repos/%s/%s/contents/%s",
request... | @Test
public void getContentForOrgFolder() throws UnirestException {
String credentialId = createGithubCredential(user);
StaplerRequest staplerRequest = mockStapler();
MultiBranchProject mbp = mockMbp(credentialId, user, GithubScm.DOMAIN_NAME);
GithubFile content = (GithubFile) ne... |
@Override
public CompletableFuture<HeartbeatResponseData> heartbeat(
RequestContext context,
HeartbeatRequestData request
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(new HeartbeatResponseData()
.setErrorCode(Errors.COORDINATOR_NOT_AVAIL... | @Test
public void testHeartbeat() throws Exception {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
new Gro... |
@Override
public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) {
return consumerUsesReadCommitted(props)
? ExactlyOnceSupport.SUPPORTED
: ExactlyOnceSupport.UNSUPPORTED;
} | @Test
public void testExactlyOnceSupport() {
String readCommitted = "read_committed";
String readUncommitted = "read_uncommitted";
String readGarbage = "read_garbage";
// Connector is configured correctly, but exactly-once can't be supported
assertExactlyOnceSupport(null, nu... |
public void populate(LiveOperations liveOperations) {
this.liveOperations.forEach((key, value) -> value.keySet().forEach(callId -> liveOperations.add(key, callId)));
} | @Test
public void testPopulate() throws UnknownHostException {
r.register(createOperation("1.2.3.4", 1234, 2223L));
r.register(createOperation("1.2.3.4", 1234, 2222L));
r.register(createOperation("1.2.3.3", 1234, 2222L));
CallsPerMember liveOperations = new CallsPerMember(new Addres... |
public static Position emptyPosition() {
return new Position(new ConcurrentHashMap<>());
} | @Test
public void shouldNotMatchNull() {
final Position position = Position.emptyPosition();
assertNotEquals(position, null);
} |
@Udf
public int instr(final String str, final String substring) {
return instr(str, substring, 1);
} | @Test
public void shouldTruncateOutOfBoundIndexes() {
assertThat(udf.instr("CORPORATE FLOOR", "OR", 100), is(0));
assertThat(udf.instr("CORPORATE FLOOR", "OR", -100), is(0));
} |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testInfoDefault() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("info").get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
response.getType(... |
@Override
public String begin(String applicationId, String transactionServiceGroup, String name, int timeout)
throws TransactionException {
GlobalSession session = GlobalSession.createGlobalSession(applicationId, transactionServiceGroup, name, timeout);
MDC.put(RootContext.MDC_KEY_XID, sessi... | @Test
public void beginTest() throws Exception {
String xid = core.begin(applicationId, txServiceGroup, txName, timeout);
globalSession = SessionHolder.findGlobalSession(xid);
Assertions.assertNotNull(globalSession);
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM
&& event.getType() != ChatMessageType.GAMEMESSAGE
&& event.getType() != ChatMessageType.MESBOX)
{
return;
}
final var msg = event.getMessage();
if (WOOD_CUT_PATTERN.matcher(msg).matches())
{
... | @Test
public void testAnimaInfusedBark()
{
var chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", "You've been awarded <col=0000b2>88 Anima-infused bark</col>.", "", 0);
woodcuttingPlugin.onChatMessage(chatMessage);
assertNotNull(woodcuttingPlugin.getSession());
assertEquals(88, woodcuttingP... |
public RowExpression extract(PlanNode node)
{
return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null);
} | @Test
public void testInnerJoin()
{
ImmutableList.Builder<EquiJoinClause> criteriaBuilder = ImmutableList.builder();
criteriaBuilder.add(new EquiJoinClause(AV, DV));
criteriaBuilder.add(new EquiJoinClause(BV, EV));
List<EquiJoinClause> criteria = criteriaBuilder.build();
... |
public Set<String> getOnValues()
{
// we need a set as the field can appear multiple times
Set<String> onValues = new LinkedHashSet<>();
List<String> exportValues = getExportValues();
if (!exportValues.isEmpty())
{
onValues.addAll(exportValues);
return... | @Test
void retrieveAcrobatRadioButtonProperties()
{
PDRadioButton radioButton = (PDRadioButton) acrobatAcroForm.getField("RadioButtonGroup");
assertNotNull(radioButton);
assertEquals(2, radioButton.getOnValues().size());
assertTrue(radioButton.getOnValues().contains("RadioButton0... |
public static JsonObject build(JsonObject lockJson, JsonObject packageJson,
MultiValuedMap<String, String> dependencyMap, boolean skipDevDependencies) {
final JsonObjectBuilder payloadBuilder = Json.createObjectBuilder();
addProjectInfo(packageJson, payloadBuilder);
// NPM Audit exp... | @Test
public void testSanitizer() {
JsonObjectBuilder builder = Json.createObjectBuilder()
.add("name", "my app")
.add("version", "1.0.0")
.add("random", "random")
.add("lockfileVersion", 1)
.add("requires", true)
... |
public static FileRewriteCoordinator get() {
return INSTANCE;
} | @TestTemplate
public void testBinPackRewrite() throws NoSuchTableException, IOException {
sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName);
Dataset<Row> df = newDF(1000);
df.coalesce(1).writeTo(tableName).append();
df.coalesce(1).writeTo(tableName).append();
df.coalesce(1).wr... |
public String getTaskState(String taskName)
throws IOException, HttpException {
HttpGet httpGet = createHttpGetRequest(MinionRequestURLBuilder.baseUrl(_controllerUrl).forTaskState(taskName));
try (CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet)) {
int statusCode = response.getCode();
... | @Test
public void testTaskState()
throws IOException, HttpException {
HttpServer httpServer = startServer(14204, "/tasks/task/Task_SegmentGenerationAndPushTask_1607470525615/state",
createHandler(200, "\"COMPLETED\"", 0));
MinionClient minionClient = new MinionClient("http://localhost:14204", nu... |
public static byte[] encryptAES(byte[] data, byte[] key) {
return desTemplate(data, key, AES_Algorithm, AES_Transformation, true);
} | @Test
public void encryptAES() throws Exception {
TestCase.assertTrue(
Arrays.equals(
bytesResAES,
EncryptKit.encryptAES(bytesDataAES, bytesKeyAES)
)
);
Assert.assertEquals(
resAES,
... |
@Nonnull
public static <T> Sink<T> list(@Nonnull String listName) {
return fromProcessor("listSink(" + listName + ')', writeListP(listName));
} | @Test
public void when_writeToMultipleStagesToSingleSink_then_allItemsInSink() {
// Given
String secondSourceName = randomName();
List<Integer> input = sequence(itemCount);
addToSrcList(input);
hz().getList(secondSourceName).addAll(input);
BatchStage<Entry<Object, Obj... |
void recoverTransitionRead(DataNode datanode, NamespaceInfo nsInfo,
Collection<StorageLocation> dataDirs, StartupOption startOpt) throws IOException {
if (addStorageLocations(datanode, nsInfo, dataDirs, startOpt).isEmpty()) {
throw new IOException("All specified directories have failed to load.");
}... | @Test
public void testRecoverTransitionReadDoTransitionFailure()
throws IOException {
final int numLocations = 3;
List<StorageLocation> locations = createStorageLocations(numLocations);
// Prepare volumes
storage.recoverTransitionRead(mockDN, nsInfo, locations, START_OPT);
assertEquals(numLo... |
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
SlaveStepCopyPartitionDistribution that = (SlaveStepCopyPartitionDistribution) o;
return Objects.equals( distribution, that.distribution ... | @Test
public void equalsSameInstanceTest() {
Assert.assertTrue( slaveStep.equals( slaveStep ) );
} |
@Nonnull
@Override
public ILogger getLogger(@Nonnull String name) {
checkNotNull(name, "name must not be null");
return getOrPutIfAbsent(mapLoggers, name, loggerConstructor);
} | @Test
public void testLog_whenLogEvent_thenNothingHappens() {
ILogger logger = loggingService.getLogger("test");
logger.log(logEvent);
} |
@Override
public Mono<GetExternalServiceCredentialsResponse> getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request) {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator... | @Test
public void testInvalidRequest() throws Exception {
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getExternalServiceCredentials(
GetExternalServiceCredentialsRequest.newBuilder()
.build()));
} |
@Override
public void send(final String command, final ProgressListener progress, final TranscriptListener transcript) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Send command %s", command));
}
progress.message(command);
final Protocol... | @Test
public void testSend() throws Exception {
final StringBuilder t = new StringBuilder();
new FTPCommandFeature(session).send("HELP", new ProgressListener() {
@Override
public void message(final String message) {
assertEquals("HELP", message);
}... |
void start(Iterable<ShardCheckpoint> checkpoints) {
LOG.info(
"Pool {} - starting for stream {} consumer {}. Checkpoints = {}",
poolId,
read.getStreamName(),
consumerArn,
checkpoints);
for (ShardCheckpoint shardCheckpoint : checkpoints) {
checkState(
!stat... | @Test
public void poolReSubscribesAndReadsRecords() throws Exception {
kinesis = new EFOStubbedKinesisAsyncClient(10);
kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3));
kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3, 7));
kinesis.stubSubscribeToShard("shard-000", eventsWith... |
@Override
public void print(MetadataNodePrinter printer) {
StringBuilder bld = new StringBuilder();
bld.append("ScramCredentialData");
bld.append("(salt=");
if (printer.redactionCriteria().shouldRedactScram()) {
bld.append("[redacted]");
} else {
array... | @Test
public void testPrintUnredacted() {
NodeStringifier stringifier = new NodeStringifier(Disabled.INSTANCE);
new ScramCredentialDataNode(DATA).print(stringifier);
assertEquals("ScramCredentialData(" +
"salt=4f1d6ea31e58c5ad3aaeb3266f55cce6, " +
"storedKey=3cfa1c342... |
public ClassData getClassDataOrNull(String className) {
ClassData classData = loadBytecodesFromClientCache(className);
if (classData != null) {
return classData;
}
if (providerMode == UserCodeDeploymentConfig.ProviderMode.OFF) {
return null;
}
clas... | @Test
public void givenProviderModeSetToLOCAL_AND_CACHED_CLASSES_whenMapClassContainsClass_thenReturnIt() {
UserCodeDeploymentConfig.ProviderMode providerMode = LOCAL_AND_CACHED_CLASSES;
String className = "className";
ClassSource classSource = newMockClassSource();
ClassLoader paren... |
@VisibleForTesting
void handleResult(Record srcRecord, JavaExecutionResult result) throws Exception {
if (result.getUserException() != null) {
Exception t = result.getUserException();
log.warn("Encountered exception when processing message {}",
srcRecord, t);
... | @Test
public void testFunctionResultNull() throws Exception {
JavaExecutionResult javaExecutionResult = new JavaExecutionResult();
// ProcessingGuarantees == MANUAL, not need ack.
Record record = mock(Record.class);
getJavaInstanceRunnable(true, org.apache.pulsar.functions.proto.Fun... |
public static boolean doExistingCertificatesDiffer(Secret current, Secret desired) {
Map<String, String> currentData = current.getData();
Map<String, String> desiredData = desired.getData();
if (currentData == null) {
return true;
} else {
for (Map.Entry<String, ... | @Test
public void testExistingCertificatesDiffer() {
Secret defaultSecret = new SecretBuilder()
.withNewMetadata()
.withName("my-secret")
.endMetadata()
.addToData("my-cluster-kafka-0.crt", "Certificate0")
.addToData("my-clust... |
public Img stroke(Color color, float width) {
return stroke(color, new BasicStroke(width));
} | @Test
@Disabled
public void strokeTest() {
Img.from(FileUtil.file("d:/test/公章3.png"))
.stroke(null, 2f)
.write(FileUtil.file("d:/test/stroke_result.png"));
} |
public static void checkState(boolean isValid, String message) throws IllegalStateException {
if (!isValid) {
throw new IllegalStateException(message);
}
} | @Test
public void testCheckStateWithMoreThanThreeParams() {
try {
Preconditions.checkState(true, "Test message %s %s %s %s", 12, null, "column", true);
} catch (IllegalStateException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkStat... |
public short get2BytesLittleEndian() {
throw new UnsupportedOperationException("Not implemented");
} | @Test
public void testGet2BytesLittleEndian() {
// ByteBufferBackedBinary: get2BytesLittleEndian
Binary b1 = Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[] {0x01, 0x02}));
assertEquals((short) 0x0201, b1.get2BytesLittleEndian());
// ByteArrayBackedBinary: get2BytesLittleEndian
Binary b2... |
public final void containsAnyOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
containsAnyIn(accumulate(first, second, rest));
} | @Test
public void iterableContainsAnyOf() {
assertThat(asList(1, 2, 3)).containsAnyOf(1, 5);
} |
public static <T> T execute(Single<T> apiCall) {
try {
return apiCall.blockingGet();
} catch (HttpException e) {
try {
if (e.response() == null || e.response().errorBody() == null) {
throw e;
}
String errorBody =... | @Test
void executeParseHttpError() {
String errorBody = "{\"error\":{\"message\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}";
HttpException httpException = createException(errorBody, 401);
Single<CompletionResult> single = Single.error(httpException);
... |
public void convertQueueHierarchy(FSQueue queue) {
List<FSQueue> children = queue.getChildQueues();
final String queueName = queue.getName();
emitChildQueues(queueName, children);
emitMaxAMShare(queueName, queue);
emitMaxParallelApps(queueName, queue);
emitMaxAllocations(queueName, queue);
... | @Test
public void testQueueMaxParallelApps() {
converter = builder.build();
converter.convertQueueHierarchy(rootQueue);
assertEquals("root.admins.alice max apps", 2,
csConfig.getMaxParallelAppsForQueue(ADMINS_ALICE), 0);
Set<String> remaining = Sets.difference(ALL_QUEUES,
Sets.newHa... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseSetUnsetStatements() {
List<CommandParser.ParsedCommand> commands = parse("SeT 'foo.property'='bar';UnSET 'foo.property';");
assertThat(commands.size(), is(2));
assertThat(commands.get(0).getStatement().isPresent(), is (true));
assertThat(commands.get(0).getStatement().get... |
public void addPartition(RangePartition p) {
if (p instanceof RangeEdgePartition) {
edgePartitions.add((RangeEdgePartition)p);
} else {
partitions.add(p);
}
} | @Test
void requireThatRangePartitionsCanBeAdded() {
FeatureRange range = new FeatureRange("foo", 10L, 22L);
range.addPartition(new RangePartition("foo=10-19"));
range.addPartition(new RangePartition("foo", 0, 0x8000000000000000L, true));
range.addPartition(new RangeEdgePartition("foo... |
public static Object convert(final Object o) {
if (o == null) {
return RubyUtil.RUBY.getNil();
}
final Class<?> cls = o.getClass();
final Valuefier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return converter.convert(o);
... | @Test
public void testZonedDateTime() {
ZonedDateTime zdt = ZonedDateTime.of(2022,4,4,5,6,13,123, ZoneId.of("Europe/London"));
JrubyTimestampExtLibrary.RubyTimestamp result = (JrubyTimestampExtLibrary.RubyTimestamp) Valuefier.convert(zdt);
assertEquals(zdt.toInstant().toEpochMilli(), result.... |
<T> T call() throws IOException {
if (shouldMock()) {
// ce générique doit être conservé pour la compilation javac en intégration continue
return this.createMockResultOfCall();
}
final long start = System.currentTimeMillis();
int dataLength = -1;
try {
final URLConnection connection = openConnection(... | @Test
public void testCall() throws IOException {
Utils.setProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "mockLabradorRetriever", "false");
final File file = File.createTempFile("test", ".ser");
try {
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file))) {
output.writeObject... |
public static String createJobName(Function.FunctionDetails functionDetails, String jobName) {
return jobName == null ? createJobName(functionDetails.getTenant(),
functionDetails.getNamespace(), functionDetails.getName()) :
createJobName(jobName, functionDetails.getTenant(),
... | @Test
public void testCreateJobName() throws Exception {
verifyCreateJobNameWithBackwardCompatibility();
verifyCreateJobNameWithUpperCaseFunctionName();
verifyCreateJobNameWithDotFunctionName();
verifyCreateJobNameWithDotAndUpperCaseFunctionName();
verifyCreateJobNameWithInva... |
static BlockStmt getIntervalVariableDeclaration(final String variableName,
final Interval interval) {
final MethodDeclaration methodDeclaration =
INTERVAL_TEMPLATE.getMethodsByName(GETKIEPMMLINTERVAL).get(0).clone();
final BlockStmt... | @Test
void getIntervalVariableDeclaration() throws IOException {
String variableName = "variableName";
double leftMargin = 45.32;
Interval interval = new Interval();
interval.setLeftMargin(leftMargin);
interval.setRightMargin(null);
interval.setClosure(Interval.Closu... |
@Override
public String toString() {
return "EipStatistic{" +
"id='" + id + '\'' +
", tested=" + tested +
", totalProcessingTime=" + totalProcessingTime +
", properties=" + properties +
", childEipStatisticMap=" + childEipStatisticM... | @Test
public void testToString() {
String toString = getInstance().toString();
assertNotNull(toString);
assertTrue(toString.contains("EipStatistic"));
} |
public static void print(Object obj) {
print(TEMPLATE_VAR, obj);
} | @Test
public void printColorTest(){
System.out.print("\33[30;1m A \u001b[31;2m B \u001b[32;1m C \u001b[33;1m D \u001b[0m");
} |
@Override
public Set<Entry<K, V>> entrySet() {
return set;
} | @Test
public void testEntrySet() {
Map<String, Integer> underlying = createTestMap();
TranslatedValueMapView<String, String, Integer> view =
new TranslatedValueMapView<>(underlying, v -> v.toString());
assertEquals(3, view.entrySet().size());
assertFalse(view.entrySet().i... |
@Udf(description = "Converts a TIMESTAMP value into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'"
+ " The system default time zone is used when no time zone is explicitly ... | @Test
public void shouldReturnNullOnNullDate() {
// When:
final String returnValue = udf.formatTimestamp(null, "yyyy-MM-dd");
// Then:
assertThat(returnValue, is(nullValue()));
} |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
final IRODSFileSystemAO fs = session.getClient();
final IRODSFile s = fs.getIRO... | @Test
public void testMoveFile() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant Collab... |
public ClusterStateBundle getLastClusterStateBundleConverged() {
return lastClusterStateBundleConverged;
} | @Test
@SuppressWarnings("unchecked")
void activation_not_sent_before_all_distributors_have_acked_state_bundle() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
f.expectSetSystemStateInvocationsToBothDistributors();
f.simulateBroadcastTick(cf, 123);
... |
@Override
protected int compareFirst(final Path p1, final Path p2) {
if(StringUtils.isBlank(p1.attributes().getGroup()) && StringUtils.isBlank(p2.attributes().getGroup())) {
return 0;
}
if(StringUtils.isBlank(p1.attributes().getGroup())) {
return -1;
}
... | @Test
public void testCompareFirst() {
assertEquals(0,
new GroupComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file))));
final Path p = new Path("/a", EnumSet.of(Path.Type.file));
p.attributes().setGroup("g");
... |
@Override
public double entropy() {
return entropy;
} | @Test
public void testEntropy() {
System.out.println("entropy");
BernoulliDistribution instance = new BernoulliDistribution(0.3);
instance.rand();
assertEquals(-0.3* MathEx.log2(0.3) - 0.7* MathEx.log2(0.7), instance.entropy(), 1E-7);
} |
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final Boolean verbose = namespace.getBoolean("verbose");
liquibase.reportStatus(verbose != null && verbose,
getContext(namespace),
... | @Test
void testRun() throws Exception {
statusCommand.run(null, new Namespace(Collections.emptyMap()), MigrationTestSupport.createConfiguration());
assertThat(baos.toString(UTF_8.name())).matches(
"3 changesets have not been applied to \\S+\\R");
} |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_object() {
Object original = new SerializableObject("value");
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
public static int[] computePhysicalIndicesOrTimeAttributeMarkers(
TableSource<?> tableSource,
List<TableColumn> logicalColumns,
boolean streamMarkers,
Function<String, String> nameRemapping) {
Optional<String> proctimeAttribute = getProctimeAttribute(tableSource);... | @Test
void testWrongLogicalTypeForRowtimeAttribute() {
TestTableSource tableSource =
new TestTableSource(
DataTypes.BIGINT(), Collections.singletonList("rowtime"), "proctime");
assertThatThrownBy(
() ->
... |
public static String render(String templateName, Map<String, Object> data) {
TemplateEngine templateEngine = new TemplateEngine();
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8"... | @Test
public void testRender() {
String result = TemplateRenderer.render("index", Map.of("testValue", "testRender"));
assertEquals(EXPECTED, result);
} |
public AstNode rewrite(final AstNode node, final C context) {
return rewriter.process(node, context);
} | @Test
public void shouldRewriteWindowExpression() {
// Given:
final KsqlWindowExpression ksqlWindowExpression = mock(KsqlWindowExpression.class);
final WindowExpression windowExpression =
new WindowExpression(location, "name", ksqlWindowExpression);
// When:
final AstNode rewritten = rewr... |
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!"alerts".equals(notification.getType())) {
return null;
}
// Retrieve useful values
String projectId = notification.getFieldValue("projectId");
String projectKey = notification.getFieldValue("projectKey")... | @Test
public void shouldFormatNewAlertWithSeveralMessages() {
Notification notification = createNotification("Failed", "violations > 4, coverage < 75%", "ERROR", "true");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getS... |
@Override
@Deprecated
public <VR> KStream<K, VR> transformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, ? extends VR> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransformerSup... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNamesOnTransformValuesWithValueTransformerWithKeySupplier() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transformValues(
valueTransfor... |
@Override
public final void writeRecord(OUT record) throws IOException {
checkAsyncErrors();
tryAcquire(1);
final CompletionStage<V> completionStage;
try {
completionStage = send(record);
} catch (Throwable e) {
semaphore.release();
throw e... | @Test
void testMaxConcurrentRequestsReached() throws Exception {
try (TestOutputFormat testOutputFormat =
createOpenedTestOutputFormat(Duration.ofMillis(1))) {
CompletableFuture<Void> completableFuture = new CompletableFuture<>();
testOutputFormat.enqueueCompletableFu... |
public static Locale localeFromString(String s) {
if (!s.contains(LOBAR)) {
return new Locale(s);
}
String[] items = s.split(LOBAR);
return new Locale(items[0], items[1]);
} | @Test
public void localeFromStringItIT() {
title("localeFromStringItIT");
locale = LionUtils.localeFromString("it_IT");
checkLanguageCountry(locale, "it", "IT");
} |
@Override
public void remove(String key) {
if (key == null) {
return;
}
Map<String, String> current = readWriteThreadLocalMap.get();
if (current != null) {
current.remove(key);
nullifyReadOnlyThreadLocalMap();
}
} | @Test
public void removeInexistentKey() {
mdcAdapter.remove("abcdlw0");
} |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testValidationSkippedWhenOutputIsConsole() throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
new FSConfigToCSConfigArgumentHandler(conversionOptions,
mockValidator);
String[] args = getArgumentsAsArrayWithDefa... |
@Override
public AppResponse process(Flow flow, ActivationUsernamePasswordRequest body) throws SharedServiceClientException {
digidClient.remoteLog("1088", Map.of(lowerUnderscore(HIDDEN), true));
var result = digidClient.authenticate(body.getUsername(), body.getPassword());
if (result.get(l... | @Test
void nokResponseToManyAmountOfApps() throws SharedServiceClientException {
when(sharedServiceClientMock.getSSConfigInt("Maximum_aantal_DigiD_apps_eindgebruiker")).thenReturn(5);
AppAuthenticator oldApp = new AppAuthenticator();
oldApp.setDeviceName("test_device");
oldApp.setLas... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseVarArgsIfSpecificDoesntMatch() {
// Given:
givenFunctions(
function(OTHER, -1, STRING),
function(EXPECTED, 0, STRING_VARARGS)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(
SqlArgument.of(SqlTypes.STRING)... |
@Override
protected Object getTargetObject(boolean key) {
Object targetObject;
if (key) {
// keyData is never null
if (keyData.isPortable() || keyData.isJson() || keyData.isCompact()) {
targetObject = keyData;
} else {
targetObject ... | @Test(expected = NullPointerException.class)
public void testGetTargetObject_givenInstanceIsNotInitialized_whenKeyFlagIsTrue_thenThrowNPE() {
QueryableEntry entry = createEntry();
entry.getTargetObject(true);
} |
protected static boolean isBeanPropertyReadMethod(Method method) {
return method != null
&& Modifier.isPublic(method.getModifiers())
&& !Modifier.isStatic(method.getModifiers())
&& method.getReturnType() != void.class
&& method.getDeclaringClass() != Object.class
... | @Test
public void testIsBeanPropertyReadMethod() throws Exception {
Assert.assertFalse(isBeanPropertyReadMethod(null));
Assert.assertTrue(isBeanPropertyReadMethod(TestReflect.class.getMethod("getS")));
Assert.assertFalse(isBeanPropertyReadMethod(TestReflect.class.getMethod("get")));
... |
@Override
protected String getRootKey() {
return Constants.HEADER_COS + mBucketName;
} | @Test
public void testGetRootKey() {
Assert.assertEquals(Constants.HEADER_COS + BUCKET_NAME, mCOSUnderFileSystem.getRootKey());
} |
@Override
public boolean hasVariable(String name) {
if (variables.containsKey(name)) {
return true;
}
if (parent != null) {
return parent.hasVariable(name);
}
return false;
} | @Test
public void testHasVariable() {
ProcessContextImpl context = new ProcessContextImpl();
Assertions.assertFalse(context.hasVariable("key"));
} |
@Override
public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionOffset, final int connectionSize,
final ConnectionMode connectionMode) throws SQLException {
Preconditions.checkNotNull(databaseName, "Curre... | @Test
void assertGetConnectionWithConnectionOffset() throws SQLException {
when(backendDataSource.getConnections(anyString(), anyString(), eq(1), any())).thenReturn(MockConnectionUtils.mockNewConnections(1));
assertThat(databaseConnectionManager.getConnections(DefaultDatabase.LOGIC_NAME, "ds1", 0, 1... |
public String route(final ReadwriteSplittingDataSourceGroupRule rule) {
return rule.getLoadBalancer().getTargetName(rule.getName(), getFilteredReadDataSources(rule));
} | @Test
void assertRoute() {
assertThat(new StandardReadwriteSplittingDataSourceRouter().route(rule), is("read_ds_0"));
} |
@Override
public PageResult<GoViewProjectDO> getMyProjectPage(PageParam pageReqVO, Long userId) {
return goViewProjectMapper.selectPage(pageReqVO, userId);
} | @Test
public void testGetMyGoViewProjectPage() {
// mock 数据
GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class, o -> { // 等会查询到
o.setCreator("1");
});
goViewProjectMapper.insert(dbGoViewProject);
// 测试 userId 不匹配
goViewProjectMapper.insert(... |
public static <T> CsvIOParse<T> parse(Class<T> klass, CSVFormat csvFormat) {
CsvIOParseHelpers.validateCsvFormat(csvFormat);
SchemaProvider provider = new DefaultSchema.DefaultSchemaProvider();
TypeDescriptor<T> type = TypeDescriptor.of(klass);
Schema schema =
checkStateNotNull(
prov... | @Test
public void givenNonSchemaMappedClass_throws() {
Pipeline pipeline = Pipeline.create();
CSVFormat csvFormat =
CSVFormat.DEFAULT
.withHeader("a_string", "an_integer", "a_double")
.withAllowDuplicateHeaderNames(false);
assertThrows(
IllegalStateException.class, ... |
public RuleDescriptionSectionsGenerator getRuleDescriptionSectionsGenerator(RulesDefinition.Rule ruleDef) {
Set<RuleDescriptionSectionsGenerator> generatorsFound = ruleDescriptionSectionsGenerators.stream()
.filter(generator -> generator.isGeneratorForRule(ruleDef))
.collect(toSet());
checkState(gen... | @Test
public void getRuleDescriptionSectionsGenerator_returnsTheCorrectGenerator() {
when(generator2.isGeneratorForRule(rule)).thenReturn(true);
assertThat(resolver.getRuleDescriptionSectionsGenerator(rule)).isEqualTo(generator2);
} |
@Override
public boolean isAddressReachable(String addr) {
if (addr == null || addr.isEmpty()) {
return false;
}
try {
Channel channel = getAndCreateChannel(addr);
return channel != null && channel.isActive();
} catch (Exception e) {
LO... | @Test
public void testIsAddressReachableFail() throws NoSuchFieldException, IllegalAccessException {
Bootstrap bootstrap = spy(Bootstrap.class);
Field field = NettyRemotingClient.class.getDeclaredField("bootstrap");
field.setAccessible(true);
field.set(remotingClient, bootstrap);
... |
@Override
public ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id) {
TaskStatus status = statusBackingStore.get(id);
if (status == null)
throw new NotFoundException("No status found for task " + id);
return new ConnectorStateInfo.TaskState(id.task(), status.state().to... | @Test
public void testTaskStatus() {
ConnectorTaskId taskId = new ConnectorTaskId(connectorName, 0);
String workerId = "workerId";
AbstractHerder herder = testHerder();
final ArgumentCaptor<TaskStatus> taskStatusArgumentCaptor = ArgumentCaptor.forClass(TaskStatus.class);
do... |
public static boolean isValidIpV6Address(String ip) {
return isValidIpV6Address((CharSequence) ip);
} | @Test
public void testIsValidIpV6Address() {
for (String host : validIpV6Hosts.keySet()) {
assertTrue(isValidIpV6Address(host), host);
if (host.charAt(0) != '[' && !host.contains("%")) {
assertNotNull(getByName(host, true), host);
String hostMod = '['... |
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
if (response.status() == 404 || response.status() == 204)
if (JSONObject.class.isAssignableFrom((Class<?>) type))
return new JSONObject();
else if (JSONArray.class.isAssignableFrom((Class<?>) typ... | @Test
void unknownTypeThrowsDecodeException() throws IOException {
String json = "[{\"a\":\"b\",\"c\":1},123]";
Response response = Response.builder()
.status(200)
.reason("OK")
.headers(Collections.emptyMap())
.body(json, UTF_8)
.request(request)
.build();
... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatRightJoinWithoutJoinWindow() {
final Join join = new Join(leftAlias, ImmutableList.of(new JoinedSource(
Optional.empty(),
rightAlias,
JoinedSource.Type.RIGHT,
criteria,
Optional.empty())));
final String result = SqlFormatter.formatSql(join... |
@Override
public int reacquireContainer(ContainerReacquisitionContext ctx)
throws IOException, InterruptedException {
try {
if (numaResourceAllocator != null) {
numaResourceAllocator.recoverNumaResource(ctx.getContainerId());
}
return super.reacquireContainer(ctx);
} finall... | @Test
public void testReacquireContainer() throws Exception {
@SuppressWarnings("unchecked")
ConcurrentHashMap<ContainerId, Container> mockContainers = mock(
ConcurrentHashMap.class);
Context mockContext = mock(Context.class);
NMStateStoreService mock = mock(NMStateStoreService.class);
... |
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> acknowledge(
String memberId,
String groupId,
Map<TopicIdPartition, List<ShareAcknowledgementBatch>> acknowledgeTopics
) {
log.trace("Acknowledge request for topicIdPartitions: {} with groupId... | @Test
public void testAcknowledgeSinglePartition() {
String groupId = "grp";
String memberId = Uuid.randomUuid().toString();
TopicIdPartition tp = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0));
SharePartition sp = mock(SharePartition.class);
when(sp.... |
@Override
public int run(String[] argv) throws Exception {
Options options = buildOptions();
if(argv.length == 0) {
printHelp();
return 0;
}
// print help and exit with zero exit code
if (argv.length == 1 && isHelpOption(argv[0])) {
printHelp();
return 0;
}
CommandL... | @Test
public void testOfflineEditsViewerHelpMessage() throws Throwable {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(bytes);
final PrintStream oldOut = System.out;
try {
System.setOut(out);
int status = new OfflineEditsViewer().r... |
@Override
public int getStatusCode() {
return this.response.getStatusLine().getStatusCode();
} | @Test
void testGetStatusCode() {
when(statusLine.getStatusCode()).thenReturn(200);
assertEquals(200, clientHttpResponse.getStatusCode());
} |
@Override
public ImmutableList<String> computeEntrypoint(List<String> jvmFlags) {
ImmutableList.Builder<String> entrypoint = ImmutableList.builder();
entrypoint.add("java");
entrypoint.addAll(jvmFlags);
entrypoint.add("-jar");
entrypoint.add(JarLayers.APP_ROOT + "/" + jarPath.getFileName().toStrin... | @Test
public void testComputeEntrypoint_jvmFlag() throws URISyntaxException {
Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI());
SpringBootPackagedProcessor springBootProcessor =
new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION);
ImmutableList<String> a... |
public SortedSet<Path> getLogDirs(Set<Path> logDirs, Predicate<String> predicate) {
// we could also make this static, but not to do it due to mock
TreeSet<Path> ret = new TreeSet<>();
for (Path logDir: logDirs) {
String workerId = "";
try {
Optional<Path>... | @Test
public void testIdentifyWorkerLogDirs() throws Exception {
try (TmpPath testDir = new TmpPath()) {
Path port1Dir = Files.createDirectories(testDir.getFile().toPath().resolve("workers-artifacts/topo1/port1"));
Path metaFile = Files.createFile(testDir.getFile().toPath().resolve("... |
@GET
@Path(RMWSConsts.CHECK_USER_ACCESS_TO_QUEUE)
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public RMQueueAclInfo checkUserAccessToQueue(
@PathParam(RMWSConsts.QUEUE) String queue,
@QueryParam(RMWSConsts.USE... | @Test
public void testCheckUserAccessToQueue() throws Exception {
ResourceManager mockRM = mock(ResourceManager.class);
Configuration conf = new YarnConfiguration();
// Inject a mock scheduler implementation.
// Only admin user has ADMINISTER_QUEUE access.
// For SUBMIT_APPLICATION ACL, both of ... |
public String convert(ILoggingEvent le) {
List<Marker> markers = le.getMarkerList();
if (markers == null || markers.isEmpty()) {
return EMPTY;
}
int size = markers.size();
if (size == 1)
return markers.get(0).toString();
StringBuffer buf = new St... | @Test
public void testWithNullMarker() {
String result = converter.convert(createLoggingEvent(null));
assertEquals("", result);
} |
static String constructJQLQuery( Collection<String> issueKeys) {
StringBuilder jql = new StringBuilder();
jql.append("key in (");
Iterator<String> iterator = issueKeys.iterator();
while ( iterator.hasNext() ) {
String key = iterator.next();
jql.append("'");
... | @Test
public void constructJQLQuery() throws Exception {
Assert.assertEquals("key in ('JENKINS-123')",
JiraSCMListener.constructJQLQuery(Collections.singletonList("JENKINS-123")));
Assert.assertEquals("key in ('JENKINS-123','FOO-123','VIVEK-123')",
... |
public long getElapsedTimeAndClean(final TargetAdviceMethod method) {
String key = getKey(method);
try {
return getElapsedTime(key);
} finally {
clean(key);
}
} | @Test
void assertGetElapsedTimeAndCleanWithoutRecorded() {
TargetAdviceMethod method = new TargetAdviceMethod("test");
assertThat(new MethodTimeRecorder(AgentAdvice.class).getElapsedTimeAndClean(method), is(0L));
} |
@Override
public boolean processSnapshot(DistroData distroData) {
ClientSyncDatumSnapshot snapshot = ApplicationUtils.getBean(Serializer.class)
.deserialize(distroData.getContent(), ClientSyncDatumSnapshot.class);
for (ClientSyncData each : snapshot.getClientSyncDataList()) {
... | @Test
void testProcessSnapshot() {
ClientSyncDatumSnapshot snapshot = new ClientSyncDatumSnapshot();
snapshot.setClientSyncDataList(Collections.singletonList(clientSyncData));
when(serializer.deserialize(any(), eq(ClientSyncDatumSnapshot.class))).thenReturn(snapshot);
assertEquals(0L... |
@Override
public void onStreamRequest(StreamRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
disruptRequest(req, requestContext, wireAttrs, nextFilter);
} | @Test
public void testStreamErrorDisrupt() throws Exception
{
final RequestContext requestContext = new RequestContext();
requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.error(REQUEST_LATENCY));
final DisruptFilter filter = new DisruptFilter(_scheduler, _executor, REQUEST_TIMEOUT, _clo... |
public static RunResponse from(WorkflowInstance instance, int state) {
return RunResponse.builder()
.workflowId(instance.getWorkflowId())
.workflowVersionId(instance.getWorkflowVersionId())
.workflowInstanceId(instance.getWorkflowInstanceId())
.workflowRunId(instance.getWorkflowRunId... | @Test
public void testBuildFromState() {
RunResponse res = RunResponse.from(instance, 1);
Assert.assertEquals(RunResponse.Status.WORKFLOW_RUN_CREATED, res.getStatus());
res = RunResponse.from(instance, 0);
Assert.assertEquals(RunResponse.Status.DUPLICATED, res.getStatus());
res = RunResponse.from(... |
public static RuntimeMetric merge(RuntimeMetric metric1, RuntimeMetric metric2)
{
if (metric1 == null) {
return metric2;
}
if (metric2 == null) {
return metric1;
}
checkState(metric1.getUnit() == metric2.getUnit(), "Two metrics to be merged must have t... | @Test(expectedExceptions = {IllegalStateException.class})
public void testMergeWithConflictUnits()
{
RuntimeMetric metric1 = new RuntimeMetric(TEST_METRIC_NAME, NANO, 5, 2, 4, 1);
RuntimeMetric metric2 = new RuntimeMetric(TEST_METRIC_NAME, BYTE, 20, 2, 11, 9);
RuntimeMetric.merge(metric1... |
public String getDefaultSchemaName(final String databaseName) {
return dialectDatabaseMetaData.getDefaultSchema().orElseGet(() -> null == databaseName ? null : databaseName.toLowerCase());
} | @Test
void assertGetDefaultSchemaNameWhenDatabaseTypeNotContainsDefaultSchemaAndNullDatabaseName() {
assertNull(new DatabaseTypeRegistry(TypedSPILoader.getService(DatabaseType.class, "BRANCH")).getDefaultSchemaName(null));
} |
@Deprecated
@Override public void toXML(Object obj, OutputStream out) {
super.toXML(obj, out);
} | @Test
public void annotations() {
assertEquals("not registered, so sorry", "<hudson.util.XStream2Test_-C1/>", Jenkins.XSTREAM2.toXML(new C1()));
assertEquals("manually registered", "<C-2/>", Jenkins.XSTREAM2.toXML(new C2()));
assertEquals("manually processed", "<C-3/>", Jenkins.XSTREAM2.toXM... |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testEmptyFairSchedulerXmlSpecified() throws Exception {
FSConfigConverterTestCommons.configureEmptyFairSchedulerXml();
FSConfigConverterTestCommons.configureEmptyYarnSiteXml();
FSConfigConverterTestCommons.configureDummyConversionRulesFile();
FSConfigToCSConfigArgumentHandler argume... |
public static void assertParamsMatchWithDescription(
String descriptionTemplate, Map<String, String> params) {
getParams(descriptionTemplate)
.forEach(
param -> {
if (!params.containsKey(param)) {
thr... | @Test
void testAssertParamsMatchWithDescription() {
String description = "test description with param <key1>, <key2> and <key3>.";
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
params.put("key3", "value3");
E... |
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) {
NewExternalIssue newExternalIssue = sensorContext.newExternalIssue();
newExternalIssue.type(DEFAULT_TYPE);
newExternalIssue.engineId(driverName);
newExte... | @Test
public void mapResult_whenRelatedLocationExists_createsSecondaryFileLocation_no_messages() {
Location relatedLocationWithoutMessage = new Location();
result.withRelatedLocations(Set.of(relatedLocationWithoutMessage));
var newIssueLocationCall2 = mock(NewIssueLocation.class);
when(mockExternalIss... |
@Override
public boolean registerListener(Object listener) {
if (listener instanceof HazelcastInstanceAware aware) {
aware.setHazelcastInstance(node.hazelcastInstance);
}
if (listener instanceof ClusterVersionListener clusterVersionListener) {
clusterVersionListeners.... | @Test
public void test_listenerHazelcastInstanceInjected_whenHazelcastInstanceAware() {
HazelcastInstanceAwareVersionListener listener = new HazelcastInstanceAwareVersionListener();
assertTrue(nodeExtension.registerListener(listener));
assertEquals(hazelcastInstance, listener.getInstance());... |
@Override
public Set<Rule<?>> rules()
{
return ImmutableSet.of(filterRowExpressionRewriteRule(), projectRowExpressionRewriteRule());
} | @Test
public void testSubscriptCast()
{
tester().assertThat(
ImmutableSet.<Rule<?>>builder().addAll(new SimplifyRowExpressions(getMetadata()).rules()).addAll(new RemoveMapCastRule(getFunctionManager()).rules()).build())
.setSystemProperty(REMOVE_MAP_CAST, "true")
... |
public void execute(final PrioritizableRunnable runnable) {
_queue.add(runnable);
// Guarantees that execution loop is scheduled only once to the underlying executor.
// Also makes sure that all memory effects of last Runnable are visible to the next Runnable
// in case value returned by decrementAndGet... | @Test(dataProvider = "draining")
public void testExecuteTwoStepPlan(boolean draining) throws InterruptedException {
final LatchedRunnable inner = new LatchedRunnable();
final Runnable outer = new Runnable() {
@Override
public void run() {
_serialExecutor.execute(inner);
}
};
... |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateUnaryArithmetic() {
// Given:
final Expression expression1 = new ArithmeticUnaryExpression(
Optional.empty(), Sign.PLUS, new IntegerLiteral(1)
);
final Expression expression2 = new ArithmeticUnaryExpression(
Optional.empty(), Sign.MINUS, new IntegerLiter... |
@Override
public void execute( RunConfiguration runConfiguration, ExecutionConfiguration executionConfiguration,
AbstractMeta meta, VariableSpace variableSpace, Repository repository ) throws KettleException {
DefaultRunConfiguration defaultRunConfiguration = (DefaultRunConfiguration) runCo... | @Test
public void testExecutePentahoTrans() throws Exception {
DefaultRunConfiguration defaultRunConfiguration = new DefaultRunConfiguration();
defaultRunConfiguration.setName( "Default Configuration" );
defaultRunConfiguration.setLocal( false );
defaultRunConfiguration.setPentaho( true );
default... |
@SuppressWarnings("unchecked")
public final void isAtLeast(@Nullable T other) {
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) < 0) {
failWithActual("expected to be at least", other);
}
} | @Test
public void isAtLeast() {
assertThat(4).isAtLeast(3);
assertThat(4).isAtLeast(4);
expectFailureWhenTestingThat(4).isAtLeast(5);
assertFailureValue("expected to be at least", "5");
} |
@Override
protected double maintain() {
if ( ! nodeRepository().nodes().isWorking()) return 0.0;
if (nodeRepository().zone().environment().isTest()) return 1.0;
int attempts = 0;
int failures = 0;
outer:
for (var applicationNodes : activeNodesByApplication().entrySet... | @Test
public void empty_autoscaling_is_ignored() {
ApplicationId app1 = AutoscalingMaintainerTester.makeApplicationId("app1");
ClusterSpec cluster1 = AutoscalingMaintainerTester.containerClusterSpec();
NodeResources resources = new NodeResources(4, 4, 10, 1);
ClusterResources min = n... |
@Override
public void doSendSms(SmsSendMessage message) {
// 获得渠道对应的 SmsClient 客户端
SmsClient smsClient = smsChannelService.getSmsClient(message.getChannelId());
Assert.notNull(smsClient, "短信客户端({}) 不存在", message.getChannelId());
// 发送短信
try {
SmsSendRespDTO sendRe... | @Test
@SuppressWarnings("unchecked")
public void testDoSendSms() throws Throwable {
// 准备参数
SmsSendMessage message = randomPojo(SmsSendMessage.class);
// mock SmsClientFactory 的方法
SmsClient smsClient = spy(SmsClient.class);
when(smsChannelService.getSmsClient(eq(message.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.