focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final CloudBlobContainer container = session.getClient().getContainerReference(containerService.getContainer(directory).getName());
final Attribute... | @Test(expected = NotfoundException.class)
public void testListNotFoundFolder() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
new AzureObjectListService(session, null).list(new Path(container, "notfound", EnumSet.of(Path.Type.direc... |
void placeOrder(Order order) {
sendShippingRequest(order);
} | @Test
void testPlaceOrderNoExceptionShortMsgDuration() throws Exception {
long paymentTime = timeLimits.paymentTime();
long queueTaskTime = timeLimits.queueTaskTime();
long messageTime = timeLimits.messageTime();
long employeeTime = timeLimits.employeeTime();
long queueTime = timeLimit... |
@Override
public Enumeration<URL> getResources(String name) throws IOException {
List<URL> resources = new ArrayList<>();
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resources '{}'", name);
for (ClassLoadingStrategy.Source... | @Test
void parentFirstGetResourcesExistsOnlyInDependency() throws IOException, URISyntaxException {
Enumeration<URL> resources = parentFirstPluginClassLoader.getResources("META-INF/dependency-file");
assertNumberOfResourcesAndFirstLineOfFirstElement(1, "dependency", resources);
} |
@Override
public void updateLockStatus(String xid, LockStatus lockStatus) {
} | @Test
public void testUpdateLockStatus() {
LocalDBLocker locker = new LocalDBLocker();
String xid = "xid";
LockStatus lockStatus = LockStatus.Locked;
locker.updateLockStatus(xid, lockStatus);
} |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null!");
byte[] ... | @Test
public void testRename_keyNotExist() {
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot));
if (sameSlot) {
// This is a quirk of the implementation - since same-slot renames use the non... |
@Override
public Neighbor<double[], E> nearest(double[] q) {
NeighborBuilder<double[], E> neighbor = new NeighborBuilder<>();
search(q, root, neighbor);
neighbor.key = keys[neighbor.index];
neighbor.value = data[neighbor.index];
return neighbor.toNeighbor();
} | @Test
public void testBenchmark() throws Exception {
System.out.println("----- Benchmark -----");
int N = 40000;
int scale = 100;
int numTests = 100_000;
double[][] coords = new double[N][3];
for (int i = 0; i < N; i++) {
coords[i][0] = MathEx.random() *... |
public static OptExpression bind(Pattern pattern, GroupExpression groupExpression) {
Binder binder = new Binder(pattern, groupExpression);
return binder.next();
} | @Test
public void testBinder2() {
OptExpression expr = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN),
new OptExpression(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN)),
new OptExpression(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN)));
Pattern... |
public void drainHandler(final Runnable handler) {
checkContext();
if (drainHandler != null) {
throw new IllegalStateException("drainHandler already set");
}
this.drainHandler = Objects.requireNonNull(handler);
} | @Test
public void shouldNotAllowSettingDrainHandlerMoreThanOnce() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
context.runOnContext(v -> {
getBufferedPublisher().drainHandler(() -> {
});
try {
getBufferedPublisher().drainHandler(() -> {
});
fail("S... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldEvaluateAnyNumberOfArgumentLambda() {
// Given:
givenUdfWithNameAndReturnType("TRANSFORM", SqlTypes.STRING);
when(function.parameters()).thenReturn(
ImmutableList.of(
ArrayType.of(DoubleType.INSTANCE),
StringType.INSTANCE,
MapType.of(Long... |
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {
final long now = System.cur... | @Test
public void reportsByteGaugeValues() throws Exception {
reporter
.report(map("gauge", gauge((byte) 1)), this.map(), this.map(), this.map(), this.map());
final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class);
Mockito.veri... |
public static Match match() {
return new AutoValue_FileIO_Match.Builder()
.setConfiguration(MatchConfiguration.create(EmptyMatchTreatment.DISALLOW))
.build();
} | @Test
@Category(NeedsRunner.class)
public void testMatchDisallowEmptyExplicit() throws IOException {
p.apply(
FileIO.match()
.filepattern(tmpFolder.getRoot().getAbsolutePath() + "/*")
.withEmptyMatchTreatment(EmptyMatchTreatment.DISALLOW));
thrown.expectCause(isA(FileNotFoun... |
static boolean empty(String s) {
return (s == null || s.equals(""));
} | @Test
public void testEmpty() {
assertTrue(LogUtil.empty(null));
assertTrue(LogUtil.empty(""));
assertFalse(LogUtil.empty("f"));
assertFalse(LogUtil.empty("fo"));
assertFalse(LogUtil.empty("foo"));
} |
@Override
public ValidationResult validate(Object value) {
if (value instanceof org.joda.time.DateTime && value.toString().endsWith("Z")) {
return new ValidationResult.ValidationPassed();
} else {
return new ValidationResult.ValidationFailed(value + " is not a valid date!");
... | @Test
public void testValidate() throws Exception {
Validator v = new DateValidator();
assertFalse(v.validate(null).passed());
assertFalse(v.validate(9001).passed());
assertFalse(v.validate("").passed());
assertFalse(v.validate(new java.util.Date()).passed());
// On... |
@Override
public Integer getJavaVersion() {
return jarJavaVersion;
} | @Test
public void testGetJavaVersion() {
StandardPackagedProcessor standardPackagedProcessor =
new StandardPackagedProcessor(Paths.get("ignore"), 8);
assertThat(standardPackagedProcessor.getJavaVersion()).isEqualTo(8);
} |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldNotStartValidationPhaseQueries() {
// Given:
givenFileContainsAPersistentQuery();
when(sandBox.execute(any(), any(ConfiguredStatement.class)))
.thenReturn(ExecuteResult.of(sandBoxQuery));
// When:
standaloneExecutor.startAsync();
// Then:
verify(sandBoxQue... |
public List<String> getVehicles() {
return getEncodedValues().stream()
.filter(ev -> ev.getName().endsWith("_access"))
.map(ev -> ev.getName().replaceAll("_access", ""))
.filter(v -> getEncodedValues().stream().anyMatch(ev -> ev.getName().contains(VehicleSpeed.key... | @Test
public void testGetVehicles() {
EncodingManager em = EncodingManager.start()
.add(VehicleAccess.create("car"))
.add(VehicleAccess.create("bike")).add(VehicleSpeed.create("bike", 4, 2, true))
.add(VehicleSpeed.create("roads", 5, 5, false))
... |
public static <T> T newInstanceOrNull(Class<? extends T> clazz, Object... params) {
Constructor<T> constructor = selectMatchingConstructor(clazz, params);
if (constructor == null) {
return null;
}
try {
return constructor.newInstance(params);
} catch (Ill... | @Test
public void newInstanceOrNull_createInstanceWithSingleArgument() {
ClassWithStringConstructor instance = InstantiationUtils.newInstanceOrNull(ClassWithStringConstructor.class,
"foo");
assertNotNull(instance);
} |
public ExecCommandExecutor getCommandExecutor() {
return commandExecutor;
} | @Test
@DirtiesContext
public void testCreateEndpointCustomCommandExecutor() throws Exception {
ExecEndpoint e = createExecEndpoint("exec:test?commandExecutor=#customExecutor");
assertSame(customExecutor, e.getCommandExecutor(),
"Expected is the custom customExecutor reference fro... |
public ArrayList<AnalysisResult<T>> getOutliers(Track<T> track) {
// the stream is wonky due to the raw type, probably could be improved
return track.points().stream()
.map(point -> analyzePoint(point, track))
.filter(analysisResult -> analysisResult.isOutlier())
.c... | @Test
public void testNoOutlier_2() {
/*
* Confirm that a flat altitude profile with a single 300-foot deviation (i.e. 3 times the
* minimum possible altitude change) does not create an outlier.
*/
Track<NopHit> testTrack2 = createTrackFromResource(VerticalOutlierDetector.... |
public static void isNull(Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
} | @Test(expected = IllegalArgumentException.class)
public void assertIsNullAndMessageIsNull() {
Assert.isNull("");
} |
public Map<String, Object> getExtras() {
return Collections.unmodifiableMap(extras);
} | @Test
public void testGetExtras() {
Request request = new Request();
request.putExtra("a", "1");
assertThat(request.getExtras()).containsEntry("a", "1");
} |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithAlreadyEscapedQuote() {
CharSequence value = "foo\"\"goo";
CharSequence expected = "foo\"\"goo";
escapeCsv(value, expected);
} |
public int getASNum() {
return asNum;
} | @Test
public void testConstruction() {
LispAsAddress asAddress = address1;
assertThat(asAddress.getASNum(), is(1));
} |
public static String serializeRecordToJsonExpandingValue(ObjectMapper mapper, Record<GenericObject> record,
boolean flatten)
throws JsonProcessingException {
JsonRecord jsonRecord = new JsonRecord();
GenericObject value = record.ge... | @Test(dataProvider = "schemaType")
public void testKeyValueSerializeNoValue(SchemaType schemaType) throws Exception {
RecordSchemaBuilder keySchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("key");
keySchemaBuilder.field("a").type(SchemaType.STRING).optional().defaultValue(nu... |
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
... | @Test
public void decodeSucceedsWithMinimalMessages() throws Exception {
assertThat(codec.decode(new RawMessage("{\"short_message\":\"0\"}".getBytes(StandardCharsets.UTF_8)))).isNotNull();
assertThat(codec.decode(new RawMessage("{\"message\":\"0\"}".getBytes(StandardCharsets.UTF_8)))).isNotNull();
... |
public String getBuilderName(String propertyName, JsonNode node) {
propertyName = getPropertyNameForAccessor(propertyName, node);
String prefix = "with";
if (propertyName.length() > 1 && Character.isUpperCase(propertyName.charAt(1))) {
return prefix + propertyName;
} else {... | @Test
public void testBuilderNamedCorrectly() {
assertThat(nameHelper.getBuilderName("foo", NODE), is("withFoo"));
assertThat(nameHelper.getBuilderName("oAuth2State", NODE), is("withoAuth2State"));
assertThat(nameHelper.getBuilderName("URL", NODE), is("withUrl"));
} |
public void pop() {
Preconditions.checkState(!stack.isEmpty(), "Error in file properties stack pop, popping at 0");
stack.remove(stack.size() - 1);
updateProperties();
} | @Test
public void testPop_nothingToPop() {
FilePropertiesStack testStack = new FilePropertiesStack();
try {
testStack.pop();
Assert.fail();
} catch (IllegalStateException ise) {
Assert.assertEquals("Error in file properties stack pop, popping at 0", ise.getMessage());
}
} |
public void launch(Monitored mp) {
if (!lifecycle.tryToMoveTo(Lifecycle.State.STARTING)) {
throw new IllegalStateException("Already started");
}
monitored = mp;
Logger logger = LoggerFactory.getLogger(getClass());
try {
launch(logger);
} catch (Exception e) {
logger.warn("Fail... | @Test
public void fail_to_launch_multiple_times() throws IOException {
Props props = createProps();
ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime);
entryPoint.launch(new NoopProcess());
try {
entryPoint.launch(new NoopProcess());
fail();
} catch (... |
@Override
public int getMaxColumnNameLength() {
return 0;
} | @Test
void assertGetMaxColumnNameLength() {
assertThat(metaData.getMaxColumnNameLength(), is(0));
} |
@Override
public String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
JMeterVariables vars = getVariables();
String stringToSplit = ((CompoundVariable) values[0]).execute();
String varNamePrefix = ((CompoundVariable) values[1]).ex... | @Test
public void shouldSplitWithPreviousResultOnly() throws Exception {
String src = "a,,c,";
vars.put("VAR", src);
SplitFunction split = splitParams("${VAR}", "VAR5", null);
SampleResult previousResult = new SampleResult();
previousResult.setResponseData("Some data", null)... |
@Override
public String toString(@Nullable String root, Iterable<String> names) {
StringBuilder builder = new StringBuilder();
if (root != null) {
builder.append(root);
}
joiner().appendTo(builder, names);
return builder.toString();
} | @Test
public void testUnix_toUri_escaping() {
URI uri = PathType.unix().toUri(fileSystemUri, "/", ImmutableList.of("foo bar"), false);
assertThat(uri.toString()).isEqualTo("jimfs://foo/foo%20bar");
assertThat(uri.getRawPath()).isEqualTo("/foo%20bar");
assertThat(uri.getPath()).isEqualTo("/foo bar");
... |
@Override
public CompletableFuture<YarnWorkerNode> requestResource(
TaskExecutorProcessSpec taskExecutorProcessSpec) {
checkInitialized();
final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>();
final Optional<TaskExecutorProcessSpecContainerR... | @Test
void testRunAsyncCausesFatalError() throws Exception {
new Context() {
{
final String exceptionMessage = "runAsyncCausesFatalError";
addContainerRequestFutures.add(CompletableFuture.completedFuture(null));
testingYarnAMRMClientAsyncBuilder.s... |
@Override
public Optional<ShardingConditionValue> generate(final InExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) {
if (predicate.isNot()) {
return Optional.empty();
}
Collection<ExpressionSegment> expression... | @Test
void assertNotInExpression() {
ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("id"));
ListExpression right = new ListExpression(0, 0);
right.getItems().add(new ParameterMarkerExpressionSegment(0, 0, 0));
InExpression inExpression = new InExpression(0, 0, left,... |
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 invokeTimeUnitsParamsNull() {
FunctionTestUtil.assertResultError(timeFunction.invoke(null, null, null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(timeFunction.invoke(null, null, 1, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultErr... |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava2RetryAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava2RetryAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
@Override
public <T> UncommittedBundle<T> createRootBundle() {
return underlying.createRootBundle();
} | @Test
public void rootBundleSucceeds() {
UncommittedBundle<byte[]> root = factory.createRootBundle();
byte[] array = new byte[] {0, 1, 2};
root.add(WindowedValue.valueInGlobalWindow(array));
CommittedBundle<byte[]> committed = root.commit(Instant.now());
assertThat(
committed.getElements(... |
private KvSwap() {} | @Test
@Category(ValidatesRunner.class)
public void testKvSwap() {
PCollection<KV<String, Integer>> input =
p.apply(
Create.of(Arrays.asList(TABLE))
.withCoder(
KvCoder.of(
StringUtf8Coder.of(), NullableCoder.of(BigEndianIntegerCoder... |
@Override
public Iterator<V> descendingIterator() {
return new Iterator<V>() {
private int currentIndex = size();
private boolean removeExecuted;
@Override
public boolean hasNext() {
int size = size();
return currentIndex > 0 ... | @Test
public void testDescendingIteratorOrigin() {
final Deque<Integer> queue = new ArrayDeque<Integer>();
queue.addAll(Arrays.asList(1, 2, 3));
assertThat(queue.descendingIterator()).toIterable().containsExactly(3, 2, 1);
} |
@Override
public Enumeration<URL> getResources(String name) throws IOException {
List<URL> resources = new ArrayList<>();
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resources '{}'", name);
for (ClassLoadingStrategy.Source... | @Test
void parentLastGetResourcesExistsOnlyInPlugin() throws IOException, URISyntaxException {
Enumeration<URL> resources = parentLastPluginClassLoader.getResources("META-INF/plugin-file");
assertNumberOfResourcesAndFirstLineOfFirstElement(1, "plugin", resources);
} |
public List<Chapter> getChapters() {
return chapters;
} | @Test
public void testRealFileMp3chapsPy() throws IOException, ID3ReaderException {
CountingInputStream inputStream = new CountingInputStream(getClass().getClassLoader()
.getResource("mp3chaps-py.mp3").openStream());
ChapterReader reader = new ChapterReader(inputStream);
read... |
@Override
public boolean isFinished()
{
return finishing && outputPage == null;
} | @Test(dataProvider = "hashEnabledValues")
public void testSemiJoin(boolean hashEnabled)
{
DriverContext driverContext = taskContext.addPipelineContext(0, true, true, false).addDriverContext();
// build
OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanNodeId(... |
@Bean
public FilterRegistrationBean<HttpRequestContextFilter> requestContextFilterRegistration(
HttpRequestContextFilter requestContextFilter) {
FilterRegistrationBean<HttpRequestContextFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(requestContextFilter);
... | @Test
void testRequestContextFilterRegistration() {
HttpRequestContextConfig contextConfig = new HttpRequestContextConfig();
HttpRequestContextFilter filter = contextConfig.nacosRequestContextFilter();
FilterRegistrationBean<HttpRequestContextFilter> actual = contextConfig.requestContextFilt... |
public ProtocolBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
} | @Test
void prompt() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.prompt("prompt");
Assertions.assertEquals("prompt", builder.build().getPrompt());
} |
public static Object typeConvert(String tableName ,String columnName, String value, int sqlType, String mysqlType) {
if (value == null
|| (value.equals("") && !(isText(mysqlType) || sqlType == Types.CHAR || sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR))) {
return null;
... | @Test
public void typeConvertInputNotNullNotNullNotNullPositiveNotNullOutputTrue() {
// Arrange
final String tableName = "?????????";
final String columnName = "?";
final String value = "5";
final int sqlType = 16;
final String mysqlType = "bigintsunsigned";
// Act
final Object actua... |
public void run() {
try {
InputStreamReader isr = new InputStreamReader( this.is );
BufferedReader br = new BufferedReader( isr );
String line = null;
while ( ( line = br.readLine() ) != null ) {
String logEntry = this.type + " " + line;
switch ( this.logLevel ) {
c... | @Test
public void testLogError() {
streamLogger = new ConfigurableStreamLogger( log, is, LogLevel.ERROR, PREFIX );
streamLogger.run();
Mockito.verify( log ).logError( OUT1 );
Mockito.verify( log ).logError( OUT2 );
} |
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return ClusterHealthStatus.unHealth("can't get the instance list");
}
if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) {
List<RemoteInstance... | @Test
public void healthWhenReceiverRoleWithEmptySelfInstance() {
List<RemoteInstance> remoteInstances = new ArrayList<>();
remoteInstances.add(new RemoteInstance(new Address("192.168.0.1", 8892, false)));
OAPNodeChecker.setROLE(CoreModuleConfig.Role.Receiver);
ClusterHealthStatus cl... |
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) {
if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) {
throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG);
}
final String[] split = filterExpression.... | @Test
void parsesFilterExpressionForStringFieldsCorrectlyEvenIfValueContainsRangeSeparator() {
final List<EntityAttribute> entityAttributes = List.of(EntityAttribute.builder()
.id("text")
.title("Text")
.type(SearchQueryField.Type.STRING)
.filt... |
@Override
public String requestMessageForIsRepositoryConfigurationValid(RepositoryConfiguration repositoryConfiguration) {
Map configuredValues = new LinkedHashMap();
configuredValues.put("repository-configuration", jsonResultMessageHandler.configurationToMap(repositoryConfiguration));
retur... | @Test
public void shouldBuildRequestBodyForCheckRepositoryConfigurationValidRequest() throws Exception {
String requestMessage = messageHandler.requestMessageForIsRepositoryConfigurationValid(repositoryConfiguration);
assertThat(requestMessage, is("{\"repository-configuration\":{\"key-one\":{\"value... |
@Override
public Optional<RegistryAuthenticator> handleHttpResponseException(
ResponseException responseException) throws ResponseException, RegistryErrorException {
// Only valid for status code of '401 Unauthorized'.
if (responseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) {
... | @Test
public void testHandleHttpResponseException_noHeader() throws ResponseException {
Mockito.when(mockResponseException.getStatusCode())
.thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
Mockito.when(mockResponseException.getHeaders()).thenReturn(mockHeaders);
Mockito.when(mockHeaders.getA... |
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_always_returns_empty_if_RuleRepository_is_empty() {
NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap());
DetailsSupplier detailsSupplier = readDetailsSupplier(underTest);
assertThat(de... |
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Timed
@ApiOperation("Add a list of new patterns")
@AuditEvent(type = AuditEventTypes.GROK_PATTERN_IMPORT_CREATE)
public Response bulkUpdatePatternsFromTextFile(@ApiParam(name = "patterns", required = true) @NotNull InputStream patternsFile,
... | @Test
public void bulkUpdatePatternsFromTextFileWithCR() throws Exception {
final String patterns = Arrays.stream(GROK_LINES).collect(Collectors.joining("\r"));
final ByteArrayInputStream inputStream = new ByteArrayInputStream(patterns.getBytes(StandardCharsets.UTF_8));
final GrokPattern exp... |
@Override
public long pageIdx2size(int pageIdx) {
return sizeClass.pageIdx2size(pageIdx);
} | @Test
public void testPageIdx2size() {
SizeClasses sc = new SizeClasses(PAGE_SIZE, PAGE_SHIFTS, CHUNK_SIZE, 0);
PoolArena<ByteBuffer> arena = new PoolArena.DirectArena(null, sc);
for (int i = 0; i < arena.sizeClass.nPSizes; i++) {
assertEquals(arena.sizeClass.pageIdx2sizeCompute(... |
@Override
public HttpResponse send(HttpRequest httpRequest) throws IOException {
return send(httpRequest, null);
} | @Test
public void send_whenRequestFailed_throwsException() {
assertThrows(
IOException.class,
() -> httpClient.send(get("http://unknownhost/path").withEmptyHeaders().build()));
} |
public static boolean isLinkLocalAddress(byte[] targetIp) {
checkArgument(targetIp.length == Ip6Address.BYTE_LENGTH);
return (targetIp[0] & 0xff) == 0xfe && (targetIp[1] & 0xc0) == 0x80;
} | @Test
public void testIsLinkLocalAddress() {
assertFalse(isLinkLocalAddress(SOURCE_ADDRESS));
assertFalse(isLinkLocalAddress(DESTINATION_ADDRESS));
assertFalse(isLinkLocalAddress(SOLICITATION_NODE_ADDRESS));
assertTrue(isLinkLocalAddress(LINK_LOCAL_ADDRESS_1));
assertTrue(isL... |
public static InternalLogger getInstance(Class<?> clazz) {
return getInstance(clazz.getName());
} | @Test
public void testIsInfoEnabled() {
when(mockLogger.isInfoEnabled()).thenReturn(true);
InternalLogger logger = InternalLoggerFactory.getInstance("mock");
assertTrue(logger.isInfoEnabled());
verify(mockLogger).isInfoEnabled();
} |
public static boolean isSecond(long ts) {
return (ts & SECOND_MASK) == 0;
} | @Test
public void testIsSecond() {
Assert.assertFalse(TimeUtils.isSecond(System.currentTimeMillis()));
Assert.assertTrue(TimeUtils.isSecond(System.currentTimeMillis() / 1000));
} |
Map<ProjectionProducer<PTransform<?, ?>>, Map<PCollection<?>, FieldAccessDescriptor>>
getPushdownOpportunities() {
return pushdownOpportunities.build();
} | @Test
public void testProjectionProducerInsideNonProducer_returnsInnerPushdown() {
Pipeline p = Pipeline.create();
CompositeTransformWithPushdownInside source = new CompositeTransformWithPushdownInside();
PCollection<Row> output = p.apply(source);
Map<PCollection<?>, FieldAccessDescriptor> pCollectio... |
public static Transcript parse(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
str = str.replaceAll("\r\n", "\n");
Transcript transcript = new Transcript();
List<String> lines = Arrays.asList(str.split("\n"));
Iterator<String> iter = lines.iterat... | @Test
public void testParseSrt() {
Transcript result = SrtTranscriptParser.parse(srtStr);
assertEquals(result.getSegmentAtTime(0L).getWords(), "Promoting your podcast in a new");
assertEquals(result.getSegmentAtTime(0L).getSpeaker(), "John Doe");
assertEquals(result.getSegmentAtTime... |
@Override
protected void setProperties(Map<String, String> properties) throws DdlException {
Preconditions.checkState(properties != null);
for (String key : properties.keySet()) {
if (!DRIVER_URL.equals(key) && !URI.equals(key) && !USER.equals(key) && !PASSWORD.equals(key)
... | @Test(expected = DdlException.class)
public void testWithoutPassword() throws Exception {
Map<String, String> configs = getMockConfigs();
configs.remove(JDBCResource.PASSWORD);
JDBCResource resource = new JDBCResource("jdbc_resource_test");
resource.setProperties(configs);
} |
@Override public HashSlotCursor16byteKey cursor() {
return new CursorLongKey2();
} | @Test(expected = AssertionError.class)
public void testCursor_valueAddress_whenDisposed() {
HashSlotCursor16byteKey cursor = hsa.cursor();
hsa.dispose();
cursor.valueAddress();
} |
public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) {
JsonNode oldConfiguration = node.getConfiguration();
int configurationVersion = node.getConfigurationVersion();
int currentVersion = nodeInfo.getCurrentVersion();
var configClass = nodeInfo.ge... | @Test
public void testUpgradeRuleNodeConfigurationWithNewConfigAndOldConfigVersion() throws Exception {
// GIVEN
var node = new RuleNode();
var nodeInfo = mock(RuleNodeClassInfo.class);
var nodeConfigClazz = TbGetEntityDataNodeConfiguration.class;
var annotation = mock(org.th... |
@Override
public void start() {
this.executorService.scheduleAtFixedRate(this::tryBroadcastEvents, getInitialDelay(), getPeriod(), TimeUnit.SECONDS);
} | @Test
public void nothing_to_broadcast_when_client_list_is_empty() {
when(clientsRegistry.getClients()).thenReturn(emptyList());
var underTest = new PushEventPollScheduler(executorService, clientsRegistry, db.getDbClient(), system2, config);
underTest.start();
executorService.runCommand();
veri... |
@Override
public void updateDataSourceConfig(DataSourceConfigSaveReqVO updateReqVO) {
// 校验存在
validateDataSourceConfigExists(updateReqVO.getId());
DataSourceConfigDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceConfigDO.class);
validateConnectionOK(updateObj);
// 更新
... | @Test
public void testUpdateDataSourceConfig_success() {
try (MockedStatic<JdbcUtils> databaseUtilsMock = mockStatic(JdbcUtils.class)) {
// mock 数据
DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class);
dataSourceConfigMapper.insert(dbDataSourceConf... |
@SuppressWarnings("fallthrough")
public static long[] murmurhash3_x64_128(byte[] key, int offset, int len, int seed) {
// The original algorithm does have a 32 bit unsigned seed.
// We have to mask to match the behavior of the unsigned types and prevent sign extension.
long h1 = seed & 0x00000000FFFFFFFFL... | @Test
public void testMurmurhash3_x64_128() {
Random random = new Random(17);
for (int i = 0; i < 128; i++) {
byte[] bytes = new byte[i];
random.nextBytes(bytes);
long hashCode1 = MurmurHash3.murmurhash3_x64_128(bytes, 0, bytes.length, 47)[0];
long hashCode2 = Hashing.murmur3_128(47).h... |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testRun() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
Pipeline p = buildDataflowPipeline(options);
DataflowPipelineJob job = (DataflowPipelineJob) p.run();
assertEquals("newid", job.getJobId());
ArgumentCaptor<Job> jobCaptor = ArgumentCaptor.fo... |
@SuppressWarnings("unchecked")
public static Object castValue(Object inputValue, FieldType input, FieldType output) {
TypeName inputType = input.getTypeName();
TypeName outputType = output.getTypeName();
if (inputValue == null) {
return null;
}
switch (inputType) {
case ROW:
... | @Test
public void testCastArray() {
Object output =
Cast.castValue(
Arrays.asList((short) 1, (short) 2, (short) 3),
Schema.FieldType.array(Schema.FieldType.INT16),
Schema.FieldType.array(Schema.FieldType.INT32));
assertEquals(Arrays.asList(1, 2, 3), output);
} |
@Override
public GrokPattern save(GrokPattern pattern) throws ValidationException {
try {
if (!validate(pattern)) {
throw new ValidationException("Invalid pattern " + pattern);
}
} catch (GrokException | PatternSyntaxException e) {
throw new Valida... | @Test
public void saveSucceedsWithValidGrokPattern() throws ValidationException {
service.save(GrokPattern.create("NUMBER", "[0-9]+"));
verify(clusterEventBus, times(1)).post(any(GrokPatternsUpdatedEvent.class));
assertThat(collection.countDocuments()).isEqualTo(1L);
} |
public static long getDU(File dir) {
long size = 0;
if (!dir.exists())
return 0;
if (!dir.isDirectory()) {
return dir.length();
} else {
File[] allFiles = dir.listFiles();
if (allFiles != null) {
for (File f : allFiles) {
if (!org.apache.commons.io.FileUtils.isS... | @Test (timeout = 30000)
public void testGetDU() throws Exception {
long du = FileUtil.getDU(testFolder.getRoot());
// Only two files (in partitioned). Each has 3 characters + system-specific
// line separator.
final long expected = 2 * (3 + System.getProperty("line.separator").length());
Assert.a... |
public void verifyState(HttpRequest request, @Nullable String csrfState, @Nullable String login) {
if (!shouldRequestBeChecked(request)) {
return;
}
String failureCause = checkCsrf(csrfState, request.getHeader(CSRF_HEADER));
if (failureCause != null) {
throw AuthenticationException.newBuild... | @Test
public void verify_state() {
mockRequestCsrf(CSRF_STATE);
mockPostJavaWsRequest();
underTest.verifyState(request, CSRF_STATE, LOGIN);
} |
public static void smooth(PointList geometry, double maxWindowSize) {
if (geometry.size() <= 2) {
// geometry consists only of tower nodes, there are no pillar nodes to be smoothed in between
return;
}
// calculate the distance between all points once here to avoid repea... | @Test
public void testDenseWay() {
// distance: 100m, 50m, 50m, 100m
PointList pl = new PointList(5, true);
pl.add(47.32763157186426, 10.158549243021412, 30);
pl.add(47.32846770417248, 10.159039980808643, 20);
pl.add(47.32891933217678, 10.159062491716355, 0);
pl.add(4... |
@SafeVarargs
public static <T> Set<T> createSetContaining(T... contents) {
return new HashSet<>(Arrays.asList(contents));
} | @Test
public void testCreateSetContaining() {
Set<String> set = CollectionHelper.createSetContaining("foo", "bar", "baz");
assertEquals(3, set.size());
assertTrue(set.contains("foo"));
assertTrue(set.contains("bar"));
assertTrue(set.contains("baz"));
} |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testStringType() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder.startAnd().equals("string", PredicateLeaf.Type.STRING, "Joe").end().build();
UnboundPredicate expected = Expressions.equal("string", "Joe");
UnboundPredicate ... |
public static <T> T createNewClassInstance(Class<T> cls, Class<?>[] ctorClassArgs,
Object[] ctorArgs) {
try {
if (ctorClassArgs == null) {
return cls.newInstance();
}
Constructor<T> ctor = cls.getConstructor(ctorClassArgs);
return ctor.newInstance(ctorArgs);
} catch (Invoca... | @Test
public void createNewClassInstance() {
class TestCase {
Class<?> mCls;
Class<?>[] mCtorClassArgs;
Object[] mCtorArgs;
String mExpected;
public TestCase(String expected, Class<?> cls, Class<?>[] ctorClassArgs, Object... ctorArgs) {
mCls = cls;
mCtorClassArgs = c... |
public static Object convert(final Object o) {
if (o == null) {
return RubyUtil.RUBY.getNil();
}
final Class<?> cls = o.getClass();
final Valuefier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return converter.convert(o);
... | @Test
public void testJodaDateTIme() {
DateTime jo = DateTime.now();
Object result = Valuefier.convert(jo);
assertEquals(JrubyTimestampExtLibrary.RubyTimestamp.class, result.getClass());
} |
@Nullable
public String getLeadingPath(int n) {
String path = mUri.getPath();
if (n == 0 && path.indexOf(AlluxioURI.SEPARATOR) == 0) { // the special case
return AlluxioURI.SEPARATOR;
}
int depth = getDepth();
if (depth < n) {
return null;
} else if (depth == n) {
return path... | @Test
public void getLeadingPath() {
assertEquals("/", new AlluxioURI("/a/b/c/").getLeadingPath(0));
assertEquals("/a", new AlluxioURI("/a/b/c/").getLeadingPath(1));
assertEquals("/a/b", new AlluxioURI("/a/b/c/").getLeadingPath(2));
assertEquals("/a/b/c", new AlluxioURI("/a/b/c/").getLeadin... |
@Override
public void close() throws UnavailableException {
// JournalContext is closed before block deletion context so that file system master changes
// are written before block master changes. If a failure occurs between deleting an inode and
// remove its blocks, it's better to have an orphaned block... | @Test
public void journalContextThrows() throws Throwable {
Exception jcException = new UnavailableException("journal context exception");
doThrow(jcException).when(mMockJC).close();
checkClose(jcException);
} |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldResolveInterNodeListenerToFirstListenerSetToResolvableHost() {
// Given:
final URL expected = url("https://example.com:12345");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9... |
public double getNormalizedEditDistance(String source, String target) {
ImmutableList<String> sourceTerms = NamingConventions.splitToLowercaseTerms(source);
ImmutableList<String> targetTerms = NamingConventions.splitToLowercaseTerms(target);
// costMatrix[s][t] is the edit distance between source term s a... | @Test
public void getNormalizedEditDistance_returnsNoMatch_withDifferentTerms() {
TermEditDistance termEditDistance =
new TermEditDistance((s, t) -> s.equals(t) ? 0.0 : 1.0, (s, t) -> 1.0);
String sourceIdentifier = "fooBar";
String targetIdentifier = "bazQux";
double distance =
term... |
@Override
public Map<String, String> getLabels() {
final Map<String, String> labels = new HashMap<>();
labels.putAll(
flinkConfig
.getOptional(KubernetesConfigOptions.JOB_MANAGER_LABELS)
.orElse(Collections.emptyMap()));
labels.... | @Test
void testPrioritizeBuiltInLabels() {
final Map<String, String> userLabels = new HashMap<>();
userLabels.put(Constants.LABEL_TYPE_KEY, "user-label-type");
userLabels.put(Constants.LABEL_APP_KEY, "user-label-app");
userLabels.put(Constants.LABEL_COMPONENT_KEY, "user-label-compone... |
@Override
public Validation validate(Validation val) {
if (StringUtils.isBlank(systemEnvironment.getPropertyImpl("jetty.home"))) {
systemEnvironment.setProperty("jetty.home", systemEnvironment.getPropertyImpl("user.dir"));
}
systemEnvironment.setProperty("jetty.base", systemEnvir... | @Test
public void shouldSetJettyHomeAndBasePropertyIfItsNotSet() {
when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn("");
when(systemEnvironment.getPropertyImpl("user.dir")).thenReturn("junk");
Validation val = new Validation();
jettyWorkDirValidator.validate(val);
... |
@Override
public Num calculate(BarSeries series, Position position) {
return position.hasProfit() ? series.one() : series.zero();
} | @Test
public void calculateWithOneLongPosition() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(2, series));
assertNumEquals(1, getCriterion().calculate(series, position));
} |
@Nonnull
@Override
public Sketch<IntegerSummary> getResult() {
return unionAll();
} | @Test
public void testThresholdBehavior() {
IntegerSketch input1 = new IntegerSketch(_lgK, IntegerSummary.Mode.Sum);
IntStream.range(0, 1000).forEach(i -> input1.update(i, 1));
CompactSketch<IntegerSummary> sketch1 = input1.compact();
IntegerSketch input2 = new IntegerSketch(_lgK, IntegerSummary.Mode.... |
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public List<String> getChildrenKeys(final String key) {
String prefix = key + PATH_SEPARATOR;
ByteSequence prefixByteSequence = ByteSequence.from(prefix, StandardCharsets.UTF_8);
GetOption getOption = GetOpti... | @Test
void assertGetChildrenKeysWhenThrowExecutionException() throws ExecutionException, InterruptedException {
doThrow(ExecutionException.class).when(getFuture).get();
try {
repository.getChildrenKeys("/key/key1");
// CHECKSTYLE:OFF
} catch (final Exception ex) {
... |
@Override
public ShardingStrategyConfiguration swapToObject(final YamlShardingStrategyConfiguration yamlConfig) {
int shardingStrategyConfigCount = 0;
ShardingStrategyConfiguration result = null;
if (null != yamlConfig.getStandard()) {
shardingStrategyConfigCount++;
r... | @Test
void assertSwapToObjectForNoneShardingStrategy() {
YamlShardingStrategyConfiguration yamlConfig = new YamlShardingStrategyConfiguration();
yamlConfig.setNone(new YamlNoneShardingStrategyConfiguration());
YamlShardingStrategyConfigurationSwapper swapper = new YamlShardingStrategyConfigu... |
@Override
public TempFileSpace newSpace(final String subdirectoryPrefix) {
// TODO: Accept only ISO 8601-style timestamp in the v0.10 series.
if (!ISO8601_BASIC_PATTERN.matcher(subdirectoryPrefix).matches()) {
logger.warn("TempFileSpaceAllocator#newSpace should be called with ISO 8601 ba... | @Test
public void testNewSpaceWithIso8601Basic() {
final TempFileSpaceAllocator allocator = new SimpleTempFileSpaceAllocator();
allocator.newSpace("20191031T123456Z");
} |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testSubscriptionPositionUpdatedWithEpoch() {
// Create some records that include a leader epoch (1)
MemoryRecordsBuilder builder = MemoryRecords.builder(
ByteBuffer.allocate(1024),
RecordBatch.CURRENT_MAGIC_VALUE,
Compression.NONE,
... |
public static Date parseHttpDate(CharSequence txt) {
return parseHttpDate(txt, 0, txt.length());
} | @Test
public void testParseAllMonths() {
assertEquals(Calendar.JANUARY, getMonth(parseHttpDate("Sun, 06 Jan 1994 08:49:37 GMT")));
assertEquals(Calendar.FEBRUARY, getMonth(parseHttpDate("Sun, 06 Feb 1994 08:49:37 GMT")));
assertEquals(Calendar.MARCH, getMonth(parseHttpDate("Sun, 06 Mar 1994 ... |
public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName) {
long startTime = System.nanoTime();
final MutableObject<CompletableFuture> newFutureCreated = new MutableObject<>();
try {
return lookupInProgress.computeIfAbsent(topicName, tpName -> {
Compl... | @Test(invocationTimeOut = 3000)
public void maxLookupRedirectsTest1() throws Exception {
LookupTopicResult lookupResult = lookup.getBroker(topicName).get();
assertEquals(lookupResult.getLogicalAddress(), InetSocketAddress
.createUnresolved("broker2.pulsar.apache.org" ,6650));
... |
public static SnapshotRef fromJson(String json) {
Preconditions.checkArgument(
json != null && !json.isEmpty(), "Cannot parse snapshot ref from invalid JSON: %s", json);
return JsonUtil.parse(json, SnapshotRefParser::fromJson);
} | @Test
public void testFailParsingWhenNullOrEmptyJson() {
String nullJson = null;
assertThatThrownBy(() -> SnapshotRefParser.fromJson(nullJson))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("Cannot parse snapshot ref from invalid JSON");
String emptyJson = "";
... |
public static boolean codeAwareEqualsIgnoreSpaces(String in1, String in2) {
if ( in1 == null || in2 == null ) {
return in1 == null && in2 == null;
}
if ( in1.isEmpty() && in2.isEmpty() ) {
return true;
}
if ( in1.length() == 0 ) {
in1 ... | @Test
public void test_codeAwareEqualsIgnoreSpaces() {
assertThat(StringUtils.codeAwareEqualsIgnoreSpaces(null, null)).isTrue();
assertThat(StringUtils.codeAwareEqualsIgnoreSpaces("", "")).isTrue();
assertThat(StringUtils.codeAwareEqualsIgnoreSpaces("", null)).isFalse();
assertThat(S... |
@Override
public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable) {
Map<DeviceId, Link> links = new HashMap<>();
ConnectPoint egressPoint = intent.egressPoint();
final boolean allowMissingPaths = intentAllowsPartialFailure(intent);
boolean hasPath... | @Test
public void testSameDeviceCompilation() {
Set<FilteredConnectPoint> ingress =
Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)),
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_2)));
FilteredConnectPoint egress =
... |
static double toDouble(final JsonNode object) {
if (object instanceof NumericNode) {
return object.doubleValue();
}
if (object instanceof TextNode) {
try {
return Double.parseDouble(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionExc... | @Test
public void shouldConvertLongToDoubleCorrectly() {
final Double d = JsonSerdeUtils.toDouble(JsonNodeFactory.instance.numberNode(1L));
assertThat(d, equalTo(1.0));
} |
@Override
public List<String> listPartitionColumns(Connection connection, String databaseName, String tableName) {
String partitionColumnsQuery = "SELECT DISTINCT PARTITION_EXPRESSION FROM INFORMATION_SCHEMA.PARTITIONS " +
"WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND PARTITION_NAME IS NOT ... | @Test
public void testListPartitionColumns() {
try {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
Integer size = jdbcMetadata.listPartitionColumns("test", "tbl1",
Arrays.asList(new Column("d", Type.VARCHAR))).size();
... |
@Override
public String version() {
return VERSION;
} | @Test
public void shouldReturnOneDotZeroForVersion() {
assertThat(new JsonBasedTaskExtensionHandler_V1().version(), is("1.0"));
} |
public abstract byte[] encode(MutableSpan input); | @Test void span_JSON_V2() {
assertThat(new String(encoder.encode(clientSpan), UTF_8))
.isEqualTo(
"{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"name\":\"get\",\"timestamp\":1472470996199000,\"duration\":2070... |
@Override
public void onDraw(Canvas canvas) {
final boolean keyboardChanged = mKeyboardChanged;
super.onDraw(canvas);
// switching animation
if (mAnimationLevel != AnimationsLevel.None && keyboardChanged && (mInAnimation != null)) {
startAnimation(mInAnimation);
mInAnimation = null;
}
... | @Test
public void testDoesNotAddExtraDrawIfRtlWorkaround() {
SharedPrefsHelper.setPrefsValue(R.string.settings_key_workaround_disable_rtl_fix, false);
ExtraDraw mockDraw1 = Mockito.mock(ExtraDraw.class);
Mockito.doReturn(true).when(mockDraw1).onDraw(any(), any(), same(mViewUnderTest));
Robolectric.ge... |
@VisibleForTesting
String importSingleAlbum(UUID jobId, TokensAndUrlAuthData authData, MediaAlbum inputAlbum)
throws IOException, InvalidTokenException, PermissionDeniedException, UploadErrorException {
// Set up album
GoogleAlbum googleAlbum = new GoogleAlbum();
googleAlbum.setTitle(GooglePhotosImp... | @Test
public void importAlbumWithITString()
throws PermissionDeniedException, InvalidTokenException, IOException, UploadErrorException {
String albumId = "Album Id";
String albumName = "Album Name";
String albumDescription = "Album Description";
MediaAlbum albumModel = new MediaAlbum(albumId, a... |
static JobVertexInputInfo computeVertexInputInfoForPointwise(
int sourceCount,
int targetCount,
Function<Integer, Integer> numOfSubpartitionsRetriever,
boolean isDynamicGraph) {
final List<ExecutionVertexInputInfo> executionVertexInputInfos = new ArrayList<>();
... | @Test
void testComputeVertexInputInfoForPointwiseWithDynamicGraph() {
final JobVertexInputInfo jobVertexInputInfo =
computeVertexInputInfoForPointwise(2, 3, ignored -> 4, true);
assertThat(jobVertexInputInfo.getExecutionVertexInputInfos())
.containsExactlyInAnyOrder(
... |
public static Object getProperty(Object source, String key) {
if (source instanceof Map) {
return ((Map<?, ?>) source).get(key);
}
SingleValueMap<Object, Object> map = new SingleValueMap<>();
copy(source, map, include(key));
return map.getValue();
} | @Test
public void testGetProperty() {
Assert.assertEquals(1, FastBeanCopier.getProperty(ImmutableMap.of("a", 1, "b", 2), "a"));
} |
public void applyClientConfiguration(String account, DataLakeFileSystemClientBuilder builder) {
String sasToken = adlsSasTokens.get(account);
if (sasToken != null && !sasToken.isEmpty()) {
builder.sasToken(sasToken);
} else if (namedKeyCreds != null) {
builder.credential(
new StorageSh... | @Test
public void testNoSasToken() {
AzureProperties props = new AzureProperties();
DataLakeFileSystemClientBuilder clientBuilder = mock(DataLakeFileSystemClientBuilder.class);
props.applyClientConfiguration("account", clientBuilder);
verify(clientBuilder, times(0)).sasToken(any());
verify(client... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.