focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Member getMember() {
return member;
} | @Test
public void testGetMember() {
assertEquals(member, logEvent.getMember());
} |
public static void saveConsanguinity(Consanguinity consanguinity) {
if (CONSANGUINITY_MAP.containsKey(consanguinity.getServiceKey())) {
Consanguinity consanguinityOld = CONSANGUINITY_MAP.get(consanguinity.getServiceKey());
consanguinityOld.setProviders(consanguinity.getProviders());
... | @Test
public void saveConsanguinity() {
Consanguinity consanguinity = new Consanguinity();
List<Contract> contractList = new ArrayList<>();
Contract contract = new Contract();
contract.setIp(DEFAULT_IP);
contract.setPort(DEFAULT_PORT);
contractList.add(contract);
... |
List<ParsedTerm> identifyUnknownFields(final Set<String> availableFields, final List<ParsedTerm> terms) {
final Map<String, List<ParsedTerm>> groupedByField = terms.stream()
.filter(t -> !t.isDefaultField())
.filter(term -> !SEARCHABLE_ES_FIELDS.contains(term.getRealFieldName()))... | @Test
void testDoesNotIdentifyGraylogReservedFieldsAsUnknown() {
final List<ParsedTerm> unknownFields = toTest.identifyUnknownFields(
Set.of("some_normal_field"),
RESERVED_SETTABLE_FIELDS.stream().map(f -> ParsedTerm.create(f, "buba")).collect(Collectors.toList())
);
... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testPartitionedOr() throws Exception {
createPartitionedTable(spark, tableName, "years(ts), bucket(5, id)");
SparkScanBuilder builder = scanBuilder();
YearsFunction.TimestampToYearsFunction tsToYears = new YearsFunction.TimestampToYearsFunction();
UserDefinedScalarFunc udf1 = toUDF... |
@Override
protected Future<KafkaMirrorMakerStatus> createOrUpdate(Reconciliation reconciliation, KafkaMirrorMaker assemblyResource) {
String namespace = reconciliation.namespace();
KafkaMirrorMakerCluster mirror;
KafkaMirrorMakerStatus kafkaMirrorMakerStatus = new KafkaMirrorMakerStatus();
... | @Test
public void testUpdateClusterNoDiff(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true);
CrdOperator<KubernetesClient, KafkaMirrorMaker, KafkaMirrorMakerList> mockMirrorOps = supplier.mirrorMakerOperator;
DeploymentOperator mockDcOps = ... |
public Token nextToken() throws IOException
{
Token curToken = aheadToken;
//System.out.println(curToken); // for debugging
aheadToken = readToken(curToken);
return curToken;
} | @Test
void testEmptyName() throws IOException
{
String s = "dup 127 / put";
Type1Lexer t1l = new Type1Lexer(s.getBytes(StandardCharsets.US_ASCII));
Token nextToken;
try
{
do
{
nextToken = t1l.nextToken();
}
w... |
@Override
public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) {
Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:"
+ " URI path should not be null");
try {
return S3AUnderFileSystem.createInstance(new AlluxioURI(path), conf);
} catch (Ama... | @Test
public void createInstanceWithNullPath() {
Exception e = assertThrows(NullPointerException.class, () -> mFactory1.create(
null, mConf));
assertTrue(e.getMessage().contains("Unable to create UnderFileSystem instance: URI "
+ "path should not be null"));
} |
public Predicate convert(List<ScalarOperator> operators, DeltaLakeContext context) {
DeltaLakeExprVisitor visitor = new DeltaLakeExprVisitor();
List<Predicate> predicates = Lists.newArrayList();
for (ScalarOperator operator : operators) {
Predicate predicate = operator.accept(visito... | @Test
public void testConvertIsNullPredicate() {
ScalarOperationToDeltaLakeExpr converter = new ScalarOperationToDeltaLakeExpr();
ScalarOperationToDeltaLakeExpr.DeltaLakeContext context =
new ScalarOperationToDeltaLakeExpr.DeltaLakeContext(schema, new HashSet<>());
List<Scala... |
MatchResult matchPluginTemplate(String ownerTemplate, String template) {
boolean matches = false;
String pluginName = null;
String templateName = template;
String ownerTemplateName = ownerTemplate;
if (StringUtils.isNotBlank(ownerTemplate)) {
Matcher ownerTemplateMatc... | @Test
void matchPluginTemplateWhenDoesNotMatch() {
var result =
templateResolver.matchPluginTemplate("doc", "modules/layout");
assertThat(result.matches()).isFalse();
} |
public static ByteString dataMapToByteString(Map<String, String> headers, DataMap dataMap) throws MimeTypeParseException, IOException
{
return ByteString.unsafeWrap(getContentType(headers).getCodec().mapToBytes(dataMap));
} | @Test
public void testDataMapToJSONByteStringWithUnsupportedContentType() throws MimeTypeParseException, IOException
{
// unsupport content type should fallback to JSON
DataMap testDataMap = createTestDataMap();
byte[] expectedBytes = JACKSON_DATA_CODEC.mapToBytes(testDataMap);
Map<String, String> ... |
@VisibleForTesting
static String convertProtoPropertyNameToJavaPropertyName(String input) {
boolean capitalizeNextLetter = true;
Preconditions.checkArgument(!Strings.isNullOrEmpty(input));
StringBuilder result = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
final ... | @Test
public void testGetterNameCreationForProtoPropertyWithUnderscore() {
Assert.assertEquals(
JAVA_PROPERTY_FOR_PROTO_PROPERTY_WITH_UNDERSCORE,
ProtoByteBuddyUtils.convertProtoPropertyNameToJavaPropertyName(
PROTO_PROPERTY_WITH_UNDERSCORE));
} |
@Override
public DataNodeDto startNode(String nodeId) throws NodeNotFoundException {
final DataNodeDto node = nodeService.byNodeId(nodeId);
if (node.getDataNodeStatus() != DataNodeStatus.UNAVAILABLE && node.getDataNodeStatus() != DataNodeStatus.PREPARED) {
throw new IllegalArgumentExcep... | @Test
public void startNodePublishesClusterEvent() throws NodeNotFoundException {
final String testNodeId = "node";
nodeService.registerServer(buildTestNode(testNodeId, DataNodeStatus.UNAVAILABLE));
classUnderTest.startNode(testNodeId);
verify(clusterEventBus).post(DataNodeLifecycleE... |
static void validateCsvFormat(CSVFormat format) {
String[] header =
checkArgumentNotNull(format.getHeader(), "Illegal %s: header is required", CSVFormat.class);
checkArgument(header.length > 0, "Illegal %s: header cannot be empty", CSVFormat.class);
checkArgument(
!format.getAllowMissingCo... | @Test
public void givenCSVFormatWithHeader_validates() {
CSVFormat format = csvFormatWithHeader();
CsvIOParseHelpers.validateCsvFormat(format);
} |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testFromOptionsWithUppercaseConvertsToLowercase() throws Exception {
String mixedCase = "ThisJobNameHasMixedCase";
DataflowPipelineOptions options = buildPipelineOptions();
options.setJobName(mixedCase);
DataflowRunner.fromOptions(options);
assertThat(options.getJobName(), equal... |
public static Duration parseDuration(String text) {
checkNotNull(text);
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while ... | @Test
void testParseDurationTrim() {
assertThat(TimeUtils.parseDuration(" 155 ").toMillis()).isEqualTo(155L);
assertThat(TimeUtils.parseDuration(" 155 ms ").toMillis()).isEqualTo(155L);
} |
@Override
public Sensor addRateTotalSensor(final String scopeName,
final String entityName,
final String operationName,
final Sensor.RecordingLevel recordingLevel,
fina... | @Test
public void shouldAddRateTotalSensorWithCustomTags() {
final Sensor sensor = streamsMetrics.addRateTotalSensor(
SCOPE_NAME,
ENTITY_NAME,
OPERATION_NAME,
RecordingLevel.DEBUG,
CUSTOM_TAG_KEY1,
CUSTOM_TAG_VALUE1,
CUSTOM_... |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
switch (request.getCode()) {
case RequestCode.QUERY_ASSIGNMENT:
return this.queryAssignment(ctx, request);
case RequestCode.SE... | @Test
public void testSetMessageRequestMode_Success() throws Exception {
brokerController.getProducerManager().registerProducer(group, clientInfo);
final RemotingCommand request = createSetMessageRequestModeRequest(topic);
RemotingCommand responseToReturn = queryAssignmentProcessor.processRe... |
@Override
public ConsumeQueueInterface getConsumeQueue(String topic, int queueId) {
return findConsumeQueue(topic, queueId);
} | @Test
public void testGetStoreTime_EverythingIsOk() {
if (notExecuted()) {
return;
}
final int totalCount = 10;
int queueId = 0;
String topic = "FooBar";
AppendMessageResult[] appendMessageResults = putMessages(totalCount, topic, queueId, false);
/... |
@Override
public ValidationResult validateSecretsConfig(String pluginId, final Map<String, String> configuration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_SECRETS_CONFIG,
new DefaultPluginInteractionCallback<>() {
@Override
public Stri... | @Test
void shouldTalkToPlugin_toValidateSecretsConfig() {
String responseBody = "[{\"message\":\"Vault Url cannot be blank.\",\"key\":\"Url\"},{\"message\":\"Path cannot be blank.\",\"key\":\"Path\"}]";
when(pluginManager.submitTo(eq(PLUGIN_ID), eq(SECRETS_EXTENSION), requestArgumentCaptor.capture()... |
@Override
public void createFolder() throws FileSystemException {
requireResolvedFileObject().createFolder();
} | @Test
public void testDelegatesCreateFolder() throws FileSystemException {
fileObject.createFolder();
verify( resolvedFileObject, times( 1 ) ).createFolder();
} |
public static JsonToRowWithErrFn withExceptionReporting(Schema rowSchema) {
return JsonToRowWithErrFn.forSchema(rowSchema);
} | @Test
@Category(NeedsRunner.class)
public void testParsesErrorWithErrorMsgRowsDeadLetter() throws Exception {
PCollection<String> jsonPersons =
pipeline.apply("jsonPersons", Create.of(JSON_PERSON_WITH_ERR));
ParseResult results =
jsonPersons.apply(JsonToRow.withExceptionReporting(PERSON_SCH... |
public static void setOutput(Job job, OutputJobInfo outputJobInfo) throws IOException {
setOutput(job.getConfiguration(), job.getCredentials(), outputJobInfo);
} | @Test
public void testGetTableSchema() throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "test getTableSchema");
HCatOutputFormat.setOutput(
job,
OutputJobInfo.create(
dbName,
tblName,
new HashMap<String, Strin... |
public NewTopic configs(Map<String, String> configs) {
this.configs = configs;
return this;
} | @Test
public void testConfigsNotNull() {
NewTopic newTopic = new NewTopic(TEST_TOPIC, NUM_PARTITIONS, REPLICATION_FACTOR);
Map<String, String> configs = new HashMap<>();
configs.put(CLEANUP_POLICY_CONFIG_KEY, CLEANUP_POLICY_CONFIG_VALUE);
newTopic.configs(configs);
assertEqua... |
@Override
public Health check() {
if (isConnectedToDB()) {
return Health.GREEN;
}
return RED_HEALTH;
} | @Test
public void status_is_RED_with_single_cause_if_isAlive_does_not_return_1() {
when(isAliveMapper.isAlive()).thenReturn(12);
Health health = underTest.check();
verifyRedStatus(health);
} |
@Override
public <V> MultiLabel generateOutput(V label) {
if (label instanceof Collection) {
Collection<?> c = (Collection<?>) label;
List<Pair<String,Boolean>> dimensions = new ArrayList<>();
for (Object o : c) {
dimensions.add(MultiLabel.parseElement(o.t... | @Test
public void testGenerateOutput_set() {
MultiLabelFactory factory = new MultiLabelFactory();
MultiLabel output = factory.generateOutput(new HashSet<>(Arrays.asList("a=true", "b=true", "c=true")));
assertEquals(3, output.getLabelSet().size());
assertEquals("a,b,c", output.getLabe... |
public static <T, PartitionColumnT> ReadWithPartitions<T, PartitionColumnT> readWithPartitions(
TypeDescriptor<PartitionColumnT> partitioningColumnType) {
return new AutoValue_JdbcIO_ReadWithPartitions.Builder<T, PartitionColumnT>()
.setPartitionColumnType(partitioningColumnType)
.setNumPartit... | @Test
public void testIfNumPartitionsIsZero() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("numPartitions can not be less than 1");
pipeline.apply(
JdbcIO.<TestRow>readWithPartitions()
.withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION)
.withRow... |
public static List<SessionInformations> getAllSessionsInformations() {
final Collection<HttpSession> sessions = SESSION_MAP_BY_ID.values();
final List<SessionInformations> sessionsInformations = new ArrayList<>(sessions.size());
for (final HttpSession session : sessions) {
try {
sessionsInformations.add(ne... | @Test
public void testGetAllSessionsInformations() {
final long now = System.currentTimeMillis();
sessionListener.sessionCreated(createSessionEvent("1", true, now));
sessionListener.sessionCreated(createSessionEvent("2", true, now + 2));
sessionListener.sessionCreated(createSessionEvent("3", true, now));
ses... |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testInvalidStrategySpecifiedInClusterConfig() {
final Configuration conf = new Configuration();
conf.set(RestartStrategyOptions.RESTART_STRATEGY, "invalid-strategy");
assertThatThrownBy(
() ->
RestartBackoffTimeStrategyFacto... |
@Override
protected int compareFirst(final Path p1, final Path p2) {
if((p1.isDirectory() && p2.isDirectory())
|| p1.isFile() && p2.isFile()) {
if(ascending) {
return impl.compare(descriptor.getKind(p1), descriptor.getKind(p2));
}
return -i... | @Test
public void testCompareFirst() {
assertEquals(0,
new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/a", EnumSet.of(Path.Type.file))));
assertEquals(0,
new FileTypeComparator(true).compareFirst(new Path("/a", EnumSet.... |
public void close() {
spillAndReleaseAllData();
spiller.close();
poolSizeChecker.shutdown();
} | @Test
void testResultPartitionClosed() throws Exception {
CompletableFuture<Void> resultPartitionReleaseFuture = new CompletableFuture<>();
HsSpillingStrategy spillingStrategy =
TestingSpillingStrategy.builder()
.setOnResultPartitionClosedFunction(
... |
public NamesrvConfig getNamesrvConfig() {
return namesrvConfig;
} | @Test
public void getNamesrvConfig() {
NamesrvConfig namesrvConfig = namesrvController.getNamesrvConfig();
Assert.assertNotNull(namesrvConfig);
} |
public static void checkTenant(String tenant) {
if (StringUtils.isNotBlank(tenant)) {
if (!isValid(tenant.trim())) {
throw new IllegalArgumentException("invalid tenant");
}
if (tenant.length() > TENANT_MAX_LEN) {
throw new IllegalArgumentExcept... | @Test
void testCheckTenant() {
//tag invalid
String tenant = "test!";
try {
ParamUtils.checkTenant(tenant);
fail();
} catch (IllegalArgumentException e) {
System.out.println(e.toString());
}
//tag over length
int ta... |
public static <T> int getNullIndex(final T[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
return -1;
} | @Test
public void shouldGetCorrectNullIndex() {
final Double[] doubles1 = new Double[]{10.0, null, null};
final Double[] doubles2 = new Double[]{null, null, null};
final Double[] doubles3 = new Double[]{10.0, 9.0, 8.0};
assertThat(ArrayUtil.getNullIndex(doubles1), equalTo(1));
assertThat(ArrayUti... |
@Udf(description = "Returns a masked version of the input string. All characters except for the"
+ " last n will be replaced according to the default masking rules.")
@SuppressWarnings("MethodMayBeStatic") // Invoked via reflection
public String mask(
@UdfParameter("input STRING to be masked") final Str... | @Test
public void shouldApplyAllExplicitTypeMasks() {
final String result = udf.mask("AbCd#$123xy Z", 5, "Q", "q", "9", "@");
assertThat(result, is("QqQq@@993xy Z"));
} |
public static String getClientIp(ServerHttpRequest request) {
for (String header : IP_HEADER_NAMES) {
String ipList = request.getHeaders().getFirst(header);
if (StringUtils.hasText(ipList) && !UNKNOWN.equalsIgnoreCase(ipList)) {
String[] ips = ipList.trim().split("[,;]");... | @Test
void testGetIPAddressFromXRealIpHeader() {
var request = MockServerHttpRequest.get("/")
.header("X-Real-IP", "127.0.0.1")
.build();
var expected = "127.0.0.1";
var actual = IpAddressUtils.getClientIp(request);
assertEquals(expected, actual);
} |
@Override
public void publish(ScannerReportWriter writer) {
List<Map.Entry<String, String>> properties = new ArrayList<>(cache.getAll().entrySet());
properties.add(constructScmInfo());
properties.add(constructCiInfo());
// properties that are automatically included to report so that
// they can be... | @Test
public void publish_settings_prefixed_with_sonar_analysis_for_webhooks() {
props.put("foo", "should not be exported");
props.put("sonar.analysis.revision", "ab45b3");
props.put("sonar.analysis.build.number", "B123");
underTest.publish(writer);
List<ScannerReport.ContextProperty> expected =... |
public Schema addToSchema(Schema schema) {
validate(schema);
schema.addProp(LOGICAL_TYPE_PROP, name);
schema.setLogicalType(this);
return schema;
} | @Test
void durationExtendsFixed12() {
Schema durationSchema = LogicalTypes.duration().addToSchema(Schema.createFixed("f", null, null, 12));
assertEquals(LogicalTypes.duration(), durationSchema.getLogicalType());
assertThrows("Duration requires a fixed(12)", IllegalArgumentException.class,
"Durati... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldFailIfThereIsInvalidFieldNameInStructCall() {
// Given:
final Expression expression = new DereferenceExpression(
Optional.empty(),
new UnqualifiedColumnReferenceExp(ColumnName.of("COL6")),
"ZIP"
);
// When:
final Exception e = assertThrows(
... |
@Override
public Mono<LookupUsernameHashResponse> lookupUsernameHash(final LookupUsernameHashRequest request) {
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
throw Status.INVALID_ARGUMENT
.withDescription(String.format("Illegal username hash length; expected %d ... | @Test
void lookupUsernameHashRateLimited() {
final Duration retryAfter = Duration.ofSeconds(13);
when(rateLimiter.validateReactive(anyString()))
.thenReturn(Mono.error(new RateLimitExceededException(retryAfter)));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExceeded... |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void beanMethodSpelTest() throws Exception {
String testExpression = "@dummySpelBean.getBulkheadName(#parameter)";
String testMethodArg = "argg";
String bulkheadName = "sgt. bulko";
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod... |
@POST
@Path("run/{noteId}/{paragraphId}")
@ZeppelinApi
public Response runParagraphSynchronously(@PathParam("noteId") String noteId,
@PathParam("paragraphId") String paragraphId,
@QueryParam("sessionId") String sessionId,
... | @Test
void testRunParagraphSynchronously() throws IOException {
LOG.info("Running testRunParagraphSynchronously");
String note1Id = null;
try {
note1Id = notebook.createNote("note1", anonymous);
Paragraph p = notebook.processNote(note1Id,
note1 -> {
return note1.addNewParagra... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void power4() {
String inputExpression = "y ** ( 5 * 3 )";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix).isInstanceOf(InfixOpNode.class);
assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat... |
public Map<String, String> getProperties() {
return properties;
} | @Test
public void testInlinePropertiesUDF() throws Exception {
String createFunctionSql = "CREATE FUNCTION get_typeb(INT) RETURNS \n" +
"STRING\n" +
" type = 'Python'\n" +
" symbol = 'echo'\n" +
"AS \n" +
"$$ \n" +
... |
public static SessionBytesStoreSupplier persistentSessionStore(final String name,
final Duration retentionPeriod) {
Objects.requireNonNull(name, "name cannot be null");
final String msgPrefix = prepareMillisCheckFailMsgPrefix(retentionPe... | @Test
public void shouldThrowIfIPersistentSessionStoreStoreNameIsNull() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.persistentSessionStore(null, ofMillis(0)));
assertEquals("name cannot be null", e.getMessage());
} |
@Override
public void setDefaultHandler(final Application application, final List<String> schemes) {
final WorkspaceSchemeHandlerProxy proxy = WorkspaceSchemeHandlerProxy.create();
for(String scheme : schemes) {
final String path = workspace.absolutePathForAppBundleWithIdentifier(applica... | @Test
@Ignore
public void testSetDefaultHandler() {
assumeTrue(Factory.Platform.osversion.matches("12\\..*"));
final Application application = new Application("com.apple.finder");
final WorkspaceSchemeHandler handler = new WorkspaceSchemeHandler(new LaunchServicesApplicationFinder());
... |
@VisibleForTesting
static Comparator<ActualProperties> streamingExecutionPreference(PreferredProperties preferred)
{
// Calculating the matches can be a bit expensive, so cache the results between comparisons
LoadingCache<List<LocalProperty<VariableReferenceExpression>>, List<Optional<LocalPrope... | @Test
public void testPickLayoutAnyPreference()
{
Comparator<ActualProperties> preference = streamingExecutionPreference(PreferredProperties.any());
List<ActualProperties> input = ImmutableList.<ActualProperties>builder()
.add(builder()
.global(streamPart... |
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
doEvaluateDisruptContext(request, requestContext);
return _client.sendRequest(request, requestContext);
} | @Test
public void testSendRequest11()
{
when(_controller.getDisruptContext(any(String.class))).thenReturn(_disrupt);
_client.sendRequest(_multiplexed);
verify(_underlying, times(1)).sendRequest(eq(_multiplexed), any(RequestContext.class), any(Callback.class));;
} |
@Udf
public List<String> keys(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final List<String> ret = new ArrayList<>();
node.fi... | @Test
public void shouldReturnNullForString() {
assertNull(udf.keys("\"abc\""));
} |
public static void negate(Slice decimal)
{
setNegative(decimal, !isNegative(decimal));
} | @Test
public void testUnscaledBigIntegerToDecimal()
{
assertConvertsUnscaledBigIntegerToDecimal(MAX_DECIMAL_UNSCALED_VALUE);
assertConvertsUnscaledBigIntegerToDecimal(MIN_DECIMAL_UNSCALED_VALUE);
assertConvertsUnscaledBigIntegerToDecimal(BigInteger.ZERO);
assertConvertsUnscaledBi... |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamRangeAndRange() {
FunctionTestUtil.assertResult( startsFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ) ),
... |
public synchronized void add(T node) {
add(node, defaultReplication);
} | @Test
public void usesCustomHash() {
final RuntimeException exception = new RuntimeException();
ConsistentHash.Hash<String> hashFunction = str -> {
throw exception;
};
ConsistentHash<String> hash = new ConsistentHash<>(hashFunction);
final RuntimeException e = as... |
@Secured(resource = Commons.NACOS_CORE_CONTEXT_V2 + "/loader", action = ActionTypes.READ)
@GetMapping("/cluster")
public ResponseEntity<Map<String, Object>> loaderMetrics() {
Map<String, Object> serverLoadMetrics = getServerLoadMetrics();
return ResponseEntity.ok().body(serverL... | @Test
void testLoaderMetrics() throws NacosException {
EnvUtil.setEnvironment(new MockEnvironment());
Member member = new Member();
member.setIp("1.1.1.1");
member.setPort(8848);
ServerAbilities serverAbilities = new ServerAbilities();
ServerRemoteAbility serverRemote... |
public static ColumnIndex build(
PrimitiveType type,
BoundaryOrder boundaryOrder,
List<Boolean> nullPages,
List<Long> nullCounts,
List<ByteBuffer> minValues,
List<ByteBuffer> maxValues) {
return build(type, boundaryOrder, nullPages, nullCounts, minValues, maxValues, null, null);
... | @Test
public void testStaticBuildInt64() {
ColumnIndex columnIndex = ColumnIndexBuilder.build(
Types.required(INT64).named("test_int64"),
BoundaryOrder.UNORDERED,
asList(true, false, true, false, true, false),
asList(1l, 2l, 3l, 4l, 5l, 6l),
toBBList(null, 2l, null, 4l, nul... |
public static byte[] serializeToByteArray(Serializable value) {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(new SnappyOutputStream(buffer))) {
oos.writeObject(value);
}
return buffer.toByteArray();
} catch... | @Test
public void testSerializationError() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("unable to serialize");
SerializableUtils.serializeToByteArray(new UnserializableByJava());
} |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalStruct() {
// Given:
final Schema structSchema = SchemaBuilder.struct()
.field("COL1", Schema.OPTIONAL_STRING_SCHEMA)
.field("COL4", SchemaBuilder
.array(Schema.OPTIONAL_FLOAT64_SCHEMA)
.optional()
.build())
.fie... |
public Random() {
real = new UniversalGenerator();
twister = new MersenneTwister();
} | @Test
public void testRandom() {
System.out.println("random");
smile.math.Random instance = new Random(System.currentTimeMillis());
for (int i = 0; i < 1000000; i++) {
double result = instance.nextDouble();
assertTrue(result >= 0.0);
assertTrue(result < 1.... |
void handleFinish(HttpResponse response, Span span) {
if (response == null) throw new NullPointerException("response == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
if (response.error() != null) {
span.error(response.error()); // Ensures Mut... | @Test void handleFinish_parsesTagsWithCustomizer() {
when(span.customizer()).thenReturn(spanCustomizer);
handler.handleFinish(response, span);
verify(responseParser).parse(response, context, spanCustomizer);
} |
@Override
public PlanNode optimize(
PlanNode maxSubplan,
ConnectorSession session,
VariableAllocator variableAllocator,
PlanNodeIdAllocator idAllocator)
{
return rewriteWith(new Rewriter(session, idAllocator), maxSubplan);
} | @Test
public void testJdbcComputePushdownBooleanOperations()
{
String table = "test_table";
String schema = "test_schema";
String expression = "(((c1 + c2) - c2 <> c2) OR c2 = c1) AND c1 <> c2";
TypeProvider typeProvider = TypeProvider.copyOf(ImmutableMap.of("c1", BIGINT, "c2", ... |
@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")... | @UseDataProvider("alertTextAndFormattedText")
@Test
public void shouldFormatNewAlertWithThresholdProperlyFormatted(String alertText, String expectedFormattedAlertText) {
Notification notification = createNotification("Failed", alertText, "ERROR", "true");
EmailMessage message = template.format(notification... |
@Override
public Token redeem(@NonNull String code, String redirectUri, String clientId) {
var redeemed = codeRepo.remove(code).orElse(null);
if (redeemed == null) {
return null;
}
if (!validateCode(redeemed, redirectUri, clientId)) {
return null;
}
var accessTokenTtl = Duration... | @Test
void redeem_twice() throws JOSEException {
var issuer = URI.create("https://idp.example.com");
var k = genKey();
var keyStore = mock(KeyStore.class);
when(keyStore.signingKey()).thenReturn(k);
var codeRepo = mock(CodeRepo.class);
var sut = new TokenIssuerImpl(issuer, keyStore, codeRep... |
public long getWorkerTabletNum(String workerIpPort) {
try {
WorkerInfo workerInfo = client.getWorkerInfo(serviceId, workerIpPort);
return workerInfo.getTabletNum();
} catch (StarClientException e) {
LOG.info("Failed to get worker tablet num from starMgr, Error: {}.", ... | @Test
public void testGetWorkerTabletNumExcepted() throws StarClientException {
String serviceId = "1";
String workerIpPort = "127.0.0.1:8093";
Deencapsulation.setField(starosAgent, "serviceId", serviceId);
new Expectations() {
{
client.getWorkerInfo(serv... |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_density_mdpi() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("mdpi", config);
assertThat(config.density).isEqualTo(DENSITY_MEDIUM);
} |
static Type inferIcebergType(Object value, IcebergSinkConfig config) {
return new SchemaGenerator(config).inferIcebergType(value);
} | @Test
public void testInferIcebergTypeEmpty() {
IcebergSinkConfig config = mock(IcebergSinkConfig.class);
// skip infer for null
assertThat(SchemaUtils.inferIcebergType(null, config)).isNull();
// skip infer for empty list
assertThat(SchemaUtils.inferIcebergType(ImmutableList.of(), config)).isNu... |
@Override
public void onWorkflowFinalized(Workflow workflow) {
WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput());
WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow);
String reason = workflow.getReasonForIncompletion();
LOG.inf... | @Test
public void testWorkflowFinalizedFailed() {
StepRuntimeState state = new StepRuntimeState();
state.setStatus(StepInstance.Status.FATALLY_FAILED);
when(stepInstanceDao.getAllStepStates(any(), anyLong(), anyLong()))
.thenReturn(singletonMap("foo", state));
when(workflow.getStatus()).thenRe... |
public boolean subsumedBy(BlocksGroup other, int indexCorrection) {
return subsumedBy(this, other, indexCorrection);
} | @Test
public void testSubsumedBy() {
BlocksGroup group1 = newBlocksGroup(newBlock("a", 1), newBlock("b", 2));
BlocksGroup group2 = newBlocksGroup(newBlock("a", 2), newBlock("b", 3), newBlock("c", 4));
// block "c" from group2 does not have corresponding block in group1
assertThat(group2.subsumedBy(gro... |
@Override
public Authentication getAuthentication(String token) throws AccessException {
return getExecuteTokenManager().getAuthentication(token);
} | @Test
void testGetAuthentication() throws AccessException {
assertNotNull(tokenManagerDelegate.getAuthentication("token"));
} |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ... | @Test
public void shouldNotCaptureWindowEndAsRequiredColumn() {
// Given:
givenWindowExpression();
givenSelectExpression(new UnqualifiedColumnReferenceExp(SystemColumns.WINDOWEND_NAME));
// When:
final AggregateAnalysisResult result = analyzer.analyze(analysis, selects);
// Then:
final L... |
public MergePolicyConfig setBatchSize(int batchSize) {
this.batchSize = checkPositive("batchSize", batchSize);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setBatchSize_withZero() {
config.setBatchSize(0);
} |
public boolean unsetLine(DefaultIssue issue, IssueChangeContext context) {
Integer currentValue = issue.line();
if (currentValue != null) {
issue.setFieldChange(context, LINE, currentValue, "");
issue.setLine(null);
issue.setChanged(true);
return true;
}
return false;
} | @Test
void unset_line_has_no_effect_if_line_is_already_null() {
issue.setLine(null);
boolean updated = underTest.unsetLine(issue, context);
assertThat(updated).isFalse();
assertThat(issue.line()).isNull();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.currentChange()).isNull();
... |
public static void prepareFilesForStaging(FileStagingOptions options) {
List<String> filesToStage = options.getFilesToStage();
if (filesToStage == null || filesToStage.isEmpty()) {
filesToStage = detectClassPathResourcesToStage(ReflectHelpers.findClassLoader(), options);
LOG.info(
"Pipelin... | @Test
public void testPackagingDirectoryResourceToJarFile() throws IOException {
String directoryPath = tmpFolder.newFolder().getAbsolutePath();
List<String> filesToStage = Arrays.asList(directoryPath);
String temporaryLocation = tmpFolder.newFolder().getAbsolutePath();
List<String> result = Pipeline... |
public boolean setResolution(DefaultIssue issue, @Nullable String resolution, IssueChangeContext context) {
if (!Objects.equals(resolution, issue.resolution())) {
issue.setFieldChange(context, RESOLUTION, issue.resolution(), resolution);
issue.setResolution(resolution);
issue.setUpdateDate(context... | @Test
void setResolution_shouldNotTriggerFieldChange() {
boolean updated = underTest.setResolution(issue, Issue.STATUS_OPEN, context);
assertThat(updated).isTrue();
assertThat(issue.resolution()).isEqualTo(Issue.STATUS_OPEN);
FieldDiffs.Diff diff = issue.currentChange().get(IssueFieldsSetter.RESOLUTI... |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull29() {
// Arrange
final int type = 22;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Delete_rows_event_old", actual);
} |
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) {
Objects.requireNonNull(metric);
if (batchMeasure == null) {
return Optional.empty();
}
Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder();
switch (metric.getType().getValueType()) {
... | @Test
public void toMeasure_returns_no_value_if_dto_has_no_value_for_Long_Metric() {
Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_LONG_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE);
} |
@Override
public ObjectNode encode(VirtualHost vHost, CodecContext context) {
checkNotNull(vHost, NULL_OBJECT_MSG);
final JsonCodec<HostLocation> locationCodec =
context.codec(HostLocation.class);
final ObjectNode result = context.mapper().createObjectNode()
... | @Test
public void testEncode() {
MockCodecContext context = new MockCodecContext();
NetworkId networkId = NetworkId.networkId(TEST_NETWORK_ID);
HostId id = NetTestTools.hid(TEST_HOST_ID);
MacAddress mac = MacAddress.valueOf(TEST_MAC_ADDRESS);
VlanId vlan = VlanId.vlanId(TEST_... |
public Flux<E> getCacheAll() {
return getCache().getFlux(ALL_DATA_KEY, () -> EnableCacheReactiveCrudService.super.createQuery().fetch());
} | @Test
public void test2() {
TestEntity entity = TestEntity.of("test1",100,"testName");
entityService
.createDelete()
.notNull(TestEntity::getId)
.execute()
.block();
entityService
.insert(Mono.just(entity))
... |
public static Type toZetaSqlType(FieldType fieldType) {
switch (fieldType.getTypeName()) {
case INT64:
return TypeFactory.createSimpleType(TypeKind.TYPE_INT64);
case DOUBLE:
return TypeFactory.createSimpleType(TypeKind.TYPE_DOUBLE);
case BOOLEAN:
return TypeFactory.createSi... | @Test
public void testBeamFieldTypeToZetaSqlType() {
assertEquals(ZetaSqlBeamTranslationUtils.toZetaSqlType(TEST_FIELD_TYPE), TEST_TYPE);
} |
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException {
byte[] bytes = pollEntryBytes(timeout);
if (bytes == null) {
return null;
}
return DLQEntry.deserialize(bytes);
} | @Test
public void testBlockAndSegmentBoundary() throws Exception {
Event event = createEventWithConstantSerializationOverhead();
event.setField("T", generateMessageContent(PAD_FOR_BLOCK_SIZE_EVENT));
Timestamp timestamp = constantSerializationLengthTimestamp();
try(DeadLetterQueueWr... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldProvideContextWhenAnExceptionOccursBecauseOfIncompleteParamAtEnd() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("abc#{");
new ParamResolver(new ParamSubstitutionHandlerFactory(para... |
public List<DirectEncryptedPseudonymType> provideDep(ProvideDEPsRequest request) throws BsnkException {
try {
return ((BSNKDEPPort) this.bindingProvider).bsnkProvideDEPs(request).getDirectEncryptedPseudonyms();
} catch (SOAPFaultException ex) {
if (ex.getCause().getMessage().equa... | @Test
public void testRequestHasValidSignature() throws BsnkException {
setupWireMock();
client.provideDep(request);
wireMockServer.verify(postRequestedFor(urlPathEqualTo("/bsnk_stub/provideDep")).withHeader("Content-Type",
containing("xml")));
ServeEvent serveEvent... |
Optional<ImageMetadataTemplate> retrieveMetadata(ImageReference imageReference)
throws IOException, CacheCorruptedException {
Path imageDirectory = cacheStorageFiles.getImageDirectory(imageReference);
Path metadataPath = imageDirectory.resolve("manifests_configs.json");
if (!Files.exists(metadataPath)... | @Test
public void testRetrieveMetadata_v22SingleManifest()
throws IOException, URISyntaxException, CacheCorruptedException {
setupCachedMetadataV22(cacheDirectory);
ImageMetadataTemplate metadata =
cacheStorageReader.retrieveMetadata(ImageReference.of("test", "image", "tag")).get();
Assert.... |
public static void preserve(FileSystem targetFS, Path path,
CopyListingFileStatus srcFileStatus,
EnumSet<FileAttribute> attributes,
boolean preserveRawXattrs) throws IOException {
// strip out those attributes we don't need a... | @Test
public void testSkipsNeedlessAttributes() throws Exception {
FileSystem fs = FileSystem.get(config);
// preserve replication, block size, user, group, permission,
// checksum type and timestamps
Path src = new Path("/tmp/testSkipsNeedlessAttributes/source");
Path dst = new Path("/tmp/testS... |
public void remove(Supplier<JournalContext> ctx, String path, Set<String> keys) {
try (LockResource r = new LockResource(mLock.writeLock())) {
Map<String, String> properties = mState.getProperties(path);
if (!properties.isEmpty()) {
keys.forEach(properties::remove);
if (properties.isEmpt... | @Test
public void remove() {
PathProperties properties = new PathProperties();
// remove from empty properties
properties.remove(NoopJournalContext.INSTANCE, ROOT, new HashSet<>(Arrays.asList(
PropertyKey.USER_FILE_READ_TYPE_DEFAULT.getName(),
PropertyKey.USER_FILE_WRITE_TYPE_DEFAULT.getN... |
public void removeExpireConsumerGroupInfo() {
List<String> removeList = new ArrayList<>();
consumerCompensationTable.forEach((group, consumerGroupInfo) -> {
List<String> removeTopicList = new ArrayList<>();
ConcurrentMap<String, SubscriptionData> subscriptionTable = consumerGroup... | @Test
public void removeExpireConsumerGroupInfo() {
SubscriptionData subscriptionData = new SubscriptionData(TOPIC, SubscriptionData.SUB_ALL);
subscriptionData.setSubVersion(System.currentTimeMillis() - brokerConfig.getSubscriptionExpiredTimeout() * 2);
consumerManager.compensateSubscribeDat... |
@Override
public Optional<NativeEntity<GrokPattern>> findExisting(Entity entity, Map<String, ValueReference> parameters) {
if (entity instanceof EntityV1) {
return findExisting((EntityV1) entity);
} else {
throw new IllegalArgumentException("Unsupported entity version: " + en... | @Test
public void findExistingFailsWithDivergingPatterns() throws ValidationException {
grokPatternService.save(GrokPattern.create("Test", "[a-z]+"));
final Entity grokPatternEntity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.GROK_PATTERN_V1)
... |
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
... | @Test
public void testMergeAclEntriesAutomaticDefaultGroup() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, READ))
.build();
List<AclEntry> aclSpec ... |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = false,通过 + code
public void testApproveOrDeny_approveWithCode() {
// 准备参数
String responseType = "code";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = "https://www.iocoder.cn";
String ... |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringNullWithDelimiterNullAndEnclosureNull() {
String[] result = Const.splitString( null, null, null );
assertNull( result );
} |
@Override
public void deleteAiVideoConfig(Long id) {
// 校验存在
validateAiVideoConfigExists(id);
// 删除
aiVideoConfigMapper.deleteById(id);
} | @Test
public void testDeleteAiVideoConfig_success() {
// mock 数据
AiVideoConfigDO dbAiVideoConfig = randomPojo(AiVideoConfigDO.class);
aiVideoConfigMapper.insert(dbAiVideoConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbAiVideoConfig.getId();
// 调用
aiVideoConf... |
public Entry findChildByPath(Entry top, String path) {
final String canonicalPath = replaceAliases(path);
return top.getChildByPath(canonicalPath.split("/"));
} | @Test
public void findsChildByPathAlias() throws Exception {
final EntryNavigator entryNavigator = new EntryNavigator(Collections.singletonMap("medium", "middle"));
Entry top = new Entry();
Entry middle = new Entry();
top.addChild(middle);
middle.setName("middle");
Entry down = new Entry();
middle.addChi... |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
try {
if(null != status.getModified()) {
final FileEntity response = new FilesApi(new BrickApiClient(session))
.patchFilesPath(StringUtils.removeS... | @Test
public void testSetTimestampFile() throws Exception {
final Path file = new BrickTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(),
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final TransferStat... |
@Override
public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
if (!coordinatorRequestManager.coordinator().isPresent() ||
shareMembershipManager.shouldSkipHeartbeat() ||
pollTimer.isExpired()) {
shareMembershipManager.onHeartbeatRequestSkipped();
... | @Test
public void testHeartbeatNotSentIfAnotherOneInFlight() {
time.sleep(DEFAULT_HEARTBEAT_INTERVAL_MS);
// Heartbeat sent (no response received)
NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
assertEquals(1, result.unsentRequests.size(... |
public WorkflowTimeline getWorkflowTimeline(String workflowId) {
List<WorkflowVersionUpdateJobEvent> jobEvents =
withMetricLogError(
() ->
getPayloads(
GET_WORKFLOW_TIMELINE_QUERY,
stmt -> {
stmt.setString(1, workflowI... | @Test
public void testGetWorkflowTimeline() throws Exception {
WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID1);
WorkflowDefinition definition =
workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties());
assertNotNull(wfd.getInternalId());
assertEquals(wfd... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void set_created_after_from_created_since() {
Date now = parseDateTime("2013-07-25T07:35:00+0100");
when(clock.instant()).thenReturn(now.toInstant());
when(clock.getZone()).thenReturn(ZoneOffset.UTC);
SearchRequest request = new SearchRequest()
.setCreatedInLast("1y2m3w4d");
ass... |
public static StanzaError parseError(XmlPullParser parser) throws XmlPullParserException, IOException, SmackParsingException {
return parseError(parser, null);
} | @Test
public void ensureNoNullLangInParsedDescriptiveTexts() throws Exception {
final String text = "Dummy descriptive text";
final String errorXml = XMLBuilder
.create(StanzaError.ERROR).a("type", "cancel").up()
.element("internal-server-error", StanzaError.ERROR_CONDITION_A... |
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("start position") Number start) {
return invoke(string, start, null);
} | @Test
void invokeNull3ParamsMethod() {
FunctionTestUtil.assertResultError(substringFunction.invoke(null, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(substringFunction.invoke("test", null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultEr... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_multipleEntriesWithDefaultValueAndEnvDefined() {
environment.set("FOO", "hello");
environment.set("BAR", "world");
assertThat(resolve("${FOO:-default}:${BAR:-default}"), equalTo("hello:world"));
} |
@VisibleForTesting
static void startSqlGateway(PrintStream stream, String[] args) {
SqlGatewayOptions cliOptions = SqlGatewayOptionsParser.parseSqlGatewayOptions(args);
if (cliOptions.isPrintHelp()) {
SqlGatewayOptionsParser.printHelpSqlGateway(stream);
return;
}
... | @Test
void testFailedToStartSqlGateway() {
try (PrintStream stream = new PrintStream(output)) {
assertThatThrownBy(() -> SqlGateway.startSqlGateway(stream, new String[0]))
.doesNotHaveToString(
"Unexpected exception. This is a bug. Please consider ... |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) {
return aggregate(initializer, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullInitializerTwoOptionNamedOnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(null, Named.as("test")));
} |
@Override
public Predicate accept(Visitor visitor, IndexRegistry indexes) {
Predicate[] result = VisitorUtils.acceptVisitor(predicates, visitor, indexes);
if (result != predicates) {
//inner predicates were modified by a visitor
AndPredicate newPredicate = new AndPredicate(re... | @Test
public void accept_whenInnerPredicateChangedOnAccept_thenReturnAndNewAndPredicate() {
Visitor mockVisitor = createPassthroughVisitor();
IndexRegistry mockIndexes = mock(IndexRegistry.class);
Predicate transformed = mock(Predicate.class);
Predicate innerPredicate = createMockVi... |
public static String getAttributesXml( Map<String, Map<String, String>> attributesMap ) {
return getAttributesXml( attributesMap, XML_TAG );
} | @Test
public void testGetAttributesXml_CustomTag() {
try ( MockedStatic<AttributesUtil> attributesUtilMockedStatic = mockStatic( AttributesUtil.class ) ) {
attributesUtilMockedStatic.when( () -> AttributesUtil.getAttributesXml( anyMap(), anyString() ) )
.thenCallRealMethod();
Map<String, Stri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.