focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public QueryBuilder createQueryFilter() {
BoolQueryBuilder filter = boolQuery();
// anyone
filter.should(QueryBuilders.termQuery(FIELD_ALLOW_ANYONE, true));
// users
Optional.ofNullable(userSession.getUuid())
.ifPresent(uuid -> filter.should(termQuery(FIELD_USER_IDS, uuid)));
// groups
... | @Test
public void createQueryFilter_sets_filter_on_anyone_and_user_id_and_group_ids_if_user_is_logged_in_and_has_groups() {
GroupDto group1 = GroupTesting.newGroupDto().setUuid("10");
GroupDto group2 = GroupTesting.newGroupDto().setUuid("11");
UserDto userDto = UserTesting.newUserDto();
userSession.lo... |
public void onEvent(ServiceInstancesChangedEvent event) {
if (destroyed.get() || !accept(event) || isRetryAndExpired(event)) {
return;
}
doOnEvent(event);
} | @Test
@Order(12)
public void testInstanceWithoutRevision() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add("app1");
ServiceDiscovery serviceDiscovery = Mockito.mock(ServiceDiscovery.class);
listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscove... |
public boolean isEmpty() {
return resources.isEmpty();
} | @Test
void testIsEmpty() {
final ResourceCounter empty = ResourceCounter.empty();
assertThat(empty.isEmpty()).isTrue();
} |
@Override
public RedisClusterNode clusterGetNodeForKey(byte[] key) {
int slot = executorService.getConnectionManager().calcSlot(key);
return clusterGetNodeForSlot(slot);
} | @Test
public void testClusterGetNodeForKey() {
RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes());
assertThat(node).isNotNull();
} |
@Override
public String toString() {
return "AfterPane.elementCountAtLeast(" + countElems + ")";
} | @Test
public void testToString() {
Trigger trigger = AfterPane.elementCountAtLeast(5);
assertEquals("AfterPane.elementCountAtLeast(5)", trigger.toString());
} |
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments(
final MethodCallExpr methodExpression,
final MvelCompilerContext mvelCompilerContext,
final Optional<TypedExpression> scope,
List<TypedExpression> arguments,
... | @Test
public void resolveMethodWithEmptyCollectionArgumentsCoerceList() {
final MethodCallExpr methodExpression = new MethodCallExpr("setAddresses", new MapCreationLiteralExpression(null, NodeList.nodeList()));
final List<TypedExpression> arguments = new ArrayList<>();
arguments.add(new MapE... |
@JsonIgnore
public Map<WorkflowInstance.Status, List<Long>> flatten(
Predicate<WorkflowInstance.Status> condition) {
return info.entrySet().stream()
.filter(e -> condition.test(e.getKey()))
.collect(
Collectors.toMap(
Map.Entry::getKey,
e -> {
... | @Test
public void testFlatten() throws Exception {
TestDetails testDetails =
loadObject("fixtures/instances/sample-foreach-details.json", TestDetails.class);
Map<WorkflowInstance.Status, List<Long>> flatten = testDetails.test1.flatten(e -> true);
assertEquals(Collections.singletonList(1L), flatten... |
public boolean transitionToFailed(Throwable throwable)
{
// When the state enters FINISHING, the only thing remaining is to commit
// the transaction. It should only be failed if the transaction commit fails.
return transitionToFailed(throwable, currentState -> currentState != FINISHING && !... | @Test
public void testFailed()
{
QueryStateMachine stateMachine = createQueryStateMachine();
assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE));
assertFinalState(stateMachine, FAILED, FAILED_CAUSE);
} |
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
public void changeLevel_fails_with_IAE_when_level_is_ERROR() {
assertThatThrownBy(() -> underTest.changeLevel(ERROR))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("ERROR log level is not supported (allowed levels are [TRACE, DEBUG, INFO])");
} |
@Override
public ImportResult importItem(UUID jobId, IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData, MediaContainerResource resource) throws Exception {
// Ensure credential is populated
getOrCreateCredential(authData);
logDebugJobStatus("%s before transmogrificati... | @Test
public void testImportItemAllSuccess() throws Exception {
List<MediaAlbum> albums =
ImmutableList.of(new MediaAlbum("id1", "albumb1", "This is a fake albumb"));
List<PhotoModel> photos = ImmutableList.of(
new PhotoModel("Pic1", "http://fake.com/1.jpg", "A pic", "image/jpg", "p1", "id1",... |
private EntityRelation doDelete(String strFromId, String strFromType, String strRelationType, String strRelationTypeGroup, String strToId, String strToType) throws ThingsboardException {
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
checkParameter(RELATION_TYPE, str... | @Test
public void testDeleteRelationWithOtherToDeviceError() throws Exception {
Device device = buildSimpleDevice("Test device 1");
EntityRelation relation = createFromRelation(mainDevice, device, "CONTAINS");
doPost("/api/relation", relation).andExpect(status().isOk());
Device dev... |
public PageListResponse<IndexSetFieldType> getIndexSetFieldTypesListPage(
final String indexSetId,
final String fieldNameQuery,
final List<String> filters,
final int page,
final int perPage,
final String sort,
final Sorting.Direction or... | @Test
void testReturnsEmptyPageIfCannotCreateIndexSetFromConfig() {
IndexSetConfig indexSetConfig = mock(IndexSetConfig.class);
doReturn(Optional.of(indexSetConfig)).when(indexSetService).get("I_am_strangely_broken!");
doReturn(new CustomFieldMappings()).when(indexSetConfig).customFieldMappi... |
@Override
public int compareTo( MonetDbVersion mDbVersion ) {
int result = majorVersion.compareTo( mDbVersion.majorVersion );
if ( result != 0 ) {
return result;
}
result = minorVersion.compareTo( mDbVersion.minorVersion );
if ( result != 0 ) {
return result;
}
result = patch... | @Test
public void testCompareVersions_TheSame() throws Exception {
String dbVersionBigger = "11.11.7";
String dbVersion = "11.11.7";
assertEquals( 0, new MonetDbVersion( dbVersionBigger ).compareTo( new MonetDbVersion( dbVersion ) ) );
} |
public DirectoryEntry lookUp(
File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
DirectoryEntry result = lookUp(workingDirectory, path, options, 0);
if (result == null) {
// an intermediate file in the path... | @Test
public void testLookup_absolute_withDotDotsInPath() throws IOException {
assertExists(lookup("/.."), "/", "/");
assertExists(lookup("/../../.."), "/", "/");
assertExists(lookup("/work/.."), "/", "/");
assertExists(lookup("/work/../work/one/two/../two/three"), "two", "three");
assertExists(lo... |
@Override
public void setRuntimeContext(RuntimeContext runtimeContext) {
Preconditions.checkNotNull(runtimeContext);
if (runtimeContext instanceof IterationRuntimeContext) {
super.setRuntimeContext(
new RichAsyncFunctionIterationRuntimeContext(
... | @Test
void testRuntimeContext() {
RichAsyncFunction<Integer, Integer> function =
new RichAsyncFunction<Integer, Integer>() {
private static final long serialVersionUID = 1707630162838967972L;
@Override
public void asyncInvoke(Integ... |
@Override
public Server build(Environment environment) {
printBanner(environment.getName());
final ThreadPool threadPool = createThreadPool(environment.metrics());
final Server server = buildServer(environment.lifecycle(), threadPool);
final Handler applicationHandler = createAppServ... | @Test
void configuresDumpBeforeExit() {
http.setDumpBeforeStop(true);
assertThat(http.build(environment).isDumpBeforeStop()).isTrue();
} |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void use_contains_instead_of_contains_equiv_when_input_size_is_1() {
String q = Q.p("f1").containsEquiv(List.of("p1"))
.build();
assertEquals(q, "yql=select * from sources * where f1 contains \"p1\"");
} |
@Override
public void startLeaderElection(LeaderContender contender) throws Exception {
synchronized (lock) {
Preconditions.checkState(
leaderContender == null,
"No LeaderContender should have been registered with this LeaderElection, yet.");
t... | @Test
void testRevokeCallOnClose() throws Exception {
final AtomicBoolean revokeLeadershipCalled = new AtomicBoolean(false);
final TestingGenericLeaderContender contender =
TestingGenericLeaderContender.newBuilder()
.setRevokeLeadershipRunnable(() -> revokeLea... |
@Override
public void add(Component component, Metric metric, Measure measure) {
requireNonNull(component);
checkValueTypeConsistency(metric, measure);
Optional<Measure> existingMeasure = find(component, metric);
if (existingMeasure.isPresent()) {
throw new UnsupportedOperationException(
... | @Test
public void add_throws_NPE_if_Component_argument_is_null() {
assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE))
.isInstanceOf(NullPointerException.class);
} |
@Override
public String arguments() {
ArrayList<String> args = new ArrayList<>();
if (buildFile != null) {
args.add("-f \"" + FilenameUtils.separatorsToUnix(buildFile) + "\"");
}
if (target != null) {
args.add(target);
}
return StringUtils.jo... | @Test
public void shouldContainBuildFileAndTargetWhenBothDefined() throws Exception {
RakeTask rakeTask = new RakeTask();
rakeTask.setBuildFile("myrakefile.rb");
rakeTask.setTarget("db:migrate VERSION=0");
assertThat(rakeTask.arguments(), is("-f \"myrakefile.rb\" db:migrate VERSION=0... |
public static SegmentAssignmentStrategy getSegmentAssignmentStrategy(HelixManager helixManager,
TableConfig tableConfig, String assignmentType, InstancePartitions instancePartitions) {
String assignmentStrategy = null;
TableType currentTableType = tableConfig.getTableType();
// TODO: Handle segment a... | @Test
public void testSegmentAssignmentStrategyForDimTable() {
TableConfig tableConfig =
new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).setIsDimTable(true).build();
SegmentAssignmentStrategy segmentAssignmentStrategy = SegmentAssignmentStrategyFactory
.getSegmentAssignm... |
public static Schema schemaFromJavaBeanClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedMap() {
Schema schema =
JavaBeanUtils.schemaFromJavaBeanClass(
new TypeDescriptor<NestedMapBean>() {}, GetterTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_MAP_BEAN_SCHEMA, schema);
} |
@Override
public Job getJobById(UUID id) {
try (final Connection conn = dataSource.getConnection()) {
return jobTable(conn)
.selectJobById(id)
.orElseThrow(() -> new JobNotFoundException(id));
} catch (SQLException e) {
throw new Storag... | @Test
void testGetJobById() throws SQLException {
when(resultSet.next()).thenReturn(false);
assertThatThrownBy(() -> jobStorageProvider.getJobById(randomUUID())).isInstanceOf(JobNotFoundException.class);
} |
@Override
public Collection<Process> getProcessList() {
String taskId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString().replace("-", "");
Collection<String> triggerPaths = getShowProcessListTriggerPaths(taskId);
boolean isCompleted = false;... | @Test
void assertGetProcessList() {
when(repository.getChildrenKeys(ComputeNode.getOnlineNodePath(InstanceType.JDBC))).thenReturn(Collections.emptyList());
when(repository.getChildrenKeys(ComputeNode.getOnlineNodePath(InstanceType.PROXY))).thenReturn(Collections.singletonList("abc"));
when(r... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void name_with_spaces_is_preserved() {
RuntimeOptions options = parser
.parse("--name", "some Name")
.build();
Pattern actualPattern = options.getNameFilters().iterator().next();
assertThat(actualPattern.pattern(), is("some Name"));
} |
@Override
public GroupingShuffleReaderIterator<K, V> iterator() throws IOException {
ApplianceShuffleEntryReader entryReader =
new ApplianceShuffleEntryReader(
shuffleReaderConfig, executionContext, operationContext, true);
initCounter(entryReader.getDatasetId());
return iterator(ent... | @Test
public void testShuffleReadCounterMultipleExecutingSteps() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
options
.as(DataflowPipelineDebugOptions.class)
.setExperiments(Lists.newArrayList(Experiment.IntertransformIO.getName()));
BatchModeExecutionConte... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("eue.listing.chunksize"));
} | @Test
public void testListForSharedFolder() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), ... |
public static long estimateSize(StructType tableSchema, long totalRecords) {
if (totalRecords == Long.MAX_VALUE) {
return totalRecords;
}
long result;
try {
result = LongMath.checkedMultiply(tableSchema.defaultSize(), totalRecords);
} catch (ArithmeticException e) {
result = Long.... | @Test
public void testEstimateSize() throws IOException {
long tableSize = SparkSchemaUtil.estimateSize(SparkSchemaUtil.convert(TEST_SCHEMA), 1);
assertThat(tableSize).as("estimateSize matches with expected approximation").isEqualTo(24);
} |
@SuppressWarnings("unchecked")
public static void validateResponse(HttpURLConnection conn,
int expectedStatus) throws IOException {
if (conn.getResponseCode() != expectedStatus) {
Exception toThrow;
InputStream es = null;
try {
es = conn.getErrorStream();
Map json = JsonSer... | @Test
public void testValidateResponseJsonErrorUnknownException()
throws Exception {
Map<String, Object> json = new HashMap<String, Object>();
json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "FooException");
json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, "foo.FooException");
json.put(HttpEx... |
public MultiMap<Value, T, List<T>> get(final KeyDefinition keyDefinition) {
return tree.get(keyDefinition);
} | @Test
void testUpdateAge() throws Exception {
final MultiMapChangeHandler changeHandler = mock(MultiMapChangeHandler.class);
map.get(AGE).addChangeListener(changeHandler);
toni.setAge(10);
final MultiMap<Value, Person, List<Person>> age = map.get(AGE);
assertThat(age.get(n... |
public String get(String key) {
return properties.getProperty(key);
} | @Test(expected = NullPointerException.class)
public void testGet_whenKeyNull() {
HazelcastProperties properties = new HazelcastProperties(config);
properties.get(null);
} |
public static Map<String, Map<String, String>> rebalanceReplicaGroupBasedTable(
Map<String, Map<String, String>> currentAssignment, InstancePartitions instancePartitions,
Map<Integer, List<String>> instancePartitionIdToSegmentsMap) {
Map<String, Map<String, String>> newAssignment = new TreeMap<>();
... | @Test
public void testRebalanceReplicaGroupBasedTable() {
// Table is rebalanced on a per partition basis, so testing rebalancing one partition is enough
int numSegments = 90;
List<String> segments = SegmentAssignmentTestUtils.getNameList(SEGMENT_NAME_PREFIX, numSegments);
Map<Integer, List<String>> ... |
@Override
public <T> Future<T> submit(Callable<T> task) {
final RunnableFuture<T> rf = new CompletableFutureTask<>(task);
execute(rf);
return rf;
} | @Test
public void submitRunnable_withResult() throws Exception {
final int taskCount = 10;
ManagedExecutorService executorService = newManagedExecutorService(1, taskCount);
final String result = randomString();
Future[] futures = new Future[taskCount];
for (int i = 0; i < ta... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void cluster_not_down_if_more_than_min_count_of_distributors_are_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN);
final ClusterStateGenerator.Params params = fixture... |
@Override
public ServerConfiguration getServerConfiguration(String issuer) {
return servers.get(issuer);
} | @Test
public void getClientConfiguration_noIssuer() {
ServerConfiguration result = service.getServerConfiguration("www.badexample.net");
assertThat(result, is(nullValue()));
} |
public static void main(String[] args) {
if (args.length < 1 || args[0].equals("-h") || args[0].equals("--help")) {
System.out.println(usage);
return;
}
// Copy args, because CommandFormat mutates the list.
List<String> argsList = new ArrayList<String>(Arrays.asList(args));
CommandForma... | @Test
public void testGlob() {
Classpath.main(new String[] { "--glob" });
String strOut = new String(stdout.toByteArray(), UTF8);
assertEquals(System.getProperty("java.class.path"), strOut.trim());
assertTrue(stderr.toByteArray().length == 0);
} |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_with_valueFunction_parallel_stream() {
SetMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(unorderedFlattenIndex(identity(), Stream::of));
assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
} |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty()) {
return new GroupAssignment(Collections.emptyMap());
} else if (groupSpec.subscr... | @Test
public void testReassignmentWhenOnePartitionAddedForTwoMembersTwoTopics() {
// Simulating adding a partition - originally T1 -> 3 Partitions and T2 -> 3 Partitions
Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>();
topicMetadata.put(topic1Uuid, new TopicMetadata(
top... |
static boolean isValidIpEntity(String ip) {
if (ip == null) return true;
try {
InetAddress.getByName(ip);
return true;
} catch (UnknownHostException e) {
return false;
}
} | @Test
public void testIsValidIpEntityWithNull() {
assertTrue(ClientQuotaControlManager.isValidIpEntity(null));
} |
@SuppressWarnings("MethodLength")
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header)
{
messageHeaderDecoder.wrap(buffer, offset);
final int templateId = messageHeaderDecoder.templateId();
final int schemaId = messageHeaderDecoder.s... | @Test
void onFragmentShouldDelegateToEgressListenerOnUnknownSchemaId()
{
final int schemaId = 17;
final int templateId = 19;
messageHeaderEncoder
.wrap(buffer, 0)
.schemaId(schemaId)
.templateId(templateId);
final EgressListenerExtension liste... |
@Override
public void deleteSource(final SourceName sourceName, final boolean restoreInProgress) {
synchronized (metaStoreLock) {
dataSources.compute(sourceName, (ignored, sourceInfo) -> {
if (sourceInfo == null) {
throw new KsqlException(String.format("No data source with name %s exists."... | @Test
public void shouldThrowOnRemoveUnknownSource() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> metaStore.deleteSource(of("bob"))
);
// Then:
assertThat(e.getMessage(), containsString("No data source with name bob exists"));
} |
@Override
public ColumnStatistics buildColumnStatistics()
{
Optional<BinaryStatistics> binaryStatistics = buildBinaryStatistics();
if (binaryStatistics.isPresent()) {
verify(nonNullValueCount > 0);
return new BinaryColumnStatistics(nonNullValueCount, null, rawSize, storag... | @Test
public void testBlockBinaryStatistics()
{
String alphabets = "abcdefghijklmnopqrstuvwxyz";
VariableWidthBlockBuilder blockBuilder = new VariableWidthBlockBuilder(null, alphabets.length(), alphabets.length());
Slice slice = utf8Slice(alphabets);
for (int i = 0; i < slice.len... |
@Override
public Optional<NativeEntity<EventDefinitionDto>> loadNativeEntity(NativeEntityDescriptor nativeEntityDescriptor) {
final Optional<EventDefinitionDto> eventDefinition = eventDefinitionService.get(nativeEntityDescriptor.id().id());
return eventDefinition.map(eventDefinitionDto ->
... | @Test
@MongoDBFixtures("EventDefinitionFacadeTest.json")
public void loadNativeEntity() {
final NativeEntityDescriptor nativeEntityDescriptor = NativeEntityDescriptor
.create(ModelId.of("content-pack-id"),
ModelId.of("5d4032513d2746703d1467f6"),
... |
@Udf(description = "Returns all substrings of the input that matches the given regex pattern")
public List<String> regexpExtractAll(
@UdfParameter(description = "The regex pattern") final String pattern,
@UdfParameter(description = "The input string to apply regex on") final String input
) {
return ... | @Test
public void shouldReturnSubstringWhenMatched() {
assertThat(udf.regexpExtractAll("e.*", "test string"), contains("est string"));
assertThat(udf.regexpExtractAll(".", "test"), contains("t", "e", "s", "t"));
assertThat(udf.regexpExtractAll("[AEIOU].{4}", "usEr nAmE 1308"), contains("Er nA", "E 130"));... |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_UINT8() {
final MutableData data = new MutableData(new byte[1]);
data.setValue(200, Data.FORMAT_UINT8, 0);
assertArrayEquals(new byte[] { (byte) 0xC8 } , data.getValue());
} |
public void unzip(ZipInputStream zipInputStream, File destDir) throws IOException {
try(ZipInputStream zis = zipInputStream) {
destDir.mkdirs();
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
extractTo(zipEntry, zis, destDir);
... | @Test
void shouldThrowUpWhileTryingToUnzipIfAnyOfTheFilePathsInArchiveHasAPathContainingDotDotSlashPath() throws URISyntaxException, IOException {
try {
zipUtil.unzip(new File(getClass().getResource("/archive_traversal_attack.zip").toURI()), destDir);
fail("squash.zip is capable of c... |
public static <T> Iterables<T> iterables() {
return new Iterables<>();
} | @Test
@Category(ValidatesRunner.class)
public void testFlattenIterablesSets() {
Set<String> linesSet = ImmutableSet.copyOf(LINES);
PCollection<Set<String>> input =
p.apply(Create.<Set<String>>of(linesSet).withCoder(SetCoder.of(StringUtf8Coder.of())));
PCollection<String> output = input.apply(F... |
private int deregisterSubCluster(String subClusterId)
throws IOException, YarnException {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
System.out, StandardCharsets.UTF_8));
ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol();
DeregisterSubClusterRequest ... | @Test
public void testDeregisterSubCluster() throws Exception {
PrintStream oldOutPrintStream = System.out;
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(dataOut));
oldOutPrintStream.println(dataOut);
String[] args = {"-deregisterSubCluster", "-sc", "SC... |
public static String extractCharset(String line, String defaultValue) {
if (line == null) {
return defaultValue;
}
final String[] parts = line.split(" ");
String charsetInfo = "";
for (var part : parts) {
if (part.startsWith("charset")) {
... | @DisplayName("null charset information")
@Test
void testExtractCharsetNull() {
assertEquals("UTF-8", TelegramAsyncHandler.extractCharset(null, StandardCharsets.UTF_8.name()));
} |
public abstract HashMap<Integer, T_Sess> loadAllRawSessionsOf(OmemoDevice userDevice, BareJid contact) throws IOException; | @Test
public void loadAllRawSessionsReturnsEmptyMapTest() throws IOException {
HashMap<Integer, T_Sess> sessions = store.loadAllRawSessionsOf(alice, bob.getJid());
assertNotNull(sessions);
assertEquals(0, sessions.size());
} |
boolean isSignRequestsEnabled() {
return configuration.getBoolean(SIGN_REQUESTS_ENABLED).orElse(false);
} | @Test
public void is_sign_requests_enabled() {
settings.setProperty("sonar.auth.saml.signature.enabled", true);
assertThat(underTest.isSignRequestsEnabled()).isTrue();
settings.setProperty("sonar.auth.saml.signature.enabled", false);
assertThat(underTest.isSignRequestsEnabled()).isFalse();
} |
public String kv2String(String k, Object v) {
this.kvs.put(k, v == null ? "" : v);
return toString();
} | @Test
public void testKv2StringShouldPrintMessageAndAllKeyAndValuePairs() {
String result = logMessage.kv2String("key", "value");
assertEquals("key=value", result);
} |
public static void removeMatching(Collection<String> values,
String... patterns) {
removeMatching(values, Arrays.asList(patterns));
} | @Test
public void testRemoveMatchingWithMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values, "A");
assertTrue(values.isEmpty());
} |
@Override
public String decrypt(String encryptedText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decodeBase64(StringUtils.trim(encryptedText)));
byte[] iv = new byte[GCM_IV_LENGTH_IN_BYTES];
byteBuffer.g... | @Test
public void decrypt() throws Exception {
AesGCMCipher cipher = new AesGCMCipher(pathToSecretKey());
String input1 = "this is a secret";
String input2 = "asdkfja;ksldjfowiaqueropijadfskncmnv/sdjflskjdflkjiqoeuwroiqu./qewirouasoidfhjaskldfhjkhckjnkiuoewiruoasdjkfalkufoiwueroijuqwoerjsdkjflweoiru";
... |
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String mainBranchUuid,
String defaultBranchName, String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) {
boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent()... | @Test
public void createNewCodeDefinition_throw_IAE_if_previous_version_type_and_value_provided() {
assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH_UUID, MAIN_BRANCH, PREVIOUS_VERSION.name(), "10.2.3"))
.isInstanceOf(IllegalArgumentExcept... |
public void setContentType(byte[] contentType) {
this.contentType = contentType;
} | @Test
public void testSetContentType() {
restValue.setContentType(PAYLOAD);
assertEquals(PAYLOAD, restValue.getContentType());
assertContains(restValue.toString(), "contentType='" + new String(PAYLOAD, StandardCharsets.UTF_8));
} |
@Override
public final void isEqualTo(@Nullable Object other) {
if (Objects.equal(actual, other)) {
return;
}
// Fail but with a more descriptive message:
if (actual == null || !(other instanceof Map)) {
super.isEqualTo(other);
return;
}
containsEntriesInAnyOrder((Map<?, ?... | @Test
public void isEqualToNotConsistentWithEquals() {
TreeMap<String, Integer> actual = new TreeMap<>(CASE_INSENSITIVE_ORDER);
TreeMap<String, Integer> expected = new TreeMap<>(CASE_INSENSITIVE_ORDER);
actual.put("one", 1);
expected.put("ONE", 1);
/*
* Our contract doesn't guarantee that the... |
@Override
public Serde<List<?>> getSerde(
final PersistenceSchema schema,
final Map<String, String> formatProperties,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final boolean isKey) {
FormatProperties.validateProperties(name(), formatProperties... | @Test
public void shouldThrowOnColumns() {
// Given:
when(schema.columns()).thenReturn(ImmutableList.of(column));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> format.getSerde(schema, formatProps, ksqlConfig, srClientFactory, false)
);
// Then:
ass... |
@Override
public void execute(Exchange exchange) throws SmppException {
CancelSm cancelSm = createCancelSm(exchange);
if (log.isDebugEnabled()) {
log.debug("Canceling a short message for exchange id '{}' and message id '{}'",
exchange.getExchangeId(), cancelSm.getMes... | @Test
public void executeWithConfigurationData() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "CancelSm");
exchange.getIn().setHeader(SmppConstants.ID, "1");
command.ex... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComStmtFetchPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_STMT_FETCH, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testMultimapEntriesAndKeysMergeLocalAdd() {
final String tag = "multimap";
StateTag<MultimapState<byte[], Integer>> addr =
StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of());
MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr);
final b... |
public void prepareFieldNamesParameters( String[] parameters, String[] parameterFieldNames, String[] parameterValues,
NamedParams namedParam, JobEntryTrans jobEntryTrans )
throws UnknownParamException {
for ( int idx = 0; idx < parameters.length; idx++ ) {
... | @Test
public void testPrepareFieldNamesParametersWithNulls() throws UnknownParamException {
//NOTE: this only tests the prepareFieldNamesParameters function not all variable substitution logic
// array of params
String[] parameterNames = new String[7];
parameterNames[0] = "param1";
parameterNames[... |
@PostMapping("/refresh-token")
public CustomResponse<TokenResponse> refreshToken(@RequestBody @Valid final TokenRefreshRequest tokenRefreshRequest) {
return refreshTokenService.refreshToken(tokenRefreshRequest);
} | @Test
void refreshToken_ValidRequest_ReturnsTokenResponse() throws Exception {
// Given
TokenRefreshRequest tokenRefreshRequest = TokenRefreshRequest.builder()
.refreshToken("validRefreshToken")
.build();
TokenResponse tokenResponse = TokenResponse.builder()... |
static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) {
while (messageCount < maxMessages || maxMessages == -1) {
ConsumerRecord<byte[], byte[]> msg;
try {
msg = consumer.receive();
... | @Test
public void shouldStopWhenOutputCheckErrorFails() {
ConsoleConsumer.ConsumerWrapper consumer = mock(ConsoleConsumer.ConsumerWrapper.class);
MessageFormatter formatter = mock(MessageFormatter.class);
PrintStream printStream = mock(PrintStream.class);
ConsumerRecord<byte[], byte... |
public void run(OutputReceiver<PartitionRecord> receiver) throws InvalidProtocolBufferException {
// Erase any existing missing partitions.
metadataTableDao.writeDetectNewPartitionMissingPartitions(new HashMap<>());
List<PartitionRecord> partitions = metadataTableDao.readAllStreamPartitions();
for (Pa... | @Test
public void testOutputNewPartitions() throws InvalidProtocolBufferException {
ByteStringRange partition1 = ByteStringRange.create("A", "B");
ChangeStreamContinuationToken token1 =
ChangeStreamContinuationToken.create(partition1, "tokenAB");
Instant watermark1 = Instant.now().minus(Duration.s... |
public static <InputT, OutputT> PTransform<PCollection<InputT>, PCollection<OutputT>> to(
Class<OutputT> clazz) {
return to(TypeDescriptor.of(clazz));
} | @Test
@Category(NeedsRunner.class)
public void testFromRowsUnboxingPrimitive() {
PCollection<Long> longs =
pipeline
.apply(Create.of(new POJO1()))
.apply(Select.fieldNames("field2"))
.apply(Convert.to(TypeDescriptors.longs()));
PAssert.that(longs).containsInAnyOrd... |
private boolean needBrokerDataUpdate() {
final long updateMaxIntervalMillis = TimeUnit.MINUTES
.toMillis(conf.getLoadBalancerReportUpdateMaxIntervalMinutes());
long timeSinceLastReportWrittenToStore = System.currentTimeMillis() - localData.getLastUpdate();
if (timeSinceLastReport... | @Test
public void testNeedBrokerDataUpdate() throws Exception {
final LocalBrokerData lastData = new LocalBrokerData();
final LocalBrokerData currentData = new LocalBrokerData();
final ServiceConfiguration conf = pulsar1.getConfiguration();
// Set this manually in case the default ch... |
void logRun(long runIndex, boolean runSucceeded, Duration pollInterval, Instant runStartTime, Instant runEndTime) {
if (runSucceeded && exceptionCounter > 0) {
--exceptionCounter;
}
Duration actualRunDuration = Duration.between(runStartTime, runEndTime);
if (actualRunDuration... | @Test
void ifThreeNotConsecutiveRunsTookTooLongNoNotificationIsShown() {
statistics.logRun(2, true, pollInterval, now().minusSeconds(45), now().minusSeconds(30));
statistics.logRun(3, true, pollInterval, now().minusSeconds(30), now().minusSeconds(15));
statistics.logRun(4, true, pollInterval... |
public static void retryWithBackoff(
final int maxRetries,
final int initialWaitMs,
final int maxWaitMs,
final Runnable runnable,
final Class<?>... passThroughExceptions) {
retryWithBackoff(
maxRetries,
initialWaitMs,
maxWaitMs,
runnable,
() -> f... | @Test
public void shouldThrowPassThroughExceptions() {
doThrow(new IllegalArgumentException("error")).when(runnable).run();
try {
RetryUtil.retryWithBackoff(3, 1, 3, runnable, IllegalArgumentException.class);
fail("retry should have thrown");
} catch (final IllegalArgumentException e) {
}
... |
public static File createTmpFile(String dir, String prefix, String suffix) throws IOException {
return Files.createTempFile(Paths.get(dir), prefix, suffix).toFile();
} | @Test
void testCreateTmpFileWithPath() throws IOException {
File tmpFile = null;
try {
tmpFile = DiskUtils.createTmpFile(EnvUtil.getNacosTmpDir(), "nacos1", ".ut");
assertEquals(EnvUtil.getNacosTmpDir(), tmpFile.getParent());
assertTrue(tmpFile.getName().startsWit... |
boolean isUpstreamDefinite() {
if (upstreamDefinite == null) {
upstreamDefinite = isRoot() || prev.isTokenDefinite() && prev.isUpstreamDefinite();
}
return upstreamDefinite;
} | @Test
public void is_upstream_definite_in_simple_case() {
assertThat(makePathReturningTail(makePPT("foo")).isUpstreamDefinite()).isTrue();
assertThat(makePathReturningTail(makePPT("foo"), makePPT("bar")).isUpstreamDefinite()).isTrue();
assertThat(makePathReturningTail(makePPT("foo", "foo2"... |
public <T> void addStoreLevelMutableMetric(final String taskId,
final String metricsScope,
final String storeName,
final String name,
... | @Test
public void shouldNotAddStoreLevelMutableMetricIfAlreadyExists() {
final Metrics metrics = mock(Metrics.class);
final MetricName metricName =
new MetricName(METRIC_NAME1, STATE_STORE_LEVEL_GROUP, DESCRIPTION1, STORE_LEVEL_TAG_MAP);
when(metrics.metricName(METRIC_NAME1, STAT... |
public static Optional<String> getRuleName(final String rulePath) {
Pattern pattern = Pattern.compile(getRuleNameNode() + "/(\\w+)" + ACTIVE_VERSION_SUFFIX, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(rulePath);
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.em... | @Test
void assertGetRuleNameWhenNotFound() {
Optional<String> actual = GlobalNodePath.getRuleName("/invalid/transaction/active_version");
assertFalse(actual.isPresent());
} |
public List<Entity> query(String gqlQuery) {
try {
QueryResults<Entity> queryResults =
datastore.run(
GqlQuery.newGqlQueryBuilder(ResultType.ENTITY, gqlQuery)
.setNamespace(namespace)
.build());
List<Entity> entities = new ArrayList<>();
... | @Test
public void testQuery() {
// Prepare test data
String gqlQuery = "SELECT * FROM test_kind";
// Mock the Datastore run method
QueryResults<Entity> mockResult = mock(QueryResults.class);
Entity mockEntity = mock(Entity.class);
when(datastoreMock.run(any(GqlQuery.class))).thenReturn(mockRe... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatDecimalLiteral() {
assertThat(ExpressionFormatter.formatExpression(new DecimalLiteral(new BigDecimal("3.5"))), equalTo("3.5"));
} |
public static List<List<GtfsStorage.FeedIdWithStopId>> findStronglyConnectedComponentsOfStopGraph(PtGraph ptGraph) {
PtGraphAsAdjacencyList ptGraphAsAdjacencyList = new PtGraphAsAdjacencyList(ptGraph);
TarjanSCC.ConnectedComponents components = TarjanSCC.findComponents(ptGraphAsAdjacencyList, EdgeFilter... | @Test
public void testStronglyConnectedComponentsOfStopGraph() {
PtGraph ptGraph = graphHopperGtfs.getPtGraph();
List<List<GtfsStorage.FeedIdWithStopId>> stronglyConnectedComponentsOfStopGraph = Analysis.findStronglyConnectedComponentsOfStopGraph(ptGraph);
List<GtfsStorage.FeedIdWithStopId> ... |
public Map<String, String> parse(String body) {
final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder();
final String[] lines = body.split(lineSeparator);
for (String line : lines) {
if (line.startsWith(this.ignorechar)) {
continue;
... | @Test
public void parseFileWithSwappedColumns() throws Exception {
final String input = "# Sample file for testing\n" +
"foo:23\n" +
"bar:42\n" +
"baz:17";
final DSVParser dsvParser = new DSVParser("#", "\n", ":", "", false, false, 1, Optional.of(0));
... |
static public int facilityStringToint(String facilityStr) {
if ("KERN".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_KERN;
} else if ("USER".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_USER;
} else if ("MAIL".equalsIgnoreCase(facilityStr)) {
return SyslogConst... | @Test
public void testFacilityStringToint() throws InterruptedException
{
assertEquals(SyslogConstants.LOG_KERN, SyslogAppenderBase.facilityStringToint("KERN"));
assertEquals(SyslogConstants.LOG_USER, SyslogAppenderBase.facilityStringToint("USER"));
assertEquals(SyslogConstants.LOG_MAIL, SyslogAppenderB... |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_mcc_upperCase() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("MCC310", config);
assertThat(config.mcc).isEqualTo(310);
} |
public static void hookPendingIntentGetBroadcast(PendingIntent pendingIntent, Context context, int requestCode, Intent intent, int flags) {
hookPendingIntent(intent, pendingIntent);
} | @Test
public void hookPendingIntentGetBroadcast() {
PushAutoTrackHelper.hookPendingIntentGetBroadcast(MockDataTest.mockPendingIntent(), mApplication, 100, MockDataTest.mockJPushIntent(), 100);
} |
@VisibleForTesting
V1StatefulSet createStatefulSet() {
final String jobName = createJobName(instanceConfig.getFunctionDetails(), this.jobName);
final V1StatefulSet statefulSet = new V1StatefulSet();
// setup stateful set metadata
final V1ObjectMeta objectMeta = new V1ObjectMeta();
... | @Test
public void testCustomKubernetesDownloadCommandsWithAuthWithoutAuthSpec() throws Exception {
InstanceConfig config = createJavaInstanceConfig(FunctionDetails.Runtime.JAVA, false);
config.setFunctionDetails(createFunctionDetails(FunctionDetails.Runtime.JAVA, false));
factory = createKu... |
@Nonnull
public InstanceConfig setBackupCount(int newBackupCount) {
checkBackupCount(newBackupCount, 0);
this.backupCount = newBackupCount;
return this;
} | @Test
public void when_TooBigBackupCount_thenThrowsException() {
// When
InstanceConfig instanceConfig = new InstanceConfig();
// Then
Assert.assertThrows(IllegalArgumentException.class, () -> instanceConfig.setBackupCount(10));
} |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Deserialization parameters
Object[] a = new Object[length];
for (int i = 0; i < length; i++) {
a[i] = s.readObject();
}
this.parameters = a;
... | @Test
public void testReadObject() throws IOException, ClassNotFoundException {
Object[] parameters = new Object[1];
parameters[0] = hippo4j;
Request request = new DefaultRequest(rid, name, parameters);
byte[] bytes;
try (
ByteArrayOutputStream byteArrayOutput... |
@Override
public void error(String msg) {
logger.error(msg);
} | @Test
public void testError() {
Log mockLog = mock(Log.class);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
logger.error("a");
verify(mockLog).error("a");
} |
@SafeVarargs
public static <T> Stream<T> of(T... array) {
Assert.notNull(array, "Array must be not null!");
return Stream.of(array);
} | @Test
public void streamTestEmptyIterator() {
assertStreamIsEmpty(StreamUtil.of(Collections.emptyIterator()));
} |
public static List<ByteBuffer> cloneByteBufferList(List<ByteBuffer> source) {
List<ByteBuffer> ret = new ArrayList<>(source.size());
for (ByteBuffer b : source) {
ret.add(cloneByteBuffer(b));
}
return ret;
} | @Test
public void cloneDirectByteBufferList() {
final int bufferSize = 10;
final int listLength = 10;
ArrayList<ByteBuffer> bufDirectList = new ArrayList<>(listLength);
for (int k = 0; k < listLength; k++) {
ByteBuffer bufDirect = ByteBuffer.allocateDirect(bufferSize);
for (byte i = 0; i <... |
public static String substVars(String val, PropertyContainer pc1) throws ScanException {
return substVars(val, pc1, null);
} | @Test
public void openBraceAsLastCharacter() throws JoranException, ScanException {
Exception e = assertThrows(IllegalArgumentException.class, () -> {
OptionHelper.substVars("a{a{", context);
});
String expectedMessage = "All tokens consumed but was expecting \"}\"";
asse... |
public AstNode rewrite(final AstNode node, final C context) {
return rewriter.process(node, context);
} | @Test
public void shouldRewriteGroupBy() {
// Given:
final Expression exp1 = mock(Expression.class);
final Expression exp2 = mock(Expression.class);
final Expression rewrittenExp1 = mock(Expression.class);
final Expression rewrittenExp2 = mock(Expression.class);
final GroupBy groupBy = new Gro... |
public FileIO getFileIO(StorageType.Type storageType) throws IllegalArgumentException {
Supplier<? extends RuntimeException> exceptionSupplier =
() -> new IllegalArgumentException(storageType.getValue() + " is not configured");
if (HDFS.equals(storageType)) {
return Optional.ofNullable(hdfsFileIO)... | @Test
public void testGetUndefinedFileIOThrowsException() {
// hdfs storage is not configured
Assertions.assertThrows(
IllegalArgumentException.class, () -> fileIOManager.getFileIO(StorageType.HDFS));
} |
@GET
@Path("/{connector}/offsets")
@Operation(summary = "Get the current offsets for the specified connector")
public ConnectorOffsets getOffsets(final @PathParam("connector") String connector) throws Throwable {
FutureCallback<ConnectorOffsets> cb = new FutureCallback<>();
herder.connectorO... | @Test
public void testGetOffsets() throws Throwable {
final ArgumentCaptor<Callback<ConnectorOffsets>> cb = ArgumentCaptor.forClass(Callback.class);
ConnectorOffsets offsets = new ConnectorOffsets(Arrays.asList(
new ConnectorOffset(Collections.singletonMap("partitionKey", "partitionV... |
public static ExternalServiceCredentialsGenerator.Builder builder(final SecretBytes key) {
return builder(key.value());
} | @Test
void testInvalidConstructor() {
assertThrows(RuntimeException.class, () -> ExternalServiceCredentialsGenerator
.builder(new byte[32])
.withUsernameTimestampTruncatorAndPrefix(null, PREFIX)
.build());
assertThrows(RuntimeException.class, () -> ExternalServiceCredentialsGenerator
... |
@Override
public V remove(Object o) {
if (o instanceof String) {
lowerKeyToOriginMap.remove(((String) o).toLowerCase());
return targetMap.remove(((String) o).toLowerCase());
}
return null;
} | @Test
void testRemove() {
Map<String, Object> map = new LowerCaseLinkHashMap<>(lowerCaseLinkHashMap);
Object value = map.remove("key");
Assertions.assertEquals("Value", value);
Assertions.assertFalse(map.containsKey("key"));
Assertions.assertTrue(map.containsKey("key2"));
... |
public void logOnCatchupPosition(
final int memberId,
final long leadershipTermId,
final long logPosition,
final int followerMemberId,
final String catchupEndpoint)
{
final int length = catchupPositionLength(catchupEndpoint);
final int captureLength = captureL... | @Test
void logCatchupPosition()
{
final int offset = ALIGNMENT * 4;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
final long leadershipTermId = 1233L;
final long logPosition = 100L;
final int followerMemberId = 18;
final int memberId = -901;
... |
public boolean isExist(final String key) {
try {
return null != client.checkExists().forPath(key);
} catch (Exception e) {
LOGGER.error("check if key exist error", e);
return false;
}
} | @Test
void isExist() throws Exception {
assertFalse(() -> client.isExist("/test"));
ExistsBuilderImpl existsBuilder = mock(ExistsBuilderImpl.class);
when(curatorFramework.checkExists()).thenReturn(existsBuilder);
when(existsBuilder.forPath(anyString())).thenReturn(new Stat());
... |
@Override
public String toString() {
return getClass().getSimpleName() + "[lastConnectUrl=" + Parameters.getLastConnectUrl()
+ ", lastConnectInfo=" + Parameters.getLastConnectInfo() + ']';
} | @Test
public void testToString() {
final String string = driver.toString();
assertNotNull("toString not null", string);
assertFalse("toString not empty", string.isEmpty());
} |
void validateFileLength(final Location location) throws IOException {
final long recordEnd = location.getOffset() + location.getSize();
//Check if the end of the record will go past the file length
if (recordEnd > dataFile.length) {
/*
* AMQ-9254 if the read request is ... | @Test
public void testValidateUsingRealFileLength() throws IOException {
//Create file of size 1024
final DataFile dataFile = newTestDataFile(1024);
final DataFileAccessor accessor = new DataFileAccessor(mock(Journal.class), dataFile);
//Set a bad length value on the dataFile so th... |
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) {
return drlxParse(patternType, bindingId, expression, false);
} | @Test
public void testNullSafeExpressionsWithContains() {
SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "address!.city contains (\"Mi\")");
List<Expression> nullSafeExpressions = result.getNullSafeExpressions();
assertThat(nullSafeExpressions)... |
public static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups) {
int errorCount = 0;
List<ConfigInfo> configInfoList = new LinkedList<>();
Map<String, ConfigValue> configValueMap = new HashMap<>();
for (C... | @Test
public void testGenerateResultWithConfigValuesAllUsingConfigKeysAndWithSomeErrors() {
String name = "com.acme.connector.MyConnector";
Map<String, ConfigDef.ConfigKey> keys = new HashMap<>();
addConfigKey(keys, "config.a1", null);
addConfigKey(keys, "config.b1", "group B");
... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void contextPathExpression3() {
String inputExpression = "{ first name : \"bob\" }.first name";
BaseNode pathBase = parse( inputExpression );
assertThat( pathBase).isInstanceOf(PathExpressionNode.class);
assertThat( pathBase.getText()).isEqualTo(inputExpression);
asser... |
@Override
public Set<String> getFileUuids() {
return ImmutableSet.copyOf(fileUuids);
} | @Test
public void getFileUuids_returns_empty_when_repository_is_empty() {
assertThat(underTest.getFileUuids()).isEmpty();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.