focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public CompletableFuture<Void> closeAsync() {
ShutdownHookUtil.removeShutdownHook(shutDownHook, getClass().getSimpleName(), LOG);
return shutDownAsync(
ApplicationStatus.UNKNOWN,
ShutdownBehaviour.PROCESS_FAILURE,
"Cl... | @Test
public void testCloseAsyncShouldNotDeregisterApp() throws Exception {
final CompletableFuture<Void> deregisterFuture = new CompletableFuture<>();
final TestingResourceManagerFactory testingResourceManagerFactory =
new TestingResourceManagerFactory.Builder()
... |
@Override
public long getMin() {
if (values.length == 0) {
return 0;
}
return values[0];
} | @Test
public void calculatesAMinOfZeroForAnEmptySnapshot() {
final Snapshot emptySnapshot = new UniformSnapshot(new long[]{});
assertThat(emptySnapshot.getMin())
.isZero();
} |
@Override
public Object getValue() {
return value;
} | @Test
public void testGetValue() {
assertEquals(VALUE, record.getValue());
assertEquals(VALUE, recordSameAttributes.getValue());
assertNotEquals(VALUE, recordOtherKeyAndValue.getValue());
} |
public Set<MapperConfig> load(InputStream inputStream) throws IOException {
final PrometheusMappingConfig config = ymlMapper.readValue(inputStream, PrometheusMappingConfig.class);
return config.metricMappingConfigs()
.stream()
.flatMap(this::mapMetric)
.c... | @Test
void inputMetricType() throws Exception {
when(messageInputFactory.getAvailableInputs()).thenReturn(
ImmutableMap.of("test.input", mock(InputDescription.class)));
final Map<String, ImmutableList<Serializable>> config = Collections.singletonMap("metric_mappings",
... |
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 getTypeNameInputPositiveOutputNotNull28() {
// Arrange
final int type = 35;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Previous_gtids", actual);
} |
public static ListenableFuture<EntityFieldsData> findAsync(TbContext ctx, EntityId originatorId) {
switch (originatorId.getEntityType()) { // TODO: use EntityServiceRegistry
case TENANT:
return toEntityFieldsDataAsync(ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), (Te... | @Test
public void givenSupportedTypeButEntityDoesNotExist_whenFindAsync_thenException() {
for (var entityType : SUPPORTED_ENTITY_TYPES) {
var entityId = EntityIdFactory.getByTypeAndUuid(entityType, RANDOM_UUID);
initMocks(entityType, true);
when(ctxMock.getTenantId()).th... |
@Override
public synchronized <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(final P prefix, final PS prefixKeySerializer) {
final Bytes from = Bytes.wrap(prefixKeySerializer.serialize(null, prefix));
final Bytes to = Bytes.increment(from);
return new DelegatingPe... | @Test
public void shouldThrowNullPointerIfPrefixKeySerializerIsNull() {
assertThrows(NullPointerException.class, () -> byteStore.prefixScan("bb", null));
} |
@Override
public Set<EntityExcerpt> listEntityExcerpts() {
return collectorService.all().stream()
.map(this::createExcerpt)
.collect(Collectors.toSet());
} | @Test
@MongoDBFixtures("SidecarCollectorFacadeTest.json")
public void listEntityExcerpts() {
final Set<EntityExcerpt> entityExcerpts = facade.listEntityExcerpts();
assertThat(entityExcerpts).containsOnly(
EntityExcerpt.builder()
.id(ModelId.of("5b4c920b4b9... |
public boolean isAllTablesInSameDataSource(final Collection<String> logicTableNames) {
Collection<String> dataSourceNames = logicTableNames.stream().map(shardingTables::get)
.filter(Objects::nonNull).flatMap(each -> each.getActualDataSourceNames().stream()).collect(Collectors.toSet());
r... | @Test
void assertIsAllTablesInSameDataSource() {
ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
ruleConfig.getTables().add(new ShardingTableRuleConfiguration("LOGIC_TABLE", "ds_${0}.table_${0..2}"));
ShardingRule shardingRule = new ShardingRule(ruleConfig, Maps.of("r... |
@Override
public int drainPermits() {
return get(drainPermitsAsync());
} | @Test
public void testDrainPermits() throws InterruptedException {
RSemaphore s = redisson.getSemaphore("test");
assertThat(s.drainPermits()).isZero();
s.trySetPermits(10);
s.acquire(3);
assertThat(s.drainPermits()).isEqualTo(7);
assertThat(s.availablePermits()).isE... |
public static void andAckSet(Position currentPosition, Position otherPosition) {
if (currentPosition == null || otherPosition == null) {
return;
}
AckSetState currentAckSetState = AckSetStateUtil.getAckSetState(currentPosition);
AckSetState otherAckSetState = AckSetStateUtil.... | @Test
public void andAckSetTest() {
Position positionOne = AckSetStateUtil.createPositionWithAckSet(1, 1, new long[0]);
Position positionTwo = AckSetStateUtil.createPositionWithAckSet(1, 2, new long[0]);
BitSet bitSetOne = new BitSet();
BitSet bitSetTwo = new BitSet();
bitSet... |
public WorkflowInstanceRestartResponse toWorkflowRestartResponse() {
return WorkflowInstanceRestartResponse.builder()
.workflowId(this.workflowId)
.workflowVersionId(this.workflowVersionId)
.workflowInstanceId(this.workflowInstanceId)
.workflowRunId(this.workflowRunId)
.workf... | @Test
public void testToWorkflowRestartResponse() {
RunResponse res = RunResponse.from(stepInstance, TimelineLogEvent.info("bar"));
WorkflowInstanceRestartResponse response = res.toWorkflowRestartResponse();
Assert.assertEquals(InstanceRunStatus.CREATED, response.getStatus());
res = RunResponse.from(i... |
@SuppressWarnings("unchecked")
public final void isLessThan(@Nullable T other) {
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(other)) >= 0) {
failWithActual("expected to be less than", other);
}
} | @Test
public void isLessThan_failsEqual() {
assertThat(4).isLessThan(5);
expectFailureWhenTestingThat(4).isLessThan(4);
assertFailureValue("expected to be less than", "4");
} |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
... | @Test
public void testAddWithNoIdentifiers() {
final String expectedMessage = "ERROR: You must supply an identifier to add";
createKeyStore();
String[] nullArguments = null;
cli.command("add", newStoreConfig.clone(), nullArguments);
assertThat(terminal.out).containsIgnoring... |
@ConstantFunction(name = "previous_day", argTypes = {DATETIME, VARCHAR}, returnType = DATE, isMonotonic = true)
public static ConstantOperator previousDay(ConstantOperator date, ConstantOperator dow) {
int dateDowValue = date.getDate().getDayOfWeek().getValue();
switch (dow.getVarchar()) {
... | @Test
public void previousDay() {
assertEquals("2015-03-22T09:23:55", ScalarOperatorFunctions.previousDay(O_DT_20150323_092355,
ConstantOperator.createVarchar("Sunday")).getDate().toString());
Assert.assertThrows("undefine_dow not supported in previous_day dow_string", IllegalArgumen... |
@Override
public long getIntentCount() {
return currentMap.size();
} | @Test
public void testGetIntentCount() {
assertThat(intentStore.getIntentCount(), is(0L));
generateIntentList(5).forEach(intentStore::write);
assertThat(intentStore.getIntentCount(), is(5L));
} |
public static Object eval(String expression, Map<String, Object> context) {
return eval(expression, context, ListUtil.empty());
} | @Test
public void jexlTest(){
final ExpressionEngine engine = new JexlEngine();
final Dict dict = Dict.create()
.set("a", 100.3)
.set("b", 45)
.set("c", -199.100);
final Object eval = engine.eval("a-(b-c)", dict, null);
assertEquals(-143.8, (double)eval, 0);
} |
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 divide() {
assertUnifiesAndInlines(
"4 / 17", UBinary.create(Kind.DIVIDE, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testStateParameterAlwaysFetched() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("ReadableStates");
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<KV<String, Integer>, Long>() {
@StateId("my-id")
private f... |
@Override
public void removeLoginStatus(Long userId) throws Exception {
redisTemplate.opsForSet().remove(LOGIN_STATUS_PREFIX,userId.toString()) ;
} | @Test
public void removeLoginStatus() throws Exception {
userInfoCacheService.removeLoginStatus(2000L);
} |
@Override
public Mono<AccessToken> createAccessToken(String clientId,
Authentication authentication,
boolean singleton) {
return singleton
? doCreateSingletonAccessToken(clientId, authentication)
... | @Test
public void testCreateSingletonAccessToken() {
RedisAccessTokenManager tokenManager = new RedisAccessTokenManager(RedisHelper.factory);
SimpleAuthentication authentication = new SimpleAuthentication();
authentication.setUser(SimpleUser.builder()
... |
public static void main(String[] args) throws Exception {
TikaCLI cli = new TikaCLI();
if (cli.testForHelp(args)) {
cli.usage();
return;
} else if (cli.testForBatch(args)) {
String[] batchArgs = BatchCommandLineBuilder.build(args);
BatchProcessDri... | @Test
public void testDefaultConfigException() throws Exception {
//default xml parser will throw TikaException
//this and TestConfig() are broken into separate tests so that
//setUp and tearDown() are called each time
String[] params = {resourcePrefix + "bad_xml.xml"};
boole... |
@Override
protected boolean isStepCompleted(@NonNull Context context) {
return isContactsPermComplete(context) && isNotificationPermComplete(context);
} | @Test
public void testKeyboardEnabledAndDefaultButNoPermission() {
final String flatASKComponent =
new ComponentName(BuildConfig.APPLICATION_ID, SoftKeyboard.class.getName())
.flattenToString();
Settings.Secure.putString(
getApplicationContext().getContentResolver(),
Settin... |
@Override
public boolean useIPAddrForServer() {
return clientConfig.getPropertyAsBoolean(IClientConfigKey.Keys.UseIPAddrForServer, true);
} | @Test
void testUseIPAddrForServer() {
assertTrue(connectionPoolConfig.useIPAddrForServer());
} |
public static <N, E> Set<N> reachableNodes(
Network<N, E> network, Set<N> startNodes, Set<N> endNodes) {
Set<N> visitedNodes = new HashSet<>();
Queue<N> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted at the input node.
while (!queu... | @Test
public void testReachableNodesWithPathAroundBoundaryNode() {
// Since there is a path around J, we will include E, G, and H
assertEquals(
ImmutableSet.of("I", "J", "E", "G", "H", "K", "L"),
Networks.reachableNodes(createNetwork(), ImmutableSet.of("I"), ImmutableSet.of("J")));
} |
@Override
protected double maintain() {
if (!nodeRepository().nodes().isWorking()) return 0.0;
if (!nodeRepository().zone().environment().isProduction()) return 1.0;
NodeList allNodes = nodeRepository().nodes().list(); // Lockless as strong consistency is not needed
if (!zoneIsStable... | @Test
public void rebalance_does_not_move_node_already_on_exclusive_switch() {
ProvisioningTester tester = new ProvisioningTester.Builder().zone(new Zone(Environment.prod, RegionName.from("us-east"))).build();
ClusterSpec spec = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("c1")... |
@Override
public Optional<Listener> acquire(ContextT context) {
final Partition partition = resolvePartition(context);
try {
lock.lock();
if (shouldBypass(context)){
return createBypassListener();
}
if (getInflight() >= getLimit() && p... | @Test
public void testBypassSimpleLimiter() {
SimpleLimiter<String> limiter = (SimpleLimiter<String>) TestPartitionedLimiter.newBuilder()
.limit(FixedLimit.of(10))
.bypassLimitResolverInternal(new ShouldBypassPredicate())
.build();
int inflightCount ... |
static <E extends Enum<E>> int encodeReplicationSessionStateChange(
final UnsafeBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final E from,
final E to,
final long replicationId,
final long srcRecordingId,
final... | @Test
void testEncodeReplicationSessionStateChange()
{
int offset = 24;
final int length = replicationSessionStateChangeLength(State.ALPHA, State.BETA, "reason");
final int captureLength = captureLength(length);
encodeReplicationSessionStateChange(buffer, offset, captureLength, ... |
public static void forceMkdir(String path) throws IOException {
FileUtils.forceMkdir(new File(path));
} | @Test
void testForceMkdirWithPath() throws IOException {
Path path = Paths.get(EnvUtil.getNacosTmpDir(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
DiskUtils.forceMkdir(path.toString());
File file = path.toFile();
assertTrue(file.exists());
file.deleteOnExit... |
@Override
public void pickSuggestionManually(
int index, CharSequence suggestion, boolean withAutoSpaceEnabled) {
if (getCurrentComposedWord().isAtTagsSearchState()) {
if (index == 0) {
// this is a special case for tags-searcher
// since we append a magnifying glass to the suggestions... | @Test
public void testTagsSearchThrice() throws Exception {
verifyNoSuggestionsInteractions();
mAnySoftKeyboardUnderTest.simulateTextTyping(":face");
List suggestions = verifyAndCaptureSuggestion(true);
Assert.assertNotNull(suggestions);
Assert.assertEquals(131, suggestions.size());
mAnySoftK... |
long remove(final long recordingId)
{
ensurePositive(recordingId, "recordingId");
final long[] index = this.index;
final int lastPosition = lastPosition();
final int position = find(index, recordingId, lastPosition);
if (position < 0)
{
return NULL_VALUE;... | @Test
void removeThrowsIllegalArgumentExceptionIfNegativeRecordingIdIsProvided()
{
assertThrows(IllegalArgumentException.class, () -> catalogIndex.remove(-1));
} |
@Override
protected Triple<List<HoodieClusteringGroup>, Integer, List<FileSlice>> buildMergeClusteringGroup(
ConsistentBucketIdentifier identifier, List<FileSlice> fileSlices, int mergeSlot) {
return super.buildMergeClusteringGroup(identifier, fileSlices, mergeSlot);
} | @Test
public void testBuildMergeClusteringGroup() throws Exception {
setup();
int maxFileSize = 5120;
Properties props = new Properties();
props.setProperty(KeyGeneratorOptions.RECORDKEY_FIELD_NAME.key(), "uuid");
HoodieWriteConfig config = HoodieWriteConfig.newBuilder().withPath(basePath)
... |
@GetMapping(value = ApiConstants.PROMETHEUS_CONTROLLER_PATH, produces = "application/json; charset=UTF-8")
public ResponseEntity<String> metric() throws NacosException {
ArrayNode arrayNode = JacksonUtils.createEmptyArrayNode();
Set<Instance> targetSet = new HashSet<>();
Set<String> allNames... | @Test
public void testMetric() throws Exception {
when(instanceServiceV2.listAllInstances(nameSpace, NamingUtils.getGroupedName(name, group))).thenReturn(testInstanceList);
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(ApiConstants.PROMETHEUS_CONTROLLER_PATH);
MockHttpSe... |
protected void update(Long elapsedTime) {
controller.moveBullet(0.5f * elapsedTime / 1000);
} | @Test
void testUpdate() {
gameLoop.update(20L);
Assertions.assertEquals(0.01f, gameLoop.controller.getBulletPosition(), 0);
} |
@Override
public Local find() {
final NSArray directories = FoundationKitFunctions.library.NSSearchPathForDirectoriesInDomains(
FoundationKitFunctions.NSSearchPathDirectory.NSApplicationSupportDirectory,
FoundationKitFunctions.NSSearchPathDomainMask.NSUserDomainMask,
... | @Test
public void testFind() {
assertNotNull(new ApplicationSupportDirectoryFinder().find());
assertEquals("~/Library/Application Support/Cyberduck", new ApplicationSupportDirectoryFinder().find().getAbbreviatedPath());
} |
@Override
public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) {
// TODO do not load everything in memory. Db rows should be scrolled.
List<IndexPermissions> authorizations = getAllAuthorizations();
Stream<AuthorizationScope> scopes = getScopes(uninitializedIndexTypes);
index(authorizati... | @Test
public void indexOnStartup_does_not_grant_access_to_anybody_on_private_project() {
ProjectDto project = createAndIndexPrivateProject();
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
indexOnStartup();
verifyAnyoneNotAuthorized(project);
verifyNotAuth... |
public ZonedDateTime createdAt() {
return ZonedDateTime.parse("2018-07-18T15:58:00Z");
} | @Test
public void createdAt() {
assertThat(migration.createdAt()).isEqualTo(ZonedDateTime.parse("2018-07-18T15:58:00Z"));
} |
static Map<String, Comparable> prepareProperties(Map<String, Comparable> properties,
Collection<PropertyDefinition> propertyDefinitions) {
Map<String, Comparable> mappedProperties = createHashMap(propertyDefinitions.size());
for (PropertyDefinition p... | @Test
public void correctDashlessPropertyConversion() {
// given
Map<String, Comparable> properties = new HashMap<>(singletonMap("customproperty", PROPERTY_VALUE_1));
Collection<PropertyDefinition> propertyDefinitions = singletonList(new SimplePropertyDefinition("custom-property", STRING));
... |
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 testJarFileMissing() throws IOException {
try {
Classpath.main(new String[] { "--jar" });
fail("expected exit");
} catch (ExitUtil.ExitException e) {
assertTrue(stdout.toByteArray().length == 0);
String strErr = new String(stderr.toByteArray(), UTF8);
assertTrue... |
public Collection<SQLException> closeConnections(final boolean forceRollback) {
Collection<SQLException> result = new LinkedList<>();
synchronized (cachedConnections) {
resetSessionVariablesIfNecessary(cachedConnections.values(), result);
for (Connection each : cachedConnections.... | @Test
void assertCloseConnectionsCorrectlyWhenSQLExceptionThrown() throws SQLException {
Connection connection = prepareCachedConnections();
SQLException sqlException = new SQLException("");
doThrow(sqlException).when(connection).close();
assertTrue(databaseConnectionManager.closeCon... |
@PublicAPI(usage = ACCESS)
public Set<Dependency> getDirectDependenciesToSelf() {
return reverseDependencies.getDirectDependenciesTo(this);
} | @Test
@UseDataProvider
public void test_direct_dependencies_to_self_by_code_unit_type_parameters(JavaClass firstOrigin, JavaClass secondOrigin, JavaClass expectedTarget) {
assertThatDependencies(expectedTarget.getDirectDependenciesToSelf())
.contain(from(firstOrigin).to(expectedTarget).i... |
public void add(String topic) {
if (topic == null) {
throw new IllegalArgumentException("topic can not be null");
}
add(Numeric.hexStringToByteArray(topic));
} | @Test
public void testEthereumSampleLogsBloomReconstructionFromItsTopics() {
Bloom reconstructedBloom = new Bloom();
for (String topic : ethereumSampleLogs) {
reconstructedBloom.add(topic);
}
assertEquals(
new Bloom(ethereumSampleLogsBloom),
... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
var certs = req.getClientCertificateChain();
log.fine(() -> "Certificate chain contains %d elements".formatted(certs.size()));
if (certs.isEmpty()) {
log.fine("Missing client certificate");
re... | @Test
void supports_handler_with_custom_request_spec() {
// Spec that maps POST as action 'read'
var spec = RequestHandlerSpec.builder()
.withAclMapping(HttpMethodAclMapping.standard()
.override(Method.POST, Action.READ).build())
... |
public void recoverFileSize() {
if (fileSegmentTable.isEmpty() || FileSegmentType.INDEX.equals(fileType)) {
return;
}
FileSegment fileSegment = fileSegmentTable.get(fileSegmentTable.size() - 1);
long fileSize = fileSegment.getSize();
if (fileSize == GET_FILE_SIZE_ERRO... | @Test
public void recoverFileSizeTest() {
String filePath = MessageStoreUtil.toFilePath(queue);
FlatAppendFile flatFile = flatFileFactory.createFlatFileForConsumeQueue(filePath);
flatFile.rollingNewFile(500L);
FileSegment fileSegment = flatFile.getFileToWrite();
flatFile.app... |
public static OriginName fromVipAndApp(String vip, String appName) {
return fromVipAndApp(vip, appName, vip);
} | @Test
void noNull() {
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp(null, "app"));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp("vip", null));
assertThrows(NullPointerException.class, () -> OriginName.fromVipAndApp(null, "app", "niws"));
... |
@Override
public FileConfigDO getFileConfig(Long id) {
return fileConfigMapper.selectById(id);
} | @Test
public void testGetFileConfig() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbFileConfig.getId();
// 调用,并断言
assertPojoEquals(dbFileConfig, f... |
public BBox calculateIntersection(BBox bBox) {
if (!this.intersects(bBox))
return null;
double minLon = Math.max(this.minLon, bBox.minLon);
double maxLon = Math.min(this.maxLon, bBox.maxLon);
double minLat = Math.max(this.minLat, bBox.minLat);
double maxLat = Math.mi... | @Test
public void testCalculateIntersection() {
BBox b1 = new BBox(0, 2, 0, 1);
BBox b2 = new BBox(-1, 1, -1, 2);
BBox expected = new BBox(0, 1, 0, 1);
assertEquals(expected, b1.calculateIntersection(b2));
//No intersection
b2 = new BBox(100, 200, 100, 200);
... |
@SuppressWarnings("unchecked")
static Object extractFromRecordValue(Object recordValue, String fieldName) {
List<String> fields = Splitter.on('.').splitToList(fieldName);
if (recordValue instanceof Struct) {
return valueFromStruct((Struct) recordValue, fields);
} else if (recordValue instanceof Map)... | @Test
public void testExtractFromRecordValueMapNull() {
Map<String, Object> val = ImmutableMap.of("key", 123L);
Object result = RecordUtils.extractFromRecordValue(val, "");
assertThat(result).isNull();
result = RecordUtils.extractFromRecordValue(val, "xkey");
assertThat(result).isNull();
} |
public static BufferDebloatConfiguration fromConfiguration(ReadableConfig config) {
Duration targetTotalBufferSize = config.get(BUFFER_DEBLOAT_TARGET);
int maxBufferSize =
Math.toIntExact(config.get(TaskManagerOptions.MEMORY_SEGMENT_SIZE).getBytes());
int minBufferSize =
... | @Test
public void testNegativeConsumptionTime() {
final Configuration config = new Configuration();
config.set(TaskManagerOptions.BUFFER_DEBLOAT_TARGET, Duration.ofMillis(-1));
assertThrows(
IllegalArgumentException.class,
() -> BufferDebloatConfiguration.from... |
protected boolean isCurrentlyPredicting() {
return isPredictionOn() && !mWord.isEmpty();
} | @Test
public void testDoesNotPostRestartOnBackspaceWhilePredicting() {
simulateFinishInputFlow();
SharedPrefsHelper.setPrefsValue(R.string.settings_key_allow_suggestions_restart, true);
simulateOnStartInputFlow();
mAnySoftKeyboardUnderTest.simulateTextTyping("hel");
Assert.assertTrue(mAnySoftKeyb... |
public static List<TierFactory> initializeTierFactories(Configuration configuration) {
String externalTierFactoryClass =
configuration.get(
NettyShuffleEnvironmentOptions
.NETWORK_HYBRID_SHUFFLE_EXTERNAL_REMOTE_TIER_FACTORY_CLASS_NAME);
... | @Test
void testInitDurableTiersWithExternalRemoteTier() {
Configuration configuration = new Configuration();
configuration.set(
NettyShuffleEnvironmentOptions
.NETWORK_HYBRID_SHUFFLE_EXTERNAL_REMOTE_TIER_FACTORY_CLASS_NAME,
ExternalRemoteTierFa... |
public void doesNotContain(@Nullable Object rowKey, @Nullable Object columnKey) {
if (checkNotNull(actual).contains(rowKey, columnKey)) {
failWithoutActual(
simpleFact("expected not to contain mapping for row-column key pair"),
fact("row key", rowKey),
fact("column key", columnKe... | @Test
public void doesNotContainFailure() {
ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val");
expectFailureWhenTestingThat(table).doesNotContain("row", "col");
assertThat(expectFailure.getFailure())
.factKeys()
.containsExactly(
"expected no... |
@Override
public Result apply(String action, Class<? extends Validatable> aClass, String resource, String resourceToOperateWithin) {
if (matchesAction(action) && matchesType(aClass) && matchesResource(resource)) {
return Result.DENY;
}
if (isRequestForElasticAgentProfiles(aClass... | @Test
void forViewOfAllClusterProfiles() {
Deny directive = new Deny("view", "cluster_profile", "*");
Result viewAllElasticAgentProfiles = directive.apply("view", ElasticProfile.class, "*", null);
Result viewAllClusterProfiles = directive.apply("view", ClusterProfile.class, "*", null);
... |
@Override
public void rollback() throws SQLException {
for (TransactionHook each : transactionHooks) {
each.beforeRollback(connection.getCachedConnections().values(), getTransactionContext());
}
if (connection.getConnectionSession().getTransactionStatus().isInTransaction()) {
... | @Test
void assertRollbackWithoutTransaction() throws SQLException {
ContextManager contextManager = mockContextManager(TransactionType.LOCAL);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
newBackendTransactionManager(TransactionType.LOCAL, false);
... |
protected Request buildRequest(String url, String sender, String data)
throws JsonProcessingException {
if (sender == null || !WalletUtils.isValidAddress(sender)) {
throw new EnsResolutionException("Sender address is null or not valid");
}
if (data == null) {
... | @Test
void buildRequestWhenWithoutSenderTest() throws IOException {
String url = "https://example.com/gateway/{sender}.json";
String data = "0xd5fa2b00";
assertThrows(EnsResolutionException.class, () -> ensResolver.buildRequest(url, null, data));
} |
@Override
public void validate(Context context) {
Optional<Reader> overrides = context.deployState().getApplicationPackage().getValidationOverrides();
if (overrides.isEmpty()) return;
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(overrides.get());
validationO... | @Test
void testValidationOverride() throws IOException, SAXException {
String tenDays = dateTimeFormatter.format(Instant.now().plus(Duration.ofDays(10)));
var validationOverridesXml = "<?xml version='1.0' encoding='UTF-8'?>\n" +
" <validation-overrides>\n" +
" <a... |
public static String toAbsolute(String baseURL, String relativeURL) {
String relURL = relativeURL;
// Relative to protocol
if (relURL.startsWith("//")) {
return StringUtils.substringBefore(baseURL, "//") + "//"
+ StringUtils.substringAfter(relURL, "//");
}... | @Test
public void testFromDomainNoTrailSlashToRelativeNoLeadSlash() {
s = "http://www.sample.com";
t = "http://www.sample.com/xyz.html";
assertEquals(t, HttpURL.toAbsolute(s, "xyz.html"));
} |
@Override
public void getData(final String path, final boolean watch, final AsyncCallback.DataCallback cb, final Object ctx)
{
if (!SymlinkUtil.containsSymlink(path))
{
_zk.getData(path, watch, cb, ctx);
}
else
{
SymlinkDataCallback compositeCallback = new SymlinkDataCallback(path, _... | @Test
public void testSymlinkGetData() throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch(1);
AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback()
{
@Override
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat)
... |
public HdfsBolt withPartitioner(Partitioner partitioner) {
this.partitioner = partitioner;
return this;
} | @Test
public void testPartitionedOutput() throws IOException {
HdfsBolt bolt = makeHdfsBolt(hdfsURI, 1, 1000f);
Partitioner partitoner = new Partitioner() {
@Override
public String getPartitionPath(Tuple tuple) {
return Path.SEPARATOR + tuple.getStringByField... |
public static HighAvailabilityServices createAvailableOrEmbeddedServices(
Configuration config, Executor executor, FatalErrorHandler fatalErrorHandler)
throws Exception {
HighAvailabilityMode highAvailabilityMode = HighAvailabilityMode.fromConfig(config);
switch (highAvailabilit... | @Test(expected = Exception.class)
public void testCustomHAServicesFactoryNotDefined() throws Exception {
Configuration config = new Configuration();
Executor executor = Executors.directExecutor();
config.set(
HighAvailabilityOptions.HA_MODE,
HighAvailability... |
public static Assignment deserializeAssignment(final ByteBuffer buffer, short version) {
version = checkAssignmentVersion(version);
try {
ConsumerProtocolAssignment data =
new ConsumerProtocolAssignment(new ByteBufferAccessor(buffer), version);
List<TopicPartiti... | @Test
public void deserializeFutureAssignmentVersion() {
// verify that a new version which adds a field is still parseable
short version = 100;
Schema assignmentSchemaV100 = new Schema(
new Field("assigned_partitions", new ArrayOf(
ConsumerProtocolAssignment.Top... |
void invokeMain(BootstrappedInstanceProxy instanceProxy, ExecuteJobParameters executeJobParameters,
Method mainMethod, List<String> args)
throws IllegalAccessException, InvocationTargetException {
try {
instanceProxy.setExecuteJobParameters(executeJobParameters);
... | @Test
public void testInvokeMain() throws InvocationTargetException, IllegalAccessException {
HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class);
AbstractJetInstance abstractJetInstance = mock(AbstractJetInstance.class);
when(hazelcastInstance.getJet()).thenReturn(abstractJe... |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void filter_on_projectUuids_if_projectUuid_is_non_empty_and_criteria_non_empty() {
ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build()),
Collections.singleton("foo"));
assertThat(query.getProjectUuids... |
@ApiOperation(value = "Get LwM2M Objects (getLwm2mListObjects)",
notes = "Returns a page of LwM2M objects parsed from Resources with type 'LWM2M_MODEL' owned by tenant or sysadmin. " +
"You can specify parameters to filter the results. " + LWM2M_OBJECT_DESCRIPTION + TENANT_AUTHORITY_PARA... | @Test
public void testGetLwm2mListObjects() throws Exception {
loginTenantAdmin();
List<TbResource> resources = loadLwm2mResources();
List<LwM2mObject> objects =
doGetTyped("/api/resource/lwm2m?sortProperty=id&sortOrder=ASC&objectIds=3_1.2,5_1.2,19_1.1", new TypeReference<>... |
public static <R> R callInstanceMethod(
final Object instance, final String methodName, ClassParameter<?>... classParameters) {
perfStatsCollector.incrementCount(
String.format(
"ReflectionHelpers.callInstanceMethod-%s_%s",
instance.getClass().getName(), methodName));
try {... | @Test
public void callInstanceMethodReflectively_callsInheritedMethods() {
ExampleDescendant example = new ExampleDescendant();
assertThat((int) ReflectionHelpers.callInstanceMethod(example, "returnNegativeNumber"))
.isEqualTo(-46);
} |
@Override
public long getCount() {
return counter.getCount();
} | @Test
void testGetCount() {
Counter c = new SimpleCounter();
c.inc(5);
Meter m = new MeterView(c);
assertThat(m.getCount()).isEqualTo(5);
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldDeserializeJsonObjectWithRedundantFields() {
// Given:
final Map<String, Object> orderRow = new HashMap<>(AN_ORDER);
orderRow.put("extraField", "should be ignored");
final byte[] bytes = serializeJson(orderRow);
// When:
final Struct result = deserializer.deserialize(... |
@Override
public List<byte[]> mGet(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key : keys) {
read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key);
}
return null;
}
CommandBatchService es = new CommandBatchServi... | @Test
public void testMGet() {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(("test" + i).getBytes(), ("test" + i*100).getBytes());
}
connection.mSet(map);
List<byte[]> r = connection.mGet(map.keySet().toArray(new byte[0][]));
... |
@Override
public ExecuteContext before(ExecuteContext context) {
Object object = context.getObject();
String serviceId = getServiceId(object).orElse(null);
if (StringUtils.isBlank(serviceId)) {
return context;
}
Object[] arguments = context.getArguments();
... | @Test
public void testBefore() {
ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", ""));
interceptor.before(context);
List<ServiceInstance> instances = (List<ServiceInstance>) context.getArguments()[0];
Assert.assertNotNull(instances);
Assert.assertE... |
@Override
public double entropy() {
return entropy;
} | @Test
public void testEntropy() {
System.out.println("entropy");
GammaDistribution instance = new GammaDistribution(3, 2.1);
instance.rand();
assertEquals(2.589516, instance.entropy(), 1E-6);
} |
@Override
public List<Intent> compile(SinglePointToMultiPointIntent intent,
List<Intent> installable) {
Set<Link> links = new HashSet<>();
final boolean allowMissingPaths = intentAllowsPartialFailure(intent);
boolean hasPaths = false;
boolean missingS... | @Test
public void testPartialFailureConstraintFailure() {
FilteredConnectPoint ingress =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
Set<FilteredConnectPoint> egress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2)),
... |
@Override
@Deprecated
public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSuppl... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNamesOnTransform() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transform(transformerSupplier, (String[]) null));
assertThat(exception.getMessa... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(false);
}
boolean result = false;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
r... | @Test
void invokeListParamReturnNull() {
FunctionTestUtil.assertResult(anyFunction.invoke(Arrays.asList(Boolean.FALSE, null, Boolean.FALSE)), false);
} |
public Shard getShardById(final int shardId) {
return shardMap.get(shardId);
} | @Test
void testGetShardById() {
var shard = new Shard(1);
shardManager.addNewShard(shard);
var tmpShard = shardManager.getShardById(1);
assertEquals(shard, tmpShard);
} |
@Override
public ListConsumerGroupsResult listConsumerGroups(ListConsumerGroupsOptions options) {
final KafkaFutureImpl<Collection<Object>> all = new KafkaFutureImpl<>();
final long nowMetadata = time.milliseconds();
final long deadline = calcDeadlineMs(nowMetadata, options.timeoutMs());
... | @Test
public void testListConsumerGroupsWithTypesOlderBrokerVersion() throws Exception {
ApiVersion listGroupV4 = new ApiVersion()
.setApiKey(ApiKeys.LIST_GROUPS.id)
.setMinVersion((short) 0)
.setMaxVersion((short) 4);
try (AdminClientUnitTestEnv env = new AdminCl... |
@VisibleForTesting
public Optional<ProcessContinuation> run(
PartitionMetadata partition,
ChildPartitionsRecord record,
RestrictionTracker<TimestampRange, Timestamp> tracker,
ManualWatermarkEstimator<Instant> watermarkEstimator) {
final String token = partition.getPartitionToken();
L... | @Test
public void testRestrictionClaimedAndIsSplitCase() {
final String partitionToken = "partitionToken";
final long heartbeat = 30L;
final Timestamp startTimestamp = Timestamp.ofTimeMicroseconds(10L);
final Timestamp endTimestamp = Timestamp.ofTimeMicroseconds(20L);
final PartitionMetadata parti... |
public static MetricName getMetricName(
String group,
String typeName,
String name
) {
return getMetricName(
group,
typeName,
name,
null
);
} | @Test
public void testUntaggedMetric() {
MetricName metricName = KafkaYammerMetrics.getMetricName(
"kafka.metrics",
"TestMetrics",
"UntaggedMetric"
);
assertEquals("kafka.metrics", metricName.getGroup());
assertEquals("TestMetrics", metricName.get... |
public List<Flow> convertFlows(String componentName, @Nullable DbIssues.Locations issueLocations) {
if (issueLocations == null) {
return Collections.emptyList();
}
return issueLocations.getFlowList().stream()
.map(sourceFlow -> toFlow(componentName, sourceFlow))
.collect(Collectors.toColle... | @Test
public void convertFlows_withSingleDbLocations_returnsCorrectFlow() {
DbIssues.Location location = createDbLocation("comp_id_1");
DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder()
.addFlow(createFlow(location))
.build();
List<Flow> flows = flowGenerator.convertFlows(CO... |
@Override
public DataTableType dataTableType() {
return dataTableType;
} | @Test
void static_methods_are_invoked_without_a_body() throws NoSuchMethodException {
Method method = JavaDataTableTypeDefinitionTest.class.getMethod("static_convert_data_table_to_string",
DataTable.class);
JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, ... |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testAtWatermarkAndLate() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
AfterWatermarkStateMachine.pastEndOfWindow().withLateFirings(mockLate),
FixedWindows.of(Duration.millis(100)));
injectElements(1);
IntervalWindow window = new Inter... |
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
QueuePath childQueuePath) {
setTemplateEntriesForChild(conf, childQueuePath, false);
} | @Test
public void testWildcardTemplateWithLimitedAutoCreatedQueueDepth() {
conf.set(getTemplateKey(TEST_QUEUE_ROOT_WILDCARD, "capacity"), "6w");
conf.set(getTemplateKey(TEST_QUEUE_A_WILDCARD, "capacity"), "5w");
conf.setMaximumAutoCreatedQueueDepth(TEST_QUEUE_A, 1);
conf.setMaximumAutoCreatedQueueDept... |
public boolean sync() throws IOException {
if (!preSyncCheck()) {
return false;
}
if (!getAllDiffs()) {
return false;
}
List<Path> sourcePaths = context.getSourcePaths();
final Path sourceDir = sourcePaths.get(0);
final Path targetDir = context.getTargetPath();
final FileSy... | @Test
public void testSyncSnapshotTimeStampChecking() throws Exception {
initData(source);
initData(target);
dfs.allowSnapshot(source);
dfs.allowSnapshot(target);
dfs.createSnapshot(source, "s2");
dfs.createSnapshot(target, "s1");
// Sleep one second to make snapshot s1 created later than ... |
private void withdraw(ResolvedRoute route) {
synchronized (this) {
IpPrefix prefix = route.prefix();
MultiPointToSinglePointIntent intent = routeIntents.remove(prefix);
if (intent == null) {
log.trace("No intent in routeIntents to delete for prefix: {}",
... | @Test
public void testRemoveEgressInterface() {
// Add a route first
testRouteAddToNoVlan();
// Create existing intent
MultiPointToSinglePointIntent removedIntent =
createIntentToThreeSrcOneTwo(PREFIX1);
// Set up expectation
reset(intentSynchronizer... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DurableExecutorWaitNotifyKey)) {
return false;
}
if (!super.equals(o)) {
return false;
}
DurableExecutorWaitNotifyKey that = (Du... | @Test
public void testEquals() {
assertEquals(notifyKey, notifyKey);
assertEquals(notifyKey, notifyKeySameAttributes);
assertNotEquals(null, notifyKey);
assertNotEquals(new Object(), notifyKey);
assertNotEquals(notifyKey, notifyKeyOtherUniqueId);
assertNotEquals(not... |
@Transactional
public MeetingCreateResponse create(MeetingCreateRequest request) {
Meeting meeting = saveMeeting(request.meetingName(), request.toMeetingStartTime(), request.toMeetingEndTime());
AvailableDates meetingDates = new AvailableDates(request.toAvailableMeetingDates(), meeting);
va... | @DisplayName("약속을 생성할 때 과거 날짜를 보내면 예외가 발생합니다.")
@Test
void throwExceptionWhenDatesHavePast() {
//given
setFixedClock();
LocalDate today = LocalDate.now(clock);
LocalDate yesterday = today.minusDays(1);
MeetingCreateRequest request = new MeetingCreateRequest(
... |
public AnalysisPropertyDto setAnalysisUuid(String analysisUuid) {
requireNonNull(analysisUuid, "analysisUuid cannot be null");
this.analysisUuid = analysisUuid;
return this;
} | @Test
void null_analysis_uuid_should_throw_NPE() {
underTest = new AnalysisPropertyDto();
assertThatThrownBy(() -> underTest.setAnalysisUuid(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("analysisUuid cannot be null");
} |
protected static boolean isSingleQuoted(String input) {
if (input == null || input.isBlank()) {
return false;
}
return input.matches("(^" + QUOTE_CHAR + "{1}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{1})");
} | @Test
public void testEmptySingleQuotedNegative() {
assertFalse(isSingleQuoted("\"\""));
} |
@Override
protected Collection<Address> getPossibleAddresses() {
Iterable<DiscoveryNode> discoveredNodes = checkNotNull(discoveryService.discoverNodes(),
"Discovered nodes cannot be null!");
MemberImpl localMember = node.nodeEngine.getLocalMember();
Set<Address> localAddress... | @Test
public void test_DiscoveryJoiner_enriches_member_with_public_address() {
DiscoveryJoiner joiner = new DiscoveryJoiner(getNode(hz), service, false);
doReturn(discoveryNodes).when(service).discoverNodes();
Collection<Address> addresses = joiner.getPossibleAddresses();
Address cli... |
public List<String> toList(boolean trim) {
return toList((str) -> trim ? StrUtil.trim(str) : str);
} | @Test
public void splitByStrTest(){
String str1 = "a, ,,efedsfs, ddf,";
SplitIter splitIter = new SplitIter(str1,
new StrFinder("e", false),
Integer.MAX_VALUE,
true
);
final List<String> strings = splitIter.toList(false);
assertEquals(3, strings.size());
} |
public Connector newConnector(String connectorClassOrAlias) {
Class<? extends Connector> klass = connectorClass(connectorClassOrAlias);
return newPlugin(klass);
} | @Test
public void shouldThrowIfDefaultConstructorPrivate() {
assertThrows(ConnectException.class, () -> plugins.newConnector(
TestPlugin.BAD_PACKAGING_DEFAULT_CONSTRUCTOR_PRIVATE_CONNECTOR.className()
));
} |
@Nullable
public static PipelineBreakerResult executePipelineBreakers(OpChainSchedulerService scheduler,
MailboxService mailboxService, WorkerMetadata workerMetadata, StagePlan stagePlan,
Map<String, String> opChainMetadata, long requestId, long deadlineMs) {
PipelineBreakerContext pipelineBreakerCont... | @Test
public void shouldReturnErrorBlocksWhenReceivedErrorFromSender() {
MailboxReceiveNode mailboxReceiveNode1 = getPBReceiveNode(1);
MailboxReceiveNode incorrectlyConfiguredMailboxNode = getPBReceiveNode(2);
JoinNode joinNode = new JoinNode(0, DATA_SCHEMA, PlanNode.NodeHint.EMPTY,
List.of(mailbo... |
@Override
public RestLiResponseData<GetResponseEnvelope> buildRestLiResponseData(Request request,
RoutingResult routingResult,
Object result,
Map<Stri... | @Test
public void testProjectionInBuildRestliResponseData()
{
MaskTree maskTree = new MaskTree();
maskTree.addOperation(new PathSpec("fruitsField"), MaskOperation.POSITIVE_MASK_OP);
ServerResourceContext mockContext = getMockResourceContext(maskTree, ProjectionMode.AUTOMATIC);
RoutingResult routing... |
static boolean applyTags(RuleDto rule, Set<String> tags) {
for (String tag : tags) {
RuleTagFormat.validate(tag);
}
Set<String> initialTags = rule.getTags();
final Set<String> systemTags = rule.getSystemTags();
Set<String> withoutSystemTags = Sets.filter(tags, input -> input != null && !syste... | @Test
public void applyTags_validate_format() {
RuleDto rule = new RuleDto();
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
assertThat(changed).isTrue();
try {
RuleTagHelper.applyTags(rule... |
public String toLoggableString(ApiMessage message) {
MetadataRecordType type = MetadataRecordType.fromId(message.apiKey());
switch (type) {
case CONFIG_RECORD: {
if (!configSchema.isSensitive((ConfigRecord) message)) {
return message.toString();
... | @Test
public void testSensitiveConfigRecordToString() {
assertEquals("ConfigRecord(resourceType=4, resourceName='0', name='quux', " +
"value='(redacted)')",
REDACTOR.toLoggableString(new ConfigRecord().
setResourceType(BROKER.id()).
setReso... |
@Override
public void run()
throws Exception {
//init all file systems
List<PinotFSSpec> pinotFSSpecs = _spec.getPinotFSSpecs();
for (PinotFSSpec pinotFSSpec : pinotFSSpecs) {
PinotFSFactory.register(pinotFSSpec.getScheme(), pinotFSSpec.getClassName(), new PinotConfiguration(pinotFSSpec));
... | @Test
public void testSegmentGeneration() throws Exception {
// TODO use common resource definitions & code shared with Hadoop unit test.
// So probably need a pinot-batch-ingestion-common tests jar that we depend on.
File testDir = Files.createTempDirectory("testSegmentGeneration-").toFile();
testDi... |
public static boolean isVariableNameValid( String source ) {
return checkVariableName( source ).isEmpty();
} | @Test
void variableNameWithValidCharactersHorseEmoji() {
String var = "🐎";
assertThat(FEELParser.isVariableNameValid(var)).isEqualTo(true);
} |
public static String escapeSpecialCharacter(String command) {
StringBuilder builder = new StringBuilder();
for (char c : command.toCharArray()) {
if (SPECIAL_CHARACTER.indexOf(c) != -1) {
builder.append("\\");
}
builder.append(c);
}
return builder.toString();
} | @Test
public void testEscapeSpecialCharacters() {
String cmd = "{}.";
assertEquals("\\{\\}\\.", InterpreterLauncher.escapeSpecialCharacter(cmd));
} |
static Optional<Object> getValueFromPMMLResultByVariableName(final String variableName,
final Map<String, Object> resultsVariables) {
return Optional.ofNullable(resultsVariables.get(variableName));
} | @Test
void getValueFromPMMLResultByVariableName() {
final String variableName = "variableName";
final Map<String, Object> resultsVariables = new HashMap<>();
Optional<Object> retrieved = KiePMMLOutputField.getValueFromPMMLResultByVariableName(variableName,
... |
static Map<String, String> toMap(List<Settings.Setting> settingsList) {
Map<String, String> result = new LinkedHashMap<>();
for (Settings.Setting s : settingsList) {
// we need the "*.file.suffixes" and "*.file.patterns" properties for language detection
// see DefaultLanguagesRepository.populateFil... | @Test
public void should_throw_exception_when_no_value_of_non_secured_settings() {
Setting setting = Setting.newBuilder().setKey("sonar.open.setting").build();
List<Setting> singletonList = singletonList(setting);
assertThatThrownBy(() -> AbstractSettingsLoader.toMap(singletonList))
.isInstanceO... |
public String toJsonString(Object object) {
return String.valueOf(toJson(object));
} | @Test
public void testJsonNode()
throws IOException {
JsonNode node = JsonUtils.stringToJsonNode("{\"key\":\"VALUE\",\"my.secret\":\"SECRET\"}");
String output = _obfuscator.toJsonString(node);
Assert.assertTrue(output.contains(VALUE));
Assert.assertFalse(output.contains(SECRET));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.