focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sort_by_path() {
ComponentTreeRequest wsRequest = newRequest(singletonList(PATH_SORT), true, null);
List<ComponentDto> result = sortComponents(wsRequest);
assertThat(result).extracting("path")
.containsExactly("path-1", "path-2", "path-3", "path-4", "path-5", "path-6", "path-7", "path-8... |
public static String getClientHostName(AlluxioConfiguration conf) {
if (conf.isSet(PropertyKey.USER_HOSTNAME)) {
return conf.getString(PropertyKey.USER_HOSTNAME);
}
return getLocalHostName((int) conf.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS));
} | @Test
public void getConfiguredClientHostname() {
mConfiguration.set(PropertyKey.USER_HOSTNAME, "clienthost");
assertEquals("clienthost", NetworkAddressUtils.getClientHostName(mConfiguration));
} |
public static String toJsonStr(JSON json, int indentFactor) {
if (null == json) {
return null;
}
return json.toJSONString(indentFactor);
} | @Test
public void testArrayEntity() {
final String jsonStr = JSONUtil.toJsonStr(new ArrayEntity());
assertEquals("{\"a\":[],\"b\":[0],\"c\":[],\"d\":[],\"e\":[]}", jsonStr);
} |
@Override
public boolean isSigned(final int columnIndex) throws SQLException {
try {
return resultSetMetaData.isSigned(columnIndex);
} catch (final SQLFeatureNotSupportedException ignored) {
return false;
}
} | @Test
void assertIsSigned() throws SQLException {
assertTrue(queryResultMetaData.isSigned(1));
} |
@SuppressWarnings("WeakerAccess")
public TimestampExtractor defaultTimestampExtractor() {
return getConfiguredInstance(DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, TimestampExtractor.class);
} | @Test
public void shouldUseCorrectDefaultsWhenNoneSpecified() {
final StreamsConfig config = new StreamsConfig(getStreamsConfig());
assertInstanceOf(FailOnInvalidTimestamp.class, config.defaultTimestampExtractor());
assertThrows(ConfigException.class, config::defaultKeySerde);
asser... |
@CanIgnoreReturnValue
public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
ListMultimap<?, ?> extra = difference(actual, expectedMult... | @Test
public void containsExactlyEntriesIn() {
ImmutableListMultimap<Integer, String> listMultimap =
ImmutableListMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ImmutableSetMultimap<Integer, String> setMultimap = ImmutableSetMultimap.copyOf(listMultimap);
assertThat(listMultimap... |
public Lock lock(ApplicationId application) {
return lock(application, defaultLockTimeout);
} | @Test
public void locks_can_be_acquired_and_released() {
ApplicationId app = ApplicationId.from(TenantName.from("testTenant"), ApplicationName.from("testApp"), InstanceName.from("testInstance"));
try (var ignored = zkClient.lock(app)) {
throw new RuntimeException();
}
ca... |
@Override
public List<String> batchUpdateMetadata(String namespaceId, InstanceOperationInfo instanceOperationInfo,
Map<String, String> metadata) throws NacosException {
boolean isEphemeral = !UtilsAndCommons.PERSIST.equals(instanceOperationInfo.getConsistencyType());
String serviceName =... | @Test
void testBatchUpdateMetadata() throws NacosException {
Instance instance = new Instance();
instance.setServiceName("C");
instance.setIp("1.1.1.1");
instance.setPort(8848);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(Collections.singletonLis... |
private CommunityName(String name) {
this.name = name;
} | @Test
public void testCommunityName() {
CommunityName communityName = CommunityName.communityName(cName);
assertNotNull("The CommunityName should not be null.", communityName);
assertEquals("The name should match the expected value.", cName, communityName.name());
} |
@Bean
@ConditionalOnMissingBean(WebsocketCollector.class)
public WebsocketCollector websocketCollector() {
return new WebsocketCollector();
} | @Test
public void testWebsocketCollector() {
WebSocketSyncConfiguration websocketListener = new WebSocketSyncConfiguration();
assertNotNull(websocketListener.websocketCollector());
} |
@Override
public Iterable<GenericRow> transform(
final K readOnlyKey,
final GenericRow value,
final KsqlProcessingContext ctx
) {
if (value == null) {
return null;
}
final List<Iterator<?>> iters = new ArrayList<>(tableFunctionAppliers.size());
int maxLength = 0;
for (fi... | @Test
public void shouldZipTwoFunctions() {
// Given:
final TableFunctionApplier applier1 = createApplier(Arrays.asList(10, 10, 10));
final TableFunctionApplier applier2 = createApplier(Arrays.asList(20, 20));
final KudtfFlatMapper<String> flatMapper =
new KudtfFlatMapper<>(ImmutableList.of(ap... |
public static void rethrowIOException(Throwable cause)
throws IOException {
if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
... | @Test
public void testRethrowIOException() {
IOException ioe = new IOException("test");
try {
rethrowIOException(ioe);
fail("Should rethrow IOException");
} catch (IOException e) {
assertSame(ioe, e);
}
} |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public static TableReference parseTableSpec(String tableSpec) {
Matcher match = BigQueryIO.TABLE_SPEC.matcher(tableSpec);
if (!match.matches()) {
throw new IllegalArgumentException(
String.format(
... | @Test
public void testTableParsingError() {
thrown.expect(IllegalArgumentException.class);
BigQueryHelpers.parseTableSpec("0123456:foo.bar");
} |
public static InetAddress getLocalAddress() {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddress0();
LOCAL_ADDRESS = localAddress;
return localAddress;
} | @Test
void testGetLocalAddress() {
InetAddress address = NetUtils.getLocalAddress();
assertNotNull(address);
assertTrue(NetUtils.isValidLocalHost(address.getHostAddress()));
} |
public TemplateResponse mapToTemplateResponse(ReviewGroup reviewGroup, Template template) {
List<SectionResponse> sectionResponses = template.getSectionIds()
.stream()
.map(templateSection -> mapToSectionResponse(templateSection, reviewGroup))
.toList();
... | @Test
void ์น์
์_์ ํ๋_์ต์
์ด_ํ์์๋_๊ฒฝ์ฐ_์ ๊ณตํ์ง_์๋๋ค() {
// given
Question question = new Question(true, QuestionType.TEXT, "์ง๋ฌธ", "๊ฐ์ด๋๋ผ์ธ", 1);
questionRepository.save(question);
Section section = new Section(VisibleType.ALWAYS, List.of(question.getId()), null, "์น์
๋ช
", "๋ง๋จธ๋ฆฌ", 1);
sectionRe... |
@VisibleForTesting
void forceFreeMemory()
{
memoryManager.close();
} | @Test
public void testForceFreeMemory()
throws Throwable
{
ArbitraryOutputBuffer buffer = createArbitraryBuffer(createInitialEmptyOutputBuffers(ARBITRARY), sizeOfPages(10));
for (int i = 0; i < 3; i++) {
addPage(buffer, createPage(i));
}
OutputBufferMemory... |
public static SqlDecimal of(final int precision, final int scale) {
return new SqlDecimal(precision, scale);
} | @Test(expected = SchemaException.class)
public void shouldThrowIfScaleGreaterThanPrecision() {
SqlDecimal.of(2, 3);
} |
@Override
public void authorize(Permission permission, NacosUser nacosUser) throws AccessException {
if (Loggers.AUTH.isDebugEnabled()) {
Loggers.AUTH.debug("auth permission: {}, nacosUser: {}", permission, nacosUser);
}
if (nacosUser.isGlobalAdmin()) {
return;
... | @Test
void testAuthorize() {
Permission permission = new Permission();
NacosUser nacosUser = new NacosUser();
when(roleService.hasPermission(nacosUser, permission)).thenReturn(false);
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.autho... |
public static BadRequestException invalidRoleTypeFormat(String format) {
return new BadRequestException("invalid roleType format:%s", format);
} | @Test
public void testInvalidRoleTypeFormat() {
BadRequestException invalidRoleTypeFormat = BadRequestException.invalidRoleTypeFormat("format");
assertEquals("invalid roleType format:format", invalidRoleTypeFormat.getMessage());
} |
public HikariDataSource getDataSource() {
return ds;
} | @Test
@Ignore
public void testCustomMysqlDataSource() {
DataSource ds = SingletonServiceFactory.getBean(CustomMysqlDataSource.class).getDataSource();
assertNotNull(ds);
try(Connection connection = ds.getConnection()){
assertNotNull(connection);
} catch (SQLException ... |
@Override
public void close() throws Exception {
if (running.compareAndSet(true, false)) {
LOG.info("Closing {}.", this);
curatorFramework.getConnectionStateListenable().removeListener(listener);
Exception exception = null;
try {
treeCache.c... | @Test
void testLeaderElectionWithMultipleDrivers() throws Exception {
final CuratorFrameworkWithUnhandledErrorListener curatorFramework = startCuratorFramework();
try {
Set<ElectionDriver> electionDrivers =
Stream.generate(
() ->
... |
@Override
public void close() {
for (ContextManagerLifecycleListener each : ShardingSphereServiceLoader.getServiceInstances(ContextManagerLifecycleListener.class)) {
each.onDestroyed(this);
}
executorEngine.close();
metaDataContexts.get().close();
persistServiceFa... | @Test
void assertClose() {
contextManager.close();
verify(metaDataContexts).close();
} |
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
URL indexResource = getServletContext().getResource("/index.html");
String content = IOUtils.toString(indexResource, StandardCharsets.UTF_8);
// read original content... | @Test
@Disabled("ignored due to zeppelin-web-angular not build for core tests")
void testZeppelinWebAngularHtmlAddon() throws IOException, ServletException {
ZeppelinConfiguration zConf = mock(ZeppelinConfiguration.class);
when(zConf.getHtmlBodyAddon()).thenReturn(TEST_BODY_ADDON);
when(zConf.... |
@Override
public Optional<SoamId> createLm(MdId mdName, MaIdShort maName, MepId mepId,
LossMeasurementCreate lm) throws CfmConfigException {
throw new UnsupportedOperationException("Not yet implemented");
} | @Test
public void testCreateLm() throws CfmConfigException {
//TODO: Implement underlying method
try {
soamManager.createLm(MDNAME1, MANAME1, MEPID1, null);
fail("Expecting UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
}
} |
public List<StageConfig> validStagesForFetchArtifact(PipelineConfig downstreamPipeline, CaseInsensitiveString currentDownstreamStage) {
for (DependencyMaterialConfig dependencyMaterial : downstreamPipeline.dependencyMaterialConfigs()) {
if (dependencyMaterial.getPipelineName().equals(name)) {
... | @Test
public void shouldReturnStagesBeforeCurrentForSelectedPipeline() {
PipelineConfig downstream = PipelineConfigMother.createPipelineConfigWithStages("downstream", "s1", "s2");
List<StageConfig> fetchableStages = downstream.validStagesForFetchArtifact(downstream, new CaseInsensitiveString("s2"));... |
private void checkVersion() throws IOException {
Version loadedVersion = loadVersion();
LOG.info("Loaded timeline store version info " + loadedVersion);
if (loadedVersion.equals(getCurrentVersion())) {
return;
}
if (loadedVersion.isCompatibleTo(getCurrentVersion())) {
LOG.info("Storing t... | @Test
void testCheckVersion() throws IOException {
RollingLevelDBTimelineStore dbStore = (RollingLevelDBTimelineStore) store;
// default version
Version defaultVersion = dbStore.getCurrentVersion();
assertEquals(defaultVersion, dbStore.loadVersion());
// compatible version
Version compatibleV... |
public static String findFirstUniqueAndStableStanzaID( final Packet packet, final String by )
{
if ( packet == null )
{
throw new IllegalArgumentException( "Argument 'packet' cannot be null." );
}
if ( by == null || by.isEmpty() )
{
throw new IllegalAr... | @Test
public void testParseNonUUIDValue() throws Exception
{
// Setup fixture.
final Packet input = new Message();
final JID self = new JID( "foobar" );
final String expected = "not-a-uuid";
final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp... |
@Override
public boolean replace(K key, long expectedOldValue, long newValue) {
return complete(asyncCounterMap.replace(key, expectedOldValue, newValue));
} | @Test
public void testReplace() {
atomicCounterMap.putIfAbsent(KEY1, VALUE1);
boolean replaced = atomicCounterMap.replace(KEY1, VALUE1, VALUE1 * 2);
assertThat(replaced, is(true));
Long afterReplace = atomicCounterMap.get(KEY1);
assertThat(afterReplace, is(VALUE1 * 2));
... |
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) {
List<String> basePath = getPathComponents(canonicalBaseFile);
List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize);
//if the roots aren't the same (i.e. different drives on a ... | @Test
public void pathUtilTest7() {
File[] roots = File.listRoots();
File basePath = new File(roots[0] + "some");
File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir");
String path = PathUtil.getRelativeFileInternal(basePath, relativePath);
Assert.as... |
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer)
{
return read(buffer, consumer, 0);
} | @Test
void shouldReadFirstObservation()
{
final ErrorConsumer consumer = mock(ErrorConsumer.class);
final long timestamp = 7;
final RuntimeException error = new RuntimeException("Test Error");
when(clock.time()).thenReturn(timestamp);
log.record(error);
assert... |
@Override
public Optional<RegistryAuthenticator> handleHttpResponseException(
ResponseException responseException) throws ResponseException, RegistryErrorException {
// Only valid for status code of '401 Unauthorized'.
if (responseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) {
... | @Test
public void testHandleHttpResponseException_badAuthenticationMethod() throws ResponseException {
String authenticationMethod = "bad authentication method";
Mockito.when(mockResponseException.getStatusCode())
.thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
Mockito.when(mockResponseExc... |
@Override
public Set<OAuth2AccessTokenEntity> getAllAccessTokensForUser(String userName) {
return tokenRepository.getAccessTokensByUserName(userName);
} | @Test
public void getAllAccessTokensForUser(){
when(tokenRepository.getAccessTokensByUserName(userName)).thenReturn(newHashSet(accessToken));
Set<OAuth2AccessTokenEntity> tokens = service.getAllAccessTokensForUser(userName);
assertEquals(1, tokens.size());
assertTrue(tokens.contains(accessToken));
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
if(containerService.isContainer(file)) {
final PathAttributes attributes = ... | @Test
public void testFindRoot() throws Exception {
final AzureAttributesFinderFeature f = new AzureAttributesFinderFeature(session, null);
assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory))));
} |
public double getX() {
return position.x();
} | @Test
public void testGetX() throws Exception {
World world = mock(World.class);
Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0));
assertEquals(TEST_VALUE, location.getX(), EPSILON);
} |
public Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> newChannelInitializers() {
Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> channelInitializers = new HashMap<>();
Set<InetSocketAddress> addresses = new HashSet<>();
for (Map.Entry<String, Proto... | @Test(expectedExceptions = RuntimeException.class)
public void testNewChannelInitializersOverlapped() {
ChannelInitializer<SocketChannel> i1 = mock(ChannelInitializer.class);
ChannelInitializer<SocketChannel> i2 = mock(ChannelInitializer.class);
Map<InetSocketAddress, ChannelInitializer<Sock... |
public static Config resolve(Config config) {
var resolveSystemProperty = System.getenv("KORA_SYSTEM_PROPERTIES_RESOLVE_ENABLED");
if (resolveSystemProperty == null) {
resolveSystemProperty = System.getProperty("kora.system.properties.resolve.enabled", "true");
}
var ctx = ne... | @Test
void testResolveReference() {
var config = fromMap(Map.of(
"object", Map.of(
"field", "test-value"
),
"reference", "${object.field}"
)).resolve();
assertThat(config.get("reference").asString()).isEqualTo("test-value");
} |
public CqlSessionSelectResult tableDetail(String clusterId, TableDTO.ClusterTableGetArgs args) {
CqlSession session = cqlSessionFactory.get(clusterId);
int limit = 1;
SimpleStatement statement = ClusterUtils.getSchemaTables(session, args.getKeyspace())
.all()
.whereColum... | @Test
@Disabled
//TODO ๋ณ๊ฒฝํ์
void get_table_in_keyspace() {
ClusterTableGetArgs args = ClusterTableGetArgs.builder()
.keyspace(keyspaceName)
.table("test_table_1")
.build();
// when
CqlSessionSelectResult sut = clusterTableGetCommander.tableDetail(CLUS... |
@Path("batch")
@POST
public Response batchReplication(ReplicationList replicationList) {
try {
ReplicationListResponse batchResponse = new ReplicationListResponse();
for (ReplicationInstance instanceInfo : replicationList.getReplicationList()) {
try {
... | @Test
public void testCancelBatching() throws Exception {
when(instanceResource.cancelLease(anyString())).thenReturn(Response.ok().build());
ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Cancel, instanceInfo));
Response response = peerReplicationResou... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest));
} | @Test
public void containsAtLeastVarargInOrderFailure() {
ImmutableMultimap<Integer, String> actual =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
assertThat(actual).containsAtLeast(4, "four", 3, "six", 3, "two", 3, "one");
expectFailureWhenTestingThat(actual)
... |
@Override
public void v(String tag, String message, Object... args) {
Log.v(tag, formatString(message, args));
} | @Test
public void verboseLoggedCorrectly() {
String expectedMessage = "Hello World";
logger.v(tag, "Hello %s", "World");
assertLogged(VERBOSE, tag, expectedMessage, null);
} |
public static List<ArtifactInformation> getArtifacts(List<String> stagingFiles) {
ImmutableList.Builder<ArtifactInformation> artifactsBuilder = ImmutableList.builder();
Set<String> deduplicatedStagingFiles = new LinkedHashSet<>(stagingFiles);
for (String path : deduplicatedStagingFiles) {
File file;
... | @Test
public void testGetArtifactsBadFileLogsInfo() throws Exception {
File file1 = File.createTempFile("file1-", ".txt");
file1.deleteOnExit();
List<ArtifactInformation> artifacts =
Environments.getArtifacts(ImmutableList.of(file1.getAbsolutePath(), "spurious_file"));
assertThat(artifacts, ... |
public Map<ReservationInterval, Resource> toIntervalMap() {
readLock.lock();
try {
Map<ReservationInterval, Resource> allocations =
new TreeMap<ReservationInterval, Resource>();
// Empty
if (isEmpty()) {
return allocations;
}
Map.Entry<Long, Resource> lastEntry... | @Test
public void testToIntervalMap() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
Map<ReservationInterval, Resource> mapAllocations;
// Check empty
mapAllocations = rleSparseVector.... |
public static MapperReference getMapper() {
return MAPPER_REFERENCE.get();
} | @Test
public void testMetricsMixIn() {
ObjectMapper objectMapper = ObjectMapperFactory.getMapper().getObjectMapper();
try {
Metrics metrics = new Metrics();
String json = objectMapper.writeValueAsString(metrics);
Assert.assertTrue(json.contains("dimensions"));
... |
@Override
protected Pair<Option<Dataset<Row>>, String> fetchNextBatch(
Option<String> lastCkptStr, long sourceLimit) {
Dataset<Row> rows = null;
final FileSystem fs = HadoopFSUtils.getFs(sourceSqlFile, sparkContext.hadoopConfiguration(), true);
try {
final Scanner scanner = new Scanner(fs.open... | @Test
public void shouldSetCheckpointForSqlFileBasedSourceWithEpochCheckpoint() throws IOException {
UtilitiesTestBase.Helpers.copyToDFS(
"streamer-config/sql-file-based-source.sql", storage,
UtilitiesTestBase.basePath + "/sql-file-based-source.sql");
props.setProperty(sqlFileSourceConfig, Ut... |
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
... | @Test
public void testMergeAclEntries() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
List<AclEntry> aclSpec = Lists.newAr... |
@Override
public ResultSet getSchemas() throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getSchemas());
} | @Test
void assertGetSchemasForCatalogAndSchemaPattern() throws SQLException {
when(databaseMetaData.getSchemas("test", null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getSchemas("test", null), instanceOf(DatabaseMetaDataResultSet.class));
} |
public void sendMessage(final Account account, final Device device, final Envelope message, final boolean online) {
final String channel;
if (device.getGcmId() != null) {
channel = "gcm";
} else if (device.getApnId() != null) {
channel = "apn";
} else if (device.getFetchesMessages()) {
... | @Test
void testSendMessageApnClientNotPresent() throws Exception {
when(clientPresenceManager.isPresent(ACCOUNT_UUID, DEVICE_ID)).thenReturn(false);
when(device.getApnId()).thenReturn("apn-id");
messageSender.sendMessage(account, device, message, false);
verify(messagesManager).insert(ACCOUNT_UUID, ... |
static KafkaNodePoolTemplate convertTemplate(KafkaClusterTemplate template) {
if (template != null) {
return new KafkaNodePoolTemplateBuilder()
.withPodSet(template.getPodSet())
.withPod(template.getPod())
.withPerPodService(template.getP... | @Test
public void testConvertNullTemplate() {
assertThat(VirtualNodePoolConverter.convertTemplate(null), is(nullValue()));
} |
@Override
public void open(Map<String, Object> map, SinkContext sinkContext) throws Exception {
try {
val configV2 = InfluxDBSinkConfig.load(map, sinkContext);
configV2.validate();
sink = new InfluxDBSink();
} catch (Exception e) {
try {
... | @Test
public void openInfluxV1() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("influxdbUrl", "http://localhost:8086");
map.put("database", "test_db");
InfluxDBGenericRecordSink sink = new InfluxDBGenericRecordSink();
try {
sink.open(map, ... |
public static Type fromHudiType(Schema avroSchema) {
Schema.Type columnType = avroSchema.getType();
LogicalType logicalType = avroSchema.getLogicalType();
PrimitiveType primitiveType = null;
boolean isConvertedFailed = false;
switch (columnType) {
case BOOLEAN:
... | @Test
public void testStructHudiSchema() {
Schema.Field field1 = new Schema.Field("field1", Schema.create(Schema.Type.INT), null, null);
Schema.Field field2 = new Schema.Field("field2", Schema.create(Schema.Type.STRING), null, null);
List<Schema.Field> fields = new LinkedList<>();
fi... |
public void check(AccessResource checkedAccess, AccessResource ownedAccess) {
PlainAccessResource checkedPlainAccess = (PlainAccessResource) checkedAccess;
PlainAccessResource ownedPlainAccess = (PlainAccessResource) ownedAccess;
if (ownedPlainAccess.isAdmin()) {
// admin user don't... | @Test
public void testCheck_withAdminPermission_shouldPass() {
PlainAccessResource checkedAccess = new PlainAccessResource();
checkedAccess.setRequestCode(Permission.SUB);
checkedAccess.addResourceAndPerm("topic1", Permission.PUB);
PlainAccessResource ownedAccess = new PlainAccessRes... |
public Optional<ApplicationRoles> readApplicationRoles(ApplicationId application) {
try {
Optional<byte[]> data = curator.getData(applicationRolesPath(application));
if (data.isEmpty() || data.get().length == 0) return Optional.empty();
Slime slime = SlimeUtils.jsonToSlime(da... | @Test
public void read_non_existent() {
var applicationRolesStore = new ApplicationRolesStore(new MockCurator(), Path.createRoot());
Optional<ApplicationRoles> applicationRoles = applicationRolesStore.readApplicationRoles(ApplicationId.defaultId());
assertTrue(applicationRoles.isEmpty());
... |
@Override
String getProperty(String key) {
String checkedKey = checkPropertyName(key);
if (checkedKey == null) {
final String upperCaseKey = key.toUpperCase();
if (!upperCaseKey.equals(key)) {
checkedKey = checkPropertyName(upperCaseKey);
}
... | @Test
void testGetEnvForLowerCaseKeyWithHyphenAndDot() {
assertEquals("value2", systemEnvPropertySource.getProperty("test.case-2"));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void restrictChatMember() {
ChatPermissions permissions = new ChatPermissions()
.canChangeInfo(true)
.canInviteUsers(true)
.canPinMessages(true)
.canSendAudios(true)
.canSendDocuments(true)
.canSendP... |
public static RuntimeException peel(final Throwable t) {
return (RuntimeException) peel(t, null, null, HAZELCAST_EXCEPTION_WRAPPER);
} | @Test
public void testPeel_whenThrowableIsExecutionException_thenReturnCause() {
RuntimeException result = ExceptionUtil.peel(new ExecutionException(throwable));
assertEquals(throwable, result);
} |
public static void serializeRecordBatch(ArrowRecordBatch recordBatch, MemoryBuffer buffer) {
// TODO(chaokunyang) add custom WritableByteChannel to avoid copy in `WritableByteChannelImpl`
try (WriteChannel channel =
new WriteChannel(Channels.newChannel(new MemoryBufferOutputStream(buffer)))) {
Mes... | @Test
public void testSerializeRecordBatch() {
VectorSchemaRoot vectorSchemaRoot = createVectorSchemaRoot(2);
VectorUnloader unloader = new VectorUnloader(vectorSchemaRoot);
ArrowRecordBatch recordBatch = unloader.getRecordBatch();
MemoryBuffer buffer = MemoryUtils.buffer(32);
ArrowUtils.serialize... |
@Override
public void writeQueryData(final ChannelHandlerContext context,
final ProxyDatabaseConnectionManager databaseConnectionManager, final QueryCommandExecutor queryCommandExecutor, final int headerPackagesCount) throws SQLException {
if (ResponseType.QUERY == queryComman... | @Test
void assertWriteQueryDataWithInactiveChannel() throws SQLException {
PostgreSQLCommandExecuteEngine commandExecuteEngine = new PostgreSQLCommandExecuteEngine();
when(queryCommandExecutor.getResponseType()).thenReturn(ResponseType.QUERY);
when(channel.isActive()).thenReturn(false);
... |
@Override
public void receiveConfigInfo(String configInfo) {
if (StringUtils.isEmpty(configInfo)) {
return;
}
Properties properties = new Properties();
try {
properties.load(new StringReader(configInfo));
innerReceive(properties);
... | @Test
void testReceiveConfigInfoEmpty() {
final Deque<Properties> q2 = new ArrayDeque<Properties>();
PropertiesListener a = new PropertiesListener() {
@Override
public void innerReceive(Properties properties) {
q2.offer(properties);
}
};
... |
@Override
public boolean match(final String rule) {
return rule.matches("^int\\|\\d+-\\d+$");
} | @Test
public void match() {
assertTrue(generator.match("int|10-15"));
assertFalse(generator.match("int|10.0-15"));
assertFalse(generator.match("int"));
assertFalse(generator.match("int|"));
} |
public ReviewGroupResponse getReviewGroupSummary(String reviewRequestCode) {
ReviewGroup reviewGroup = reviewGroupRepository.findByReviewRequestCode(reviewRequestCode)
.orElseThrow(() -> new ReviewGroupNotFoundByReviewRequestCodeException(reviewRequestCode));
return new ReviewGroupRespo... | @Test
void ๋ฆฌ๋ทฐ_์์ฒญ_์ฝ๋๋ก_๋ฆฌ๋ทฐ_๊ทธ๋ฃน์_์กฐํํ๋ค() {
// given
ReviewGroup reviewGroup = reviewGroupRepository.save(new ReviewGroup(
"ted",
"review-me",
"reviewRequestCode",
"groupAccessCode"
));
// when
ReviewGroupResponse resp... |
public boolean after(DateTimeStamp other) {
return compareTo(other) > 0;
} | @Test
void testAfter() {
DateTimeStamp a;
DateTimeStamp b;
a = new DateTimeStamp(.586);
b = new DateTimeStamp(.586);
assertFalse(b.after(a));
assertFalse(a.after(b));
b = new DateTimeStamp(.587);
assertTrue(b.after(a));
assertFalse(a.after(b))... |
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_rethrowsUncheckedException() {
ExampleDescendant example = new ExampleDescendant();
try {
ReflectionHelpers.callInstanceMethod(example, "throwUncheckedException");
fail("Expected exception not thrown");
} catch (TestRuntimeException e) {
} c... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void init_and_retired_counted_as_up_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.INITIALIZING)
.proposeStorageNodeWantedState(1, State.RETIRED);
... |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseUTCOffsetTest() {
// issue#I437AP@Gitee
String str = "2019-06-01T19:45:43+08:00";
DateTime dateTime = DateUtil.parse(str);
assert dateTime != null;
assertEquals("2019-06-01 19:45:43", dateTime.toString());
str = "2019-06-01T19:45:43 +08:00";
dateTime = DateUtil.parse(str);
asser... |
public static <T> CommonPager<T> result(final PageParameter pageParameter, final Supplier<Integer> countSupplier, final Supplier<List<T>> listSupplier) {
Integer count = countSupplier.get();
if (Objects.nonNull(count) && count > 0) {
return new CommonPager<>(new PageParameter(pageParameter.g... | @Test
public void testResult() {
final PageParameter pageParameter = new PageParameter(1, 10, 1);
final CommonPager<String> result = PageResultUtils.result(pageParameter, () -> 1,
() -> Collections.singletonList("result1"));
assertEquals(result.getDataList().size(), 1);
} |
public static AwsCredentialsProvider create(boolean isCloud,
@Nullable String stsRegion,
@Nullable String accessKey,
@Nullable String secretKey,
... | @Test
public void testKeySecret() {
final AwsCredentialsProvider awsCredentialsProvider = AWSAuthFactory.create(false, null, "key", "secret", null);
assertThat(awsCredentialsProvider).isExactlyInstanceOf(StaticCredentialsProvider.class);
assertThat("key").isEqualTo(awsCredentialsProvider.res... |
public KinesisPermissionsResponse getPermissions() {
final String setupPolicyString = policyAsJsonString(buildAwsSetupPolicy());
final String autoSetupPolicyString = policyAsJsonString(buildAwsAutoSetupPolicy());
return KinesisPermissionsResponse.create(setupPolicyString, autoSetupPolicyString)... | @Test
public void testPermissions() {
final KinesisPermissionsResponse permissions = awsService.getPermissions();
// Verify that the setup policy contains some needed permissions.
assertTrue(permissions.setupPolicy().contains("cloudwatch"));
assertTrue(permissions.setupPolicy().con... |
public T subtract(T other) {
checkNotNull(other, "Cannot subtract null resources");
checkArgument(getClass() == other.getClass(), "Minus with different resource type");
checkArgument(name.equals(other.getName()), "Minus with different resource name");
checkArgument(
value... | @Test
void testSubtract() {
final Resource v1 = new TestResource(0.2);
final Resource v2 = new TestResource(0.1);
assertTestResourceValueEquals(0.1, v1.subtract(v2));
} |
@Override
public final Scoped onStateChange(Consumer<NodeState> listener) {
// Wrap listeners in a reference of our own to guarantee uniqueness for listener references.
AtomicReference<Consumer<NodeState>> listenerRef = new AtomicReference<>(listener);
synchronized (mListeners) {
Preconditions.check... | @Test(timeout = TIMEOUT)
public void onStateChange() {
AtomicInteger primaryCounter = new AtomicInteger(0);
AtomicInteger standbyCounter = new AtomicInteger(0);
Scoped listener = mSelector.onStateChange(state -> {
if (state.equals(NodeState.PRIMARY)) {
primaryCounter.incrementAndGet();
... |
public static Pagination pageStartingAt(Integer offset, Integer total, Integer pageSize) {
return new Pagination(offset, total, pageSize);
} | @Test
public void shouldNotCreatePaginationWithMoreThan300Records() {
try {
Pagination.pageStartingAt(0, 1000, 301);
} catch (Exception e) {
assertThat(e.getMessage(), is("The max number of perPage is [300]."));
}
} |
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
checkArgument(b.signum() >= 0, () -> "b must be positive or zero: " + b);
checkArgument(numBytes > 0, () -> "numBytes must be positive: " + numBytes);
byte[] src = b.toByteArray();
byte[] dest = new byte[numBytes];
... | @Test(expected = IllegalArgumentException.class)
public void bigIntegerToBytes_convertWithNegativeLength() {
BigInteger b = BigInteger.valueOf(10);
ByteUtils.bigIntegerToBytes(b, -1);
} |
@Override
public InputStream getInputStream() throws FileSystemException {
return requireResolvedFileObject().getInputStream();
} | @Test
public void testDelegatesGetInputStreamWithBufferSize() throws FileSystemException {
InputStream inputStream = mock( InputStream.class );
when( resolvedFileObject.getInputStream( anyInt() ) ).thenReturn( inputStream );
assertSame( inputStream, fileObject.getInputStream( 10 ) );
} |
@Override
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
long toBeSkipped = Math.min(n, mLength - mPosition);
if (!mUfsInStream.isPresent()) {
mPosition += toBeSkipped;
return toBeSkipped;
}
long skipped = mUfsInStream.get().skip(toBeSkipped);
if ... | @Test
public void skip() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
Random random = new Random();
try (FileInStream inStream = getStream(ufsPath)) {
for (int i = 0; i < 10; i++) {
if (inStream.remaining() <= 0) {
b... |
@Override
protected Release findActiveOne(long id, ApolloNotificationMessages clientMessages) {
Tracer.logEvent(TRACER_EVENT_CACHE_GET_ID, String.valueOf(id));
return configIdCache.getUnchecked(id).orElse(null);
} | @Test
public void testFindActiveOneWithSameIdMultipleTimes() throws Exception {
long someId = 1;
when(releaseService.findActiveOne(someId)).thenReturn(someRelease);
assertEquals(someRelease, configServiceWithCache.findActiveOne(someId, someNotificationMessages));
assertEquals(someRelease, configServ... |
public long getTimeout() {
return timeout;
} | @Test
@DirtiesContext
public void testCreateEndpointWithTimeout() throws Exception {
long timeout = 1999999L;
ExecEndpoint e = createExecEndpoint("exec:test?timeout=" + timeout);
assertEquals(timeout, e.getTimeout());
} |
public static Pair<String, String> labelKeyValuePair(String indexedLabelKey) {
var idx = indexedLabelKey.indexOf('=');
if (idx != -1) {
return Pair.of(indexedLabelKey.substring(0, idx), indexedLabelKey.substring(idx + 1));
}
throw new IllegalArgumentException("Invalid label k... | @Test
void labelKeyValuePair() {
var pair = LabelIndexSpecUtils.labelKeyValuePair("key=value");
assertThat(pair.getFirst()).isEqualTo("key");
assertThat(pair.getSecond()).isEqualTo("value");
pair = LabelIndexSpecUtils.labelKeyValuePair("key=value=1");
assertThat(pair.getFirs... |
@Override
public AttributedList<Path> search(final Path workdir,
final Filter<Path> regex,
final ListProgressListener listener) throws BackgroundException {
final AttributedList<Path> list = new AttributedList<>();
// avo... | @Test
public void testSearchNestedDirectory() throws Exception {
Assume.assumeTrue(session.getClient().existsAndIsAccessible(testPathPrefix.getAbsolute()));
final String newDirectoryName = new AlphanumericRandomStringService().random();
final String intermediateDirectoryName = new Alphanume... |
public FileSystem get(Key key) {
synchronized (mLock) {
Value value = mCacheMap.get(key);
FileSystem fs;
if (value == null) {
// On cache miss, create and insert a new FileSystem instance,
fs = FileSystem.Factory.create(FileSystemContext.create(key.mSubject, key.mConf));
mC... | @Test
public void getTwiceThenClose2() throws IOException {
Key key1 = createTestFSKey("user1");
FileSystem fs1 = mFileSystemCache.get(key1);
FileSystem fs2 = mFileSystemCache.get(key1);
assertSame(getDelegatedFileSystem(fs1), getDelegatedFileSystem(fs2));
fs1.close();
assertTrue(fs1.isClosed(... |
@Override
public byte[] serialize(final String topic, final List<?> data) {
if (data == null) {
return null;
}
try {
final StringWriter stringWriter = new StringWriter();
final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
csvPrinter.printRecord(() -> new FieldI... | @Test
public void shouldSerializeZeroDecimalWithPaddedZeros() {
// Given:
givenSingleColumnSerializer(SqlTypes.decimal(4, 2));
final List<?> values = Collections
.singletonList(BigDecimal.ZERO.setScale(2, RoundingMode.UNNECESSARY));
// When:
final byte[] bytes = serializer.serialize("", ... |
@Udf
public boolean check(@UdfParameter(description = "The input JSON string") final String input) {
if (input == null) {
return false;
}
try {
return !UdfJsonMapper.parseJson(input).isMissingNode();
} catch (KsqlFunctionException e) {
return false;
}
} | @Test
public void shouldNotInterpretEmptyString() {
assertFalse(udf.check(""));
} |
@Override
public String evaluateWithArgs(final Map<String, Comparable<?>> map) {
Closure<?> result = ((Closure<?>) evaluate("{it -> \"" + handlePlaceHolder(inlineExpression) + "\"}")).rehydrate(new Expando(), null, null);
result.setResolveStrategy(Closure.DELEGATE_ONLY);
map.forEach(result::... | @Test
void assertEvaluateWithArgs() {
assertThat(TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build(
new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "${1+2}"))).evaluateWithArgs(new LinkedHashMap<>()), is("3"));
} |
public static <V> Read<V> read() {
return new AutoValue_SparkReceiverIO_Read.Builder<V>().build();
} | @Test
public void testReadObjectCreationFailsIfTimestampFnIsNull() {
assertThrows(
IllegalArgumentException.class, () -> SparkReceiverIO.<String>read().withTimestampFn(null));
} |
public Set<Map.Entry<PropertyKey, Object>> entrySet() {
return keySet().stream().map(key -> Maps.immutableEntry(key, get(key))).collect(toSet());
} | @Test
public void entrySet() {
Set<Map.Entry<? extends PropertyKey, Object>> expected =
PropertyKey.defaultKeys().stream()
.map(key -> Maps.immutableEntry(key, key.getDefaultValue())).collect(toSet());
assertThat(mProperties.entrySet(), is(expected));
mProperties.put(mKeyWithValue, "va... |
public static List<BindAddress> validateBindAddresses(ServiceConfiguration config, Collection<String> schemes) {
// migrate the existing configuration properties
List<BindAddress> addresses = migrateBindAddresses(config);
// parse the list of additional bind addresses
Arrays
... | @Test
public void testMigrationWithDefaults() {
ServiceConfiguration config = new ServiceConfiguration();
List<BindAddress> addresses = BindAddressValidator.validateBindAddresses(config, null);
assertEquals(Arrays.asList(
new BindAddress(null, URI.create("pulsar://0.0.0.0:665... |
@Override
public void checkApiEndpoint(GithubAppConfiguration githubAppConfiguration) {
if (StringUtils.isBlank(githubAppConfiguration.getApiEndpoint())) {
throw new IllegalArgumentException("Missing URL");
}
URI apiEndpoint;
try {
apiEndpoint = URI.create(githubAppConfiguration.getApiEnd... | @Test
@UseDataProvider("validApiEndpoints")
public void checkApiEndpoint(String url) {
GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url);
assertThatCode(() -> underTest.checkApiEndpoint(configuration)).isNull();
} |
public synchronized boolean deregister(String id) {
assert !(Thread.currentThread() instanceof PartitionOperationThread);
if (!id2InterceptorMap.containsKey(id)) {
return false;
}
Map<String, MapInterceptor> tmpMap = new HashMap<>(id2InterceptorMap);
MapInterceptor ... | @Test
public void testDeregister_whenInterceptorWasNotRegistered_thenDoNothing() {
registry.deregister(interceptor.id);
assertInterceptorRegistryContainsNotInterceptor();
} |
@VisibleForTesting
boolean prepareWorkingDir(FileSystem fs, Path workingDir) throws IOException {
if (fs.exists(workingDir)) {
if (force) {
LOG.info("Existing Working Dir detected: -" + FORCE_OPTION +
" specified -> recreating Working Dir");
fs.delete(workingDir, true);
} e... | @Test(timeout = 5000)
public void testPrepareWorkingDir() throws Exception {
Configuration conf = new Configuration();
HadoopArchiveLogs hal = new HadoopArchiveLogs(conf);
FileSystem fs = FileSystem.getLocal(conf);
Path workingDir = new Path("target", "testPrepareWorkingDir");
fs.delete(workingDir... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
String roadClassTag = readerWay.getTag("highway");
if (roadClassTag == null)
return;
RoadClass roadClass = RoadClass.find(roadClassTag);
if (roadClas... | @Test
public void testIgnore() {
ReaderWay readerWay = new ReaderWay(1);
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
readerWay.setTag("route", "ferry");
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
assertEquals(RoadCla... |
@Override
@SuppressWarnings("unchecked")
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already done.");
return;
}
final ImmutableSet.Builder<String> modifiedStreams = ImmutableSet.builder();
... | @Test
@MongoDBFixtures("V20170110150100_FixAlertConditionsMigration.json")
public void upgrade() throws Exception {
// First check all types of the existing documents
AlertConditionAssertions.assertThat(getAlertCondition("2fa6a415-ce0c-4a36-accc-dd9519eb06d9"))
.hasParameter("bac... |
public String getString(@NotNull final String key, @Nullable final String defaultValue) {
return System.getProperty(key, props.getProperty(key, defaultValue));
} | @Test
public void testGetString_String_String() {
String key = "key That Doesn't Exist";
String defaultValue = "blue bunny";
String expResult = "blue bunny";
String result = getSettings().getString(key);
Assert.assertTrue(result == null);
result = getSettings().getStr... |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
AvroSerial... | @Test
void aPojoIsCompatibleAfterARoundTrip() throws IOException {
AvroSerializer<Pojo> serializer = new AvroSerializer<>(Pojo.class);
AvroSerializerSnapshot<Pojo> restored = roundTrip(serializer.snapshotConfiguration());
assertThat(serializer.snapshotConfiguration().resolveSchemaCompatibi... |
public static AfterProcessingTimeStateMachine pastFirstElementInPane() {
return new AfterProcessingTimeStateMachine(IDENTITY);
} | @Test
public void testClear() throws Exception {
SimpleTriggerStateMachineTester<IntervalWindow> tester =
TriggerStateMachineTester.forTrigger(
AfterProcessingTimeStateMachine.pastFirstElementInPane()
.plusDelayOf(Duration.millis(5)),
FixedWindows.of(Duration.millis... |
@Override
public boolean tryAdd(double longitude, double latitude, V member) {
return get(tryAddAsync(longitude, latitude, member));
} | @Test
public void testTryAdd() {
RGeo<String> geo = redisson.getGeo("test");
assertThat(geo.add(2.51, 3.12, "city1")).isEqualTo(1);
assertThat(geo.tryAdd(2.5, 3.1, "city1")).isFalse();
assertThat(geo.tryAdd(2.12, 3.5, "city2")).isTrue();
} |
@Override
public RelativeRange apply(final Period period) {
if (period != null) {
return RelativeRange.Builder.builder()
.from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds())
... | @Test
void testSecondConversion() {
final RelativeRange result = converter.apply(Period.seconds(5));
verifyResult(result, 5);
} |
public String getExample() {
return ObjectUtils.isEmpty(example) ? xExample : example.toString();
} | @Test
public void testGetExample() {
assertEquals("shenyuExample", docParameter.getExample());
docParameter.setExample("");
final String example = docParameter.getExample();
assertEquals("shenyuXExample", docParameter.getExample());
} |
public static String md5Hex(String string) {
return compute(string, DigestObjectPools.MD5);
} | @Test
public void shouldComputeForAGivenStringUsingMD5() {
String fingerprint = "Some String";
String digest = md5Hex(fingerprint);
assertEquals(DigestUtils.md5Hex(fingerprint), digest);
} |
public SmppConfiguration getConfiguration() {
return configuration;
} | @Test
public void emptyConstructorShouldSetTheSmppConfiguration() {
assertNotNull(binding.getConfiguration());
} |
public DMNContext populateContextWith(Map<String, Object> json) {
for (Entry<String, Object> kv : json.entrySet()) {
InputDataNode idn = model.getInputByName(kv.getKey());
if (idn != null) {
processInputDataNode(kv, idn);
} else {
DecisionNode ... | @Test
void trafficViolationArbitraryFine() throws Exception {
final DMNRuntime runtime = createRuntimeWithAdditionalResources("Traffic Violation.dmn", DMNRuntimeTypesTest.class);
final DMNModel dmnModel = runtime.getModel("https://github.com/kiegroup/drools/kie-dmn/_A4BCA8B8-CF08-433F-93B2-A2598F19E... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testSpdyDataFrame() throws Exception {
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
byte flags = 0;
int length = 1024;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
for (int i ... |
@Override
public void replay(
long offset,
long producerId,
short producerEpoch,
CoordinatorRecord record
) throws RuntimeException {
ApiMessageAndVersion key = record.key();
ApiMessageAndVersion value = record.value();
switch (key.version()) {
... | @Test
public void testReplayConsumerGroupCurrentMemberAssignment() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.