focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void sessionWillPassivate(HttpSessionEvent event) {
if (!instanceEnabled) {
return;
}
// pour getSessionCount
SESSION_COUNT.decrementAndGet();
// pour invalidateAllSession
removeSession(event.getSession());
} | @Test
public void testSessionWillPassivate() {
sessionListener.sessionDidActivate(createSessionEvent());
sessionListener.sessionWillPassivate(createSessionEvent());
if (SessionListener.getSessionCount() != 0) {
fail("sessionWillPassivate");
}
if (!SessionListener.getAllSessionsInformations().isEmpty()) {
... |
public static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length) {
// Other implementation of the same algorithm:
// int crc = 0xFFFF;
//
// for (int i = offset; i < offset + length && i < data.length; ++i) {
// crc = (((crc & 0xFFFF) >> 8) | (crc << 8));
// crc ^= data[i];
// crc ... | @Test
public void CCITT_FALSE_123456789() {
final byte[] data = "123456789".getBytes();
assertEquals(0x29B1, CRC16.CCITT_FALSE(data, 0, 9));
} |
@Internal
public boolean isCompatible(Trigger other) {
if (!getClass().equals(other.getClass())) {
return false;
}
if (subTriggers == null) {
return other.subTriggers == null;
} else if (other.subTriggers == null) {
return false;
} else if (subTriggers.size() != other.subTrigger... | @Test
public void testIsCompatible() throws Exception {
assertTrue(new Trigger1(null).isCompatible(new Trigger1(null)));
assertTrue(
new Trigger1(Arrays.asList(new Trigger2(null)))
.isCompatible(new Trigger1(Arrays.asList(new Trigger2(null)))));
assertFalse(new Trigger1(null).isCompat... |
private void removeNote(Note note, AuthenticationInfo subject) throws IOException {
LOGGER.info("Remove note: {}", note.getId());
// Set Remove to true to cancel saving this note
note.setRemoved(true);
noteManager.removeNote(note.getId(), subject);
authorizationService.removeNoteAuth(note.getId());
... | @Test
void testRemoveNote() throws IOException, InterruptedException {
try {
LOGGER.info("--------------- Test testRemoveNote ---------------");
// create a note and a paragraph
String noteId = notebook.createNote("note1", anonymous);
int mock1ProcessNum = interpreterSettingManager.getByNa... |
@PublicEvolving
public static AIMDScalingStrategyBuilder builder(int rateThreshold) {
return new AIMDScalingStrategyBuilder(rateThreshold);
} | @Test
void testInvalidIncreaseRate() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() ->
AIMDScalingStrategy.builder(100)
.setIncreaseRate(0)
... |
@Override
public final void collect(T record) {
collect(record, TimestampAssigner.NO_TIMESTAMP);
} | @Test
void eventsAreBeforeWatermarks() {
final CollectingDataOutput<Integer> dataOutput = new CollectingDataOutput<>();
final SourceOutputWithWatermarks<Integer> out =
createWithSameOutputs(
dataOutput,
new RecordTimestampAssigner<>(),
... |
private void overlay(Properties to, Properties from) {
synchronized (from) {
for (Entry<Object, Object> entry : from.entrySet()) {
to.put(entry.getKey(), entry.getValue());
}
}
} | @Test
public void testOverlay() throws IOException{
out=new BufferedWriter(new FileWriter(CONFIG));
startConfig();
appendProperty("a","b");
appendProperty("b","c");
appendProperty("d","e");
appendProperty("e","f", true);
endConfig();
out=new BufferedWriter(new FileWriter(CONFIG2));
... |
public GenericRecordBuilder set(String fieldName, Object value) {
return set(schema().getField(fieldName), value);
} | @Test
void attemptToSetNonNullableFieldToNull() {
assertThrows(org.apache.avro.AvroRuntimeException.class, () -> {
new GenericRecordBuilder(recordSchema()).set("intField", null);
});
} |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed.");
return;
}
final LegacyAWSPluginConfiguration legacyConfiguration = clusterConfigService.get(
CLUSTER_CONFIG_... | @Test
public void doesNotDoAnyThingForMissingPluginConfig() {
mockExistingConfig(null);
this.migration.upgrade();
verify(clusterConfigService, never()).write(anyString(), any());
verify(clusterConfigService, times(1)).write(any(V20200505121200_EncryptAWSSecretKey.MigrationCompleted... |
public void enrichWorkflowDefinition(WorkflowDefinition workflowDefinition) {
WorkflowDefinitionExtras enrichedWorkflowDefinition = new WorkflowDefinitionExtras();
enrichParams(workflowDefinition, enrichedWorkflowDefinition);
enrichNextRunDate(workflowDefinition, enrichedWorkflowDefinition);
workflowDef... | @Test
public void testEnrichWorkflowDefinitionParams() {
Map<String, ParamDefinition> stepParams =
Collections.singletonMap("sp1", ParamDefinition.buildParamDefinition("sp1", "sv1"));
Map<String, ParamDefinition> workflowParams =
Collections.singletonMap("wp1", ParamDefinition.buildParamDefini... |
public static long memorySize2Byte(final long memorySize, @MemoryConst.Unit final int unit) {
if (memorySize < 0) return -1;
return memorySize * unit;
} | @Test
public void memorySize2ByteInputNegativeZeroOutputNegative() {
Assert.assertEquals(
-1L,
ConvertKit.memorySize2Byte(-9_223_372_036_854_775_807L, 0)
);
} |
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
try (OutputStream os = new FileOutputStream(file)) {
os.write(data.getBytes(encoding));
os.flush();
}
} | @Test
public void testWriteStringToFile() throws IOException {
File tempFile = new File(tempDir.toFile(), "testWriteStringToFile.txt");
String testString = "test string";
IoUtil.writeStringToFile(tempFile, testString, "UTF-8");
BufferedReader reader = new BufferedReader(new FileReade... |
@Override
public boolean isLeader() {
return isLeader;
} | @Test
void postsEventWhenLeaderChanges() {
when(lockService.lock(any(), isNull())).thenReturn(Optional.of(mock(Lock.class)));
leaderElectionService.startAsync().awaitRunning();
verify(eventBus, timeout(10_000)).post(any(LeaderChangedEvent.class));
assertThat(leaderElectionService.i... |
public long getLinesOfCode(){
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.projectDao().getNclocSum(dbSession);
}
} | @Test
public void should_return_metric_from_liveMeasureDao() {
when(dbClient.projectDao().getNclocSum(any(DbSession.class))).thenReturn(1800999L);
long linesOfCode = statisticsSupport.getLinesOfCode();
assertThat(linesOfCode).isEqualTo(1800999L);
} |
public static NameStep newBuilder() {
return new CharacterSteps();
} | @Test
void testBuildWeakWizard() {
final var character = CharacterStepBuilder.newBuilder()
.name("Merlin")
.wizardClass("alchemist")
.withSpell("poison")
.noAbilities()
.build();
assertEquals("Merlin", character.getName());
assertEquals("alchemist", character.getWi... |
public static String getFullElapsedTime(final long delta) {
if (delta < Duration.ofSeconds(1).toMillis()) {
return String.format("%d %s", delta, delta == 1 ? LocaleUtils.getLocalizedString("global.millisecond") : LocaleUtils.getLocalizedString("global.milliseconds"));
} else if (delta < Dura... | @Test
public void testElapsedTimeInSeconds() throws Exception {
assertThat(StringUtils.getFullElapsedTime(Duration.ofSeconds(1)), is("1 second"));
assertThat(StringUtils.getFullElapsedTime(Duration.ofMillis(1001)), is("1 second, 1 ms"));
assertThat(StringUtils.getFullElapsedTime(Duration.ofS... |
@VisibleForTesting
@Nonnull
Map<String, Object> prepareContextForPaginatedResponse(@Nonnull List<RuleDao> rules) {
final Map<String, RuleDao> ruleTitleMap = rules
.stream()
.collect(Collectors.toMap(RuleDao::title, dao -> dao));
final Map<String, List<PipelineCom... | @Test
public void prepareContextForPaginatedResponse_returnsRuleUsageMapIfRulesUsedByPipelines() {
final List<RuleDao> rules = List.of(
ruleDao("rule-1", "Rule 1"),
ruleDao("rule-2", "Rule 2"),
ruleDao("rule-3", "Rule 3"),
ruleDao("rule-4", "Ru... |
public boolean tryEnableBinlog(Database db, long tableId, long binlogTtL, long binlogMaxSize) {
// pass properties not binlogConfig is for
// unify the logic of alter table manaul and alter table of mv trigger
HashMap<String, String> properties = new HashMap<>();
properties.put(PropertyA... | @Test
public void testTryEnableBinlog() {
Database db = GlobalStateMgr.getCurrentState().getDb("test");
OlapTable table = (OlapTable) db.getTable("binlog_test");
boolean result = binlogManager.tryEnableBinlog(db, table.getId(), 200L, -1L);
Assert.assertTrue(result);
Assert.as... |
@Udf(description = "Converts the number of days since 1970-01-01 00:00:00 UTC/GMT to a date "
+ "string using the given format pattern. The format pattern should be in the format"
+ " expected by java.time.format.DateTimeFormatter")
public String formatDate(
@UdfParameter(
description = "T... | @Test
public void shouldThrowOnUnsupportedFields() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.formatDate(Date.valueOf("2014-11-09"), "yyyy-MM-dd HH:mm"));
// Then:
assertThat(e.getMessage(), is("Failed to format date 2014-11-09 with formatter '... |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(co... | @Test
void assertConvertNullValue() throws SQLException {
assertFalse((boolean) ResultSetUtils.convertValue(null, boolean.class));
assertThat(ResultSetUtils.convertValue(null, byte.class), is((byte) 0));
assertThat(ResultSetUtils.convertValue(null, short.class), is((short) 0));
asser... |
@Override
public GrokPattern load(String patternId) throws NotFoundException {
final GrokPattern pattern = dbCollection.findOneById(new ObjectId(patternId));
if (pattern == null) {
throw new NotFoundException("Couldn't find Grok pattern with ID " + patternId);
}
return pa... | @Test
public void loadNonExistentGrokPatternThrowsNotFoundException() {
assertThatThrownBy(() -> service.load("cafebabe00000000deadbeef"))
.isInstanceOf(NotFoundException.class);
} |
@Override
public void set(V value) {
get(setAsync(value));
} | @Test
public void testTouch() {
RBucket<String> bucket = redisson.getBucket("test");
bucket.set("someValue");
assertThat(bucket.touch()).isTrue();
RBucket<String> bucket2 = redisson.getBucket("test2");
assertThat(bucket2.touch()).isFalse();
} |
@Override
@SuppressWarnings("deprecation")
public HttpRoute determineRoute(HttpHost target, HttpContext context) {
if ( ! target.getSchemeName().equals("http") && ! target.getSchemeName().equals("https"))
throw new IllegalArgumentException("Scheme must be 'http' or 'https' when using HttpToH... | @Test
@SuppressWarnings("deprecation")
void verifyProxyIsDisallowed() {
HttpClientContext context = new HttpClientContext();
context.setRequestConfig(RequestConfig.custom().setProxy(new HttpHost("proxy")).build());
try {
planner.determineRoute(new HttpHost("http", "host", 1),... |
@Override
public void validateJoinRequest(JoinMessage joinMessage) {
// check joining member's major.minor version is same as current cluster version's major.minor numbers
MemberVersion memberVersion = joinMessage.getMemberVersion();
Version clusterVersion = node.getClusterService().getClust... | @Test
public void test_joinRequestFails_whenNextMinorVersion() {
MemberVersion nextMinorVersion = MemberVersion.of(nodeVersion.getMajor(), nodeVersion.getMinor() + 1,
nodeVersion.getPatch());
JoinRequest joinRequest = new JoinRequest(Packet.VERSION, buildNumber, nextMinorVersion, joi... |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testAclStatusProto() {
AclEntry e = new AclEntry.Builder().setName("test")
.setPermission(FsAction.READ_EXECUTE).setScope(AclEntryScope.DEFAULT)
.setType(AclEntryType.OTHER).build();
AclStatus s = new AclStatus.Builder().owner("foo").group("bar").addEntry(e)
.build();... |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis... | @Test
public void shouldThrowOnPullQueryThatIsWindowed() {
// Given:
when(analysis.getWindowExpression()).thenReturn(Optional.of(windowExpression));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> validator.validate(analysis)
);
// Then:
assertThat(... |
public static PemAuthIdentity clusterOperator(Secret secret) {
return new PemAuthIdentity(secret, "cluster-operator");
} | @Test
public void testMissingSecret() {
Exception e = assertThrows(NullPointerException.class, () -> PemAuthIdentity.clusterOperator(null));
assertThat(e.getMessage(), is("Cannot extract auth identity from null secret."));
} |
public NearCachePreloaderConfig setStoreIntervalSeconds(int storeIntervalSeconds) {
this.storeIntervalSeconds = checkPositive("storeIntervalSeconds", storeIntervalSeconds);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setStoreIntervalSeconds_withNegative() {
config.setStoreIntervalSeconds(-1);
} |
public boolean traced(String clientIp) {
ConnectionControlRule connectionControlRule = ControlManagerCenter.getInstance().getConnectionControlManager()
.getConnectionLimitRule();
return connectionControlRule != null && connectionControlRule.getMonitorIpList() != null
&& c... | @Test
void testTraced() {
assertFalse(connectionManager.traced(clientIp));
} |
public void put(K key, V value) {
if (value == null) {
throw new IllegalArgumentException("Null values are disallowed");
}
ValueAndTimestamp<V> oldValue = cache.put(key, new ValueAndTimestamp<>(value));
if (oldValue == null && cache.size() > cleanupThreshold) {
d... | @Test
public void test_cleanup() {
assertEntries(entry(1, 1), entry(2, 2), entry(3, 3));
put(4, 4);
assertEntries(entry(3, 3), entry(4, 4));
} |
static void valueMustBeValid(EvaluationContext ctx, Object value) {
if (!(value instanceof BigDecimal) && !(value instanceof LocalDate)) {
ctx.notifyEvt(() -> new ASTEventBase(FEELEvent.Severity.ERROR, Msg.createMessage(Msg.VALUE_X_NOT_A_VALID_ENDPOINT_FOR_RANGE_BECAUSE_NOT_A_NUMBER_NOT_A_DATE, valu... | @Test
void valueMustBeValidFalseTest() {
try {
valueMustBeValid(ctx, "INVALID");
} catch (Exception e) {
assertTrue(e instanceof EndpointOfRangeNotValidTypeException);
final ArgumentCaptor<FEELEvent> captor = ArgumentCaptor.forClass(FEELEvent.class);
v... |
public boolean checkAndRefresh() {
FileTime newLastModifiedTime = updateLastModifiedTime();
if (newLastModifiedTime != null && !newLastModifiedTime.equals(lastModifiedTime)) {
this.lastModifiedTime = newLastModifiedTime;
return true;
}
return false;
} | @Test(dataProvider = "files")
public void testFileModified(String fileName) throws IOException, InterruptedException {
Path path = Paths.get(fileName);
createFile(path);
FileModifiedTimeUpdater fileModifiedTimeUpdater = new FileModifiedTimeUpdater(fileName);
Thread.sleep(2000);
... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_SHIFT_UPS_performedBy_MOVE() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702), uuids[1]),
new Parti... |
@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 testReadCloseReleaseEntity() throws Exception {
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(32769);
final TransferStatus writeStatus = new TransferStatus();
writeStatus.setLength(content.length);
final SDS... |
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) {
NewExternalIssue newExternalIssue = sensorContext.newExternalIssue();
newExternalIssue.type(DEFAULT_TYPE);
newExternalIssue.engineId(driverName);
newExte... | @Test
public void mapResult_useResultMessageForIssue() {
Location location = new Location();
result.withLocations(List.of(location));
resultMapper.mapResult(DRIVER_NAME, WARNING, WARNING, result);
verify(newExternalIssueLocation).message("Result message");
} |
@Override
public PMML_MODEL getPMMLModelType() {
logger.trace("getPMMLModelType");
return PMML_MODEL.SCORECARD_MODEL;
} | @Test
void getPMMLModelType() {
assertThat(PROVIDER.getPMMLModelType()).isEqualTo(PMML_MODEL.SCORECARD_MODEL);
} |
public EnvironmentVariableContext initialEnvironmentVariableContext() {
return initialContext;
} | @Test
void shouldSetUpGoGeneratedEnvironmentContextCorrectly() throws Exception {
BuildAssignment buildAssigment = createAssignment(null);
EnvironmentVariableContext environmentVariableContext = buildAssigment.initialEnvironmentVariableContext();
assertThat(environmentVariableContext.getProp... |
public MemoryLRUCacheBytesIterator reverseRange(final String namespace, final Bytes from, final Bytes to) {
final NamedCache cache = getCache(namespace);
if (cache == null) {
return new MemoryLRUCacheBytesIterator(Collections.emptyIterator(), new NamedCache(namespace, this.metrics));
... | @Test
public void shouldReturnFalseIfNoNextKeyReverseRange() {
final ThreadCache cache = setupThreadCache(-1, 0, 10000L, true);
final ThreadCache.MemoryLRUCacheBytesIterator iterator = cache.reverseRange(namespace, Bytes.wrap(new byte[]{0}), Bytes.wrap(new byte[]{1}));
assertFalse(iterator.h... |
@Override
public void purgeFlowRules(DeviceId deviceId) {
checkPermission(FLOWRULE_WRITE);
checkNotNull(deviceId, DEVICE_ID_NULL);
store.purgeFlowRule(deviceId);
} | @Test
public void purgeFlowRules() {
FlowRule f1 = addFlowRule(1);
FlowRule f2 = addFlowRule(2);
FlowRule f3 = addFlowRule(3);
assertEquals("3 rules should exist", 3, flowCount());
FlowEntry fe1 = new DefaultFlowEntry(f1);
FlowEntry fe2 = new DefaultFlowEntry(f2);
... |
public JerseyClientBuilder using(JerseyClientConfiguration configuration) {
this.configuration = configuration;
apacheHttpClientBuilder.using(configuration);
return this;
} | @Test
void usesACustomHttpClientMetricNameStrategy() {
final HttpClientMetricNameStrategy customStrategy = HttpClientMetricNameStrategies.HOST_AND_METHOD;
builder.using(customStrategy);
verify(apacheHttpClientBuilder).using(customStrategy);
} |
@Override
public Class<SingleRuleConfiguration> getType() {
return SingleRuleConfiguration.class;
} | @Test
void assertGetType() {
SingleRuleConfigurationToDistSQLConverter singleRuleConfigurationToDistSQLConverter = new SingleRuleConfigurationToDistSQLConverter();
assertThat(singleRuleConfigurationToDistSQLConverter.getType().getName(), is("org.apache.shardingsphere.single.config.SingleRuleConfigur... |
int getDefaultCollationStrength() {
return getDefaultCollationStrength( Locale.getDefault() );
} | @Test
public void testGetDefaultStrength() {
SortRowsMeta srm = new SortRowsMeta();
int usStrength = srm.getDefaultCollationStrength( Locale.US );
assertEquals( Collator.TERTIARY, usStrength );
assertEquals( Collator.IDENTICAL, srm.getDefaultCollationStrength( null ) );
} |
public static Status unblock(
final UnsafeBuffer logMetaDataBuffer,
final UnsafeBuffer termBuffer,
final int blockedOffset,
final int tailOffset,
final int termId)
{
Status status = NO_ACTION;
int frameLength = frameLengthVolatile(termBuffer, blockedOffset);
... | @Test
void shouldTakeNoActionWhenNoUnblockedMessage()
{
final int termOffset = 0;
final int tailOffset = TERM_BUFFER_CAPACITY / 2;
assertEquals(
NO_ACTION, TermUnblocker.unblock(mockLogMetaDataBuffer, mockTermBuffer, termOffset, tailOffset, TERM_ID));
} |
@Override
public ChannelFuture writePing(ChannelHandlerContext ctx, boolean ack, long data, ChannelPromise promise) {
// Only apply the limit to ping acks.
if (ack) {
ChannelPromise newPromise = handleOutstandingControlFrames(ctx, promise);
if (newPromise == null) {
... | @Test
public void testNotLimitPing() {
assertTrue(encoder.writePing(ctx, false, 8, newPromise()).isSuccess());
assertTrue(encoder.writePing(ctx, false, 8, newPromise()).isSuccess());
assertTrue(encoder.writePing(ctx, false, 8, newPromise()).isSuccess());
assertTrue(encoder.writePing(... |
public void clearAllParagraphOutput() {
for (Paragraph p : paragraphs) {
p.setReturn(null, null);
}
} | @Test
void clearAllParagraphOutputTest() throws InterpreterNotFoundException {
Note note = new Note("test", "", interpreterFactory, interpreterSettingManager,
paragraphJobListener, credentials, noteEventListener, zConf, noteParser);
Paragraph p1 = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
... |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/{executionId}/flow")
@Operation(tags = {"Executions"}, summary = "Get flow information's for an execution")
public FlowForExecution getFlowForExecutionById(
@Parameter(description = "The execution that you want flow information's") String executionId
) {... | @SuppressWarnings("DataFlowIssue")
@Test
void getFlowForExecutionById() {
Execution execution = client.toBlocking().retrieve(
HttpRequest
.POST(
"/api/v1/executions/webhook/" + TESTS_FLOW_NS + "/webhook/" + TESTS_WEBHOOK_KEY + "?name=john&age=12&age=13",
... |
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
Map<String, String> instances = Collections.emptyMap();
if (!awsConfig.anyOfEcsPropertiesConfigured()) {
instances = awsEc2Api.describeInstances(credentials);
... | @Test
public void doNotGetEcsAddressesWhenEc2Configured() {
AwsCredentials credentials = AwsCredentials.builder()
.setAccessKey("access-key")
.setSecretKey("secret-key")
.setToken("token")
.build();
AwsConfig awsConfig = AwsConfig.build... |
static Version parseVersion(String versionString) {
final StringTokenizer st = new StringTokenizer(versionString, ".");
int majorVersion = Integer.parseInt(st.nextToken());
int minorVersion;
if (st.hasMoreTokens())
minorVersion = Integer.parseInt(st.nextToken());
else... | @Test
public void testJavaVersion() {
Java.Version v = Java.parseVersion("9");
assertEquals(9, v.majorVersion);
assertEquals(0, v.minorVersion);
assertTrue(v.isJava9Compatible());
v = Java.parseVersion("9.0.1");
assertEquals(9, v.majorVersion);
assertEquals(0... |
@Override
public String toString(final RouteUnit routeUnit) {
Map<String, String> logicAndActualTables = getLogicAndActualTables(routeUnit);
StringBuilder result = new StringBuilder();
int index = 0;
for (Projection each : projections) {
if (index > 0) {
r... | @Test
void assertToStringWithOwnerQuote() {
Collection<Projection> projectionsWithOwnerQuote = Collections.singletonList(new ColumnProjection(new IdentifierValue("temp", QuoteCharacter.BACK_QUOTE),
new IdentifierValue("id", QuoteCharacter.BACK_QUOTE), new IdentifierValue("id", QuoteCharacter... |
@Override
public Stream<HoodieInstant> getCandidateInstants(HoodieTableMetaClient metaClient, HoodieInstant currentInstant,
Option<HoodieInstant> lastSuccessfulInstant) {
HoodieActiveTimeline activeTimeline = metaClient.getActiveTimeline();
// To find which ... | @Test
public void tstConcurrentWritesWithPendingInsertOverwriteReplace() throws Exception {
createCommit(metaClient.createNewInstantTime(), metaClient);
HoodieActiveTimeline timeline = metaClient.getActiveTimeline();
// consider commits before this are all successful
Option<HoodieInstant> lastSuccessf... |
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 testValidJobName() throws IOException {
List<String> names =
Arrays.asList("ok", "Ok", "A-Ok", "ok-123", "this-one-is-fairly-long-01234567890123456789");
for (String name : names) {
DataflowPipelineOptions options = buildPipelineOptions();
options.setJobName(name);
... |
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 getTypeNameInputPositiveOutputNotNull9() {
// Arrange
final int type = 11;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Delete_file", actual);
} |
static BlockStmt getComplexPartialScoreVariableDeclaration(final String variableName, final ComplexPartialScore complexPartialScore) {
final MethodDeclaration methodDeclaration = COMPLEX_PARTIAL_SCORE_TEMPLATE.getMethodsByName(GETKIEPMMLCOMPLEXPARTIALSCORE).get(0).clone();
final BlockStmt complexPartial... | @Test
void getComplexPartialScoreVariableDeclarationWithApply() throws IOException {
final String variableName = "variableName";
Constant constant = new Constant();
constant.setValue(value1);
FieldRef fieldRef = new FieldRef();
fieldRef.setField("FIELD_REF");
Apply ap... |
@Override
public Object[] toArray() {
return list.toArray();
} | @Test
public void testToArray() {
Set<String> set = redisson.getSortedSet("set");
set.add("1");
set.add("4");
set.add("2");
set.add("5");
set.add("3");
assertThat(set.toArray()).contains("1", "4", "2", "5", "3");
String[] strs = set.toArray(new Strin... |
static FileFilter ignoredFilesFilter() {
var ioFileFilters = IGNORED_FILES.stream()
.map(NameFileFilter::new)
.map(IOFileFilter.class::cast)
.toList();
return new NotFileFilter(new OrFileFilter(ioFileFilters));
} | @Test
public void it_does_not_include_files_to_be_ignored() {
var dsStore = new File("target/classes/.DS_Store");
assertFalse(ignoredFilesFilter().accept(dsStore));
} |
public static byte[] parseMAC(String value) {
final byte[] machineId;
final char separator;
switch (value.length()) {
case 17:
separator = value.charAt(2);
validateMacSeparator(separator);
machineId = new byte[EUI48_MAC_ADDRESS_LENGTH];... | @Test
public void testParseMacInvalidEUI48TrailingSeparatorA() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
parseMAC("00-AA-11-BB-22-CC-");
}
});
} |
@Override
public void fetchSegmentToLocal(URI downloadURI, File dest)
throws Exception {
// Create a RoundRobinURIProvider to round robin IP addresses when retry uploading. Otherwise may always try to
// download from a same broken host as: 1) DNS may not RR the IP addresses 2) OS cache the DNS resoluti... | @Test(expectedExceptions = AttemptsExceededException.class)
public void testFetchSegmentToLocalFailureWithNoPeerServers()
throws Exception {
FileUploadDownloadClient client = mock(FileUploadDownloadClient.class);
// The download always succeeds
when(client.downloadFile(any(), any(), any())).thenRetu... |
public static void main(String[] args) {
// Getting the bar series
BarSeries series = CsvTradesLoader.loadBitstampSeries();
// Building the trading strategy
Strategy strategy = MovingMomentumStrategy.buildStrategy(series);
/*
* Building chart datasets
*/
... | @Test
public void test() {
BuyAndSellSignalsToChart.main(null);
} |
protected Permission toPermission(final Node node) {
final Permission permission = new Permission();
if(node.getPermissions() != null) {
switch(node.getType()) {
case FOLDER:
case ROOM:
if(node.getPermissions().isCreate()
... | @Test
public void testPermissionsFile() throws Exception {
final SDSAttributesAdapter f = new SDSAttributesAdapter(session);
final Node node = new Node();
node.setIsEncrypted(false);
node.setType(Node.TypeEnum.FILE);
final NodePermissions permissions = new NodePermissions().r... |
public void runPickle(Pickle pickle) {
try {
StepTypeRegistry stepTypeRegistry = createTypeRegistryForPickle(pickle);
snippetGenerators = createSnippetGeneratorsForPickle(stepTypeRegistry);
// Java8 step definitions will be added to the glue here
buildBackendWorl... | @Test
void steps_are_executed() {
StubStepDefinition stepDefinition = new StubStepDefinition("some step");
Pickle pickleMatchingStepDefinitions = createPickleMatchingStepDefinitions(stepDefinition);
TestRunnerSupplier runnerSupplier = new TestRunnerSupplier(bus, runtimeOptions) {
... |
public void loadPlugin(GoPluginBundleDescriptor bundleDescriptor) {
for (GoPluginDescriptor pluginDescriptor : bundleDescriptor.descriptors()) {
if (idToDescriptorMap.containsKey(pluginDescriptor.id().toLowerCase())) {
throw new RuntimeException("Found another plugin with ID: " + plu... | @Test
void shouldNotLoadPluginIfThereIsOneMorePluginWithTheSameIDAndDifferentCase() {
GoPluginBundleDescriptor descriptor = new GoPluginBundleDescriptor(GoPluginDescriptor.builder().id("id1").isBundledPlugin(true).build());
registry.loadPlugin(descriptor);
GoPluginBundleDescriptor secondPlu... |
public void set(final Object bean, final Object value) {
set(bean, this.patternParts, lastIsNumber(this.patternParts), value);
} | @Test
public void setTest() {
final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
pattern.set(tempMap, 2);
final Object result = pattern.get(tempMap);
assertEquals(2, result);
} |
@Override
List<DiscoveryNode> resolveNodes() {
if (serviceName != null && !serviceName.isEmpty()) {
logger.fine("Using service name to discover nodes.");
return getSimpleDiscoveryNodes(client.endpointsByName(serviceName));
} else if (serviceLabel != null && !serviceLabel.isEm... | @Test
public void resolveWithServiceNameWhenNotReadyAddressesAndNotReadyDisabled() {
// given
List<Endpoint> endpoints = createNotReadyEndpoints(2);
given(client.endpointsByName(SERVICE_NAME)).willReturn(endpoints);
KubernetesApiEndpointResolver sut = new KubernetesApiEndpointResolv... |
public boolean checkStateUpdater(final long now,
final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) {
addTasksToStateUpdater();
if (stateUpdater.hasExceptionsAndFailedTasks()) {
handleExceptionsFromStateUpdater();
}
if ... | @Test
public void shouldAddTasksToStateUpdater() {
final StreamTask task00 = statefulTask(taskId00, taskId00ChangelogPartitions)
.withInputPartitions(taskId00Partitions)
.inState(State.RESTORING).build();
final StandbyTask task01 = standbyTask(taskId01, taskId01ChangelogParti... |
public static String substringAfter(String str, String separator) {
if ((str == null) || (str.length() == 0)) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos < 0) {
return EMPTY;
... | @Test
public void testSubstringAfter() {
Assert.assertEquals(null, StringUtils.substringAfter(null, "*"));
Assert.assertEquals("", StringUtils.substringAfter("", "*"));
Assert.assertEquals("", StringUtils.substringAfter("*", null));
Assert.assertEquals("bc", StringUtils.substringAfte... |
void processSingleResource(FileStatus resource) {
Path path = resource.getPath();
// indicates the processing status of the resource
ResourceStatus resourceStatus = ResourceStatus.INIT;
// first, if the path ends with the renamed suffix, it indicates the
// directory was moved (as stale) but someho... | @Test
void testResourceIsInUseHasAnActiveApp() throws Exception {
FileSystem fs = mock(FileSystem.class);
CleanerMetrics metrics = mock(CleanerMetrics.class);
SCMStore store = mock(SCMStore.class);
FileStatus resource = mock(FileStatus.class);
when(resource.getPath()).thenReturn(new Path(ROOT + "... |
public List<BlameLine> blame(Path baseDir, String fileName) throws Exception {
BlameOutputProcessor outputProcessor = new BlameOutputProcessor();
try {
this.processWrapperFactory.create(
baseDir,
outputProcessor::process,
gitCommand,
GIT_DIR_FLAG, String.format(GIT_... | @Test
public void blame_different_author_and_committer() throws Exception {
File projectDir = createNewTempFolder();
javaUnzip("dummy-git-different-committer.zip", projectDir);
File baseDir = new File(projectDir, "dummy-git");
List<BlameLine> blame = blameCommand.blame(baseDir.toPath(), DUMMY_JAVA);
... |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testSetMyDefaultAdministratorRightsWithNone() {
SetMyDefaultAdministratorRights setMyDefaultAdministratorRights = SetMyDefaultAdministratorRights
.builder()
.build();
assertEquals("setMyDefaultAdministratorRights", setMyDefaultAdministratorRights.get... |
@Operation(summary = "Receive SAML AuthnRequest")
@PostMapping(value = {"/frontchannel/saml/v4/entrance/request_authentication", "/frontchannel/saml/v4/idp/request_authentication"})
public RedirectView requestAuthenticationService(HttpServletRequest request) throws SamlValidationException, SharedServiceClientEx... | @Test
public void failedRequestAuthenticationEntranceServiceTest() throws UnsupportedEncodingException, SamlSessionException, DienstencatalogusException, SharedServiceClientException, SamlValidationException, MessageDecodingException, ComponentInitializationException, SamlParseException {
RedirectView resul... |
@Override
public MetricsContext.Unit unit() {
return unit;
} | @Test
public void noop() {
assertThat(DefaultCounter.NOOP.unit()).isEqualTo(Unit.UNDEFINED);
assertThat(DefaultCounter.NOOP.isNoop()).isTrue();
assertThatThrownBy(DefaultCounter.NOOP::value)
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("NOOP counter has no value");
} |
private static String getActualValue(String configVal) {
if (configVal != null && configVal.matches("^.*\\$\\{[\\w.]+(:.*)?}.*$")) {
final int startIndex = configVal.indexOf("${") + 2;
final int endIndex = configVal.indexOf('}', startIndex);
final String envKey = configVal.su... | @Test
public void testGetActualValue()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Method method = BootArgsBuilder.class.getDeclaredMethod("getActualValue", String.class);
method.setAccessible(true);
assertEquals("demo",... |
public void validate(ExternalIssueReport report, Path reportPath) {
if (report.rules != null && report.issues != null) {
Set<String> ruleIds = validateRules(report.rules, reportPath);
validateIssuesCctFormat(report.issues, ruleIds, reportPath);
} else if (report.rules == null && report.issues != nul... | @Test
public void validate_whenInvalidReport_shouldThrowException() throws IOException {
ExternalIssueReport report = readInvalidReport(DEPRECATED_REPORTS_LOCATION);
assertThatThrownBy(() -> validator.validate(report, reportPath))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to p... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertTextMessageCreatesBodyUsingOriginalEncodingWithDataSection() throws Exception {
String contentString = "myTextMessageContent";
ActiveMQTextMessage outbound = createTextMessage(contentString);
outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_DATA);
... |
public CruiseConfig deserializeConfig(String content) throws Exception {
String md5 = md5Hex(content);
Element element = parseInputStream(new ByteArrayInputStream(content.getBytes()));
LOGGER.debug("[Config Save] Updating config cache with new XML");
CruiseConfig configForEdit = classPa... | @Test
void shouldAllowBothCounterAndMaterialNameInLabelTemplate() throws Exception {
CruiseConfig cruiseConfig = xmlLoader.deserializeConfig(LABEL_TEMPLATE_WITH_LABEL_TEMPLATE("1.3.0-${COUNT}-${git}"));
assertThat(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("cruise")).getLabelTemplat... |
protected static void validateTimestampColumnType(
final Optional<String> timestampColumnName,
final Schema avroSchema
) {
if (timestampColumnName.isPresent()) {
if (avroSchema.getField(timestampColumnName.get()) == null) {
throw new IllegalArgumentException("The indicated timestamp fiel... | @Test
public void shouldThrowIfTimestampColumnDoesNotExist() throws IOException {
// When
final IllegalArgumentException illegalArgumentException = assertThrows(
IllegalArgumentException.class,
() -> DataGenProducer.validateTimestampColumnType(Optional.of("page__id"), getAvroSchema())
);
... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(file.attributes().getLink() != DescriptiveUrl.EMPTY) {
list.add(file.attributes().getLink());
}
list.add(new DescriptiveUrl(URI.create(String.format("%s%... | @Test
public void testAbsoluteDocumentRoot() {
Host host = new Host(new TestProtocol(), "localhost");
host.setDefaultPath("/usr/home/dkocher/public_html");
Path path = new Path(
"/usr/home/dkocher/public_html/file", EnumSet.of(Path.Type.directory));
assertEquals("http... |
public Certificate add(CvCertificate cert) {
final Certificate db = Certificate.from(cert);
if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) {
throw new ClientException(String.format(
"Certificate of subject %s and issuer %s already exists", db.ge... | @Test
public void shouldNotAddATIfPublicKeyIsNotFound() throws Exception {
Mockito.doThrow(new nl.logius.digid.sharedlib.exception.ClientException(
"Not Found", 404
)).when(hsmClient).keyInfo(Mockito.eq("AT"), Mockito.eq("SSSSSSSSSSSSSSSS"));
certificateRepo.save(loadCvCertifica... |
@Override
public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
checkParameterCount(parameters, 0, 2);
Object []values = parameters.toArray();
int count = values.length;
if (count > 0) {
format = ((CompoundVariable) values... | @Test
void testTooMany() throws Exception {
params.add(new CompoundVariable("YMD"));
params.add(new CompoundVariable("NAME"));
params.add(new CompoundVariable("YMD"));
assertThrows(InvalidVariableException.class, () -> variable.setParameters(params));
} |
@Override
public void run() {
JobRunrMetadata metadata = storageProvider.getMetadata("database_version", "cluster");
if (metadata != null && "6.0.0".equals(metadata.getValue())) return;
migrateScheduledJobsIfNecessary();
storageProvider.saveMetadata(new JobRunrMetadata("database_ve... | @Test
void doesMigrationsOfScheduledJobsIfStorageProviderIsAnSqlStorageProvider() {
doReturn(PostgresStorageProvider.class).when(storageProviderInfo).getImplementationClass();
task.run();
verify(storageProvider).getScheduledJobs(any(), any());
} |
@Override
public boolean isOperational() {
if (nodeOperational) {
return true;
}
boolean flag = false;
try {
flag = checkOperational();
} catch (InterruptedException e) {
LOG.trace("Interrupted while checking ES node is operational", e);
Thread.currentThread().interrupt();... | @Test
public void isOperational_should_return_false_if_ElasticsearchException_thrown() {
EsConnector esConnector = mock(EsConnector.class);
when(esConnector.getClusterHealthStatus())
.thenThrow(new ElasticsearchException("test"));
EsManagedProcess underTest = new EsManagedProcess(mock(Process.class)... |
public static int divide(int num1, int num2) {
return ((int) (Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") * PERCENTAGE));
} | @Test
public void assertDivide() {
Assert.isTrue(CalculateUtil.divide(200, 100) == 200);
Assert.isTrue(CalculateUtil.divide(100, 200) == 50);
Assert.isTrue(CalculateUtil.divide(100, 100) == 100);
} |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test
public void testMergeDifferentInputSpec() {
SinkConfig sinkConfig = createSinkConfig();
sinkConfig.getInputSpecs().put("test-input", ConsumerConfig.builder().isRegexPattern(true).receiverQueueSize(1000).build());
Map<String, ConsumerConfig> inputSpecs = new HashMap<>();
inputS... |
Map<String, Object> offsetSyncsTopicProducerConfig() {
return SOURCE_CLUSTER_ALIAS_DEFAULT.equals(offsetSyncsTopicLocation())
? sourceProducerConfig(OFFSET_SYNCS_SOURCE_PRODUCER_ROLE)
: targetProducerConfig(OFFSET_SYNCS_TARGET_PRODUCER_ROLE);
} | @Test
public void testProducerConfigsForOffsetSyncsTopic() {
Map<String, String> connectorProps = makeProps(
"source.producer.batch.size", "1",
"target.producer.acks", "1",
"producer.max.poll.interval.ms", "1",
"fetch.min.bytes", "1"
);... |
@Override
public Object[] getRowFromCache( RowMetaInterface lookupMeta, Object[] lookupRow ) throws KettleException {
if ( stepData.hasDBCondition ) {
// actually, there was no sense in executing SELECT from db in this case,
// should be reported as improvement
return null;
}
SearchingC... | @Test
public void lookup_DoesNotFind_WithBetweenOperator() throws Exception {
RowMeta meta = keysMeta.clone();
meta.setValueMeta( 3, new ValueMetaDate() );
meta.addValueMeta( new ValueMetaInteger() );
ReadAllCache cache = buildCache( "<>,IS NOT NULL,BETWEEN,IS NULL" );
Object[] found = cache.getR... |
public static Interval of(String interval, TimeRange timeRange) {
switch (timeRange.type()) {
case TimeRange.KEYWORD: return timestampInterval(interval);
case TimeRange.ABSOLUTE:
return ofAbsoluteRange(interval, (AbsoluteRange)timeRange);
case TimeRange.RELATI... | @Test
public void returnsParsedIntervalIfAbsoluteRangeButAboveLimit() {
final AbsoluteRange absoluteRange = AbsoluteRange.create(
DateTime.parse("2019-12-01T14:50:23Z"),
DateTime.parse("2019-12-02T14:50:23Z")
);
final Interval interval = ApproximatedAutoInter... |
@VisibleForTesting
static OptionalDouble calculateAverageRowsPerPartition(Collection<PartitionStatistics> statistics)
{
return statistics.stream()
.map(PartitionStatistics::getBasicStatistics)
.map(HiveBasicStatistics::getRowCount)
.filter(OptionalLong::is... | @Test
public void testCalculateAverageRowsPerPartition()
{
assertThat(calculateAverageRowsPerPartition(ImmutableList.of())).isEmpty();
assertThat(calculateAverageRowsPerPartition(ImmutableList.of(PartitionStatistics.empty()))).isEmpty();
assertThat(calculateAverageRowsPerPartition(Immuta... |
public int validate(
final ServiceContext serviceContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties,
final String sql
) {
requireSandbox(serviceContext);
final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext));
... | @Test
public void shouldNotThrowIfNotQueryDespiteTooManyPersistentQueries() {
// Given:
givenPersistentQueryCount(2);
givenRequestValidator(ImmutableMap.of(ListStreams.class, StatementValidator.NO_VALIDATION));
final List<ParsedStatement> statements =
givenParsed(
"SHOW STREAMS;"
... |
@Override
public PageData<Device> findDevicesByTenantId(UUID tenantId, PageLink pageLink) {
if (StringUtils.isEmpty(pageLink.getTextSearch())) {
return DaoUtil.toPageData(
deviceRepository.findByTenantId(
tenantId,
DaoUt... | @Test
public void testFindDevicesByTenantId() {
PageLink pageLink = new PageLink(15, 0, PREFIX_FOR_DEVICE_NAME);
PageData<Device> devices1 = deviceDao.findDevicesByTenantId(tenantId1, pageLink);
assertEquals(15, devices1.getData().size());
pageLink = pageLink.nextPageLink();
... |
public FEELFnResult<List<Object>> invoke(@ParameterName( "ctx" ) EvaluationContext ctx,
@ParameterName("list") List list,
@ParameterName("precedes") FEELFunction function) {
if ( function == null ) {
return inv... | @Test
void invokeExceptionInSortFunction() {
FunctionTestUtil.assertResultError(
sortFunction.invoke(null, Arrays.asList(10, 4, 5, 12), getFunctionThrowingException()),
InvalidParametersEvent.class);
} |
public static GaussianMixture fit(int k, double[] x) {
if (k < 2)
throw new IllegalArgumentException("Invalid number of components in the mixture.");
double min = MathEx.min(x);
double max = MathEx.max(x);
double step = (max - min) / (k+1);
Component[] components = ... | @Test
public void testMixture5() {
System.out.println("Mixture5");
double[] data = new double[30000];
GaussianDistribution g1 = new GaussianDistribution(1.0, 1.0);
for (int i = 0; i < 5000; i++)
data[i] = g1.rand();
GaussianDistribution g2 = new GaussianDistrib... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void lessThanOrEqual() {
assertUnifiesAndInlines(
"4 <= 17", UBinary.create(Kind.LESS_THAN_EQUAL, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
public Collection<? extends Comparable<?>> generateKeys(final AlgorithmSQLContext algorithmSQLContext, final int keyGenerateCount) {
return getKeyGenerateAlgorithm(algorithmSQLContext.getTableName()).generateKeys(algorithmSQLContext, keyGenerateCount);
} | @Test
void assertGenerateKeyFailure() {
AlgorithmSQLContext generateContext = mock(AlgorithmSQLContext.class);
when(generateContext.getTableName()).thenReturn("table_0");
assertThrows(ShardingTableRuleNotFoundException.class, () -> createMaximumShardingRule().generateKeys(generateContext, 1)... |
@Override
public boolean hasLeadership(UUID leaderSessionId) {
synchronized (lock) {
return this.leaderContender != null && this.sessionID.equals(leaderSessionId);
}
} | @Test
void testHasLeadershipWithoutContender() throws Exception {
try (final LeaderElection testInstance = new StandaloneLeaderElection(SESSION_ID)) {
assertThat(testInstance.hasLeadership(SESSION_ID)).isFalse();
final UUID differentSessionID = UUID.randomUUID();
assertT... |
@Override
public Collection<String> allClientId() {
Collection<String> result = new HashSet<>();
result.addAll(connectionBasedClientManager.allClientId());
result.addAll(ephemeralIpPortClientManager.allClientId());
result.addAll(persistentIpPortClientManager.allClientId());
r... | @Test
void testAllClientId() {
Collection<String> actual = delegate.allClientId();
assertTrue(actual.contains(connectionId));
assertTrue(actual.contains(ephemeralIpPortId));
assertTrue(actual.contains(persistentIpPortId));
} |
public JobRunrConfiguration useDashboard() {
return useDashboardIf(true);
} | @Test
void dashboardThrowsExceptionIfNoStorageProviderIsAvailable() {
assertThatThrownBy(() -> JobRunr.configure()
.useDashboard()
).isInstanceOf(IllegalArgumentException.class)
.hasMessage("A StorageProvider is required to use a JobRunrDashboardWebServer. Please see ... |
@Override
public void doLimitForSelectRequest(SelectRequest selectRequest) throws SQLException {
if (null == selectRequest || !enabledLimit) {
return;
}
doLimit(selectRequest.getSql());
} | @Test
void testDoLimitForSelectRequestInvalid() throws SQLException {
SelectRequest selectRequest = SelectRequest.builder().sql("select * from test").build();
SelectRequest invalid = SelectRequest.builder().sql("CALL SALES.TOTAL_REVENUES()").build();
List<SelectRequest> selectRequests = new ... |
@Override
public String toJSONString(Object object) {
try {
return this.jsonParser.toJSONString(object);
} catch (Exception e) {
throw new JsonParseException(e);
}
} | @Test
public void testToJSONString() {
TwoPhaseBusinessActionParam actionParam = new TwoPhaseBusinessActionParam();
actionParam.setActionName("business_action");
actionParam.setBranchType(BranchType.TCC);
String resultString = parserWrap.toJSONString(actionParam);
assertEqu... |
Object getCellValue(Cell cell, Schema.FieldType type) {
ByteString cellValue = cell.getValue();
int valueSize = cellValue.size();
switch (type.getTypeName()) {
case BOOLEAN:
checkArgument(valueSize == 1, message("Boolean", 1));
return cellValue.toByteArray()[0] != 0;
case BYTE:
... | @Test
public void shouldFailParseFloatTypeTooLong() {
byte[] value = new byte[10];
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> PARSER.getCellValue(cell(value), FLOAT));
checkMessage(exception.getMessage(), "Float has to be 4-bytes long bytearray");
} |
@Override
public NativeEntity<PipelineDao> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() throws NotFoundException {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.PIPELINE_V1)
.data(objectMapper.convertValue(PipelineEntity.create(
ValueReference.of("Titl... |
public static String getDatabaseRuleActiveVersionNode(final String databaseName, final String ruleName, final String key) {
return String.join("/", getDatabaseRuleNode(databaseName, ruleName), key, ACTIVE_VERSION);
} | @Test
void assertGetDatabaseRuleActiveVersionNode() {
assertThat(DatabaseRuleMetaDataNode.getDatabaseRuleActiveVersionNode("foo_db", "foo_rule", "foo_tables"), is("/metadata/foo_db/rules/foo_rule/foo_tables/active_version"));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.