focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
SocketAddress clientAddress;
String roleToken;
ErrorCode errorCode = ErrorCode.UNKNOWN;
try {
if (authData.hasDataFromPeer()) {
clientAddress = authDa... | @Test
public void testAuthenticateSignedToken() throws Exception {
List<String> roles = new ArrayList<String>() {
{
add("test_role");
}
};
RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build();
Str... |
public static int computeAvailableContainers(Resource available,
Resource required, EnumSet<SchedulerResourceTypes> resourceTypes) {
if (resourceTypes.contains(SchedulerResourceTypes.CPU)) {
return Math.min(
calculateRatioOrMaxValue(available.getMemorySize(), required.getMemorySize()),
c... | @Test
public void testComputeAvailableContainers() throws Exception {
Resource clusterAvailableResources = Resource.newInstance(81920, 40);
Resource nonZeroResource = Resource.newInstance(1024, 2);
int expectedNumberOfContainersForMemory = 80;
int expectedNumberOfContainersForCPU = 20;
verifyDi... |
static InjectorFunction injectorFunction(InjectorFunction existing, InjectorFunction... update) {
if (update == null) throw new NullPointerException("injectorFunctions == null");
LinkedHashSet<InjectorFunction> injectorFunctionSet =
new LinkedHashSet<InjectorFunction>(Arrays.asList(update));
if (inj... | @Test void injectorFunction_single() {
InjectorFunction existing = mock(InjectorFunction.class);
assertThat(injectorFunction(existing, two))
.isSameAs(two);
} |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
byte[] header = new byte[4];
IOUtils.read(stream, header, 0, 4); // Extract magic byte
if (header[0] == (byte) 'i' && hea... | @Test
public void testICNS() throws Exception {
Metadata metadata = new Metadata();
metadata.set(Metadata.CONTENT_TYPE, "image/icns");
metadata.set("Icons count", "2");
metadata.set("Icons details", "16x16 (24 bpp), 32x32 (24 bpp)");
metadata.set("Masked icon count", "2");
... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_no_new_duplicated_lines_density_when_no_lines() {
underTest.execute(new TestComputationStepContext());
assertNoRawMeasures(NEW_DUPLICATED_LINES_DENSITY_KEY);
} |
public static KeyFormat sanitizeKeyFormat(
final KeyFormat keyFormat,
final List<SqlType> newKeyColumnSqlTypes,
final boolean allowKeyFormatChangeToSupportNewKeySchema
) {
return sanitizeKeyFormatWrapping(
!allowKeyFormatChangeToSupportNewKeySchema ? keyFormat :
sanitizeKeyFormat... | @Test
public void shouldNotConvertFormatWhenSanitizingWithSingleColumnAndSupportedPrimitiveType() {
// Given:
final KeyFormat format = KeyFormat.nonWindowed(
FormatInfo.of(KafkaFormat.NAME),
SerdeFeatures.of());
// When:
final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyForm... |
@Deprecated
public static boolean isEmpty( String val ) {
return Utils.isEmpty( val );
} | @Test
public void testReleaseType() {
for ( Const.ReleaseType type : Const.ReleaseType.values() ) {
assertFalse( type.getMessage().isEmpty() );
}
} |
public static List<JobDataNodeLine> convertDataNodesToLines(final Map<String, List<DataNode>> actualDataNodes) {
List<Pair<String, JobDataNodeLine>> result = new LinkedList<>();
for (Entry<String, Map<String, List<DataNode>>> entry : groupDataSourceDataNodesMapByDataSourceName(actualDataNodes).entrySet(... | @Test
void assertConvertDataNodesToLinesWithMultipleDataSource() {
List<DataNode> dataNodes = Arrays.asList(new DataNode("ds_0", "t_order_0"), new DataNode("ds_0", "t_order_2"), new DataNode("ds_1", "t_order_1"), new DataNode("ds_1", "t_order_3"));
List<JobDataNodeLine> jobDataNodeLines = JobDataNod... |
@Override
public void write(Object object) throws IOException {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
preventMemoryLeak();
} | @Test
public void flushesAfterWrite() throws IOException {
// given
ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
String object = "foo";
// when
objectWriter.write(object);
// then
InOrder inOrder = inOrder(objectOutputStream);
inOrder.verify(objec... |
private synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
... | @Test
public void testNextId() throws Exception {
UUIDUtils uuidUtils = UUIDUtils.getInstance();
Class<?> uUIDUtilsClass = uuidUtils.getClass();
Field field = uUIDUtilsClass.getDeclaredField("lastTimestamp");
field.setAccessible(true);
field.set(uuidUtils, System.currentTimeM... |
@Override
public float readFloat() throws EOFException {
return Float.intBitsToFloat(readInt());
} | @Test
public void testReadFloatByteOrder() throws Exception {
double readFloat = in.readFloat(LITTLE_ENDIAN);
int intB = Bits.readIntL(INIT_DATA, 0);
double aFloat = Float.intBitsToFloat(intB);
assertEquals(aFloat, readFloat, 0);
} |
public static <T> RetryOperator<T> of(Retry retry) {
return new RetryOperator<>(retry);
} | @Test
public void returnOnErrorUsingMono() {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
RetryOperator<String> retryOperator = RetryOperator.of(retry);
given(helloWorldService.returnHelloWorld())
.willThrow(new HelloWorldException());
... |
@Override
public DdlCommand create(
final String sqlExpression,
final DdlStatement ddlStatement,
final SessionConfig config
) {
return FACTORIES
.getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> {
throw new KsqlException(
"Unable to find ddl command ... | @Test
public void shouldCreateCommandForDropTable() {
// Given:
final DropTable ddlStatement = new DropTable(TABLE_NAME, true, true);
// When:
final DdlCommand result = commandFactories
.create(sqlExpression, ddlStatement, SessionConfig.of(ksqlConfig, emptyMap()));
// Then:
assertTha... |
public static Builder builder(String testId) {
return new Builder(testId);
} | @Test
public void testCreateResourceManagerBuilderReturnsSplunkResourceManager() {
assertThat(
SplunkResourceManager.builder(TEST_ID)
.setHecPort(DEFAULT_SPLUNK_HEC_INTERNAL_PORT)
.setSplunkdPort(DEFAULT_SPLUNKD_INTERNAL_PORT)
.setHost(HOST)
... |
@VisibleForTesting
void validateParentMenu(Long parentId, Long childId) {
if (parentId == null || ID_ROOT.equals(parentId)) {
return;
}
// 不能设置自己为父菜单
if (parentId.equals(childId)) {
throw exception(MENU_PARENT_ERROR);
}
MenuDO menu = menuMapper... | @Test
public void testValidateParentMenu_parentTypeError() {
// mock 数据
MenuDO menuDO = buildMenuDO(MenuTypeEnum.BUTTON, "parent", 0L);
menuMapper.insert(menuDO);
// 准备参数
Long parentId = menuDO.getId();
// 调用,并断言异常
assertServiceException(() -> menuService.val... |
public static Writer createWriter(Configuration conf, Writer.Option... opts
) throws IOException {
Writer.CompressionOption compressionOption =
Options.getOption(Writer.CompressionOption.class, opts);
CompressionType kind;
if (compressionOption != null) {
kin... | @Test
public void testSerializationUsingWritableNameAlias() throws IOException {
Configuration config = new Configuration();
config.set(CommonConfigurationKeys.IO_SERIALIZATIONS_KEY, SimpleSerializer.class.getName());
Path path = new Path(System.getProperty("test.build.data", "."),
"SerializationU... |
private List<TarsUpstream> buildTarsUpstreamList(final List<URIRegisterDTO> uriList) {
return uriList.stream().map(dto -> CommonUpstreamUtils.buildDefaultTarsUpstream(dto.getHost(), dto.getPort()))
.collect(Collectors.toCollection(CopyOnWriteArrayList::new));
} | @Test
public void testBuildTarsUpstreamList() {
List<URIRegisterDTO> list = new ArrayList<>();
list.add(URIRegisterDTO.builder().appName("test1").rpcType(RpcTypeEnum.TARS.getName()).host("localhost").port(8090).build());
list.add(URIRegisterDTO.builder().appName("test2").rpcType(RpcTypeEnum.... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_map_of_non_serializable_value() {
Map<String, NonSerializableObject> original = new HashMap<>();
original.put("key", new NonSerializableObject("value"));
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(o... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNonEmpty_Array_nullFirst_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", null, new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.newField... |
@Override
public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
if (!coordinatorRequestManager.coordinator().isPresent() ||
membershipManager.shouldSkipHeartbeat()) {
membershipManager.onHeartbeatRequestSkipped();
return NetworkClientDelegate.PollResult.EMPTY... | @Test
public void testSuccessfulHeartbeatTiming() {
NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
assertEquals(0, result.unsentRequests.size(),
"No heartbeat should be sent while interval has not expired");
assertEquals(heartbeatRequ... |
public static Void unwrapAndThrowException(ServiceException se)
throws IOException, YarnException {
Throwable cause = se.getCause();
if (cause == null) {
// SE generated by the RPC layer itself.
throw new IOException(se);
} else {
if (cause instanceof RemoteException) {
Remot... | @Test
void testRPCRuntimeExceptionUnwrapping() {
String message = "RPCRuntimeExceptionUnwrapping";
RuntimeException re = new NullPointerException(message);
ServiceException se = new ServiceException(re);
Throwable t = null;
try {
RPCUtil.unwrapAndThrowException(se);
} catch (Throwable ... |
public static String getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
FileChecksums fileChecksums = CHECKSUM_CACHE.get(file);
if (fileChecksums == null) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
final MessageDige... | @Test
public void testGetChecksum_String_byteArr() {
String algorithm = "SHA1";
byte[] bytes = {-16, -111, 92, 95, 70, -72, -49, -94, -125, -27, -83, 103, -96, -101, 55, -109};
String expResult = "89268a389a97f0bfba13d3ff2370d8ad436e36f6";
String result = Checksum.getChecksum(algorit... |
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) {
SourceConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!ex... | @Test
public void testBatchConfigMergeEqual() {
SourceConfig sourceConfig = createSourceConfigWithBatch();
SourceConfig newSourceConfig = createSourceConfigWithBatch();
SourceConfig mergedConfig = SourceConfigUtils.validateUpdate(sourceConfig, newSourceConfig);
assertEquals(
... |
@Override
public CloseableIterator<ScannerReport.Symbol> readComponentSymbols(int componentRef) {
ensureInitialized();
return delegate.readComponentSymbols(componentRef);
} | @Test
public void readComponentSymbols_it_not_cached() {
writer.writeComponentSymbols(COMPONENT_REF, of(SYMBOL));
assertThat(underTest.readComponentSymbols(COMPONENT_REF)).isNotSameAs(underTest.readComponentSymbols(COMPONENT_REF));
} |
@Override
public Table getTable(String dbName, String tblName) {
Identifier identifier = new Identifier(dbName, tblName);
if (tables.containsKey(identifier)) {
return tables.get(identifier);
}
org.apache.paimon.table.Table paimonNativeTable;
try {
paim... | @Test
public void testGetTable(@Mocked FileStoreTable paimonNativeTable) throws Catalog.TableNotExistException {
List<DataField> fields = new ArrayList<>();
fields.add(new DataField(1, "col2", new IntType(true)));
fields.add(new DataField(2, "col3", new DoubleType(false)));
new MockU... |
public EndpointResponse streamQuery(
final KsqlSecurityContext securityContext,
final KsqlRequest request,
final CompletableFuture<Void> connectionClosedFuture,
final Optional<Boolean> isInternalRequest,
final MetricsCallbackHolder metricsCallbackHolder,
final Context context
) {
... | @Test
public void shouldWaitIfCommandSequenceNumberSpecified() throws Exception {
// When:
testResource.streamQuery(
securityContext,
new KsqlRequest(PUSH_QUERY_STRING, Collections.emptyMap(), Collections.emptyMap(), 3L),
new CompletableFuture<>(),
Optional.empty(),
new... |
public void setThemeValues(
@NonNull KeyboardTheme keyboardTheme,
float tabTextSize,
ColorStateList tabTextColor,
Drawable closeKeyboardIcon,
Drawable backspaceIcon,
Drawable settingsIcon,
Drawable keyboardDrawable,
Drawable mediaInsertionDrawable,
Drawable deleteRe... | @Test
public void testShowMediaIcon() throws Exception {
Context context = getApplicationContext();
mUnderTest.setThemeValues(
mKeyboardTheme,
10f,
new ColorStateList(new int[][] {{0}}, new int[] {Color.WHITE}),
context.getDrawable(R.drawable.ic_cancel),
context.getDraw... |
@Udf(description = "Returns the hyperbolic cosine of an INT value")
public Double cosh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic cosine of."
) final Integer value
) {
return cosh(value == null ? null : value... | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.cosh(-9.1), closeTo(4477.646407574158, 0.000000000000001));
assertThat(udf.cosh(-6.3), closeTo(272.286873215353, 0.000000000000001));
assertThat(udf.cosh(-7), closeTo(548.317035155212, 0.000000000000001));
assertThat(udf.cosh(-7L), c... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void prints_supported_keywords() {
parser.parse("--i18n", "en");
assertThat(output(), startsWith(" | feature | \"Feature\", \"Business Need\", \"Ability\" |"));
} |
public static void addEstimateTableReadersMemMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
... | @Test
public void shouldAddEstimateTableReadersMemMetric() {
final String name = "estimate-table-readers-mem";
final String description =
"Estimated memory in bytes used for reading SST tables, excluding memory used in block cache";
runAndVerifyMutableMetric(
name,
... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final PlanNode source = getSource();
final SchemaKStream<?> schemaKStream = source.buildStream(buildContext);
final QueryContext.Stacker contextStacker = buildContext.buildNodeContext(getId().toString());
return sch... | @Test
public void shouldCallInto() {
// When:
final SchemaKStream<?> result = outputNode.buildStream(planBuildContext);
// Then:
verify(sourceStream).into(
eq(ksqlTopic),
stackerCaptor.capture(),
eq(outputNode.getTimestampColumn())
);
assertThat(
stackerCaptor.... |
public static KsqlClient createInternalClient(
final Map<String, String> clientProps,
final BiFunction<Integer, String, SocketAddress> socketAddressFactory,
final Vertx vertx) {
final String internalClientAuth = clientProps.get(
KsqlRestConfig.KSQL_INTERNAL_SSL_CLIENT_AUTHENTICATION_CONFIG... | @Test
public void shouldCreateClient() {
// When:
KsqlClient client = InternalKsqlClientFactory.createInternalClient(
ImmutableMap.of(), SocketAddress::inetSocketAddress,
vertx);
// Then:
assertThat(client, notNullValue());
} |
public static <T> RBFNetwork<T> fit(T[] x, double[] y, RBF<T>[] rbf) {
return fit(x, y, rbf, false);
} | @Test
public void testBank32nh() {
System.out.println("bank32nh");
MathEx.setSeed(19650218); // to get repeatable results.
double[][] x = MathEx.clone(Bank32nh.x);
MathEx.standardize(x);
RegressionValidations<RBFNetwork<double[]>> result = CrossValidation.regression(10, x, ... |
@Override
public NacosUser authenticate(String username, String rawPassword) throws AccessException {
if (StringUtils.isBlank(username)) {
throw new AccessException("user not found!");
}
if (!caseSensitive) {
username = username.toLowerCase();
}
... | @Test
void testLdapAuthenticate() throws AccessException {
NacosUserDetails nacosUserDetails = new NacosUserDetails(user);
when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails);
NacosUser authenticate = ldapAuthenticationManager.authenticate("nacos", "test");
... |
public static AggregationUnit create(final AggregationType type, final boolean isDistinct) {
switch (type) {
case MAX:
return new ComparableAggregationUnit(false);
case MIN:
return new ComparableAggregationUnit(true);
case SUM:
... | @Test
void assertCreateComparableAggregationUnit() {
assertThat(AggregationUnitFactory.create(AggregationType.MIN, false), instanceOf(ComparableAggregationUnit.class));
assertThat(AggregationUnitFactory.create(AggregationType.MAX, false), instanceOf(ComparableAggregationUnit.class));
} |
public boolean isValid() throws IOException {
if (contractBinary.equals(BIN_NOT_PROVIDED)) {
throw new UnsupportedOperationException(
"Contract binary not present in contract wrapper, "
+ "please generate your wrapper using -abiFile=<file>");
}... | @Test
public void testIsValid() throws Exception {
prepareEthGetCode(TEST_CONTRACT_BINARY);
Contract contract = deployContract(createTransactionReceipt());
assertTrue(contract.isValid());
} |
@Override
public Optional<IndexMetaData> revise(final String tableName, final IndexMetaData originalMetaData, final ShardingRule rule) {
if (shardingTable.getActualDataNodes().isEmpty()) {
return Optional.empty();
}
IndexMetaData result = new IndexMetaData(IndexMetaDataUtils.getL... | @Test
void assertRevise() {
shardingRule = createShardingRule();
ShardingTable shardingTable = mock(ShardingTable.class);
when(shardingTable.getActualDataNodes()).thenReturn(Arrays.asList(new DataNode("SCHEMA_NAME", "TABLE_NAME_0"), new DataNode("SCHEMA_NAME", "TABLE_NAME_1")));
shar... |
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(!(o instanceof Acl)) {
return false;
}
if(!super.equals(o)) {
return false;
}
final Acl acl = (Acl) o;
return Objects.equals(canned,... | @Test
public void testEquals() {
assertEquals(
new Acl(new Acl.UserAndRole(new Acl.CanonicalUser("i-1"), new Acl.Role("r-1"))),
new Acl(new Acl.UserAndRole(new Acl.CanonicalUser("i-1"), new Acl.Role("r-1"))));
assertNotEquals(
new Acl(new Acl.UserAndRole(n... |
@Override
protected String getScheme() {
return config.getScheme();
} | @Test
public void testGetSchemeWithS3Options() {
S3FileSystem s3FileSystem = new S3FileSystem(s3Options());
assertEquals("s3", s3FileSystem.getScheme());
} |
boolean canSwap(Replica r1, Replica r2, ClusterModel clusterModel) {
String mappedRackIdOfR1 = mappedRackIdOf(r1.broker());
String mappedRackIdOfR2 = mappedRackIdOf(r2.broker());
boolean inSameRack = r1.broker() != r2.broker() && mappedRackIdOfR1.equals(mappedRackIdOfR2);
boolean rackAware =
clu... | @Test
public void testCanSwap() {
KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal();
ClusterModel clusterModel = createClusterModel();
Replica r1 = clusterModel.broker(0).replica(T0P0);
Replica r2 = clusterModel.broker(1).replica(T2P0);
assertTrue("Replica... |
public static boolean urlEquals(String string1, String string2) {
Uri url1 = Uri.parse(string1);
Uri url2 = Uri.parse(string2);
if (url1 == null || url2 == null || url1.getHost() == null || url2.getHost() == null) {
return string1.equals(string2); // Unable to parse url properly
... | @Test
public void testUrlEqualsSame() {
assertTrue(UrlChecker.urlEquals("https://www.example.com/test", "https://www.example.com/test"));
assertTrue(UrlChecker.urlEquals("https://www.example.com/test", "https://www.example.com/test/"));
assertTrue(UrlChecker.urlEquals("https://www.example.co... |
@SuppressWarnings("unchecked")
public static <T extends InputSplit> void createSplitFiles(Path jobSubmitDir,
Configuration conf, FileSystem fs, List<InputSplit> splits)
throws IOException, InterruptedException {
T[] array = (T[]) splits.toArray(new InputSplit[splits.size()]);
createSplitFiles(jobSub... | @Test
public void testMaxBlockLocationsNewSplits() throws Exception {
TEST_DIR.mkdirs();
try {
Configuration conf = new Configuration();
conf.setInt(MRConfig.MAX_BLOCK_LOCATIONS_KEY, 4);
Path submitDir = new Path(TEST_DIR.getAbsolutePath());
FileSystem fs = FileSystem.getLocal(conf);
... |
public static FallbackMethod create(String fallbackMethodName, Method originalMethod,
Object[] args, Object original, Object proxy) throws NoSuchMethodException {
MethodMeta methodMeta = new MethodMeta(
fallbackMethodName,
originalMethod.getParamet... | @Test
public void mismatchReturnType_shouldThrowNoSuchMethodException() throws Throwable {
FallbackMethodTest target = new FallbackMethodTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
assertThatThrownBy(() -> FallbackMethod
.create("duplicat... |
@Bean
public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties,
EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry,
RegistryEventConsumer<Retry> retryRegistryEventConsumer,
@Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCus... | @Test
public void testCreateRetryRegistryWithSharedConfigs() {
InstanceProperties defaultProperties = new InstanceProperties();
defaultProperties.setMaxAttempts(3);
defaultProperties.setWaitDuration(Duration.ofMillis(100L));
InstanceProperties sharedProperties = new InstancePropertie... |
@Override
public void execute(@Nonnull Runnable command) {
throwRejectedExecutionExceptionIfShutdown();
command.run();
} | @Test
void testRejectedExecute() {
testRejectedExecutionException(testInstance -> testInstance.execute(() -> {}));
} |
@Override
public int getMaxNonReclaimableBuffers(Object owner) {
checkIsInitialized();
int numBuffersUsedOrReservedForOtherOwners = 0;
for (Map.Entry<Object, TieredStorageMemorySpec> memorySpecEntry :
tieredMemorySpecs.entrySet()) {
Object userOwner = memorySpecE... | @Test
void testGetMaxNonReclaimableBuffers() throws IOException {
int numBuffers = 10;
int numExclusive = 5;
TieredStorageMemoryManagerImpl storageMemoryManager =
createStorageMemoryManager(
numBuffers,
Collections.singletonLis... |
public static long parseBytes(String text) throws IllegalArgumentException {
Objects.requireNonNull(text, "text cannot be null");
final String trimmed = text.trim();
if (trimmed.isEmpty()) {
throw new IllegalArgumentException("argument is an empty- or whitespace-only string");
... | @Test
void testParseInvalid() {
// null
assertThatThrownBy(() -> MemorySize.parseBytes(null))
.isInstanceOf(NullPointerException.class);
// empty
assertThatThrownBy(() -> MemorySize.parseBytes(""))
.isInstanceOf(IllegalArgumentException.class);
... |
protected TransactionReceipt executeTransaction(Function function)
throws IOException, TransactionException {
return executeTransaction(function, BigInteger.ZERO);
} | @Test
public void testStaticGasProvider() throws IOException, TransactionException {
StaticGasProvider gasProvider = new StaticGasProvider(BigInteger.TEN, BigInteger.ONE);
TransactionManager txManager = mock(TransactionManager.class);
when(txManager.executeTransaction(
... |
public void send(SlackMessage message, String webhookUrl) throws TemporaryEventNotificationException,
PermanentEventNotificationException, JsonProcessingException {
final Request request = new Request.Builder()
.url(webhookUrl)
.post(RequestBody.create(MediaType.pars... | @Test
public void sendsHttpRequestAsExpected_whenInputIsGood() throws Exception {
server.enqueue(new MockResponse().setResponseCode(200));
SlackClient slackClient = new SlackClient(httpClient, objectMapper);
slackClient.send(getMessage(), server.url("/").toString());
final Recorded... |
public static Map<String, Object> xmlToMap(String xmlStr) {
return xmlToMap(xmlStr, new HashMap<>());
} | @Test
public void xmlToMapTest() {
final String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"//
+ "<returnsms>"//
+ "<returnstatus>Success</returnstatus>"//
+ "<message>ok</message>"//
+ "<remainpoint>1490</remainpoint>"//
+ "<taskID>885</taskID>"//
+ "<successCounts>1</successCounts>"/... |
public Range span(Range other)
{
checkTypeCompatibility(other);
Marker lowMarker = Marker.min(low, other.getLow());
Marker highMarker = Marker.max(high, other.getHigh());
return new Range(lowMarker, highMarker);
} | @Test
public void testSpan()
{
assertEquals(Range.greaterThan(BIGINT, 1L).span(Range.lessThanOrEqual(BIGINT, 2L)), Range.all(BIGINT));
assertEquals(Range.greaterThan(BIGINT, 2L).span(Range.lessThanOrEqual(BIGINT, 0L)), Range.all(BIGINT));
assertEquals(Range.range(BIGINT, 1L, true, 3L, fa... |
public boolean validate(final Protocol protocol, final LoginOptions options) {
return protocol.validate(this, options);
} | @Test
public void testLoginWithoutEmptyPass() {
Credentials credentials = new Credentials("guest", "");
assertTrue(credentials.validate(new TestProtocol(Scheme.ftp), new LoginOptions()));
} |
public boolean isExpired() {
return nextVisibleTime <= System.currentTimeMillis();
} | @Test
public void testIsExpired() {
long startOffset = 1000L;
long retrieveTime = System.currentTimeMillis();
long invisibleTime = 1000L;
int reviveQueueId = 1;
String topicType = "NORMAL";
String brokerName = "BrokerA";
int queueId = 2;
long offset = ... |
@Override
public void execute(final ConnectionSession connectionSession) {
String databaseName = sqlStatement.getFromDatabase().map(schema -> schema.getDatabase().getIdentifier().getValue()).orElseGet(connectionSession::getUsedDatabaseName);
queryResultMetaData = createQueryResultMetaData(databaseNa... | @Test
void assertShowTablesExecutorWithoutFilter() throws SQLException {
ShowTablesExecutor executor = new ShowTablesExecutor(new MySQLShowTablesStatement(), TypedSPILoader.getService(DatabaseType.class, "MySQL"));
Map<String, ShardingSphereDatabase> databases = getDatabases();
ContextManage... |
@Override
public TbMsgAttributesNodeConfiguration defaultConfiguration() {
TbMsgAttributesNodeConfiguration configuration = new TbMsgAttributesNodeConfiguration();
configuration.setScope(DataConstants.SERVER_SCOPE);
configuration.setNotifyDevice(false);
configuration.setSendAttribute... | @Test
void testDefaultConfig_givenUpdateAttributesOnlyOnValueChange_thenTrue_sinceVersion1() {
assertThat(new TbMsgAttributesNodeConfiguration().defaultConfiguration().isUpdateAttributesOnlyOnValueChange()).isTrue();
} |
public LightWeightCache(final int recommendedLength,
final int sizeLimit,
final long creationExpirationPeriod,
final long accessExpirationPeriod) {
this(recommendedLength, sizeLimit,
creationExpirationPeriod, accessExpirationPeriod, new Timer());
} | @Test
public void testLightWeightCache() {
// test randomized creation expiration with zero access expiration
{
final long creationExpiration = ran.nextInt(1024) + 1;
check(1, creationExpiration, 0L, 1 << 10, 65537);
check(17, creationExpiration, 0L, 1 << 16, 17);
check(255, creationE... |
@ScalarOperator(MODULUS)
@SqlType(StandardTypes.TINYINT)
public static long modulus(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right)
{
try {
return left % right;
}
catch (ArithmeticException e) {
throw new PrestoException(... | @Test
public void testModulus()
{
assertFunction("TINYINT'37' % TINYINT'37'", TINYINT, (byte) 0);
assertFunction("TINYINT'37' % TINYINT'17'", TINYINT, (byte) (37 % 17));
assertFunction("TINYINT'17' % TINYINT'37'", TINYINT, (byte) (17 % 37));
assertFunction("TINYINT'17' % TINYINT'... |
public NamespaceBundle findBundle(TopicName topicName) {
checkArgument(nsname.equals(topicName.getNamespaceObject()));
return factory.getTopicBundleAssignmentStrategy().findBundle(topicName, this);
} | @Test
public void testFindBundle() throws Exception {
SortedSet<Long> partitions = new TreeSet<>();
partitions.add(0L);
partitions.add(0x40000000L);
partitions.add(0xa0000000L);
partitions.add(0xb0000000L);
partitions.add(0xc0000000L);
partitions.add(0xfffffff... |
@Override
public void onCopied(Item src, Item item) {
// bug 5056825 - Display name field should be cleared when you copy a job within the same folder.
if (item instanceof AbstractItem && src.getParent() == item.getParent()) {
AbstractItem dest = (AbstractItem) item;
try {
... | @Test
public void testOnCopied() throws Exception {
DisplayNameListener listener = new DisplayNameListener();
StubJob src = new StubJob();
src.doSetName("src");
StubJob dest = new StubJob();
dest.doSetName("dest");
dest.setDisplayName("this should be cleared");
... |
public static <K, V> Cache<K, V> subCache(
Cache<?, ?> cache, Object keyPrefix, Object... additionalKeyPrefix) {
if (cache instanceof SubCache) {
return new SubCache<>(
((SubCache<?, ?>) cache).cache,
((SubCache<?, ?>) cache).keyPrefix.subKey(keyPrefix, additionalKeyPrefix),
... | @Test
public void testSubCache() throws Exception {
testCache(Caches.subCache(Caches.eternal(), "prefix"));
} |
public String get(final String key) {
List<KeyValue> keyValues = null;
try {
keyValues = client.getKVClient().get(bytesOf(key)).get().getKvs();
} catch (InterruptedException | ExecutionException e) {
LOG.error(e.getMessage(), e);
}
if (CollectionUtils.isE... | @Test
public void testGet() {
String result = etcdClient.get(GET_KEY);
assertEquals(VALUE, result);
} |
public void removeFromFirst(final int toIndex) {
int alignedIndex = toIndex + this.firstOffset;
int toSegmentIndex = alignedIndex >> SEGMENT_SHIFT;
int toIndexInSeg = alignedIndex & (SEGMENT_SIZE - 1);
if (toSegmentIndex > 0) {
this.segments.removeRange(0, toSegmentIndex);
... | @Test
public void testRemoveFromFirst() {
fillList();
int len = SegmentList.SEGMENT_SIZE - 1;
this.list.removeFromFirst(len);
assertEquals(1000 - len, this.list.size());
for (int i = 0; i < 1000 - len; i++) {
assertEquals(i + len, (int) this.list.get(i));
... |
public void logPublicationRemoval(final String channel, final int sessionId, final int streamId)
{
final int length = SIZE_OF_INT * 3 + channel.length();
final int captureLength = captureLength(length);
final int encodedLength = encodedLength(captureLength);
final ManyToOneRingBuffe... | @Test
void logPublicationRemoval()
{
final int recordOffset = align(1111, ALIGNMENT);
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset);
final String uri = "uri";
final int sessionId = 42;
final int streamId = 19;
final int captureLength = uri.lengt... |
@Override
public LogicalSchema getSchema() {
return schema;
} | @Test
public void shouldBuildCorrectMultiArgAggregateSchema() {
// When:
final SchemaKStream<?> stream = buildQuery("SELECT col0, multi_arg(col0, col1, 20) FROM test1 "
+ "window TUMBLING (size 2 second) "
+ "WHERE col0 > 100 GROUP BY col0 EMIT CHANGES;");
// Then:
assertThat(... |
@Override
public KTable<K, V> reduce(final Reducer<V> reducer) {
return reduce(reducer, Materialized.with(keySerde, valueSerde));
} | @Test
public void shouldNotHaveNullReducerOnReduce() {
assertThrows(NullPointerException.class, () -> groupedStream.reduce(null));
} |
static int assignActiveTaskMovements(final Map<TaskId, SortedSet<ProcessId>> tasksToCaughtUpClients,
final Map<TaskId, SortedSet<ProcessId>> tasksToClientByLag,
final Map<ProcessId, ClientState> clientStates,
... | @Test
public void shouldMoveTasksToMostCaughtUpClientsAndAssignWarmupReplicasInTheirPlace() {
final int maxWarmupReplicas = Integer.MAX_VALUE;
final Map<TaskId, Long> client1Lags = mkMap(mkEntry(TASK_0_0, 10000L), mkEntry(TASK_0_1, 20000L), mkEntry(TASK_0_2, 30000L));
final Map<TaskId, Long>... |
public static Optional<JksOptions> buildJksKeyStoreOptions(
final Map<String, String> props,
final Optional<String> alias
) {
final String location = getKeyStoreLocation(props);
final String keyStorePassword = getKeyStorePassword(props);
final String keyPassword = getKeyPassword(props);
i... | @Test
public void shouldBuildKeyStoreJksOptionsWithPathAndPassword() {
// When
final Optional<JksOptions> jksOptions = VertxSslOptionsFactory.buildJksKeyStoreOptions(
ImmutableMap.of(
SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG,
"path",
SslConfigs.SSL_KEYSTORE_PASSWORD_... |
public void getOptionHelp() {
String message = null;
DatabaseMeta database = new DatabaseMeta();
getInfo( database );
String url = database.getExtraOptionsHelpText();
if ( ( url == null ) || ( url.trim().length() == 0 ) ) {
message = Messages.getString( "DataHandler.USER_NO_HELP_AVAILABLE" ... | @Test( expected = RuntimeException.class )
public void testGetOptionHelpNoDatabase() throws Exception {
when( accessBox.getSelectedItem() ).thenReturn( "JNDI" );
when( connectionBox.getSelectedItem() ).thenReturn( "MyDB" );
dataHandler.getOptionHelp();
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void endpointsByNamespaceWithMultipleNodePortPublicIpMatchByName() throws JsonProcessingException {
// given
stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsListResponse());
stub(String.format("/api/v1/namespaces/%s/endpoints", NAMESPACE), endpointsListResponse(... |
@SuppressWarnings("unchecked")
public static <T> T[] realloc(Class<T> klass, T[] src, int size, boolean ended)
{
T[] dest;
if (size > src.length) {
dest = (T[]) Array.newInstance(klass, size);
if (ended) {
System.arraycopy(src, 0, dest, 0, src.length);
... | @Test
public void testRealloc()
{
Integer[] src = new Integer[] { 1, 3, 5 };
Integer[] dest = Utils.realloc(Integer.class, src, 3, true);
assertThat(src.length, is(3));
assertThat(src, is(dest));
dest = Utils.realloc(Integer.class, src, 5, true);
assertThat(des... |
@Override
public RLock writeLock() {
return new RedissonWriteLock(commandExecutor, getName());
} | @Test
public void testExpireWrite() throws InterruptedException {
RReadWriteLock lock = redisson.getReadWriteLock("lock");
lock.writeLock().lock(2, TimeUnit.SECONDS);
final long startTime = System.currentTimeMillis();
Thread t = new Thread() {
public void run() {
... |
public CreateTableCommand createTableCommand(
final KsqlStructuredDataOutputNode outputNode,
final Optional<RefinementInfo> emitStrategy
) {
Optional<WindowInfo> windowInfo =
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo();
if (windowInfo.isPresent() && emitStrategy.isPresent()) ... | @Test
public void shouldThrowIfTableExists() {
//Given
final CreateTable ddlStatement = new CreateTable(TABLE_NAME,
TableElements.of(
tableElement("COL1", new Type(BIGINT), PRIMARY_KEY_CONSTRAINT),
tableElement("COL2", new Type(SqlTypes.STRING))),
false, false, withProp... |
@Override
public boolean next() throws SQLException {
return mergedResult.next();
} | @Test
void assertNext() throws SQLException {
assertFalse(new MaskMergedResult(mock(MaskRule.class), mock(SelectStatementContext.class), mergedResult).next());
} |
public InputStreamWrapper getInputStreamForItem(UUID jobId, DownloadableItem item)
throws IOException {
String fetchableUrl = item.getFetchableUrl();
if (item.isInTempStore()) {
return jobStore.getStream(jobId, fetchableUrl);
}
HttpURLConnection conn = getConnection(fetchableUrl);
retu... | @Test
public void getInputStreamFromTempStore() throws Exception {
long expectedBytes = 323;
when(jobStore.getStream(any(), anyString())).thenReturn(
new InputStreamWrapper(null, expectedBytes));
boolean inTempStore = true;
String fetchableUrl = "https://example.com";
DownloadableItem item... |
@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
&& (node.has("minLength") || node.has("maxLength"))
&& isApplicableType(field... | @Test
public void testMaxLength() {
when(config.isIncludeJsr303Annotations()).thenReturn(true);
final int maxValue = new Random().nextInt();
when(subNode.asInt()).thenReturn(maxValue);
when(node.get("maxLength")).thenReturn(subNode);
when(fieldVar.annotate(sizeClass)).thenRet... |
@Override
public void onRemovedJobGraph(JobID jobId) {
runIfStateIs(State.RUNNING, () -> handleRemovedJobGraph(jobId));
} | @Test
void onRemovedJobGraph_failingRemovalCall_failsFatally() throws Exception {
final FlinkException testException = new FlinkException("Test exception");
final TestingDispatcherGatewayService testingDispatcherService =
TestingDispatcherGatewayService.newBuilder()
... |
public Optional<ScimGroupDto> findByScimUuid(DbSession dbSession, String scimGroupUuid) {
return Optional.ofNullable(mapper(dbSession).findByScimUuid(scimGroupUuid));
} | @Test
void findByScimUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() {
assertThat(scimGroupDao.findByScimUuid(db.getSession(), "unknownId")).isEmpty();
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testEmptyControlBatch() {
buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int currentOffset = 1;
/... |
@Around("dataPermissionCut()")
public Object around(final ProceedingJoinPoint point) {
// CHECKSTYLE:OFF
try {
return point.proceed(getFilterSQLData(point));
} catch (Throwable throwable) {
throw new ShenyuException(throwable);
}
// CHECKSTYLE:ON
} | @Test
public void testAround() {
ProceedingJoinPoint point = mock(ProceedingJoinPoint.class);
boolean thrown = false;
try {
dataPermissionAspect.around(point);
} catch (ShenyuException e) {
thrown = true;
}
assertTrue(thrown);
} |
static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
// copy all the bytes that return immediately, stopping at the first
// read that doesn't return a full buffer.
int nextReadLength = Math.min(buf.remaining(), temp.length);
int totalBytesRead = 0;
int bytesR... | @Test
public void testDirectLimit() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocate(20);
readBuffer.limit(8);
MockInputStream stream = new MockInputStream(7);
int len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, TEMP.get());
Assert.assertEquals(7, len);
... |
public boolean usable() {
if (path.toFile().exists()) {
return updateValues(time.milliseconds());
} else {
LOG.debug("Disabling IO metrics collection because {} does not exist.", path);
return false;
}
} | @Test
public void testUnableToReadNonexistentProcFile() throws IOException {
TestDirectory testDirectory = new TestDirectory();
Time time = new MockTime(0L, 100L, 1000L);
LinuxIoMetricsCollector collector = new LinuxIoMetricsCollector(testDirectory.baseDir.getAbsolutePath(), time);
... |
public void writeEndpointCertificateMetadata(ApplicationId application, EndpointCertificateMetadata endpointCertificateMetadata) {
try {
Slime slime = new Slime();
EndpointCertificateMetadataSerializer.toSlime(endpointCertificateMetadata, slime.setObject());
curator.set(endpo... | @Test
public void can_write_object_format() {
var endpointCertificateMetadata = new EndpointCertificateMetadata("key-name", "cert-name", 1, digicert);
endpointCertificateMetadataStore.writeEndpointCertificateMetadata(applicationId, endpointCertificateMetadata);
assertEquals("{\"keyName\":\... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void bytesToJson() throws IOException {
JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.BYTES_SCHEMA, "test-string".getBytes()));
validateEnvelope(converted);
assertEquals(parse("{ \"type\": \"bytes\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE... |
@Override
public boolean isRegistered(JobID jobId) {
return jobManagerRunners.containsKey(jobId);
} | @Test
void testIsRegistered() {
final JobID jobId = new JobID();
testInstance.register(TestingJobManagerRunner.newBuilder().setJobId(jobId).build());
assertThat(testInstance.isRegistered(jobId)).isTrue();
} |
public static String uncompress(byte[] compressedURL) {
StringBuffer url = new StringBuffer();
switch (compressedURL[0] & 0x0f) {
case EDDYSTONE_URL_PROTOCOL_HTTP_WWW:
url.append(URL_PROTOCOL_HTTP_WWW_DOT);
break;
case EDDYSTONE_URL_PROTOCOL_HTTPS_... | @Test
public void testUncompressHttpsURLWithTrailingSlash() {
String testURL = "https://www.radiusnetworks.com/";
byte[] testBytes = {0x01, 'r', 'a', 'd', 'i', 'u', 's', 'n', 'e', 't', 'w', 'o', 'r', 'k', 's', 0x00};
assertEquals(testURL, UrlBeaconUrlCompressor.uncompress(testBytes));
} |
@RequiresApi(Build.VERSION_CODES.R)
@Override
public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions();
if (inlineSuggestions.size() > 0) {
mInlineSuggestionAction.onNewSuggestions(inline... | @Test
public void testActionStripAddedForAi() {
simulateOnStartInputFlow();
mAnySoftKeyboardUnderTest.onInlineSuggestionsResponse(
mockResponse(new String[] {"aiai", "newFeature"}, Mockito.mock(InlineContentView.class)));
ImageView icon =
mAnySoftKeyboardUnderTest
.getInputView... |
@Override
public URL getLocalArtifactUrl(DependencyJar dependency) {
return delegate.getLocalArtifactUrl(dependency);
} | @Test
public void whenRobolectricDepsPropertiesPropertyAndOfflineProperty() throws Exception {
Path depsPath =
tempDirectory.createFile(
"deps.properties", "org.robolectric\\:android-all\\:" + VERSION + ": file-123.jar");
Path jarPath = tempDirectory.createFile("file-123.jar", "...");
... |
@Override
public void updateDiyTemplate(DiyTemplateUpdateReqVO updateReqVO) {
// 校验存在
validateDiyTemplateExists(updateReqVO.getId());
// 校验名称唯一
validateNameUnique(updateReqVO.getId(), updateReqVO.getName());
// 更新
DiyTemplateDO updateObj = DiyTemplateConvert.INSTANCE.... | @Test
public void testUpdateDiyTemplate_notExists() {
// 准备参数
DiyTemplateUpdateReqVO reqVO = randomPojo(DiyTemplateUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> diyTemplateService.updateDiyTemplate(reqVO), DIY_TEMPLATE_NOT_EXISTS);
} |
void pushId(int id) {
int bucketIdx = id / BUCKET_SIZE;
if (bucketIdx >= idBuckets.length) {
throw new IllegalArgumentException("id too large: " + id);
}
DnsQueryIdRange bucket = idBuckets[bucketIdx];
assert bucket != null;
bucket.pushId(id);
if (buck... | @Test
public void testOverflow() {
final DnsQueryIdSpace ids = new DnsQueryIdSpace();
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
ids.pushId(1);
}
});
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertUnsupported() {
Column column =
PhysicalColumn.of(
"test",
new MapType<>(BasicType.STRING_TYPE, BasicType.STRING_TYPE),
(Long) null,
true,
nu... |
@Override
public Map<K, V> getCachedMap() {
return localCacheView.getCachedMap();
} | @Test
public void testReplaceOldValueFail() {
RLocalCachedMap<SimpleKey, SimpleValue> map = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test"));
Map<SimpleKey, SimpleValue> cache = map.getCachedMap();
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.re... |
public String convert(ILoggingEvent event) {
StringBuilder sb = new StringBuilder();
int pri = facility + LevelToSyslogSeverity.convert(event);
sb.append("<");
sb.append(pri);
sb.append(">");
sb.append(computeTimeStampString(event.getTimeStamp()));
sb.append(' '... | @Test
public void datesLessThanTen() {
// RFC 3164, section 4.1.2:
// If the day of the month is less than 10, then it MUST be represented as
// a space and then the number. For example, the 7th day of August would be
// represented as "Aug 7", with two spaces between the "g" and the... |
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + urn.hashCode();
return result;
} | @Test
public void hashcode_sameURN() {
ScheduledTaskHandler handler = ScheduledTaskHandlerImpl.of(1, "MyScheduler", "MyTask");
String myTaskURN = handler.toUrn();
ScheduledExecutorWaitNotifyKey keyA = new ScheduledExecutorWaitNotifyKey("myScheduler", myTaskURN);
ScheduledExecutorWai... |
@Override
public Set<MappedFieldTypeDTO> fieldTypesByStreamIds(Collection<String> streamIds, TimeRange timeRange) {
final Set<String> indexSets = streamService.indexSetIdsByIds(streamIds);
final Set<String> indexNames = this.indexLookup.indexNamesForStreamsInTimeRange(ImmutableSet.copyOf(streamIds),... | @Test
public void testDifferenceBetweenStreamAwareAndUnawareFieldTypeRetrieval() {
final Configuration withStreamAwarenessOn = spy(new Configuration());
doReturn(true).when(withStreamAwarenessOn).maintainsStreamAwareFieldTypes();
MappedFieldTypesServiceImpl streamAwareMappedFieldTypesService... |
@Override
public long getLargestWorkerCount() {
return asyncExecutionMonitoring.getLargestWorkerCount();
} | @Test
public void getLargestWorkerCount_delegates_to_AsyncExecutionMonitoring() {
when(asyncExecutionMonitoring.getLargestWorkerCount()).thenReturn(12);
assertThat(underTest.getLargestWorkerCount()).isEqualTo(12);
verify(asyncExecutionMonitoring).getLargestWorkerCount();
} |
@Udf(description = "When transforming a map, "
+ "two functions must be provided. "
+ "For each map entry, the first function provided will "
+ "be applied to the key and the second one applied to the value. "
+ "Each function must have two arguments. "
+ "The two arguments for each functi... | @Test
public void shouldReturnTransformedMap() {
final Map<Integer, Integer> map1 = new HashMap<>();
assertThat(udf.transformMap(map1, biFunction1(), biFunction2()), is(Collections.emptyMap()));
map1.put(3, 100);
map1.put(1, -2);
assertThat(udf.transformMap(map1, biFunction1(), biFunction2()), is(... |
public static int getGenderByIdCard(String idcard) {
Assert.notBlank(idcard);
final int len = idcard.length();
if (!(len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH)) {
throw new IllegalArgumentException("ID Card length must be 15 or 18");
}
if (len == CHINA_ID_MIN_LENGTH) {
idcard = convert15... | @Test
public void getGenderByIdCardTest() {
int gender = IdcardUtil.getGenderByIdCard(ID_18);
assertEquals(1, gender);
} |
@Nonnull
public static <C> SourceBuilder<C>.TimestampedStream<Void> timestampedStream(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new TimestampedStream<>();
} | @Test
public void stream_socketSource_withTimestamps_andLateness() throws IOException {
// Given
try (ServerSocket serverSocket = new ServerSocket(0)) {
startServer(serverSocket);
// When
int localPort = serverSocket.getLocalPort();
FunctionEx<String,... |
public ResourceProperties getResourceProperties()
{
return _resourceProperties;
} | @Test
public void testResourceProperties()
{
Set<ResourceMethod> expectedSupportedMethods = new HashSet<>();
expectedSupportedMethods.add(ResourceMethod.GET);
expectedSupportedMethods.add(ResourceMethod.BATCH_PARTIAL_UPDATE);
ResourceSpec expectedResourceSpec = new ResourceSpecImpl(
... |
@Override
public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) {
final ModelId modelId = entityDescriptor.id();
final Optional<EventDefinitionDto> eventDefinition = eventDefinitionService.get(modelId.id());
if (!eventDefinition.isPr... | @Test
@MongoDBFixtures("EventDefinitionFacadeTest.json")
public void exportEntity() {
final ModelId id = ModelId.of("5d4032513d2746703d1467f6");
when(jobDefinitionService.getByConfigField(eq("event_definition_id"), eq(id.id())))
.thenReturn(Optional.of(mock(JobDefinitionDto.clas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.