focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
if (!stringsPresent) {
return;
}
StringsConfig stringsConfig = context.get(StringsConfig.class... | @Test
public void testParse() throws Exception {
assumeTrue(canRun());
String resource = "/test-documents/testOCTET_header.dbase3";
String[] content = {"CLASSNO", "TITLE", "ITEMNO", "LISTNO", "LISTDATE"};
String[] met_attributes = {"min-len", "encoding", "strings:file_output"};
... |
@Udf(description = "Returns the inverse (arc) sine of an INT value")
public Double asin(
@UdfParameter(
value = "value",
description = "The value to get the inverse sine of."
) final Integer value
) {
return asin(value == null ? null : value.doubleValue())... | @Test
public void shouldHandleLessThanNegativeOne() {
assertThat(Double.isNaN(udf.asin(-1.1)), is(true));
assertThat(Double.isNaN(udf.asin(-6.0)), is(true));
assertThat(Double.isNaN(udf.asin(-2)), is(true));
assertThat(Double.isNaN(udf.asin(-2L)), is(true));
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldDeserializeScientificNotation() {
// Given:
final KsqlJsonDeserializer<BigDecimal> deserializer =
givenDeserializerForSchema(DecimalUtil.builder(3, 1).build(), BigDecimal.class);
final byte[] bytes = addMagic("1E+1".getBytes(UTF_8));
// When:
final Object result ... |
Future<Boolean> canRoll(int podId) {
LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId);
return canRollBroker(descriptions, podId);
} | @Test
public void testBelowMinIsr(VertxTestContext context) {
KSB ksb = new KSB()
.addNewTopic("A", false)
.addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
.addNewPartition(0)
.replicaOn(0, 1, 3)
.leader(0)
... |
@GET
@Produces(MediaTypeRestconf.APPLICATION_YANG_DATA_JSON)
@Path("data/{identifier : .+}")
public Response handleGetRequest(@PathParam("identifier") String uriString) {
log.debug("handleGetRequest: {}", uriString);
URI uri = uriInfo.getRequestUri();
try {
ObjectNode n... | @Test
public void testHandleGetRequest() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
expect(restconfService
.runGetOperationOnDataResource(URI.create(getBaseUri() + DATA_IETF_SYSTEM_SYSTEM)))
.andReturn(node).anyTim... |
@Activate
public void activate(ComponentContext context) {
providerService = providerRegistry.register(this);
appId = coreService.registerApplication(APP_NAME);
netCfgService.registerConfigFactory(factory);
netCfgService.addListener(cfgLister);
connectDevices();
modi... | @Test
public void testActivate() {
assertEquals("Incorrect provider service", deviceProviderService, provider.providerService);
assertEquals("Incorrect application id", applicationId, provider.appId);
assertTrue("Incorrect config factories", cfgFactories.contains(provider.factory));
... |
@Nullable
public static TimeHandlerConfig getTimeHandlerConfig(TableConfig tableConfig, Schema schema,
Map<String, String> taskConfig) {
String timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
if (timeColumn == null) {
return null;
}
DateTimeFieldSpec fieldSpec = schema.... | @Test
public void testGetTimeHandlerConfig() {
TableConfig tableConfig =
new TableConfigBuilder(TableType.OFFLINE).setTableName("myTable").setTimeColumnName("dateTime").build();
Schema schema = new Schema.SchemaBuilder()
.addDateTime("dateTime", DataType.LONG, "1:SECONDS:SIMPLE_DATE_FORMAT:yyy... |
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) {
Future<Integer> tlsFuture;
if (certSecretSources == null || certSecretSources.isEmpty()) {
tlsFuture = Future.succeededFutu... | @Test
void testAuthTlsPlainSecretFoundAndPasswordNotFound() {
SecretOperator secretOperator = mock(SecretOperator.class);
Map<String, String> data = new HashMap<>();
data.put("passwordKey", "my-password");
Secret secret = new Secret();
secret.setData(data);
Completion... |
@Override
public void notifyRequiredSegmentId(int subpartitionId, int segmentId) {
if (segmentId > requiredSegmentId) {
requiredSegmentId = segmentId;
stopSendingData = false;
availabilityListener.notifyDataAvailable(this);
}
} | @Test
void testNotifyRequiredSegmentId() {
tieredStorageResultSubpartitionView.notifyRequiredSegmentId(0, 1);
assertThat(availabilityListener).isDone();
} |
public Span nextSpan(TraceContextOrSamplingFlags extracted) {
if (extracted == null) throw new NullPointerException("extracted == null");
TraceContext context = extracted.context();
if (context != null) return newChild(context);
TraceIdContext traceIdContext = extracted.traceIdContext();
if (traceI... | @Test void localRootId_nextSpan_flags_debug() {
TraceContextOrSamplingFlags flags = TraceContextOrSamplingFlags.DEBUG;
localRootId(flags, flags, ctx -> tracer.nextSpan(ctx));
} |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueFailWrongValue() {
expectFailureWhenTestingThat(fact("foo", "the foo")).factValue("foo").isEqualTo("the bar");
assertFailureValue("value of", "failure.factValue(foo)");
} |
@Override
void execute() throws HiveMetaException {
// Need to confirm unless it's a dry run or specified -yes
if (!schemaTool.isDryRun() && !this.yes) {
boolean confirmed = promptToConfirm();
if (!confirmed) {
System.out.println("Operation cancelled, exiting.");
return;
}
... | @Test
public void testExecuteDryRun() throws Exception {
setUpTwoDatabases();
when(uut.schemaTool.isDryRun()).thenReturn(true);
uut.execute();
Mockito.verify(stmtMock, times(0)).execute(anyString());
} |
static void populateSchemaWithConstraints(Schema toPopulate, SimpleTypeImpl t) {
if (t.getAllowedValues() != null && !t.getAllowedValues().isEmpty()) {
parseSimpleType(DMNOASConstants.X_DMN_ALLOWED_VALUES, toPopulate, t.getAllowedValuesFEEL(), t.getAllowedValues());
}
if (t.getTypeCo... | @Test
void populateSchemaWithConstraintsForTypeConstraints() {
List<String> enumBase = Arrays.asList("DMN", "PMML", "JBPMN", "DRL");
List<Object> toEnum =
enumBase.stream().map(toMap -> String.format("\"%s\"", toMap)).collect(Collectors.toUnmodifiableList());
String typeConst... |
boolean acceptClass(String classname) {
if (inclusions.isEmpty() && exclusions.isEmpty()) {
return true;
}
return acceptResource(classToResource(classname));
} | @Test
void ALL_accepts_everything() throws Exception {
assertThat(Mask.ALL.acceptClass("org.sonar.Bar")).isTrue();
assertThat(Mask.ALL.acceptClass("Bar")).isTrue();
} |
static ExecutorService getConfiguredExecutorService(
CamelContext camelContext, String name, DynamicRouterConfiguration cfg, boolean useDefault)
throws IllegalArgumentException {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ObjectHelper.notNull(manag... | @Test
void testGetConfiguredExecutorServiceWithoutBeanAndServiceRefAndUseDefaultFalse() {
when(mockConfig.getExecutorServiceBean()).thenReturn(null);
when(mockConfig.getExecutorService()).thenReturn(null);
when(camelContext.getExecutorServiceManager()).thenReturn(manager);
ExecutorSe... |
protected static int findSequence(byte[] sequence, byte[] buffer) {
int pos = -1;
for (int i = 0; i < buffer.length - sequence.length + 1; i++) {
if (buffer[i] == sequence[0] && testRemaining(sequence, buffer, i)) {
pos = i;
break;
}
}
... | @Test
public void testFindSequence() throws IOException {
byte[] sequence = "project".getBytes(StandardCharsets.UTF_8);
byte[] buffer = "my big project".getBytes(StandardCharsets.UTF_8);
int expResult = 7;
int result = PomProjectInputStream.findSequence(sequence, buffer);
a... |
public static void checkArgument(boolean expression, String errorMessage)
{
checkArgument(expression, () -> errorMessage);
} | @Test
public void testCheckingCorrectArgument()
{
try {
Utils.checkArgument(true, "Error");
}
catch (Throwable t) {
fail("Checking argument should not fail");
}
} |
void executeWork(DataflowWorkExecutor worker, DataflowWorkProgressUpdater progressUpdater)
throws Exception {
progressUpdater.startReportingProgress();
// Blocks while executing the work.
try {
worker.execute();
} finally {
// stopReportingProgress can throw an exception if the final p... | @Test
public void testStopProgressReportInCaseOfFailure() throws Exception {
doThrow(new WorkerException()).when(mockWorkExecutor).execute();
BatchDataflowWorker worker =
new BatchDataflowWorker(
mockWorkUnitClient, IntrinsicMapTaskExecutorFactory.defaultFactory(), options);
try {
... |
public static RelDataType create(HazelcastIntegerType type, boolean nullable) {
if (type.isNullable() == nullable) {
return type;
}
return create0(type.getSqlTypeName(), nullable, type.getBitWidth());
} | @Test
public void testNullableIntegerTypeOfTypeName() {
assertType(TINYINT, Byte.SIZE - 1, false, HazelcastIntegerType.create(TINYINT, false));
assertType(SMALLINT, Short.SIZE - 1, false, HazelcastIntegerType.create(SMALLINT, false));
assertType(INTEGER, Integer.SIZE - 1, false, HazelcastInt... |
@Override
public void setConfigAttributes(Object attributes) {
clear();
if (attributes == null) {
return;
}
Map attributeMap = (Map) attributes;
String materialType = (String) attributeMap.get(AbstractMaterialConfig.MATERIAL_TYPE);
if (SvnMaterialConfig.TY... | @Test
public void shouldClearExistingAndSetHgConfigAttributesForMaterial() {
MaterialConfigs materialConfigs = new MaterialConfigs();
materialConfigs.add(hg("", null));
materialConfigs.add(svn("", "", "", false));
Map<String, String> hashMap = new HashMap<>();
hashMap.put(Hg... |
@Override
public CompletableFuture<Void> closeAsync() {
synchronized (lock) {
if (isShutdown) {
return terminationFuture;
} else {
isShutdown = true;
final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(3);
... | @Test
void testConfigurableDelimiter() throws Exception {
Configuration config = new Configuration();
config.set(MetricOptions.SCOPE_DELIMITER, "_");
config.set(MetricOptions.SCOPE_NAMING_TM, "A.B.C.D.E");
MetricRegistryImpl registry =
new MetricRegistryImpl(
... |
public static PlanNodeStatsEstimate computeSemiJoin(PlanNodeStatsEstimate sourceStats, PlanNodeStatsEstimate filteringSourceStats, VariableReferenceExpression sourceJoinVariable, VariableReferenceExpression filteringSourceJoinVariable)
{
return compute(sourceStats, filteringSourceStats, sourceJoinVariable, ... | @Test
public void testSemiJoin()
{
// overlapping ranges
assertThat(computeSemiJoin(inputStatistics, inputStatistics, x, w))
.variableStats(x, stats -> stats
.lowValue(xStats.getLowValue())
.highValue(xStats.getHighValue())
... |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
CasdoorAuthService casdoorAuthService = Singleton.INST.get(CasdoorAuthService.class);
ServerHttpRequest request = exchange.getRequest();
... | @Test
void doExecute() {
final PluginData pluginData = new PluginData("pluginId", "pluginName", "{\"organization-name\":\"test\",\"application-name\":\"app-test\",\"endpoint\":\"http://localhost:8000\",\"client_secrect\":\"a4209d412a33a842b7a9c05a3446e623cbb7262d\",\"client_id\":\"6e3a84154e73d1fb156a\",\"c... |
public ControlledFragmentHandler.Action onExtensionMessage(
final int actingBlockLength,
final int templateId,
final int schemaId,
final int actingVersion,
final DirectBuffer buffer,
final int offset,
final int length,
final Header header)
{
if... | @Test
void shouldThrowExceptionOnUnknownSchemaAndNoAdapter()
{
final TestClusterClock clock = new TestClusterClock(TimeUnit.MILLISECONDS);
ctx.epochClock(clock).clusterClock(clock);
final ConsensusModuleAgent agent = new ConsensusModuleAgent(ctx);
assertThrows(ClusterException.... |
static <T> ByteBuddyProxyInvoker<T> newInstance(T proxy, Class<T> type, URL url) {
return new ByteBuddyProxyInvoker<>(proxy, type, url, MethodInvoker.newInstance(proxy.getClass()));
} | @Test
void testNewInstance() throws Throwable {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
RemoteService proxy = Mockito.mock(RemoteService.class);
ByteBuddyProxyInvoker<RemoteService> invoker =
ByteBuddyProxyInvoker.newInstance(proxy, RemoteService... |
public ExecutorService getExecutorService() {
return executorService;
} | @Test
public void testTikaExecutorServiceFromConfig() throws Exception {
URL url = getResourceAsUrl("TIKA-1762-executors.xml");
TikaConfig config = new TikaConfig(url);
ThreadPoolExecutor executorService = (ThreadPoolExecutor) config.getExecutorService();
assertTrue((executorServi... |
@Override
public int getMediumLE(int index) {
int value = getUnsignedMediumLE(index);
if ((value & 0x800000) != 0) {
value |= 0xff000000;
}
return value;
} | @Test
public void testGetMediumLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().getMediumLE(0);
}
});
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testMissedMatch() {
StreamRule rule = getSampleRule();
Message msg = getSampleMessage();
msg.addField("something", "nonono");
StreamRuleMatcher matcher = getMatcher(rule);
assertFalse(matcher.match(msg, rule));
} |
@Override
public void unsubscribe(URL url, NotifyListener listener) {
super.unsubscribe(url, listener);
received.remove(url);
} | @Test
void testUnsubscribe() {
// subscribe first
registry.subscribe(consumerUrl, new NotifyListener() {
@Override
public void notify(List<URL> urls) {
// do nothing
}
});
// then unsubscribe
registry.unsubscribe(consumerUr... |
@Override
public void report(SortedMap<MetricName, Gauge> gauges,
SortedMap<MetricName, Counter> counters,
SortedMap<MetricName, Histogram> histograms,
SortedMap<MetricName, Meter> meters,
SortedMap<MetricName, Timer> timers... | @Test
public void reportsMeterValues() throws Exception {
final Meter meter = mock(Meter.class);
when(meter.getCount()).thenReturn(1L);
when(meter.getMeanRate()).thenReturn(2.0);
when(meter.getOneMinuteRate()).thenReturn(3.0);
when(meter.getFiveMinuteRate()).thenReturn(4.0);
... |
@Override
public AllocatedSlotsAndReservationStatus removeSlots(ResourceID owner) {
final Set<AllocationID> slotsOfTaskExecutor = slotsPerTaskExecutor.remove(owner);
if (slotsOfTaskExecutor != null) {
final Collection<AllocatedSlot> removedSlots = new ArrayList<>();
final Ma... | @Test
void testRemoveSlotsOfUnknownOwnerIsIgnored() {
final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
slotPool.removeSlots(ResourceID.generate());
} |
public CompletableFuture<Long> compact(String topic) {
return RawReader.create(pulsar, topic, COMPACTION_SUBSCRIPTION, false).thenComposeAsync(
this::compactAndCloseReader, scheduler);
} | @Test
public void testCompactedWithConcurrentSend() throws Exception {
String topic = "persistent://my-property/use/my-ns/testCompactedWithConcurrentSend";
@Cleanup
Producer<byte[]> producer = pulsarClient.newProducer().topic(topic)
.enableBatching(false)
.me... |
String getSubstitutionVariable(String key) {
return substitutionVariables.get(key);
} | @Test
public void testMavenFormat() {
assertThat(new LoggingConfiguration(new EnvironmentInformation("maven", "1.0"))
.getSubstitutionVariable(LoggingConfiguration.PROPERTY_FORMAT)).isEqualTo(LoggingConfiguration.FORMAT_MAVEN);
} |
public int getUpdateAppQueueFailedRetrieved() {
return numUpdateAppQueueFailedRetrieved.value();
} | @Test
public void testUpdateAppQueueRetrievedFailed() {
long totalBadBefore = metrics.getUpdateAppQueueFailedRetrieved();
badSubCluster.getUpdateQueueFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getUpdateAppQueueFailedRetrieved());
} |
DatanodeDescriptor getDatanodeByHost(String ipAddr) {
if (ipAddr == null) {
return null;
}
hostmapLock.readLock().lock();
try {
DatanodeDescriptor[] nodes = map.get(ipAddr);
// no entry
if (nodes== null) {
return null;
}
// one node
if (nodes.leng... | @Test
public void testGetDatanodeByHost() throws Exception {
assertEquals(map.getDatanodeByHost("1.1.1.1"), dataNodes[0]);
assertEquals(map.getDatanodeByHost("2.2.2.2"), dataNodes[1]);
DatanodeDescriptor node = map.getDatanodeByHost("3.3.3.3");
assertTrue(node == dataNodes[2] || node == dataNodes[3]);... |
@Override
public Set<Class<? extends BaseStepMeta>> getSupportedSteps() {
return new HashSet<Class<? extends BaseStepMeta>>() {
{
add( ExcelOutputMeta.class );
}
};
} | @Test
public void testGetSupportedSteps() {
ExcelOutputStepAnalyzer analyzer = new ExcelOutputStepAnalyzer();
Set<Class<? extends BaseStepMeta>> types = analyzer.getSupportedSteps();
assertNotNull( types );
assertEquals( types.size(), 1 );
assertTrue( types.contains( ExcelOutputMeta.class ) );
} |
public static Schema schemaFromPojoClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedPOJOWithSimplePOJO() {
Schema schema =
POJOUtils.schemaFromPojoClass(
new TypeDescriptor<TestPOJOs.NestedPOJOWithSimplePOJO>() {},
JavaFieldTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_POJO_WITH_SIMPLE_POJO_SCHEMA, schema);
... |
public void changeToSlave(final String newMasterAddress, final int newMasterEpoch, Long newMasterBrokerId) {
synchronized (this) {
if (newMasterEpoch > this.masterEpoch) {
LOGGER.info("Begin to change to slave, brokerName={}, brokerId={}, newMasterBrokerId={}, newMasterAddress={}, ne... | @Test
public void changeToSlaveTest() {
Assertions.assertThatCode(() -> replicasManager.changeToSlave(NEW_MASTER_ADDRESS, NEW_MASTER_EPOCH, BROKER_ID_2))
.doesNotThrowAnyException();
} |
public static <T> T getItemAtPositionOrNull(T[] array, int position) {
if (position >= 0 && array.length > position) {
return array[position];
}
return null;
} | @Test
public void getItemAtPositionOrNull_whenSmallerArray_thenReturnNull() {
Object obj = new Object();
Object[] src = new Object[1];
src[0] = obj;
Object result = ArrayUtils.getItemAtPositionOrNull(src, 1);
assertNull(result);
} |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void givenDefaultTypeName_whenLoad_thenReturnGenericRecordMapNameAsTypeName() {
ObjectSpec spec = objectProvider.createObject(mapName, false);
objectProvider.insertItems(spec, 1);
mapLoader = createMapLoader();
CompactGenericRecord genericRecord = (CompactGenericRecord... |
@SuppressWarnings("unchecked")
public static <T> T newInstanceIfPossible(Class<T> type) {
Assert.notNull(type);
// 原始类型
if (type.isPrimitive()) {
return (T) ClassUtil.getPrimitiveDefaultValue(type);
}
// 某些特殊接口的实例化按照默认实现进行
if (type.isAssignableFrom(AbstractMap.class)) {
type = (Class<T>) HashMap.cl... | @Test
public void noneStaticInnerClassTest() {
final NoneStaticClass testAClass = ReflectUtil.newInstanceIfPossible(NoneStaticClass.class);
assertNotNull(testAClass);
assertEquals(2, testAClass.getA());
} |
static MetricsConfig loadFirst(String prefix, String... fileNames) {
for (String fname : fileNames) {
try {
PropertiesConfiguration pcf = new PropertiesConfiguration();
pcf.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
FileHandler fh = new FileHandler(pcf);
fh.... | @Test public void testLoadFirst() throws Exception {
String filename = getTestFilename("hadoop-metrics2-p1");
new ConfigBuilder().add("p1.foo", "p1foo").save(filename);
MetricsConfig mc = MetricsConfig.create("p1");
MetricsConfig mc2 = MetricsConfig.create("p1", "na1", "na2", filename);
Configurati... |
@Override
public String getType() {
return POST_DOCUMENT_TYPE;
} | @Test
void ensureTypeNotModified() {
assertEquals("post.content.halo.run", provider.getType());
} |
public String metricsJson(Reconciliation reconciliation, ConfigMap configMap) {
if (isEnabled) {
if (configMap == null) {
LOGGER.warnCr(reconciliation, "ConfigMap {} does not exist.", configMapName);
throw new InvalidConfigurationException("ConfigMap " + configMapNam... | @Test
public void testProblemWithConfigMap() {
MetricsConfig metricsConfig = new JmxPrometheusExporterMetricsBuilder()
.withNewValueFrom()
.withConfigMapKeyRef(new ConfigMapKeySelector("my-key", "my-name", false))
.endValueFrom()
.build();
... |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test(expected=AclException.class)
public void testFilterAclEntriesByAclSpecRemoveDefaultMaskRequired()
throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, N... |
public void setTimeoutSeconds(int timeout) {
kp.put("timeoutSeconds",timeout);
} | @Test
public void testFetchTimeout() throws Exception {
CrawlURI curi = makeCrawlURI("http://localhost:7777/slow.txt");
fetcher().setTimeoutSeconds(2);
fetcher().process(curi);
// logger.info('\n' + httpRequestString(curi) + "\n\n" + rawResponseString(curi));
assertT... |
@Override
public ValidationResponse validate(ValidationRequest req) {
if (req.isEmptyQuery()) {
return ValidationResponse.ok();
}
try {
final ParsedQuery parsedQuery = luceneQueryParser.parse(req.rawQuery());
final ValidationContext context = Validation... | @Test
void validateMixedTypes() {
// validator returns one error
final QueryValidator errorValidator = context -> Collections.singletonList(
ValidationMessage.builder(ValidationStatus.ERROR, ValidationType.QUERY_PARSING_ERROR)
.errorMessage("Query can't be pa... |
@Override
public void getErrors(ErrorCollection errors, String parentLocation) {
String location = getLocation(parentLocation);
errors.checkMissing(location, "link", link);
errors.checkMissing(location, "regex", regex);
validateLink(errors, location);
} | @Test
public void shouldDeserializeFromAPILikeObject() {
String json = """
{
"link": "https://github.com/gocd/api.go.cd/issues/${ID}",
"regex": "##(d+)"
}""";
CRTrackingTool deserializedValue = gson.fromJson(json,CRTrackingToo... |
@Override
public Future<RestResponse> restRequest(RestRequest request)
{
return restRequest(request, new RequestContext());
} | @Test(retryAnalyzer = ThreeRetries.class) // Known to be flaky in CI
public void testRestRetryExceedsClientRetryRatio() throws Exception
{
SimpleLoadBalancer balancer = prepareLoadBalancer(Arrays.asList("http://test.linkedin.com/retry1", "http://test.linkedin.com/good"),
HttpClientFactory.DEFAULT_MAX_CL... |
@Override
public NSImage folderIcon(final Integer size) {
NSImage folder = this.iconNamed("NSFolder", size);
if(null == folder) {
return this.iconNamed("NSFolder", size);
}
return folder;
} | @Test
public void testFolderIcon128() {
final NSImage icon = new NSImageIconCache().folderIcon(128);
assertNotNull(icon);
assertTrue(icon.isValid());
assertFalse(icon.isTemplate());
assertEquals(128, icon.size().width.intValue());
assertEquals(128, icon.size().height.... |
public synchronized long getSplitPointsConsumed() {
if (position == null) {
return 0;
} else if (isDone()) {
return splitPointsSeen;
} else {
// There is a current split point, and it has not finished processing.
checkState(
splitPointsSeen > 0,
"A started rangeTr... | @Test
public void testGetSplitPointsConsumed() {
ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE);
assertEquals(0, tracker.getSplitPointsConsumed());
// Started, 0 split points consumed
assertTrue(tracker.tryReturnRecordAt(true, INITIAL_START_KEY));
assertEquals(0, tracker.getS... |
public static Object convertFromJs( Object value, int type, String fieldName ) throws KettleValueException {
String classType = value.getClass().getName();
switch ( type ) {
case ValueMetaInterface.TYPE_NUMBER:
return jsToNumber( value, classType );
case ValueMetaInterface.TYPE_INTEGER:
... | @Test( expected = RuntimeException.class )
public void convertFromJs_TypeNone() throws Exception {
JavaScriptUtils.convertFromJs( null, ValueMetaInterface.TYPE_NONE, "qwerty" );
} |
public List<String> toMnemonic(byte[] entropy) {
checkArgument(entropy.length % 4 == 0, () ->
"entropy length not multiple of 32 bits");
checkArgument(entropy.length > 0, () ->
"entropy is empty");
// We take initial entropy of ENT bits and compute its
//... | @Test(expected = RuntimeException.class)
public void testEmptyEntropy() throws Exception {
byte[] entropy = {};
mc.toMnemonic(entropy);
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(new DefaultPathContainerService().isContainer(file)) {
return PathAttributes.EMPTY;
}
... | @Test
@Ignore
public void testFindSharedDriveAsDefaultPath() throws Exception {
final DriveAttributesFinderFeature f = new DriveAttributesFinderFeature(session, new DriveFileIdProvider(session));
assertNotEquals(PathAttributes.EMPTY, f.find(new Path(DriveHomeFinderService.SHARED_DRIVES_NAME, "it... |
public String parseToPlainText() throws IOException, SAXException, TikaException {
BodyContentHandler handler = new BodyContentHandler();
AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata();
try (InputStream stream = ContentHandlerExample.class.getResour... | @Test
public void testParseToPlainText() throws IOException, SAXException, TikaException {
String result = example
.parseToPlainText()
.trim();
assertEquals("test", result, "Expected 'test', but got '" + result + "'");
} |
@Override
public List<Column> getPartitionColumns(Map<ColumnId, Column> idToColumn) {
List<Column> columns = MetaUtils.getColumnsByColumnIds(idToColumn, partitionColumnIds);
for (int i = 0; i < columns.size(); i++) {
Expr expr = partitionExprs.get(i).convertToColumnNameExpr(idToColumn);
... | @Test
public void testInitHybrid() {
Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATETIME), true, null, "", "");
SlotRef slotRef = new SlotRef(tableName, "k1");
partitionExprs.add(ColumnIdExpr.create(slotRef));
partitionExprs.add(ColumnIdExpr.create(functionCallExpr));
... |
@Override
public StatusOutputStream<ObjStat> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
try {
final IRODSFileSystemAO fs = session.getClient();
final IRODSFileOutputStream out = fs.getI... | @Test
public void testWrite() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant Collabora... |
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) {
final String parameterName = descriptor.name(); // parameter name needed by function
final Map<String, Object> parameters = step.parameters();
if (Objects.isNull(parameters)) {
return nul... | @Test
public void addFunctionParameterNull_WhenNoParametersAreSet() {
RuleBuilderStep step = mock(RuleBuilderStep.class);
when(step.parameters()).thenReturn(null);
ParameterDescriptor descriptor = mock(ParameterDescriptor.class);
assertThat(ParserUtil.addFunctionParameter(descriptor,... |
public List<RuleData> obtainRuleData(final String selectorId) {
return RULE_MAP.get(selectorId);
} | @Test
public void testObtainRuleData() throws NoSuchFieldException, IllegalAccessException {
RuleData ruleData = RuleData.builder().id("1").selectorId(mockSelectorId1).build();
ConcurrentHashMap<String, List<RuleData>> ruleMap = getFieldByName(ruleMapStr);
ruleMap.put(mockSelectorId1, Lists.... |
protected GelfMessage toGELFMessage(final Message message) {
final DateTime timestamp;
final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP);
if (fieldTimeStamp instanceof DateTime) {
timestamp = (DateTime) fieldTimeStamp;
} else {
timestamp = To... | @Test
public void testToGELFMessageWithInvalidStringLevel() throws Exception {
final GelfTransport transport = mock(GelfTransport.class);
final GelfOutput gelfOutput = new GelfOutput(transport);
final DateTime now = DateTime.now(DateTimeZone.UTC);
final Message message = messageFacto... |
@Override
public boolean tryLock(String name) {
return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS);
} | @Test
public void tryLock_fails_with_IAE_if_name_is_empty() {
String badLockName = "";
expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName);
} |
public static int checkGreaterThanOrEqual(int n, int expected, String name)
{
if (n < expected)
{
throw new IllegalArgumentException(name + ": " + n + " (expected: >= " + expected + ')');
}
return n;
} | @Test
public void checkGreaterThanOrEqualMustPassIfArgumentIsEqualToExpected()
{
final int n = 1;
final int actual = RangeUtil.checkGreaterThanOrEqual(n, 1, "var");
assertThat(actual, is(equalTo(n)));
} |
@Override
public String getValue(EvaluationContext context) {
String result = null;
if (expressions.length > 0) {
// Execute first expression for getting result.
result = expressions[0].getValue(context);
for (int i = 1; i < expressions.length; i++) {
Expression exp... | @Test
void testLiteralRedirectToMultiContext() {
EvaluationContext context = new EvaluationContext();
Expression[] expressions = new Expression[] { new LiteralExpression("hello"),
new FunctionExpression(new PutInContextELFunction(), new String[] { "greeting1" }),
new FunctionExpr... |
@Override
public GroupingShuffleReaderIterator<K, V> iterator() throws IOException {
ApplianceShuffleEntryReader entryReader =
new ApplianceShuffleEntryReader(
shuffleReaderConfig, executionContext, operationContext, true);
initCounter(entryReader.getDatasetId());
return iterator(ent... | @Test
public void testReadFromShuffleAndDynamicSplit() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
BatchModeExecutionContext context = BatchModeExecutionContext.forTesting(options, "testStage");
TestOperationContext operationContext = TestOperationContext.create();
Gr... |
Boolean processPayment() {
try {
ResponseEntity<Boolean> paymentProcessResult = restTemplateBuilder
.build()
.postForEntity("http://localhost:30301/payment/process", "processing payment",
Boolean.class);
LOGGER.info("Payment processing result: {}", paymentProcessResult.... | @Test
void testProcessPayment_HttpClientErrorException() {
// Arrange
when(restTemplate.postForEntity(eq("http://localhost:30301/payment/process"), anyString(), eq(Boolean.class)))
.thenThrow(new HttpClientErrorException(org.springframework.http.HttpStatus.BAD_REQUEST, "Bad request"));
// Act
... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetName() {
assertEquals("Pipfile.lock Analyzer", analyzer.getName());
} |
boolean isModified(Namespace namespace) {
Release release = releaseService.findLatestActiveRelease(namespace);
List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId());
if (release == null) {
return hasNormalItems(items);
}
Map<String, String> releasedConfiguration = GSON.fr... | @Test
public void testNamespaceModifyItem() {
long namespaceId = 1;
Namespace namespace = createNamespace(namespaceId);
Release release = createRelease("{\"k1\":\"v1\"}");
List<Item> items = Collections.singletonList(createItem("k1", "v2"));
when(releaseService.findLatestActiveRelease(namespace)... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestListRecordingSubscriptions()
{
internalEncodeLogHeader(buffer, 0, 90, 90, () -> 10_325_000_000L);
final ListRecordingSubscriptionsRequestEncoder requestEncoder = new ListRecordingSubscriptionsRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_... |
public ASN1Sequence signedPipFromPplist(List<PolymorphicPseudonymType> response) {
for (PolymorphicPseudonymType polymorphicPseudonymType : response) {
ASN1Sequence sequence;
try {
sequence = (ASN1Sequence) ASN1Sequence.fromByteArray(polymorphicPseudonymType.getValue());
... | @Test
public void signedPipFromPplistTest() throws IOException, BsnkException {
List<PolymorphicPseudonymType> pplist = new ArrayList<>();
pplist.add(new PolymorphicPseudonymType() {
{
value = signedPip.getEncoded();
}
});
ASN1Sequence result ... |
@Override
public Table getTable(String dbName, String tblName) {
try {
return deltaOps.getTable(dbName, tblName);
} catch (Exception e) {
LOG.error("Failed to get table {}.{}", dbName, tblName, e);
return null;
}
} | @Test
public void testGetTable() {
new MockUp<DeltaUtils>() {
@mockit.Mock
public DeltaLakeTable convertDeltaToSRTable(String catalog, String dbName, String tblName, String path,
Engine deltaEngine, long createTime) {
... |
public MijnDigidSessionStatus sessionStatus(String mijnDigiDSessionId) {
Optional<MijnDigidSession> optionalSession = mijnDigiDSessionRepository.findById(mijnDigiDSessionId);
if( optionalSession.isEmpty()) {
return MijnDigidSessionStatus.INVALID;
}
MijnDigidSession session = ... | @Test
void testStatusAuthenticatedExistingSession() {
MijnDigidSession session = new MijnDigidSession(1L);
session.setAuthenticated(true);
when(mijnDigiDSessionRepository.findById(eq(session.getId()))).thenReturn(Optional.of(session));
MijnDigidSessionStatus status = mijnDigiDSessio... |
public static PluginOption parse(String pluginSpecification) {
Matcher pluginWithFile = PLUGIN_WITH_ARGUMENT_PATTERN.matcher(pluginSpecification);
if (!pluginWithFile.matches()) {
Class<? extends Plugin> pluginClass = parsePluginName(pluginSpecification, pluginSpecification);
ret... | @Test
void throws_for_plugins_that_do_not_implement_plugin() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> PluginOption.parse(String.class.getName()));
assertThat(exception.getMessage(), is("The plugin specification 'java.lang.String' has a pr... |
@Override public E intern(E sample) {
E canonical = map.get(sample);
if (canonical != null) {
return canonical;
}
var value = map.putIfAbsent(sample, sample);
return (value == null) ? sample : value;
} | @Test(dataProvider = "interners")
public void intern(Interner<Int> interner) {
var canonical = new Int(1);
var other = new Int(1);
assertThat(interner.intern(canonical)).isSameInstanceAs(canonical);
assertThat(interner.intern(other)).isSameInstanceAs(canonical);
checkSize(interner, 1);
var n... |
public static AmountRequest fromString(String amountRequestAsString) {
if (isNullOrEmpty(amountRequestAsString)) return null;
return new AmountRequest(
lenientSubstringBetween(amountRequestAsString, "order=", "&"),
Integer.parseInt(lenientSubstringBetween(amountRequestAs... | @Test
void testAmountRequestWithEmptyString() {
AmountRequest amountRequest = AmountRequest.fromString("");
assertThat(amountRequest).isNull();
} |
public void afterTaskCompletion(MigrationRunnable task) {
if (migrateTaskCount.decrementAndGet() < 0) {
throw new IllegalStateException();
}
} | @Test(expected = IllegalStateException.class)
public void test_migrateTaskCount_notDecremented_belowZero() {
migrationQueue.afterTaskCompletion(mock(MigrationRunnable.class));
} |
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) {
LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName);
if (keyProperties == null) {
keyProperties = new LinkedHashMap<>();
String properties = mbeanName.getKeyPropertyListS... | @Test
public void testQuotedObjectNameWithEquals() throws Throwable {
JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache();
LinkedHashMap<String, String> parameterList =
testCache.getKeyPropertyList(
new ObjectName("com.organisation:name=\"value=more\... |
@Override
public CompletableFuture<Map<String, BrokerLookupData>> filterAsync(Map<String, BrokerLookupData> brokers,
ServiceUnitId serviceUnit,
LoadManagerContext context) ... | @Test
public void testFilter() throws BrokerFilterException, ExecutionException, InterruptedException {
Map<String, BrokerLookupData> originalBrokers = Map.of(
"localhost:6650", getLookupData("2.10.0"),
"localhost:6651", getLookupData("2.10.1"),
"localhost:665... |
public boolean sendRequest(AfnemersberichtAanDGL request) {
Map<String, Object> extraHeaders = new HashMap<>();
extraHeaders.put(Headers.X_AUX_SENDER_ID, digidOIN);
extraHeaders.put(Headers.X_AUX_RECEIVER_ID, digileveringOIN);
try {
digileveringSender.sendMessage(request, He... | @Test
public void testSendAp01Correct(){
AfnemersberichtAanDGLFactory afnemersberichtAanDGLFactory = new AfnemersberichtAanDGLFactory("oin1", "oin2");
AfnemersberichtAanDGL message = afnemersberichtAanDGLFactory.createAfnemersberichtAanDGL(TestDglMessagesUtil.createTestAp01("bsn"));
classUnd... |
public void process()
throws Exception {
if (_segmentMetadata.getTotalDocs() == 0) {
LOGGER.info("Skip preprocessing empty segment: {}", _segmentMetadata.getName());
return;
}
// Segment processing has to be done with a local directory.
File indexDir = new File(_indexDirURI);
// ... | @Test
public void testV1UpdateDefaultColumns()
throws Exception {
constructV1Segment(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyList());
IngestionConfig ingestionConfig = new IngestionConfig();
ingestionConfig.setTransformConfigs(
Immu... |
public String compile(final String xls,
final String template,
int startRow,
int startCol) {
return compile( xls,
template,
InputType.XLS,
startRow,
... | @Test
public void testPricing() throws Exception {
final List<DataListener> listeners = new ArrayList<>();
TemplateDataListener l1 = new TemplateDataListener(10, 3, "/templates/test_pricing1.drl");
listeners.add(l1);
TemplateDataListener l2 = new TemplateDataListener(30, 3, "/templat... |
@Override
public void updateRewardActivity(RewardActivityUpdateReqVO updateReqVO) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(updateReqVO.getId());
if (dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 已关闭的活动,不能修改噢
... | @Test
public void testUpdateRewardActivity_success() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
... |
public static <E extends Enum<E>> Map<String, E> mapEnumNamesToValues(
final String prefix,
final Class<E> enumClass) {
final E[] constants = enumClass.getEnumConstants();
Map<String, E> mapping = new HashMap<>(constants.length);
for (E constant : constants) {
final String lc = constant.na... | @Test
public void testEmptyEnumMap() {
Assertions.assertThat(mapEnumNamesToValues("", EmptyEnum.class))
.isEmpty();
} |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void creates_no_formatter_by_default() {
RuntimeOptions options = parser
.parse()
.build();
Plugins plugins = new Plugins(new PluginFactory(), options);
plugins.setEventBusOnEventListenerPlugins(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID... |
@Override
public void reloadSegment(String segmentName, IndexLoadingConfig indexLoadingConfig, SegmentZKMetadata zkMetadata,
SegmentMetadata localMetadata, @Nullable Schema schema, boolean forceDownload)
throws Exception {
Preconditions.checkState(!_shutDown,
"Table data manager is already shu... | @Test
public void testReloadSegmentForceDownload()
throws Exception {
File indexDir = createSegment(SegmentVersion.v3, 5);
SegmentZKMetadata zkMetadata =
makeRawSegment(indexDir, new File(TEMP_DIR, SEGMENT_NAME + TarCompressionUtils.TAR_GZ_FILE_EXTENSION), false);
// Same CRC but force to d... |
@Override
public Optional<Lock> unlock(@Nonnull String resource, @Nullable String lockContext) {
return doUnlock(resource, getLockedByString(lockContext));
} | @Test
void unlock(MongoDBTestService mongodb) {
final MongoLockService otherNodesLockService =
new MongoLockService(otherNodeId, mongodb.mongoConnection(), MongoLockService.MIN_LOCK_TTL);
final Lock orig = otherNodesLockService.lock("test-resource", null)
.orElseThro... |
public void checkLimit() {
if (!rateLimiter.tryAcquire()) {
rejectSensor.record();
throw new KsqlRateLimitException("Host is at rate limit for pull queries. Currently set to "
+ rateLimiter.getRate() + " qps.");
}
} | @Test
public void shouldError_atLimit() {
final Metrics metrics = new Metrics();
final Map<String, String> tags = Collections.emptyMap();
// It doesn't look like the underlying guava rate limiter has a way to control time, so we're
// just going to have to hope that these tests reliably run in under a... |
@Override
public NearCacheStats getNearCacheStats() {
throw new UnsupportedOperationException("Replicated map has no Near Cache!");
} | @Test(expected = UnsupportedOperationException.class)
public void testNearCacheStats() {
localReplicatedMapStats.getNearCacheStats();
} |
@SuppressWarnings("deprecation")
public boolean setSocketOpt(int option, Object optval)
{
final ValueReference<Boolean> result = new ValueReference<>(false);
switch (option) {
case ZMQ.ZMQ_SNDHWM:
sendHwm = (Integer) optval;
if (sendHwm < 0) {
thro... | @Test(expected = IllegalArgumentException.class)
public void testHeartbeatTtlUnderflow()
{
options.setSocketOpt(ZMQ.ZMQ_HEARTBEAT_TTL, -100);
} |
RegistryEndpointProvider<Optional<URL>> initializer() {
return new Initializer();
} | @Test
public void testInitializer_handleResponse_created() throws IOException, RegistryException {
Mockito.when(mockResponse.getStatusCode()).thenReturn(201); // Created
Assert.assertFalse(testBlobPusher.initializer().handleResponse(mockResponse).isPresent());
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatCreateMapExpression() {
assertThat(ExpressionFormatter.formatExpression(
new CreateMapExpression(ImmutableMap.<Expression, Expression>builder()
.put(new StringLiteral("foo"), new SubscriptExpression(new UnqualifiedColumnReferenceExp(ColumnName.of("abc")), new Inte... |
public static Builder custom() {
return new Builder();
} | @Test
public void shouldCreatePercentCutoff() {
HedgeConfig config = HedgeConfig.custom()
.averagePlusPercentageDuration(100, false).build();
then(HedgeDurationSupplier.fromConfig(config)).isInstanceOf(AverageDurationSupplier.class);
} |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeFromUnsupportedKafkaVersionWithAllVersions(VertxTestContext context) {
String oldKafkaVersion = "2.8.0";
String oldInterBrokerProtocolVersion = "2.8";
String oldLogMessageFormatVersion = "2.8";
String kafkaVersion = VERSIONS.defaultVersion().version();
... |
public void offerToQueue(Point p) {
// @todo -- THIS IS FLAWED, this call WILL drop point data when the queue is
// full
// WE CANNOT (???) BLOCK (i.e. swap to queue.put(p)) BECAUSE THE "DATA LOADING
// THREAD" IS THE SAME AS THE "DATA PROCESSING THREAD"
// ARE YOU SURE? The one ... | @Test
public void swimLaneEmitsBreadcrumbsOnOverflow() {
SwimLane lane = new SwimLane(simpleStreamingKpi(), 1);
Point point = Point.builder().latLong(0.0, 1.0).time(EPOCH).build();
//these files should be made when the swim lane rejects data because the queue was full
File warn1 = ... |
@Override
public int getSessionIntervalTime() {
return 30 * 1000;
} | @Test
public void getSessionIntervalTime() {
Assert.assertEquals(30 * 1000, mSensorsAPI.getSessionIntervalTime());
} |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testSchemaRead() {
run("schema-read.feature");
} |
public LockedInodePath lockFinalEdgeWrite() throws InvalidPathException {
Preconditions.checkState(!fullPathExists());
LockedInodePath newPath =
new LockedInodePath(mUri, this, mPathComponents, LockPattern.WRITE_EDGE, mUseTryLock);
newPath.traverse();
return newPath;
} | @Test
public void lockFinalEdgeWrite() throws Exception {
mInodeStore.removeChild(mRootDir.getId(), "a");
mPath = create("/a", LockPattern.READ);
mPath.traverse();
LockedInodePath writeLocked = mPath.lockFinalEdgeWrite();
assertFalse(writeLocked.fullPathExists());
assertEquals(Arrays.asList(m... |
@Override
public List<T> getResults() {
return multiResult.getResults();
} | @Test
public void testGetResults() {
List<Integer> results = immutableMultiResult.getResults();
assertEquals(2, results.size());
assertTrue(results.contains(23));
assertTrue(results.contains(42));
} |
@Override
public String getHostname(final String alias) {
if(StringUtils.isBlank(alias)) {
return alias;
}
final String hostname = configuration.lookup(alias).getHostName();
if(StringUtils.isBlank(hostname)) {
return alias;
}
if(log.isInfoEnabl... | @Test
public void testLookup() {
OpenSSHHostnameConfigurator c = new OpenSSHHostnameConfigurator(
new OpenSshConfig(
new Local("src/test/resources", "openssh/config")));
assertEquals("cyberduck.ch", c.getHostname("alias"));
} |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test(expected = IllegalArgumentException.class)
public void saveNewClient_badId() {
// Set up a mock client.
ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class);
Mockito.when(client.getId()).thenReturn(12345L); // any non-null ID will work
service.saveNewClient(client);
} |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_with_valueFunction_fails_if_value_function_is_null() {
assertThatThrownBy(() -> unorderedFlattenIndex(MyObj2::getId, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Value function can't be null");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.