focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (SplitFieldToRowsMeta) smi;
data = (SplitFieldToRowsData) sdi;
if ( super.init( smi, sdi ) ) {
data.rownr = 1L;
try {
String delimiter = Const.nullToEmpty( meta.getDelimiter() );
if ( meta.isDelimiterR... | @Test
public void interpretsNullDelimiterAsEmpty() throws Exception {
SplitFieldToRows step =
StepMockUtil.getStep( SplitFieldToRows.class, SplitFieldToRowsMeta.class, "handlesNullDelimiter" );
SplitFieldToRowsMeta meta = new SplitFieldToRowsMeta();
meta.setDelimiter( null );
meta.setDelimiterR... |
public static JsonSchemaValidator matchesJsonSchemaInClasspath(String pathToSchemaInClasspath) {
return matchesJsonSchema(Thread.currentThread().getContextClassLoader().getResource(pathToSchemaInClasspath));
} | @Test public void
validates_schema_in_classpath() {
// Given
String greetingJson = "{\n" +
" \"greeting\": {\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\": \"Doe\"\n" +
" }\n" +
"}";
//... |
@Nullable
public static ByteBuf accumulate(
ByteBuf target, ByteBuf source, int targetAccumulationSize, int accumulatedSize) {
if (accumulatedSize == 0 && source.readableBytes() >= targetAccumulationSize) {
return source;
}
int copyLength = Math.min(source.readableBy... | @Test
void testAccumulateWithCopy() {
int sourceLength = 128;
int firstSourceReaderIndex = 32;
int secondSourceReaderIndex = 0;
int expectedAccumulationSize = 128;
int firstAccumulationSize = sourceLength - firstSourceReaderIndex;
int secondAccumulationSize = expecte... |
@Override
public void seek(long desired) throws IOException {
final int available = compressingDelegate.available();
if (available > 0) {
if (available != compressingDelegate.skip(available)) {
throw new IOException("Unable to skip buffered data.");
}
... | @Test
void testSeek() throws IOException {
final List<String> records = Arrays.asList("first", "second", "third", "fourth", "fifth");
final Map<String, Long> positions = new HashMap<>();
byte[] compressedBytes;
try (final TestingOutputStream outputStream = new TestingOutputStream();... |
public void addUndetected(String shardId, BigInteger startingHashKey, long currentTimeMs) {
assert !info.containsKey(shardId);
info.put(shardId, new TrackingInfo(findOwner(startingHashKey), currentTimeMs));
} | @Test
public void detection() {
addUndetected(SHARD2, 0);
addUndetected(SHARD4, 0);
assertNew(set(SHARD0, SHARD2, SHARD5), SHARD0, 0, SHARD2, 1, SHARD5, 2);
assertNew(set(SHARD0, SHARD2, SHARD5));
assertNew(set(SHARD1, SHARD3, SHARD4), SHARD1, 0, SHARD3, 1, SHARD4, 2);
... |
@NonNull
public <T extends VFSConnectionDetails> VFSConnectionProvider<T> getExistingProvider(
@NonNull ConnectionManager manager,
@Nullable String key )
throws KettleException {
VFSConnectionProvider<T> provider = getProvider( manager, key );
if ( provider == null ) {
throw new KettleExcep... | @Test( expected = KettleException.class )
public void testGetExistingProviderOfDetailsReturnsNullForNonExistingProviderInManager() throws KettleException {
String provider1Key = "missingProvider1";
VFSConnectionDetails details1 = mock( VFSConnectionDetails.class );
doReturn( provider1Key ).when( details1... |
public NamenodeBeanMetrics getNamenodeMetrics() throws IOException {
if (this.metrics == null) {
throw new IOException("Namenode metrics is not initialized");
}
return this.metrics.getNamenodeMetrics();
} | @Test
public void testRouterMetricsWhenDisabled() throws Exception {
Router router = new Router();
router.init(new RouterConfigBuilder(conf).rpc().build());
router.start();
intercept(IOException.class, "Namenode metrics is not initialized",
() -> router.getNamenodeMetrics().getCacheCapacity(... |
public boolean statsHaveChanged() {
if (!aggregatedStats.hasUpdatesFromAllDistributors()) {
return false;
}
for (ContentNodeStats contentNodeStats : aggregatedStats.getStats()) {
int nodeIndex = contentNodeStats.getNodeIndex();
boolean currValue = mayHaveMerge... | @Test
void stats_have_changed_if_one_node_has_in_sync_to_buckets_pending_transition() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).inSync(1));
f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1));
assertTrue(f.statsHaveChanged());
} |
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
TemporalAccessor parsed = FEEL_TIME.parse(val);
i... | @Test
void invokeTemporalAccessorParamUnsupportedAccessor() {
FunctionTestUtil.assertResultError(timeFunction.invoke(DayOfWeek.MONDAY), InvalidParametersEvent.class);
} |
@Override
public void downgradeLastEdge() {
Preconditions.checkState(!endsInInode(),
"Cannot downgrade last edge when lock list %s ends in an inode", this);
Preconditions.checkState(!mLocks.isEmpty(),
"Cannot downgrade last edge when the lock list is empty");
Preconditions.checkState(endsI... | @Test
public void downgradeLastEdge() {
mLockList.lockRootEdge(LockMode.WRITE);
mLockList.downgradeLastEdge();
assertEquals(LockMode.READ, mLockList.getLockMode());
mLockList.lockInode(mRootDir, LockMode.READ);
mLockList.lockEdge(mRootDir, mDirA.getName(), LockMode.WRITE);
mLockList.downgrade... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListFilePlusCharacter() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(
new Path(c... |
public static Read read() {
return new AutoValue_RabbitMqIO_Read.Builder()
.setQueueDeclare(false)
.setExchangeDeclare(false)
.setMaxReadTime(null)
.setMaxNumRecords(Long.MAX_VALUE)
.setUseCorrelationId(false)
.build();
} | @Test
public void testReadQueue() throws Exception {
final int maxNumRecords = 10;
PCollection<RabbitMqMessage> raw =
p.apply(
RabbitMqIO.read()
.withUri("amqp://guest:guest@localhost:" + port)
.withQueue("READ")
.withMaxNumRecords(maxNumReco... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return positionFilter == PositionFilter.PROFIT ? criterionValue1.isGreaterThan(criterionValue2)
: criterionValue1.isLessThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion winningPositionsRatio = getCriterion(PositionFilter.PROFIT);
assertTrue(winningPositionsRatio.betterThan(numOf(12), numOf(8)));
assertFalse(winningPositionsRatio.betterThan(numOf(8), numOf(12)));
AnalysisCriterion losingPositionsRat... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testRequiresStableInputProcessElement() throws Exception {
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<String, String>() {
@ProcessElement
@RequiresStableInput
public void process(ProcessContext c) {}
}.getCl... |
@Override
public boolean checkIndexExists( Database database, String schemaName, String tableName, String[] idxFields ) throws KettleDatabaseException {
String tablename = database.getDatabaseMeta().getQuotedSchemaTableCombination( schemaName, tableName );
boolean[] exists = new boolean[idxFields.length];
... | @Test
public void testCheckIndexExists() throws Exception {
Database db = Mockito.mock( Database.class );
ResultSet rs = Mockito.mock( ResultSet.class );
DatabaseMetaData dmd = Mockito.mock( DatabaseMetaData.class );
DatabaseMeta dm = Mockito.mock( DatabaseMeta.class );
Mockito.when( dm.getQuoted... |
public static BuildInfo getBuildInfo() {
if (Overrides.isEnabled()) {
// never use cache when override is enabled -> we need to re-parse everything
Overrides overrides = Overrides.fromProperties();
return getBuildInfoInternalVersion(overrides);
}
return BUILD... | @Test
public void testReadValues() {
BuildInfo buildInfo = BuildInfoProvider.getBuildInfo();
String version = buildInfo.getVersion();
String build = buildInfo.getBuild();
int buildNumber = buildInfo.getBuildNumber();
assertTrue(buildInfo.toString(), VERSION_PATTERN.matcher(... |
@ExceptionHandler(ShenyuException.class)
protected ShenyuAdminResult handleShenyuException(final ShenyuException exception) {
String message = Objects.isNull(exception.getCause()) ? null : exception.getCause().getMessage();
if (!StringUtils.hasText(message)) {
message = exception.getMess... | @Test
public void testServerExceptionHandlerByShenyuException() {
ShenyuException shenyuException = new ShenyuException(new Throwable("Test shenyuException message!"));
ShenyuAdminResult result = exceptionHandlersUnderTest.handleShenyuException(shenyuException);
Assertions.assertEquals(resul... |
@Override
public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) {
final ModelId modelId = entityDescriptor.id();
final Configuration configuration = configurationService.find(modelId.id());
if (isNull(configuration)) {
LO... | @Test
@MongoDBFixtures("SidecarCollectorConfigurationFacadeTest.json")
public void exportEntity() {
final EntityDescriptor descriptor = EntityDescriptor.create("5b17e1a53f3ab8204eea1051", ModelTypes.SIDECAR_COLLECTOR_CONFIGURATION_V1);
final EntityDescriptor collectorDescriptor = EntityDescripto... |
@Override
public void run() {
try {
// We kill containers until the kernel reports the OOM situation resolved
// Note: If the kernel has a delay this may kill more than necessary
while (true) {
String status = cgroups.getCGroupParam(
CGroupsHandler.CGroupController.MEMORY,
... | @Test
public void testKillBothOpportunisticContainerUponOOM() throws Exception {
int currentContainerId = 0;
ConcurrentHashMap<ContainerId, Container> containers =
new ConcurrentHashMap<>();
Container c1 = createContainer(currentContainerId++, false, 2, true);
containers.put(c1.getContainerId... |
@Override
protected void setKeyboard(@NonNull AnyKeyboard newKeyboard, float verticalCorrection) {
mExtensionKey = null;
mExtensionVisible = false;
mUtilityKey = null;
super.setKeyboard(newKeyboard, verticalCorrection);
setProximityCorrectionEnabled(true);
// looking for the space-bar, so I'... | @Test
public void testKeyClickDomain() {
mEnglishKeyboard =
AnyApplication.getKeyboardFactory(getApplicationContext())
.getEnabledAddOn()
.createKeyboard(Keyboard.KEYBOARD_ROW_MODE_URL);
mEnglishKeyboard.loadKeyboard(mViewUnderTest.getThemedKeyboardDimens());
mViewUnderTes... |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void feed_block_engage_edge_emits_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
.clusterStateAfter("distributor:3 storage:3")
.feedBlock... |
@Override
public NetworkId networkId() {
return networkId;
} | @Test
public void testEquality() {
DefaultVirtualHost host1 =
new DefaultVirtualHost(NetworkId.networkId(0), HID1, MAC1, VLAN1, LOC1, IPSET1);
DefaultVirtualHost host2 =
new DefaultVirtualHost(NetworkId.networkId(0), HID1, MAC1, VLAN1, LOC1, IPSET1);
DefaultVi... |
public Value get( Key key ) throws Exception {
ActiveCacheResult<Value> result = null;
Future<ActiveCacheResult<Value>> futureResult = null;
synchronized ( this ) {
result = valueMap.get( key );
boolean shouldReload = false;
long time = System.currentTimeMillis();
if ( result == null... | @Test
public void testActiveCacheDoesntCacheExceptions() throws Exception {
long timeout = 100;
@SuppressWarnings( "unchecked" )
ActiveCacheLoader<String, String> mockLoader = mock( ActiveCacheLoader.class );
ActiveCache<String, String> cache = new ActiveCache<String, String>( mockLoader, timeout );
... |
public static String getGroupedName(final String serviceName, final String groupName) {
if (StringUtils.isBlank(serviceName)) {
throw new IllegalArgumentException("Param 'serviceName' is illegal, serviceName is blank");
}
if (StringUtils.isBlank(groupName)) {
throw new Il... | @Test
void testGetGroupedName() {
assertEquals("group@@serviceName", NamingUtils.getGroupedName("serviceName", "group"));
} |
@Override
public Object parse(final String property, final Object value) {
if (property.equalsIgnoreCase(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT)) {
validator.validate(property, value);
return value;
}
final ConfigItem configItem = resolver.resolve(property, true)
.orElseTh... | @Test
public void shouldNotCallResolverForRunScriptConstant() {
// When:
parser.parse(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT, "100");
// Then:
verify(resolver, never()).resolve(anyString(), anyBoolean());
} |
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) {
switch (trigger.getTriggerCase()) {
case AFTER_ALL:
return AfterAllStateMachine.of(
stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList()));
case AFTER_ANY:
return AfterFirstSt... | @Test
public void testDefaultTriggerTranslation() {
RunnerApi.Trigger trigger =
RunnerApi.Trigger.newBuilder()
.setDefault(RunnerApi.Trigger.Default.getDefaultInstance())
.build();
assertThat(
TriggerStateMachines.stateMachineForTrigger(trigger),
instanceOf(Def... |
public String getTableName() {
return tableName;
} | @Test
public void testSetGetTableName() {
String tableName = "tableName";
assertEquals(tableName, tableMeta.getTableName(), "Table name should match the value set");
} |
public static List<String> listFileNames(String path) throws IORuntimeException {
if (path == null) {
return new ArrayList<>(0);
}
int index = path.lastIndexOf(FileUtil.JAR_PATH_EXT);
if (index < 0) {
// 普通目录
final List<String> paths = new ArrayList<>();
final File[] files = ls(path);
for (File f... | @Test
@Disabled
public void listFileNamesTest2() {
final List<String> names = FileUtil.listFileNames("D:\\m2_repo\\commons-cli\\commons-cli\\1.0\\commons-cli-1.0.jar!org/apache/commons/cli/");
for (final String string : names) {
Console.log(string);
}
} |
public static Collection<AndPredicate> getAndPredicates(final ExpressionSegment expression) {
Collection<AndPredicate> result = new LinkedList<>();
extractAndPredicates(result, expression);
return result;
} | @Test
void assertExtractAndPredicatesOrCondition() {
ColumnSegment columnSegment1 = new ColumnSegment(28, 33, new IdentifierValue("status"));
ParameterMarkerExpressionSegment parameterMarkerExpressionSegment1 = new ParameterMarkerExpressionSegment(35, 35, 0);
ExpressionSegment expressionSegm... |
@Override
public double mean() {
return 1 / p;
} | @Test
public void testMean() {
System.out.println("mean");
ShiftedGeometricDistribution instance = new ShiftedGeometricDistribution(0.3);
instance.rand();
assertEquals(3.333333, instance.mean(), 1E-6);
} |
@Override
public void onOutOfMemory(OutOfMemoryError oome, HazelcastInstance[] hazelcastInstances) {
for (HazelcastInstance instance : hazelcastInstances) {
if (instance instanceof HazelcastClientInstanceImpl impl) {
ClientHelper.cleanResources(impl);
}
}
... | @Test
public void testOnOutOfMemory() {
outOfMemoryHandler.onOutOfMemory(new OutOfMemoryError(), instances);
assertTrueEventually(() -> assertFalse("The client should be shutdown", client.getLifecycleService().isRunning()));
} |
public void update(Map<String, NamespaceBundleStats> bundleStats, int topk) {
arr.clear();
try {
var isLoadBalancerSheddingBundlesWithPoliciesEnabled =
pulsar.getConfiguration().isLoadBalancerSheddingBundlesWithPoliciesEnabled();
for (var etr : bundleStats.ent... | @Test
public void testSystemNamespace() {
Map<String, NamespaceBundleStats> bundleStats = new HashMap<>();
var topKBundles = new TopKBundles(pulsar);
NamespaceBundleStats stats1 = new NamespaceBundleStats();
stats1.msgRateIn = 500;
bundleStats.put("pulsar/system/0x00000000_0x... |
@Override
public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) {
if (ER_PARSE_ERROR == ex.getErrorCode()) {
return Optional.empty();
}
if (sqlStatement instanceof SelectStatement) {
return createQueryResult((SelectS... | @Test
void assertGetSaneQueryResultForOtherStatements() {
assertThat(new MySQLDialectSaneQueryResultEngine().getSaneQueryResult(new MySQLInsertStatement(), new SQLException("")), is(Optional.empty()));
} |
public static ThreadFactory create(final String namePrefix, final boolean daemon) {
return create(namePrefix, daemon, Thread.NORM_PRIORITY);
} | @Test
public void testCreate() {
ThreadFactory threadFactory = ShenyuThreadFactory.create(NAME_PREFIX, true);
assertThat(threadFactory, notNullValue());
} |
@Override
public long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp) {
try {
return delegate.extract(record, previousTimestamp);
} catch (final RuntimeException e) {
return handleFailure(record.key(), record.value(), e);
}
} | @Test
public void shouldLogExceptionsAndNotFailOnExtractFromRecordWithNullKeyAndValue() {
// Given:
when(record.key()).thenReturn(null);
when(record.value()).thenReturn(null);
final KsqlException e = new KsqlException("foo");
final LoggingTimestampExtractor extractor = new LoggingTimestampExtract... |
private void initConfig() {
LOG.info("job config file path: " + jobConfigFilePath);
Dataset<String> ds = spark.read().textFile(jobConfigFilePath);
String jsonConfig = ds.first();
LOG.info("rdd read json config: " + jsonConfig);
etlJobConfig = EtlJobConfig.configFromJson(jsonConfi... | @Test
public void testInitConfig(@Mocked SparkSession spark, @Injectable Dataset<String> ds) {
new Expectations() {
{
SparkSession.builder().enableHiveSupport().getOrCreate();
result = spark;
spark.read().textFile(anyString);
result... |
@VisibleForTesting
Path getStagingDir(FileSystem defaultFileSystem) throws IOException {
final String configuredStagingDir =
flinkConfiguration.get(YarnConfigOptions.STAGING_DIRECTORY);
if (configuredStagingDir == null) {
return defaultFileSystem.getHomeDirectory();
... | @Test
void testGetStagingDirWithSpecifyingStagingDir() throws IOException {
final Configuration flinkConfig = new Configuration();
flinkConfig.set(YarnConfigOptions.STAGING_DIRECTORY, "file:///tmp/path1");
try (final YarnClusterDescriptor yarnClusterDescriptor =
createYarnClu... |
public DataSinkTask(Environment environment) {
super(environment);
} | @Test
void testDataSinkTask() {
FileReader fr = null;
BufferedReader br = null;
try {
int keyCnt = 100;
int valCnt = 20;
super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
super.addInput(new UniformRecordGenerator(keyCnt, valCnt,... |
@Operation(summary = "Download metadata from processed file")
@GetMapping(value = "show_metadata/results/{result_id}", produces = "application/xml")
@ResponseBody
public String getProcessedMetadata(@PathVariable("result_id") Long resultId) {
return metadataRetrieverService.getProcessedMetadata(resul... | @Test
public void getProcessedMetadata() {
when(metadataRetrieverServiceMock.getProcessedMetadata(anyLong())).thenReturn("metadata");
String result = controllerMock.getProcessedMetadata(1L);
verify(metadataRetrieverServiceMock, times(1)).getProcessedMetadata(anyLong());
assertNotNu... |
static void moveAuthTag(byte[] messageKey,
byte[] cipherText,
byte[] messageKeyWithAuthTag,
byte[] cipherTextWithoutAuthTag) {
// Check dimensions of arrays
if (messageKeyWithAuthTag.length != messageKey.length + 16) {
... | @Test
public void testMoveAuthTag() {
// Extract authTag for testing purposes
byte[] authTag = new byte[16];
System.arraycopy(cipherTextWithAuthTag, 35, authTag, 0, 16);
byte[] messageKeyWithAuthTag = new byte[16 + 16];
byte[] cipherTextWithoutAuthTag = new byte[35];
... |
static Optional<Integer> typePrefixLength(List<String> nameParts) {
TyParseState state = TyParseState.START;
Optional<Integer> typeLength = Optional.empty();
for (int i = 0; i < nameParts.size(); i++) {
state = state.next(JavaCaseFormat.from(nameParts.get(i)));
if (state == TyParseState.REJECT) ... | @Test
public void typePrefixLength() {
assertThat(getPrefix("fieldName")).isEmpty();
assertThat(getPrefix("CONST")).isEmpty();
assertThat(getPrefix("ClassName")).hasValue(0);
assertThat(getPrefix("com.ClassName")).hasValue(1);
assertThat(getPrefix("ClassName.foo")).hasValue(1);
assertThat(getP... |
public static void rethrowIfFatalError(Throwable t) {
if (isJvmFatalError(t)) {
throw (Error) t;
}
} | @Test
void testRethrowFatalError() {
// fatal error is rethrown
assertThatThrownBy(() -> ExceptionUtils.rethrowIfFatalError(new InternalError()))
.isInstanceOf(InternalError.class);
// non-fatal error is not rethrown
ExceptionUtils.rethrowIfFatalError(new NoClassDefF... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateSingleStat() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
ColumnStatisticsData data1 = new ColStatsBuilder<>(Decimal.class).numNulls(1).numDVs(2)
.low(ONE).high(FOUR).hll(1, 4).kll(1, 4).build();
List<ColStatsObjWithSourceInfo... |
public static <T> T loadData(Map<String, Object> config,
T existingData,
Class<T> dataCls) {
try {
String existingConfigJson = MAPPER.writeValueAsString(existingData);
Map<String, Object> existingConfig = MAPPER.readValue(... | @Test
public void testLoadClientConfigurationData() {
ClientConfigurationData confData = new ClientConfigurationData();
confData.setServiceUrl("pulsar://unknown:6650");
confData.setMaxLookupRequest(600);
confData.setMaxLookupRedirects(10);
confData.setNumIoThreads(33);
... |
public <T extends Notification> int deliverEmails(Collection<T> notifications) {
if (handlers.isEmpty()) {
return 0;
}
Class<T> aClass = typeClassOf(notifications);
if (aClass == null) {
return 0;
}
checkArgument(aClass != Notification.class, "Type of notification objects must be a... | @Test
public void deliverEmails_collection_has_no_effect_if_no_handler() {
NotificationDispatcher dispatcher = mock(NotificationDispatcher.class);
List<Notification> notifications = IntStream.range(0, 10)
.mapToObj(i -> mock(Notification.class))
.toList();
NotificationService underTest = new N... |
private ResourceMethodIdentifierGenerator() {
} | @Test(dataProvider = "testData")
public void testResourceMethodIdentifierGenerator(String baseUriTemplate, ResourceMethod method, String methodName,
String expected) {
final String resourceMethodIdentifier = ResourceMethodIdentifierGenerator.generate(baseUriTemplate, method, methodName);
final String ke... |
public Stream<ColumnName> resolveSelectStar(
final Optional<SourceName> sourceName
) {
return getSources().stream()
.filter(s -> !sourceName.isPresent()
|| !s.getSourceName().isPresent()
|| sourceName.equals(s.getSourceName()))
.flatMap(s -> s.resolveSelectStar(source... | @Test
public void shouldResolveAliasedSelectStarByCallingOnlyCorrectParent() {
// When:
final Stream<ColumnName> result = planNode.resolveSelectStar(Optional.of(SOURCE_2_NAME));
// Then:
final List<ColumnName> columns = result.collect(Collectors.toList());
assertThat(columns, contains(COL2, COL3)... |
@Override
public void importFrom(Import theImport, String sourceSystemId) {
this.namespace = theImport.getNamespace() == null ? "" : theImport.getNamespace() + ":";
this.importFrom(theImport.getLocation());
} | @Test
public void testComplexTypeMixed() throws Exception {
URL url = ReflectUtil.getResource("org/flowable/engine/impl/webservice/complexType-mixed.wsdl");
importer.importFrom(url.toString());
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldFailIfMultipleQueriesWritingToTable() {
// Given:
when(sourceDescription.writeQueries()).thenReturn(ImmutableList.of(ctasQueryInfo, otherQueryInfo));
// When:
final int status = command.command(config, cfg -> client);
// Then:
assertThat(status, is(1));
verify(cl... |
public synchronized Collection<StreamsMetadata> getAllMetadataForStore(final String storeName) {
Objects.requireNonNull(storeName, "storeName cannot be null");
if (topologyMetadata.hasNamedTopologies()) {
throw new IllegalArgumentException("Cannot invoke the getAllMetadataForStore(storeName)... | @Test
public void shouldReturnEmptyCollectionOnGetAllInstancesWithStoreWhenStoreDoesntExist() {
final Collection<StreamsMetadata> actual = metadataState.getAllMetadataForStore("not-a-store");
assertTrue(actual.isEmpty());
} |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentImportExecutor,
TokensAndUrlAuthData authData,
MusicContainerResource data)
throws Exception {
if (data == null) {
// Nothing to do
re... | @Test
public void importPlaylists() throws Exception {
List<MusicPlaylist> musicPlaylists = createTestMusicPlaylists();
setUpImportPlaylistsBatchResponse(musicPlaylists.stream().collect(
Collectors.toMap(MusicPlaylist::getId, playlist -> SC_OK)));
MusicContainerResource pla... |
@Override
public PageResult<ProductSpuDO> getSpuPage(ProductSpuPageReqVO pageReqVO) {
return productSpuMapper.selectPage(pageReqVO);
} | @Test
void getSpuPage_alarmStock_empty() {
// 准备参数
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(... |
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@PutMapping(value = IMAGE_URL, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public TbResourceInfo updateImage(@Parameter(description = IMAGE_TYPE_PARAM_DESCRIPTION, schema = @Schema(allowableValues = {"tenant", "system"}), required = true)
... | @Test
public void testUpdateImage() throws Exception {
String filename = "my_png_image.png";
TbResourceInfo imageInfo = uploadImage(HttpMethod.POST, "/api/image", filename, "image/png", PNG_IMAGE);
checkPngImageDescriptor(imageInfo.getDescriptor(ImageDescriptor.class));
String newFi... |
private void removePublisherIndexes(Service service, String clientId) {
publisherIndexes.computeIfPresent(service, (s, ids) -> {
ids.remove(clientId);
NotifyCenter.publishEvent(new ServiceEvent.ServiceChangedEvent(service, true));
return ids.isEmpty() ? null : ids;
})... | @Test
void testRemovePublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String clientId = "clientId";
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Method removePublisherIndexes = cli... |
public String getDefaultResourceRequestAppPlacementType() {
if (this.rmContext != null
&& this.rmContext.getYarnConfiguration() != null) {
String appPlacementClass = applicationSchedulingEnvs.get(
ApplicationSchedulingConfig.ENV_APPLICATION_PLACEMENT_TYPE_CLASS);
if (null != appPlacem... | @Test
public void testApplicationPlacementTypeNotConfigured() {
Configuration conf = new Configuration();
RMContext rmContext = mock(RMContext.class);
when(rmContext.getYarnConfiguration()).thenReturn(conf);
ApplicationId appIdImpl = ApplicationId.newInstance(0, 1);
ApplicationAttemptId appAttempt... |
public static String version() {
if (null == VERSION.get()) {
String detectedVersion;
try {
detectedVersion = versionFromJar();
// use unknown version in case exact implementation version can't be found from the jar
// (this can happen if the DataStream class appears multiple tim... | @Test
public void testVersion() {
assertThat(FlinkPackage.version()).isEqualTo("1.19.0");
} |
@Nullable static String channelKind(@Nullable Destination destination) {
if (destination == null) return null;
return isQueue(destination) ? "queue" : "topic";
} | @Test void channelKind_queueAndTopic_topicOnNoQueueName() throws JMSException {
QueueAndTopic destination = mock(QueueAndTopic.class);
when(destination.getTopicName()).thenReturn("topic-foo");
assertThat(MessageParser.channelKind(destination))
.isEqualTo("topic");
} |
protected Map<String, Object> headersToMap(Http2Headers trailers, Supplier<Object> convertUpperHeaderSupplier) {
if (trailers == null) {
return Collections.emptyMap();
}
Map<String, Object> attachments = new HashMap<>(trailers.size());
for (Map.Entry<CharSequence, CharSequenc... | @Test
void headersToMap() {
AbstractH2TransportListener listener = new AbstractH2TransportListener() {
@Override
public void onHeader(Http2Headers headers, boolean endStream) {}
@Override
public void onData(ByteBuf data, boolean endStream) {}
@Ov... |
public V remove(K key) {
requireNonNull(key);
long h = hash(key);
return getSection(h).remove(key, null, (int) h);
} | @Test
public void testRemove() {
ConcurrentOpenHashMap<String, String> map =
ConcurrentOpenHashMap.<String, String>newBuilder().build();
assertTrue(map.isEmpty());
assertNull(map.put("1", "one"));
assertFalse(map.isEmpty());
assertFalse(map.remove("0", "zero... |
public V put(K key, V value) {
return resolve(map.put(key, new WeakReference<>(value)));
} | @Test
public void testPruneNullEntries() {
referenceMap.put(1, "1");
assertPruned(0);
referenceMap.put(2, null);
assertMapSize(2);
assertPruned(1);
assertMapSize(1);
assertMapDoesNotContainKey(2);
assertMapEntryEquals(1, "1");
assertLostCount(1);
} |
public static String join(CharSequence delimiter, CharSequence... elements) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (CharSequence element : elements) {
if(first) {
first = false;
} else {
builder.append(de... | @Test
public void testJoin(){
assertEquals(
"Oracle,PostgreSQL,MySQL,SQL Server",
StringUtils.join(",", "Oracle", "PostgreSQL", "MySQL", "SQL Server")
);
} |
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
String typeName = type.toString();
TypeDefinition typeDefinition = new TypeDefinition(typeName);
// Generic Type arguments
type.getTypeA... | @Test
void testBuild() {
buildAndAssertTypeDefinition(
processingEnv, stringsField, "java.util.Collection<java.lang.String>", "java.lang.String", builder);
buildAndAssertTypeDefinition(
processingEnv,
colorsField,
"java.util.List<org.... |
public static <K, V> KafkaRecordCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) {
return new KafkaRecordCoder<>(keyCoder, valueCoder);
} | @Test
public void testCoderIsSerializableWithWellKnownCoderType() {
CoderProperties.coderSerializable(
KafkaRecordCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE));
} |
public double[] getInitialStateProbabilities() {
return pi;
} | @Test
public void testGetInitialStateProbabilities() {
System.out.println("getInitialStateProbabilities");
HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b));
double[] result = hmm.getInitialStateProbabilities();
for (int i = 0; i < pi.length; i++) {
assertEquals(pi[i], re... |
@Override
public List<String> readFilesWithRetries(Sleeper sleeper, BackOff backOff)
throws IOException, InterruptedException {
IOException lastException = null;
do {
try {
// Match inputPath which may contains glob
Collection<Metadata> files =
Iterables.getOnlyElement... | @Test
public void testReadEmpty() throws Exception {
File emptyFile = tmpFolder.newFile("result-000-of-001");
Files.asCharSink(emptyFile, StandardCharsets.UTF_8).write("");
NumberedShardedFile shardedFile = new NumberedShardedFile(filePattern);
assertThat(shardedFile.readFilesWithRetries(), empty());... |
static S3ResourceId fromUri(String uri) {
Matcher m = S3_URI.matcher(uri);
checkArgument(m.matches(), "Invalid S3 URI: [%s]", uri);
String scheme = m.group("SCHEME");
String bucket = m.group("BUCKET");
String key = Strings.nullToEmpty(m.group("KEY"));
if (!key.startsWith("/")) {
key = "/" ... | @Test
public void testInvalidPathNoBucket() {
assertThrows(
"Invalid S3 URI: [s3://]",
IllegalArgumentException.class,
() -> S3ResourceId.fromUri("s3://"));
} |
public static boolean acceptsGzip(Headers headers) {
String ae = headers.getFirst(HttpHeaderNames.ACCEPT_ENCODING);
return ae != null && ae.contains(HttpHeaderValues.GZIP.toString());
} | @Test
void acceptsGzip_only() {
Headers headers = new Headers();
headers.add("Accept-Encoding", "deflate");
assertFalse(HttpUtils.acceptsGzip(headers));
} |
@Override
public Optional<GaugeMetricFamilyMetricsCollector> export(final String pluginType) {
if (null == ProxyContext.getInstance().getContextManager()) {
return Optional.empty();
}
GaugeMetricFamilyMetricsCollector result = MetricsCollectorRegistry.get(config, pluginType);
... | @Test
void assertExportWithContextManager() {
ContextManager contextManager = mockContextManager();
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
Optional<GaugeMetricFamilyMetricsCollector> collector = new ProxyMetaDataInfoExporter().export("FIXTURE");
... |
@Override
public void deleteConfig(Long id) {
// 校验配置存在
ConfigDO config = validateConfigExists(id);
// 内置配置,不允许删除
if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) {
throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE);
}
// 删除
configMapp... | @Test
public void testDeleteConfig_success() {
// mock 数据
ConfigDO dbConfig = randomConfigDO(o -> {
o.setType(ConfigTypeEnum.CUSTOM.getType()); // 只能删除 CUSTOM 类型
});
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbConfig.getId();
... |
@Override
public boolean supportsGroupByUnrelated() {
return false;
} | @Test
void assertSupportsGroupByUnrelated() {
assertFalse(metaData.supportsGroupByUnrelated());
} |
public void transferAllStateDataToDirectory(
Collection<StateHandleDownloadSpec> downloadRequests,
CloseableRegistry closeableRegistry)
throws Exception {
// We use this closer for fine-grained shutdown of all parallel downloading.
CloseableRegistry internalCloser = ... | @Test
public void testMultiThreadCleanupOnFailure() throws Exception {
int numRemoteHandles = 3;
int numSubHandles = 6;
byte[][][] contents = createContents(numRemoteHandles, numSubHandles);
List<StateHandleDownloadSpec> downloadRequests = new ArrayList<>(numRemoteHandles);
f... |
public static boolean deleteQuietly(@Nullable File file) {
if (file == null) {
return false;
}
return deleteQuietly(file.toPath());
} | @Test
public void deleteQuietly_deletes_symbolicLink() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path folder = temporaryFolder.newFolder().toPath();
Path file1 = Files.createFile(folder.resolve("file1.txt"));
Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
... |
public UiLinkId uiLinkId() {
return uiLinkId;
} | @Test
public void uiLinkId() {
blink = new ConcreteLink(UiLinkId.uiLinkId(RA, RB));
print(blink);
assertEquals("non-canon AB", EXP_RA_RB, blink.linkId());
assertNull("key not null", blink.key());
assertNull("one not null", blink.one());
assertNull("two not null", bli... |
public List<InsertBucketCumulativeWeightPair> getInsertBuckets(String partitionPath) {
return partitionPathToInsertBucketInfos.get(partitionPath);
} | @Test
public void testUpsertPartitionerWithRecordsPerBucket() throws Exception {
final String testPartitionPath = "2016/09/26";
// Inserts + Updates... Check all updates go together & inserts subsplit
UpsertPartitioner partitioner = getUpsertPartitioner(0, 250, 100, 1024, testPartitionPath, false);
Li... |
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException {
if (response.length == 1 && response[0] == OAuthBearerSaslClient.BYTE_CONTROL_A && errorMessage != null) {
log.debug("Received %x01 response from client after it received our error");
... | @Test
public void throwsAuthenticationExceptionOnInvalidExtensions() {
OAuthBearerUnsecuredValidatorCallbackHandler invalidHandler = new OAuthBearerUnsecuredValidatorCallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
... |
public B delay(Integer delay) {
this.delay = delay;
return getThis();
} | @Test
void delay() {
ServiceBuilder builder = new ServiceBuilder();
builder.delay(1000);
Assertions.assertEquals(1000, builder.build().getDelay());
} |
public static boolean authenticate(String username, String password) {
try {
String dn = getUid(username);
if (dn != null) {
/* Found user - test password */
if ( testBind( dn, password ) ) {
if(logger.isDebugEnabled()) logger.debug("us... | @Ignore
@Test
public void testAuthentication() throws Exception {
String user = "jduke";
String password = "theduke";
Assert.assertEquals(true, LdapUtil.authenticate(user, password));
} |
public RecordType getRecordType(String cuid) {
if (cuid == null)
throw new NullPointerException();
lazyLoadDefaultConfiguration();
RecordType recordType = recordTypes.get(cuid);
return recordType != null ? recordType : RecordType.PRIVATE;
} | @Test
public void testGetRecordType() {
RecordFactory f = new RecordFactory();
assertEquals(RecordType.IMAGE,
f.getRecordType(UID.SecondaryCaptureImageStorage));
} |
public static long noHeapMemoryUsed() {
return noHeapMemoryUsage.getUsed();
} | @Test
public void noHeapMemoryUsed() {
long memoryUsed = MemoryUtil.noHeapMemoryUsed();
Assert.assertNotEquals(0, memoryUsed);
} |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDecodeTupleDynamicStructNested() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000001"
+ "0000000000000000000000000000... |
@Override
public void install(SAContextManager contextManager) {
mEncryptAPIImpl = new SAEncryptAPIImpl(contextManager);
if (!contextManager.getInternalConfigs().saConfigOptions.isDisableSDK()) {
setModuleState(true);
}
} | @Test
public void install() {
SAHelper.initSensors(mApplication);
SAEncryptProtocolImpl encryptProtocol = new SAEncryptProtocolImpl();
encryptProtocol.install(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager());
} |
public PackageRevision latestModificationSince(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration, final PackageRevision previouslyKnownRevision) {
return pluginRequestHelper.submitRequ... | @Test
public void shouldTalkToPluginToGetLatestModificationSinceLastRevision() throws Exception {
String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," +
"\"package-configuration\":{\"key-three\":{\"value\"... |
@Override
public Boolean addIfExists(double longitude, double latitude, V member) {
return get(addIfExistsAsync(longitude, latitude, member));
} | @Test
public void testAddIfExists() {
RGeo<String> geo = redisson.getGeo("test");
assertThat(geo.add(2.51, 3.12, "city1")).isEqualTo(1);
assertThat(geo.addIfExists(2.9, 3.9, "city1")).isTrue();
Map<String, GeoPosition> pos = geo.pos("city1");
System.out.println("" + pos.get(... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM)
{
return;
}
if (event.getMessage().startsWith("You retrieve a bar of"))
{
if (session == null)
{
session = new SmeltingSession();
}
session.increaseBarsSmelted();
}
else if (event.g... | @Test
public void testBars()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", SMELT_BAR, "", 0);
smeltingPlugin.onChatMessage(chatMessage);
SmeltingSession smeltingSession = smeltingPlugin.getSession();
assertNotNull(smeltingSession);
assertEquals(1, smeltingSession.getBarsSmelte... |
protected boolean evaluation(Object rawValue) {
String stringValue = (String) ConverterTypeUtil.convert(String.class, rawValue);
Object convertedValue = arrayType.getValue(stringValue);
switch (inNotIn) {
case IN:
return values.contains(convertedValue);
ca... | @Test
void evaluationStringIn() {
ARRAY_TYPE arrayType = ARRAY_TYPE.STRING;
List<Object> values = getObjects(arrayType, 1);
KiePMMLSimpleSetPredicate kiePMMLSimpleSetPredicate = getKiePMMLSimpleSetPredicate(values, arrayType,
... |
@Override
public void afterPropertiesSet() {
Collection<DataChangedListener> listenerBeans = applicationContext.getBeansOfType(DataChangedListener.class).values();
this.listeners = Collections.unmodifiableList(new ArrayList<>(listenerBeans));
} | @Test
@SuppressWarnings("unchecked")
public void afterPropertiesSetTest() {
List<DataChangedListener> listeners = (List<DataChangedListener>) ReflectionTestUtils.getField(dataChangedEventDispatcher, "listeners");
assertTrue(listeners.contains(httpLongPollingDataChangedListener));
assertT... |
public String migrate(String oldJSON, int targetVersion) {
LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON);
Chainr transform = getTransformerFor(targetVersion);
Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion));
... | @Test
void migrateV2ToV3_shouldDoNothingIfFetchExternalArtifactTaskIsConfiguredInV2() {
ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother();
String oldJSON = documentMother.v2WithFetchExternalArtifactTask();
String newJson = documentMother.v3WithFetchExternalArtifactTask... |
public boolean poll(Timer timer, boolean waitForJoinGroup) {
maybeUpdateSubscriptionMetadata();
invokeCompletedOffsetCommitCallbacks();
if (subscriptions.hasAutoAssignedPartitions()) {
if (protocol == null) {
throw new IllegalStateException("User configured " + Cons... | @Test
public void testAutoCommitManualAssignmentCoordinatorUnknown() {
try (ConsumerCoordinator coordinator = buildCoordinator(rebalanceConfig, new Metrics(), assignors, true, subscriptions)) {
subscriptions.assignFromUser(singleton(t1p));
subscriptions.seek(t1p, 100);
/... |
@Override
public void recordStateMachineRestarted(StateMachineInstance machineInstance, ProcessContext context) {
if (machineInstance != null) {
//save to db
Date gmtUpdated = new Date();
int effect = executeUpdate(stateLogStoreSqls.getUpdateStateMachineRunningStatusSql(... | @Test
public void testRecordStateMachineRestarted() {
DbAndReportTcStateLogStore dbAndReportTcStateLogStore = new DbAndReportTcStateLogStore();
StateMachineInstanceImpl stateMachineInstance = new StateMachineInstanceImpl();
ProcessContextImpl context = new ProcessContextImpl();
conte... |
public GsubData getGsubData()
{
return gsubData;
} | @Test
void testGetGsubData() throws IOException
{
// given
RandomAccessReadBuffer randomAccessReadBuffer = new RandomAccessReadBuffer(
GSUBTableDebugger.class.getResourceAsStream("/ttf/Lohit-Bengali.ttf"));
RandomAccessReadDataStream randomAccessReadBufferDataStream = new... |
public long getUnknownLen() {
return unknown_len;
} | @Test
public void getUnknownLen() {
assertEquals(TestParameters.VP_UNKNOWN_LEN, chmItsfHeader.getUnknownLen());
} |
public void clean(final Date now) {
List<String> files = this.findFiles();
List<String> expiredFiles = this.filterFiles(files, this.createExpiredFileFilter(now));
for (String f : expiredFiles) {
this.delete(new File(f));
}
if (this.totalSizeCap != CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP && thi... | @Test
public void removesOlderFilesThatExceedTotalSizeCap() {
setupSizeCapTest();
remover.clean(EXPIRY);
for (File f : Arrays.asList(expiredFiles).subList(MAX_HISTORY - NUM_FILES_TO_KEEP, expiredFiles.length)) {
verify(fileProvider).deleteFile(f);
}
} |
public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function,
CheckedFunction1<Throwable, T> exceptionHandler) {
return () -> {
try {
return function.apply();
} catch (Throwable throwable) {
return exceptionHandler.apply(throwable);
... | @Test(expected = RuntimeException.class)
public void shouldRethrowException() throws Throwable {
CheckedFunction0<String> callable = () -> {
throw new IOException("BAM!");
};
CheckedFunction0<String> callableWithRecovery = VavrCheckedFunctionUtils.recover(callable, (ex) -> {
... |
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (StringUtils.isNotBlank(protocol)) {
b.append(protocol);
b.append("://");
}
if (StringUtils.isNotBlank(host)) {
b.append(host);
}
if (!isPortDefault() &&... | @Test
public void testRelativeURLs() {
s = "./blah";
t = "./blah";
assertEquals(t, new HttpURL(s).toString());
s = "/blah";
t = "/blah";
assertEquals(t, new HttpURL(s).toString());
s = "blah?param=value#frag";
t = "blah?param=value#frag";
asser... |
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (component.getType() != Component.Type.FILE || component.getUuid().equals(issue.componentUuid())) {
return;
}
Optional<OriginalFile> originalFileOptional = movedFilesRepository.getOriginalFile(component);
checkState(orig... | @Test
public void onIssue_does_not_alter_issue_if_component_is_not_a_file() {
DefaultIssue issue = mock(DefaultIssue.class);
underTest.onIssue(ReportComponent.builder(Component.Type.DIRECTORY, 1).build(), issue);
verifyNoInteractions(issue);
} |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_navigation_wheel() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("wheel", config);
assertThat(config.navigation).isEqualTo(NAVIGATION_WHEEL);
} |
public MeterProducer(MetricsEndpoint endpoint) {
super(endpoint);
} | @Test
public void testMeterProducer() {
assertThat(producer, is(notNullValue()));
assertThat(producer.getEndpoint(), is(equalTo(endpoint)));
} |
public static NameMapping of(MappedField... fields) {
return new NameMapping(MappedFields.of(ImmutableList.copyOf(fields)));
} | @Test
public void testAllowsDuplicateNamesInSeparateContexts() {
new NameMapping(
MappedFields.of(
MappedField.of(1, "x", MappedFields.of(MappedField.of(3, "x"))),
MappedField.of(2, "y", MappedFields.of(MappedField.of(4, "x")))));
} |
public synchronized void changeBrokerRole(final Long newMasterBrokerId, final String newMasterAddress,
final Integer newMasterEpoch,
final Integer syncStateSetEpoch, final Set<Long> syncStateSet) throws Exception {
if (newMasterBrokerId != null && newMasterEpoch > this.masterEpoch) {
... | @Test
public void changeBrokerRoleTest() {
HashSet<Long> syncStateSetA = new HashSet<>();
syncStateSetA.add(BROKER_ID_1);
HashSet<Long> syncStateSetB = new HashSet<>();
syncStateSetA.add(BROKER_ID_2);
// not equal to localAddress
Assertions.assertThatCode(() -> replic... |
@Override
public <T> T serialize(final Serializer<T> dict) {
dict.setStringForKey(String.valueOf(type), "Type");
dict.setStringForKey(this.getAbsolute(), "Remote");
if(symlink != null) {
dict.setObjectForKey(symlink, "Symbolic Link");
}
dict.setObjectForKey(attrib... | @Test
public void testDictionaryDirectory() {
Path path = new Path("/path", EnumSet.of(Path.Type.directory));
assertEquals(path, new PathDictionary<>().deserialize(path.serialize(SerializerFactory.get())));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.