focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void preflight(final Path source, final Path target) throws BackgroundException {
if(source.isDirectory()) {
throw new UnsupportedException(MessageFormat.format(LocaleFactory.localizedString("Cannot copy {0}", "Error"), source.getName())).withFile(source);
}
} | @Test
public void testCopyDirectory() throws Exception {
final DeepboxIdProvider fileid = new DeepboxIdProvider(session);
final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path directory = new Deepbo... |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
int n = (int) Math.max(Math.sqrt(1 / this.p), 5.0);
int nl, nu, inc = 1;
if (p < cdf(n)) {
do {
n = Math.m... | @Test
public void testQuantile() {
System.out.println("quantile");
GeometricDistribution instance = new GeometricDistribution(0.3);
instance.rand();
assertEquals(0, instance.quantile(0.01), 1E-6);
assertEquals(0, instance.quantile(0.1), 1E-6);
assertEquals(0, instance... |
@Override
public boolean add(V e) {
return get(addAsync(e));
} | @Test
public void testClusteredIterator() {
testInCluster(redisson -> {
int size = 10000;
RSet<String> set = redisson.getSet("{test");
for (int i = 0; i < size; i++) {
set.add("" + i);
}
Set<String> keys = new HashSet<>();
... |
public <E extends Enum<E>> void logOnTruncateLogEntry(
final int memberId,
final E state,
final long logLeadershipTermId,
final long leadershipTermId,
final long candidateTermId,
final long commitPosition,
final long logPosition,
final long appendPosition,... | @Test
void logTruncateLogEntry()
{
final int offset = align(22, ALIGNMENT);
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
final ChronoUnit state = ChronoUnit.FOREVER;
final int memberId = 8;
final long logLeadershipTermId = 777L;
final long leadershi... |
@Override
public boolean validateTree(ValidationContext validationContext) {
validate(validationContext);
return (onCancelConfig.validateTree(validationContext) && errors.isEmpty() && !configuration.hasErrors());
} | @Test
public void validateTreeShouldVerifyIfConfigurationHasErrors() {
Configuration configuration = mock(Configuration.class);
PluggableTask pluggableTask = new PluggableTask(new PluginConfiguration(), configuration);
when(configuration.hasErrors()).thenReturn(true);
assertFalse(... |
public Canvas canvas() {
Canvas canvas = new Canvas(getLowerBound(), getUpperBound());
canvas.add(this);
if (name != null) {
canvas.setTitle(name);
}
return canvas;
} | @Test
public void testIris() throws Exception {
System.out.println("Iris");
var canvas = ScatterPlot.of(iris, "sepallength", "sepalwidth", "petallength", "class", '*').canvas();
canvas.setAxisLabels("sepallength", "sepalwidth", "petallength");
canvas.window();
} |
private static void updateQueue(QueueConfigInfo updateInfo,
CapacitySchedulerConfiguration proposedConf,
Map<String, String> confUpdate) {
if (updateInfo == null) {
return;
}
QueuePath queuePath = new QueuePath(updateInfo.getQueue());... | @Test
public void testUpdateQueue() throws Exception {
SchedConfUpdateInfo updateInfo = new SchedConfUpdateInfo();
Map<String, String> updateMap = new HashMap<>();
updateMap.put(CONFIG_NAME, A_CONFIG_VALUE);
QueueConfigInfo queueAConfigInfo = new QueueConfigInfo(A_PATH, updateMap);
updateInfo.getU... |
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) {
if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) {
throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'.");
}
return loadManagerWrapper.get();... | @Test(timeOut = 30 * 1000)
public void testDeleteNamespace() throws Exception {
String namespace = "public/test-delete-namespace";
TopicName topicName = TopicName.get(namespace + "/test-delete-namespace-topic");
admin.namespaces().createNamespace(namespace);
admin.namespaces().setNam... |
@Override
public String getDescription() {
return "time: " + time
+ ", field: " + field
+ ", check type: " + type.toString().toLowerCase(Locale.ENGLISH)
+ ", threshold_type: " + thresholdType.toString().toLowerCase(Locale.ENGLISH)
+ ", threshold: " + decimalFo... | @Test
public void testConstructor() throws Exception {
Map<String, Object> parameters = getParametersMap(0,
0,
FieldValueAlertCondition.ThresholdType.HIGHER,
FieldValueAlertCondition.CheckType.MAX,
0,
"response_time");
final FieldValueAler... |
@Override
public TransactionType getTransactionType() {
return TransactionType.XA;
} | @Test
void assertGetTransactionType() {
assertThat(xaTransactionManager.getTransactionType(), is(TransactionType.XA));
} |
public static IntStream allLinesFor(DefaultIssue issue, String componentUuid) {
DbIssues.Locations locations = issue.getLocations();
if (locations == null) {
return IntStream.empty();
}
Stream<DbCommons.TextRange> textRanges = Stream.concat(
locations.hasTextRange() ? Stream.of(locations.ge... | @Test
public void allLinesFor_traverses_all_flows() {
DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder();
locations.addFlowBuilder()
.addLocation(newLocation("file1", 5, 5))
.addLocation(newLocation("file2", 10, 11))
.build();
locations.addFlowBuilder()
.addLoca... |
@Override
public Result search(Query query, Execution execution) {
Result mergedResults = execution.search(query);
var targets = getTargets(query.getModel().getSources(), query.properties());
warnIfUnresolvedSearchChains(extractErrors(targets), mergedResults.hits());
var prunedTarg... | @Test
void target_selectors_can_have_multiple_targets() {
ComponentId targetSelectorId = ComponentId.fromString("TestMultipleTargetSelector");
ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>();
targetSelectors.register(targetSelectorId, new TestMultipleTargetSelec... |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testGenericGroupOffsetDeleteWithPendingTransactionalOffsets() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup(
"foo",
true
... |
@Override
public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) {
return sqlStatementContext instanceof InsertStatementContext && !((InsertStatementContext) sqlStatementContext).containsInsertColumns();
} | @Test
void assertIsGenerateSQLToken() {
assertFalse(generator.isGenerateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Collections.emptyList())));
} |
@Override
public Config build() {
return build(new Config());
} | @Override
@Test
public void testConfigurationURL() throws Exception {
URL configURL = getClass().getClassLoader().getResource("hazelcast-default.xml");
Config config = new XmlConfigBuilder(configURL).build();
assertEquals(configURL, config.getConfigurationUrl());
assertNull(confi... |
static String normalizeCpu(String milliCpu) {
return formatMilliCpu(parseCpuAsMilliCpus(milliCpu));
} | @Test
public void testNormalizeCpu() {
assertThat(normalizeCpu("1"), is("1"));
assertThat(normalizeCpu("1000m"), is("1"));
assertThat(normalizeCpu("500m"), is("500m"));
assertThat(normalizeCpu("0.5"), is("500m"));
assertThat(normalizeCpu("0.1"), is("100m"));
assertTha... |
@Override
public AppResponse process(Flow flow, CheckAuthenticationStatusRequest request){
switch(appSession.getState()) {
case "AUTHENTICATION_REQUIRED", "AWAITING_QR_SCAN":
return new CheckAuthenticationStatusResponse("PENDING", false);
case "RETRIEVED", "AWAITING_C... | @Test
void processConfirmed(){
appSession.setState("CONFIRMED");
AppResponse response = checkAuthenticationStatus.process(flow, request);
assertTrue(response instanceof StatusResponse);
assertEquals("PENDING_CONFIRMED", ((StatusResponse) response).getStatus());
} |
public String getTargetEngine() {
return targetEngine;
} | @Test
void getTargetEngine() {
String targetEngine = "targetEngine";
EfestoRedirectOutput retrieved = new EfestoRedirectOutput(modelLocalUriId, targetEngine, null) {};
assertThat(retrieved.getTargetEngine()).isEqualTo(targetEngine);
} |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void testPrintTopicDescription() {
// Given:
final KsqlEntityList entityList = new KsqlEntityList(ImmutableList.of(
new TopicDescription("e", "TestTopic", "TestKafkaTopic", "AVRO", "schemaString")
));
// When:
console.printKsqlEntityList(entityList);
// Then:
final S... |
@Udf(description = "Returns the inverse (arc) cosine of an INT value")
public Double acos(
@UdfParameter(
value = "value",
description = "The value to get the inverse cosine of."
) final Integer value
) {
return acos(value == null ? null : value.doubleValu... | @Test
public void shouldHandleLessThanNegativeOne() {
assertThat(Double.isNaN(udf.acos(-1.1)), is(true));
assertThat(Double.isNaN(udf.acos(-6.0)), is(true));
assertThat(Double.isNaN(udf.acos(-2)), is(true));
assertThat(Double.isNaN(udf.acos(-2L)), is(true));
} |
protected static String resolveEnvVars(String input) {
Preconditions.checkNotNull(input);
// match ${ENV_VAR_NAME}
Pattern p = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String env... | @Test
public void resolveEnvVars() throws Exception {
SystemLambda.withEnvironmentVariable("VARNAME1", "varvalue1")
.and("VARNAME2", "varvalue2")
.execute(() -> {
String resolved = EnvVarResolverProperties.resolveEnvVars(
"paddi... |
@Override
public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) {
JSONArray statuses = JSONUtil.parseArray(text);
// 字段参考
return convertList(statuses, status -> {
JSONObject statusObj = (JSONObject) status;
return new SmsReceiveRespDTO()
... | @Test
public void testParseSmsReceiveStatus() {
// 准备参数
String text = "[\n" +
" {\n" +
" \"phone_number\" : \"13900000001\",\n" +
" \"send_time\" : \"2017-01-01 11:12:13\",\n" +
" \"report_time\" : \"2017-02-02 22:23:24\",\n" ... |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void verify_detection_with_complex_mix_of_qps() {
final Set<Event> events = new HashSet<>();
doAnswer(invocationOnMock -> {
events.add((Event) invocationOnMock.getArguments()[0]);
return null;
}).when(eventRepository).add(any(Event.class));
Date date = new Date();
Quality... |
public static String toUnderlineCase(CharSequence str) {
return toSymbolCase(str, UNDERLINE);
} | @Test
public void toUnderlineCase() {
String string = "str";
String s = StringUtil.toUnderlineCase(string);
Assert.assertEquals("str", s);
} |
public boolean isStarted() {
return jobLeaderIdActions != null;
} | @Test
void testIsStarted() throws Exception {
final JobID jobId = new JobID();
TestingHighAvailabilityServices highAvailabilityServices =
new TestingHighAvailabilityServices();
SettableLeaderRetrievalService leaderRetrievalService =
new SettableLeaderRetrieval... |
Plugin create(Options.Plugin plugin) {
try {
return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument());
} catch (IOException | URISyntaxException e) {
throw new CucumberException(e);
}
} | @Test
void instantiates_file_or_empty_arg_plugin_without_arg() {
PluginOption option = parse(WantsFileOrEmpty.class.getName());
WantsFileOrEmpty plugin = (WantsFileOrEmpty) fc.create(option);
assertThat(plugin.out, is(nullValue()));
} |
@Override
public CRArtifact deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, TypeAdapter.ARTIFACT_ORIGIN);
} | @Test
public void shouldInstantiateATaskOfTypeExec() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "build");
artifactTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext);
verify(jsonDeserializationContext).deserialize(jsonObject, CRBuilt... |
public static NormalKey createFromSpec(String spec) {
if (spec == null || !spec.contains(":")) {
throw new IllegalArgumentException("Invalid spec format");
}
String[] parts = spec.split(":", 2);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid... | @Test
public void testCreateFromSpec() {
String base64Key = Base64.getEncoder().encodeToString(normalKey.getPlainKey());
String spec = "AES_128:" + base64Key;
NormalKey key = NormalKey.createFromSpec(spec);
assertNotNull(key);
assertEquals(EncryptionAlgorithmPB.AES_128, key.g... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Migration that = (Migration) o;
return Objects.equals(this.createdAt(), that.createdAt());
} | @Test
public void testEquals() {
final MigrationA a = new MigrationA();
final MigrationA aa = new MigrationA();
final MigrationB b = new MigrationB();
assertThat(a.equals(aa)).isTrue();
assertThat(a.equals(b)).isFalse();
} |
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) {
return new SchemaParser(typeRegistry).parse(schema);
} | @Test
public void shouldParseEmptySchema() {
// Given:
final String schema = " \t\n\r";
// When:
final TableElements elements = parser.parse(schema);
// Then:
assertThat(Iterables.isEmpty(elements), is(true));
} |
public static Autoscaling empty() {
return empty("");
} | @Test
public void autoscaling_respects_group_size_limit() {
var min = new ClusterResources( 2, 2, new NodeResources(1, 1, 10, 1));
var now = new ClusterResources(5, 5, new NodeResources(3.0, 10, 100, 1));
var max = new ClusterResources(18, 6, new NodeResources(100, 1000, 10000, 1));
... |
@Override
public boolean isCallable(NamingEvent event) {
if (event == null) {
return false;
}
NamingChangeEvent changeEvent = (NamingChangeEvent) event;
return changeEvent.isAdded() || changeEvent.isRemoved() || changeEvent.isModified();
} | @Test
public void testCallable() {
NamingSelectorWrapper selectorWrapper = new NamingSelectorWrapper(null, null);
InstancesDiff instancesDiff = new InstancesDiff(null, Collections.singletonList(new Instance()), null);
NamingChangeEvent changeEvent = new NamingChangeEvent("serviceName", Colle... |
public <T> void addThreadLevelImmutableMetric(final String name,
final String description,
final String threadId,
final T value) {
final MetricName metricName = metrics.metricName(
name, THREAD_LEVEL_GROUP, description, threadLevelTagMap(threadId));
synchronized (thre... | @Test
public void shouldAddThreadLevelImmutableMetric() {
final int measuredValue = 123;
final StreamsMetricsImpl streamsMetrics
= new StreamsMetricsImpl(metrics, THREAD_ID1, VERSION, time);
streamsMetrics.addThreadLevelImmutableMetric(
"foobar",
"test me... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldHandleErrorMessageOnPostRequests() {
// Given:
KsqlErrorMessage ksqlErrorMessage = new KsqlErrorMessage(40000, "ouch");
server.setResponseObject(ksqlErrorMessage);
server.setErrorCode(400);
// When:
KsqlTarget target = ksqlClient.target(serverUri);
RestResponse<Ksq... |
@GET
@Path("all")
@ZeppelinApi
public Response getAll() {
try {
Map<String, String> properties =
configurationService.getAllProperties(getServiceContext(), new RestServiceCallback<>());
return new JsonResponse<>(Status.OK, "", properties).build();
} catch (IOException e) {
retu... | @Test
void testGetAll() throws IOException {
try (CloseableHttpResponse get = httpGet("/configurations/all")) {
Map<String, Object> resp =
gson.fromJson(EntityUtils.toString(get.getEntity(), StandardCharsets.UTF_8),
new TypeToken<Map<String, Object>>() {
}.getType());
... |
public static ErrorCodes getErrorCode(ResponseException responseException)
throws ResponseException {
// Obtain the error response code.
String errorContent = responseException.getContent();
if (errorContent == null) {
throw responseException;
}
try {
ErrorResponseTemplate errorRe... | @Test
public void testGetErrorCode_multipleErrors() {
Mockito.when(responseException.getContent())
.thenReturn(
"{\"errors\":["
+ "{\"code\":\"MANIFEST_INVALID\",\"message\":\"message 1\",\"detail\":{}},"
+ "{\"code\":\"TAG_INVALID\",\"message\":\"message 2\",\"... |
@SuppressWarnings("unchecked")
@Override
public void punctuate(final ProcessorNode<?, ?, ?, ?> node,
final long timestamp,
final PunctuationType type,
final Punctuator punctuator) {
if (processorContext.currentNode() != null) ... | @Test
public void punctuateShouldNotThrowStreamsExceptionWhenProcessingExceptionHandlerRepliesWithContinue() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatelessTask(createConfig(
AT_LEAST_ONCE,
... |
@NonNull
public ConnectionFileName getConnectionRootFileName( @NonNull VFSConnectionDetails details ) {
String connectionName = details.getName();
if ( StringUtils.isEmpty( connectionName ) ) {
throw new IllegalArgumentException( "Unnamed connection" );
}
return new ConnectionFileName( connect... | @Test
public void testGetConnectionRootFileNameReturnsTheConnectionRoot() {
String connectionNameWithNoReservedChars = "connection-name";
when( vfsConnectionDetails.getName() ).thenReturn( connectionNameWithNoReservedChars );
// pvfs://connection-name/
ConnectionFileName fileName = vfsConnectionMana... |
@Override
public final boolean wasNull() {
return wasNull;
} | @Test
void assertWasNull() {
assertFalse(memoryMergedResult.wasNull());
} |
public List<String> getEnabledIdentityProviders() {
return identityProviderRepository.getAllEnabledAndSorted()
.stream()
.filter(IdentityProvider::isEnabled)
.map(IdentityProvider::getName)
.toList();
} | @Test
public void getEnabledIdentityProviders_whenDefined_shouldReturnOnlyEnabled() {
mockIdentityProviders(List.of(
new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true),
new TestIdentityProvider().setKey("github").setName("GitHub").setEnabled(true),
new TestIdentityProvide... |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test
public void testQueryParameterType()
{
String testParamKey = "testParam";
String expectedTestParamValue = "testParamValue";
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
EasyMock.expect(mockResourceContext.hasParameter(testParamKey)).andReturn(t... |
public static <T> T autobox(Object value, Class<T> type) {
return Autoboxer.autobox(value, type);
} | @Test
void testAutobox() {
assertThat(ReflectionUtils.autobox(null, String.class)).isEqualTo(null);
assertThat(ReflectionUtils.autobox("string", String.class)).isEqualTo("string");
assertThat(ReflectionUtils.autobox(1, int.class)).isEqualTo(1);
assertThat(ReflectionUtils.autobox(1, I... |
public static Schema getNestedFieldSchemaFromWriteSchema(Schema writeSchema, String fieldName) {
String[] parts = fieldName.split("\\.");
int i = 0;
for (; i < parts.length; i++) {
String part = parts[i];
Schema schema = writeSchema.getField(part).schema();
if (i == parts.length - 1) {
... | @Test
public void testGetNestedFieldSchema() throws IOException {
Schema schema = SchemaTestUtil.getEvolvedSchema();
GenericRecord rec = new GenericData.Record(schema);
rec.put("field1", "key1");
rec.put("field2", "val1");
rec.put("name", "val2");
rec.put("favorite_number", 2);
// test sim... |
@Override
public ListenableFuture<?> execute(StartTransaction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.isClientTransac... | @Test
public void testStartTransactionTooManyIsolationLevels()
{
Session session = sessionBuilder()
.setClientTransactionSupport()
.build();
TransactionManager transactionManager = createTestTransactionManager();
QueryStateMachine stateMachine = createQuer... |
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates)
{
List<String> perColumnExpressions = new ArrayList<>();
int expressionLength = 0;
for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) {
String columnName = partition... | @Test
public void testIntegerConversion()
{
Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR)
.addIntegerValues("col1", Long.valueOf(Integer.MAX_VALUE))
.build();
String expression = buildGlueExpression(predicates);
assertEq... |
@Override
public String toString() {
return "ReliableTopicConfig{"
+ "name='" + name + '\''
+ ", topicOverloadPolicy=" + topicOverloadPolicy
+ ", executor=" + executor
+ ", readBatchSize=" + readBatchSize
+ ", statisticsEnabled=... | @Test
public void test_toString() {
ReliableTopicConfig config = new ReliableTopicConfig("foo");
String s = config.toString();
assertEquals("ReliableTopicConfig{name='foo', topicOverloadPolicy=BLOCK, executor=null,"
+ " readBatchSize=10, statisticsEnabled=true, listenerConf... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final SDSApiClient client = session.getClient();
final DownloadTokenGenerateResponse token = new NodesApi(session.getClient()).generat... | @Test
public void testReadInterrupt() throws Exception {
final byte[] content = RandomUtils.nextBytes(32769);
final TransferStatus writeStatus = new TransferStatus();
writeStatus.setLength(content.length);
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final... |
public static HintValueContext extractHint(final String sql) {
if (!containsSQLHint(sql)) {
return new HintValueContext();
}
HintValueContext result = new HintValueContext();
int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
String hintKeyValueText = sql.su... | @Test
void assertSQLHintWriteRouteOnlyWithCommentString() {
HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: WRITE_ROUTE_ONLY=true */");
assertTrue(actual.isWriteRouteOnly());
} |
@Override
public String getSinkTableName(Table table) {
String tableName = table.getName();
Map<String, String> sink = config.getSink();
// Add table name mapping logic
String mappingRoute = sink.get(FlinkCDCConfig.TABLE_MAPPING_ROUTES);
if (mappingRoute != null) {
... | @Test
public void testGetSinkTableNameWithConversionUpperAndLowerCase() {
Map<String, String> sinkConfig = new HashMap<>();
sinkConfig.put("table.prefix", "");
sinkConfig.put("table.suffix", "");
sinkConfig.put("table.lower", "true");
sinkConfig.put("table.upper", "true");
... |
public boolean isPaneDeprecated(final Pane<T> pane) {
return isPaneDeprecated(System.currentTimeMillis(), pane);
} | @Test
void testIsPaneDeprecated() {
Pane<LongAdder> currentPane = window.currentPane();
currentPane.setStartInMs(1000000L);
assertTrue(window.isPaneDeprecated(currentPane));
} |
public static String getJwt(final String authorizationHeader) {
return authorizationHeader.replace(TOKEN_PREFIX, "");
} | @Test
void testGetJwt_WithInvalidTokenFormat() {
// Given
String authorizationHeader = "sampleAccessToken";
// When
String jwt = Token.getJwt(authorizationHeader);
// Then
assertEquals("sampleAccessToken", jwt);
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testShhUninstallFilter() throws Exception {
web3j.shhUninstallFilter(Numeric.toBigInt("0x7")).send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"shh_uninstallFilter\","
+ "\"params\":[\"0x7\"],\"id\":1}");
} |
@Override
public void post(SpanAdapter span, Exchange exchange, Endpoint endpoint) {
super.post(span, exchange, endpoint);
Message message = exchange.getMessage();
if (message != null) {
Integer responseCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
... | @Test
public void testPostResponseCode() {
Exchange exchange = Mockito.mock(Exchange.class);
Message message = Mockito.mock(Message.class);
Mockito.when(exchange.getMessage()).thenReturn(message);
Mockito.when(message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class)).thenReturn... |
String buildDefaultMessage(EventNotificationContext ctx) {
String title = ctx.eventDefinition().map(EventDefinitionDto::title).orElse("Unnamed");
// Build Message title
return String.format(Locale.ROOT, "**Alert %s triggered:**\n", title);
} | @Test
public void buildDefaultMessage() {
String message = teamsEventNotification.buildDefaultMessage(eventNotificationContext);
assertThat(message).isNotEmpty();
} |
@SuppressWarnings({"unchecked", "UnstableApiUsage"})
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement) {
if (!(statement.getStatement() instanceof DropStatement)) {
return statement;
}
final DropStatement dropStatement = (DropState... | @Test
public void shouldNotThrowIfNoOtherSourcesUsingTopic() {
// Given:
final ConfiguredStatement<DropStream> dropStatement = givenStatement(
"DROP SOMETHING DELETE TOPIC;",
new DropStream(SOURCE_NAME,
true,
true)
);
final DataSource other1 = givenSource(Source... |
@Override
public Map<String, Object> toElasticSearchObject(ObjectMapper objectMapper, @Nonnull final Meter invalidTimestampMeter) {
final Map<String, Object> obj = Maps.newHashMapWithExpectedSize(REQUIRED_FIELDS.size() + fields.size());
for (Map.Entry<String, Object> entry : fields.entrySet()) {
... | @Test
public void testToElasticSearchObject() throws Exception {
message.addField("field1", "wat");
message.addField("field2", "that");
message.addField(Message.FIELD_STREAMS, Collections.singletonList("test-stream"));
final Map<String, Object> object = message.toElasticSearchObject... |
static FeatureResolver create(
ConfigurationParameters parameters, CucumberEngineDescriptor engineDescriptor,
Predicate<String> packageFilter
) {
return new FeatureResolver(parameters, engineDescriptor, packageFilter);
} | @Test
void scenario() {
TestDescriptor scenario = getScenario();
assertEquals("A scenario", scenario.getDisplayName());
assertEquals(
asSet(create("FeatureTag"), create("ScenarioTag"), create("ResourceA"), create("ResourceAReadOnly")),
scenario.getTags());
ass... |
public static TupleDomain<ColumnHandle> computeEnforced(TupleDomain<ColumnHandle> predicate, TupleDomain<ColumnHandle> unenforced)
{
if (predicate.isNone()) {
// If the engine requests that the connector provides a layout with a domain of "none". The connector can have two possible reactions, ei... | @Test
public void testComputeEnforced()
{
assertComputeEnforced(TupleDomain.all(), TupleDomain.all(), TupleDomain.all());
assertComputeEnforcedFails(TupleDomain.all(), TupleDomain.none());
assertComputeEnforced(TupleDomain.none(), TupleDomain.all(), TupleDomain.none());
assertCom... |
public static HintValueContext extractHint(final String sql) {
if (!containsSQLHint(sql)) {
return new HintValueContext();
}
HintValueContext result = new HintValueContext();
int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql);
String hintKeyValueText = sql.su... | @Test
void assertSQLHintShardingDatabaseValue() {
HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: SHARDING_DATABASE_VALUE=10 */");
assertThat(actual.getHintShardingDatabaseValue("t_order"), is(Collections.singletonList(new BigInteger("10"))));
} |
public HttpResponse get(Application application, String hostName, String serviceType, Path path, Query query) {
return get(application, hostName, serviceType, path, query, null);
} | @Test
public void testNormalGet() {
ArgumentCaptor<HttpFetcher.Params> actualParams = ArgumentCaptor.forClass(HttpFetcher.Params.class);
ArgumentCaptor<URI> actualUrl = ArgumentCaptor.forClass(URI.class);
HttpResponse response = new StaticResponse(200, "application/json", "body");
wh... |
@Override
public String getColumnClassName(final int column) {
Preconditions.checkArgument(1 == column);
return Number.class.getName();
} | @Test
void assertGetColumnClassName() throws SQLException {
assertThat(actualMetaData.getColumnClassName(1), is("java.lang.Number"));
} |
static long averageBytesPerRecord(HoodieTimeline commitTimeline, HoodieWriteConfig hoodieWriteConfig) {
long avgSize = hoodieWriteConfig.getCopyOnWriteRecordSizeEstimate();
long fileSizeThreshold = (long) (hoodieWriteConfig.getRecordSizeEstimationThreshold() * hoodieWriteConfig.getParquetSmallFileLimit());
... | @Test
public void testErrorHandling() {
int recordSize = 10000;
HoodieWriteConfig writeConfig = HoodieWriteConfig.newBuilder()
.withProps(Collections.singletonMap(COPY_ON_WRITE_RECORD_SIZE_ESTIMATE.key(), String.valueOf(recordSize)))
.build(false);
HoodieDefaultTimeline commitsTimeline = n... |
@CheckForNull
public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) {
if (sourceLine == null) {
return null;
}
DecorationDataHolder decorationDataHolder = new DecorationDataHolder();
if (StringUtils.isNotBlank(highlighting)) ... | @Test
public void should_ignore_empty_source() {
assertThat(sourceDecorator.getDecoratedSourceAsHtml("", "0,1,cppd", "")).isEmpty();
} |
public void markCoordinatorUnknown(final String cause, final long currentTimeMs) {
if (this.coordinator != null) {
log.info("Group coordinator {} is unavailable or invalid due to cause: {}. "
+ "Rediscovery will be attempted.", this.coordinator, cause);
this.coordinat... | @Test
public void testMarkCoordinatorUnknown() {
CoordinatorRequestManager coordinatorManager = setupCoordinatorManager(GROUP_ID);
expectFindCoordinatorRequest(coordinatorManager, Errors.NONE);
assertTrue(coordinatorManager.coordinator().isPresent());
// It may take time for metada... |
@Override
public MenuButton deserializeResponse(String answer) throws TelegramApiRequestException {
return deserializeResponse(answer, MenuButton.class);
} | @Test
public void testGetChatMenuButtonErrorResponse() {
String responseText = "{\"ok\":false,\"error_code\": 404,\"description\": \"Error message\"}";
GetChatMenuButton getChatMenuButton = GetChatMenuButton
.builder()
.build();
try {
getChatMenu... |
@Nonnull
public static String removeBracketsFromIpv6Address(@Nonnull final String address)
{
final String result;
if (address.startsWith("[") && address.endsWith("]")) {
result = address.substring(1, address.length()-1);
try {
Ipv6.parse(result);
... | @Test
public void stripBracketsIpv4() throws Exception {
// Setup test fixture.
final String input = "[192.168.0.1]";
// Execute system under test.
final String result = AuthCheckFilter.removeBracketsFromIpv6Address(input);
// Verify result.
assertEquals(input, resu... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testGreaterThan() {
UnboundPredicate<Integer> expected =
org.apache.iceberg.expressions.Expressions.greaterThan("field1", 1);
Optional<org.apache.iceberg.expressions.Expression> actual =
FlinkFilters.convert(resolve(Expressions.$("field1").isGreater(Expressions.lit(1))));
... |
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise);
} | @Test
public void headersWriteShouldHalfCloseAfterOnErrorForImplicitlyCreatedStream() throws Exception {
final ChannelPromise promise = newPromise();
final Throwable ex = new RuntimeException();
// Fake an encoding error, like HPACK's HeaderListSizeException
when(writer.writeHeaders(... |
@Override
public boolean isIndexed(QueryContext queryContext) {
Index index = queryContext.matchIndex(attributeName, QueryContext.IndexMatchHint.PREFER_ORDERED);
return index != null && index.isOrdered() && expressionCanBeUsedAsIndexPrefix();
} | @Test
public void likePredicateIsNotIndexed_whenHashIndexIsUsed() {
QueryContext queryContext = mock(QueryContext.class);
when(queryContext.matchIndex("this", QueryContext.IndexMatchHint.PREFER_ORDERED)).thenReturn(createIndex(IndexType.HASH));
assertFalse(new LikePredicate("this", "string%... |
@Override
public void close(String nodeId) {
log.info("Client requested connection close from node {}", nodeId);
selector.close(nodeId);
long now = time.milliseconds();
cancelInFlightRequests(nodeId, now, null, false);
connectionStates.remove(nodeId);
} | @Test
public void testClose() {
client.ready(node, time.milliseconds());
awaitReady(client, node);
client.poll(1, time.milliseconds());
assertTrue(client.isReady(node, time.milliseconds()), "The client should be ready");
ProduceRequest.Builder builder = ProduceRequest.forCur... |
static ConfigServer toConfigServer(String configserverString) {
try {
String[] hostPortTuple = configserverString.split(":");
if (configserverString.contains(":")) {
return new ConfigServer(hostPortTuple[0], Optional.of(Integer.parseInt(hostPortTuple[1])));
} ... | @Test(expected = IllegalArgumentException.class)
public void non_numeric_port_gives_exception() {
toConfigServer("myhost:non-numeric");
} |
@Override
public Integer call() throws Exception {
super.call();
if (fileValue != null) {
value = Files.readString(Path.of(fileValue.toString().trim()));
}
if (isLiteral(value) || type == Type.STRING) {
value = wrapAsJsonLiteral(value);
}
Du... | @Test
void object() throws IOException, ResourceExpiredException {
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class);
embeddedServer.start();
String[] args = {
... |
public static CoordinatorRecord newConsumerGroupTargetAssignmentEpochRecord(
String groupId,
int assignmentEpoch
) {
return new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupTargetAssignmentMetadataKey()
.setGroupId(groupId),
... | @Test
public void testNewConsumerGroupTargetAssignmentEpochRecord() {
CoordinatorRecord expectedRecord = new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupTargetAssignmentMetadataKey()
.setGroupId("group-id"),
(short) 6),
... |
public void resetProducer() {
if (processingMode != EXACTLY_ONCE_V2) {
throw new IllegalStateException("Expected eos-v2 to be enabled, but the processing mode was " + processingMode);
}
oldProducerTotalBlockedTime += totalBlockedTime(producer);
final long start = time.nanose... | @Test
public void shouldFailOnResetProducerForAtLeastOnce() {
final IllegalStateException thrown = assertThrows(
IllegalStateException.class,
() -> nonEosStreamsProducer.resetProducer()
);
assertThat(thrown.getMessage(), is("Expected eos-v2 to be enabled, but the pro... |
@Override
public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext)
{
doEvaluateDisruptContext(request, requestContext);
return _client.sendRequest(request, requestContext);
} | @Test
public void testSendRequest2()
{
when(_controller.getDisruptContext(any(String.class), any(ResourceMethod.class))).thenReturn(_disrupt);
_client.sendRequest(_request, _context);
verify(_underlying, times(1)).sendRequest(eq(_request), eq(_context));
verify(_context, times(1)).putLocalAttr(eq(DI... |
@Override
public ValidationResult validate(RuleBuilderStep step) {
final RuleFragment ruleFragment = actions.get(step.function());
FunctionDescriptor<?> functionDescriptor = ruleFragment.descriptor();
String functionName = functionDescriptor.name();
if (functionName.equals(SetField.... | @Test
void validateSetFieldFunction() {
HashMap<String, Object> parameters = new HashMap<>();
parameters.put(FIELD_PARAM, "valid_new_field");
RuleBuilderStep validStep = RuleBuilderStep.builder()
.parameters(parameters)
.function(SetField.NAME)
... |
public Predicate convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testNullOp() {
ScalarOperator op = new IsNullPredicateOperator(false, F0);
Predicate result = CONVERTER.convert(op);
Assert.assertTrue(result instanceof LeafPredicate);
LeafPredicate leafPredicate = (LeafPredicate) result;
Assert.assertTrue(leafPredicate.fun... |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
if (isGrayImage(image))
{
return createFromGrayImage(image, document);
}
// We try to encode the image with predictor
if (USE_PREDICTOR_ENCODER... | @Test
void testCreateLosslessFromGovdocs032163() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(new File("target/imgs", "PDFBOX-4184-032163.jpg"));
PDImageXObject ximage = LosslessFactory.createFromImage(document, image);
validate(... |
static boolean isInvalidSnapshot(final Entry entry)
{
return !entry.isValid && ENTRY_TYPE_SNAPSHOT == entry.type;
} | @Test
void shouldDetermineIfSnapshotIsInvalid()
{
final RecordingLog.Entry validSnapshot = new RecordingLog.Entry(
42, 5, 1024, 701, 1_000_000_000_000L, 16, ENTRY_TYPE_SNAPSHOT, null, true, 2);
final RecordingLog.Entry invalidSnapshot = new RecordingLog.Entry(
42, 5, 1024... |
public static ScenarioRunnerProvider getSpecificRunnerProvider(Type type) {
if (Type.RULE.equals(type)) {
return RuleScenarioRunner::new;
} else if (Type.DMN.equals(type)) {
return DMNScenarioRunner::new;
} else {
throw new IllegalArgumentException("Impossible... | @Test
public void getSpecificRunnerProvider() {
// all existing types should have a dedicated runner
assertThat(ScenarioSimulationModel.Type.values()).extracting(x -> AbstractScenarioRunner.getSpecificRunnerProvider(x)).isNotNull();
} |
public Ap01 createAp01(String bsn) {
Ap01 ap01 = new Ap01();
Container container = new Container();
container.setNummer(CategorieUtil.CATEGORIE_IDENTIFICATIENUMMERS);
Element bsnElement = new Element();
bsnElement.setNummer(CategorieUtil.ELEMENT_BURGERSERVICENUMMER);
bsn... | @Test
public void testCreateAp01Test(){
String testBsn = "SSSSSSSSS";
Ap01 result = classUnderTest.createAp01(testBsn);
assertEquals(testBsn, CategorieUtil.findBsn(result.getCategorie()));
assertEquals(0, result.getHerhaling());
assertEquals("SSSSSSSS", result.getRandomKey()... |
public EventDefinitionDto create(EventDefinitionDto unsavedEventDefinition, Optional<User> user) {
final EventDefinitionDto eventDefinition = createEventDefinition(unsavedEventDefinition, user);
try {
createJobDefinitionAndTriggerIfScheduledType(eventDefinition);
} catch (Exception ... | @Test
public void create() {
final EventDefinitionDto newDto = EventDefinitionDto.builder()
.title("Test")
.description("A test event definition")
.config(TestEventProcessorConfig.builder()
.message("This is a test event processor")
... |
public final void setStrictness(Strictness strictness) {
Objects.requireNonNull(strictness);
this.strictness = strictness;
} | @Test
public void testSetStrictnessNull() {
JsonReader reader = new JsonReader(reader("{}"));
assertThrows(NullPointerException.class, () -> reader.setStrictness(null));
} |
public static SegmentGenerationJobSpec getSegmentGenerationJobSpec(String jobSpecFilePath, String propertyFilePath,
Map<String, Object> context, Map<String, String> environmentValues) {
Properties properties = new Properties();
if (propertyFilePath != null) {
try {
properties.load(FileUtils.... | @Test
public void testIngestionJobLauncherWithTemplateAndPropertyFileAndValueAndEnvironmentVariableOverride() {
Map<String, Object> context = GroovyTemplateUtils.getTemplateContext(Arrays.asList("year=2020"));
SegmentGenerationJobSpec spec = IngestionJobLauncher.getSegmentGenerationJobSpec(
GroovyTemp... |
public Flowable<Transaction> replayTransactionsFlowable(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
return replayBlocksFlowable(startBlock, endBlock, true)
.flatMapIterable(JsonRpc2_0Rx::toTransactions);
} | @Test
public void testReplayTransactionsFlowable() throws Exception {
List<EthBlock> ethBlocks =
Arrays.asList(
createBlockWithTransactions(
0,
Arrays.asList(
crea... |
public static <F extends Future<Void>> Mono<Void> deferFuture(Supplier<F> deferredFuture) {
return new DeferredFutureMono<>(deferredFuture);
} | @SuppressWarnings("FutureReturnValueIgnored")
@Test
void testDeferredFutureMonoLater() {
ImmediateEventExecutor eventExecutor = ImmediateEventExecutor.INSTANCE;
Promise<Void> promise = eventExecutor.newPromise();
Supplier<Promise<Void>> promiseSupplier = () -> promise;
StepVerifier.create(FutureMono.deferFut... |
@Override
public int get(PageId pageId, int pageOffset, ReadTargetBuffer buffer,
CacheContext cacheContext) {
ReadWriteLock pageLock = getPageLock(pageId);
long pageSize = -1L;
try (LockResource r = new LockResource(pageLock.readLock())) {
PageInfo pageInfo;
try (LockResource ... | @Test
public void getNotEnoughSpaceException() throws Exception {
byte[] buf = new byte[PAGE1.length - 1];
assertThrows(IllegalArgumentException.class, () ->
mCacheManager.get(PAGE_ID1, PAGE1.length, buf, 0));
} |
@Override
public Optional<ResultDecorator<EncryptRule>> newInstance(final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database,
final EncryptRule encryptRule, final ConfigurationProperties props, final SQLStatementContext sqlStatementCo... | @Test
void assertNewInstanceWithDALStatement() {
SQLStatementContext sqlStatementContext = mock(ExplainStatementContext.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(mock(MySQLExplainStatement.class));
EncryptResultDecoratorEngine engine = (EncryptResultDecoratorEngine) Orde... |
private static String approximateSimpleName(Class<?> clazz, boolean dropOuterClassNames) {
checkArgument(!clazz.isAnonymousClass(), "Attempted to get simple name of anonymous class");
return approximateSimpleName(clazz.getName(), dropOuterClassNames);
} | @Test
public void testDropsOuterClassNamesTrue() {
assertEquals("Bar", NameUtils.approximateSimpleName("Foo$1$Bar", true));
assertEquals("Foo$1", NameUtils.approximateSimpleName("Foo$1", true));
assertEquals("Foo$1$2", NameUtils.approximateSimpleName("Foo$1$2", true));
} |
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found e... | @Test
public void testInterAppConstraintsByAppID()
throws InvalidAllocationTagsQueryException {
AllocationTagsManager tm = new AllocationTagsManager(rmContext);
PlacementConstraintManagerService pcm =
new MemoryPlacementConstraintManager();
rmContext.setAllocationTagsManager(tm);
rmConte... |
static ProcessorSupplier readMapIndexSupplier(MapIndexScanMetadata indexScanMetadata) {
return new MapIndexScanProcessorSupplier(indexScanMetadata);
} | @Test
public void test_whenFilterAndSpecificProjectionExists_sorted() {
List<JetSqlRow> expected = new ArrayList<>();
for (int i = count; i > 0; i--) {
map.put(i, new Person("value-" + i, i));
if (i > count / 2) {
expected.add(jetRow((count - i + 1), "value-" ... |
private void logResponse(final ShenyuContext shenyuContext, final BodyWriter writer) {
if (StringUtils.isNotBlank(getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH))) {
String size = StringUtils.defaultIfEmpty(getHeaders().getFirst(HttpHeaders.CONTENT_LENGTH), "0");
logInfo.setResponseCon... | @Test
public void testLogResponse() throws Exception {
logCollector.start();
// DefaultLogCollector.getInstance().start();
loggingServerHttpResponse.setExchange(exchange);
BodyWriter writer = new BodyWriter();
String sendString = "hello, shenyu";
ByteBuffer byteBuffer... |
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) {
this.fieldLengths = fieldLengths;
return this;
} | @Test
public void shouldConfigureIgnoreTrailingWhitespaces() {
UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat()
.setFieldLengths(new int[] { 1, 2, 3 })
.setIgnoreTrailingWhitespaces(true);
assertTrue(dataFormat.getIgnoreTrailingWhitespaces());
... |
public void changeLevel(LoggerLevel level) {
Level logbackLevel = Level.toLevel(level.name());
database.enableSqlLogging(level == TRACE);
helper.changeRoot(serverProcessLogging.getLogLevelConfig(), logbackLevel);
LoggerFactory.getLogger(ServerLogging.class).info("Level of logs changed to {}", level);
... | @Test
@UseDataProvider("supportedSonarApiLevels")
public void changeLevel_calls_changeRoot_with_LogLevelConfig_and_level_converted_to_logback_class_then_log_INFO_message(LoggerLevel level) {
LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(rootLoggerName).build();
when(serverProcessLogging.getLogLe... |
@Override
public String getFullName(){
return getFullName(organization, job);
} | @Test
public void testFreestyle() throws Exception {
Job job = j.createFreeStyleProject("freestyle");
login();
Assert.assertEquals(
get("/organizations/jenkins/pipelines/" + job.getFullName() + "/").get("disabled"),
false
);
put("/organizations/jenkins... |
@Override
public String getURL( String hostname, String port, String databaseName ) {
String url = "jdbc:sqlserver://" + hostname + ":" + port + ";database=" + databaseName + ";encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
if ( getAttribute( IS_ALWAY... | @Test
public void testGetUrlWithAadPasswordAuth(){
dbMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE );
dbMeta.addAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "false" );
dbMeta.addAttribute( JDBC_AUTH_METHOD, ACTIVE_DIRECTORY_PASSWORD );
String expectedUrl = "jdbc:sqlserver://abc.database.windows.net:... |
public static String temporaryFileName(long nonce, String path) {
return path + String.format(TEMPORARY_SUFFIX_FORMAT, nonce);
} | @Test
public void temporaryFileName() {
assertEquals(PathUtils.temporaryFileName(1, "/"),
PathUtils.temporaryFileName(1, "/"));
assertNotEquals(PathUtils.temporaryFileName(1, "/"),
PathUtils.temporaryFileName(2, "/"));
assertNotEquals(PathUtils.temporaryFileName(1, "/"),
PathUtils.... |
private PolicerId(URI u) {
super(u.toString());
uri = u;
} | @Test
public void testWrongCreation() {
// Build not allowed string
String wrongString = Strings.repeat("x", 1025);
// Define expected exception
exceptionWrongId.expect(IllegalArgumentException.class);
// Create policer id
PolicerId.policerId(wrongString);
} |
public String getString(HazelcastProperty property) {
String value = properties.getProperty(property.getName());
if (value != null) {
return value;
}
value = property.getSystemProperty();
if (value != null) {
return value;
}
HazelcastProp... | @Test
public void setProperty_ensureHighestPriorityOfConfig() {
config.setProperty(ENTERPRISE_LICENSE_KEY.getName(), "configValue");
ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue");
HazelcastProperties properties = new HazelcastProperties(config);
String value = properties.g... |
@ApiOperation(value = "Delete user settings (deleteUserSettings)",
notes = "Delete user settings by specifying list of json element xpaths. \n " +
"Example: to delete B and C element in { \"A\": {\"B\": 5}, \"C\": 15} send A.B,C in jsonPaths request parameter")
@PreAuthorize("hasAnyA... | @Test
public void testDeleteUserSettings() throws Exception {
loginCustomerUser();
JsonNode userSettings = JacksonUtil.toJsonNode("{\"A\":10, \"B\":10, \"C\":{\"D\": 16}}");
JsonNode savedSettings = doPost("/api/user/settings", userSettings, JsonNode.class);
Assert.assertEquals(user... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.