focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String formatDT(TimeZone tz, Date date) {
return formatDT(tz, date, new DatePrecision());
} | @Test
public void testFormatDTwithTZ() {
assertEquals("19700101020000.000+0200",
DateUtils.formatDT(tz, new Date(0),
new DatePrecision(Calendar.MILLISECOND, true)));
} |
@Override
public void changeClusterState(@Nonnull ClusterState newState) {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void changeClusterState() {
client().getCluster().changeClusterState(ClusterState.FROZEN);
} |
public static int firstSymlinkIndex(String path)
{
int fromIndex = 0;
int index;
while ((index = path.indexOf('/', fromIndex)) >= 0)
{
fromIndex = index + 1;
if (fromIndex < path.length() && path.charAt(fromIndex) == SYMLINK_PREFIX)
{
if (path.indexOf('/', fromIndex) != -1)
... | @Test
public void testFirstSymlinkIndex()
{
Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path1), path1.length());
Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path2), path2.length());
Assert.assertEquals(SymlinkUtil.firstSymlinkIndex(path3), path1.length());
Assert.assertEquals(SymlinkUtil... |
@Override
public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) {
return store.query(query, positionBound, config);
} | @SuppressWarnings("unchecked")
@Test
public void shouldQueryTimestampedStore() {
givenWrapperWithTimestampedStore();
when(timestampedStore.query(query, positionBound, queryConfig)).thenReturn(result);
assertThat(wrapper.query(query, positionBound, queryConfig), equalTo(result));
} |
@Override
public void setDefaultDataTableCellTransformer(TableCellByTypeTransformer defaultDataTableByTypeTransformer) {
dataTableTypeRegistry.setDefaultDataTableCellTransformer(defaultDataTableByTypeTransformer);
} | @Test
void should_set_default_table_cell_transformer() {
TableCellByTypeTransformer expected = (cell, toValueType) -> null;
registry.setDefaultDataTableCellTransformer(expected);
} |
@Override
public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) {
Objects.requireNonNull(windows, "windows can't be null");
return new TimeWindowedCogroupedKStreamImpl<>(
windows,
builder,
subTopologySourceNodes,
... | @Test
public void shouldNotHaveNullWindowOnWindowedByTime() {
assertThrows(NullPointerException.class, () -> cogroupedStream.windowedBy((Windows<? extends Window>) null));
} |
public static boolean areSameColumns(List<FieldSchema> oldCols, List<FieldSchema> newCols) {
if (oldCols == newCols) {
return true;
}
if (oldCols == null || newCols == null || oldCols.size() != newCols.size()) {
return false;
}
// We should ignore the case of field names, because some co... | @Test
public void testSameColumns() {
FieldSchema col1 = new FieldSchema("col1", "string", "col1 comment");
FieldSchema Col1 = new FieldSchema("Col1", "string", "col1 comment");
FieldSchema col2 = new FieldSchema("col2", "string", "col2 comment");
Assert.assertTrue(MetaStoreServerUtils.areSameColumns(... |
public static String getMaskedStatement(final String query) {
try {
final ParseTree tree = DefaultKsqlParser.getParseTree(query);
return new Visitor().visit(tree);
} catch (final Exception | StackOverflowError e) {
return fallbackMasking(query);
}
} | @Test
public void shouldMaskInvalidSinkConnector() {
// Given:
// Typo in "CONNECTOR" => "CONNECTO"
final String query = "CREATE Sink CONNECTO `test-connector` WITH ("
+ " \"connector.class\" = 'PostgresSource', \n"
+ " 'connection.url' = 'jdbc:postgresql://localhost:5432/my.db',\n"
... |
@Override
public Response updateAppQueue(AppQueue targetQueue, HttpServletRequest hsr,
String appId) throws AuthorizationException, YarnException,
InterruptedException, IOException {
if (targetQueue == null) {
routerMetrics.incrUpdateAppQueueFailedRetrieved();
RouterAuditLogger.logFailure... | @Test
public void testUpdateAppQueue() throws IOException, InterruptedException,
YarnException {
String oldQueue = "oldQueue";
String newQueue = "newQueue";
// Submit application to multiSubCluster
ApplicationId appId = ApplicationId.newInstance(Time.now(), 1);
ApplicationSubmissionContext... |
public static <T> CompletableFuture<T> supplyAsync(
SupplierWithException<T, ?> supplier, Executor executor) {
return CompletableFuture.supplyAsync(
() -> {
try {
return supplier.get();
} catch (Throwable e) {
... | @Test
void testSupplyAsync() {
final Object expectedResult = new Object();
final CompletableFuture<Object> future =
FutureUtils.supplyAsync(() -> expectedResult, EXECUTOR_RESOURCE.getExecutor());
assertThatFuture(future).eventuallySucceeds().isEqualTo(expectedResult);
} |
@Override
public void startScheduling() {
Set<ExecutionVertexID> sourceVertices =
IterableUtils.toStream(schedulingTopology.getVertices())
.filter(vertex -> vertex.getConsumedPartitionGroups().isEmpty())
.map(SchedulingExecutionVertex::getId)
... | @Test
void testStartScheduling() {
VertexwiseSchedulingStrategy schedulingStrategy =
createSchedulingStrategy(testingSchedulingTopology);
final List<List<TestingSchedulingExecutionVertex>> expectedScheduledVertices =
new ArrayList<>();
expectedScheduledVertic... |
public String getSignature(ZonedDateTime now, String policy) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(("AWS4" + awsAccessSecret).getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] dateKey = mac.doFinal(now.format(DateTimeFormatter.ofPattern("yyyyMMdd")).ge... | @Test
void testSignature() {
Instant time = Instant.parse("2015-12-29T00:00:00Z");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(time, ZoneOffset.UTC);
String encodedPolicy = "eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tl... |
@Override
public void trackEvent(InputData input) {
process(input);
} | @Test
public void trackEventItem() throws JSONException {
initSensors();
String itemType = "product_id", itemId = "100";
InputData inputData = new InputData();
inputData.setEventType(EventType.ITEM_DELETE);
inputData.setItemId(itemId);
inputData.setItemType(itemType);... |
public String formatSourceAndFixImports(String input) throws FormatterException {
input = ImportOrderer.reorderImports(input, options.style());
input = RemoveUnusedImports.removeUnusedImports(input);
String formatted = formatSource(input);
formatted = StringWrapper.wrap(formatted, this);
return form... | @Test
public void throwsFormatterException() throws Exception {
try {
new Formatter().formatSourceAndFixImports("package foo; public class {");
fail();
} catch (FormatterException expected) {
}
} |
@Override
public AuthenticationToken authenticate(HttpServletRequest request,
final HttpServletResponse response)
throws IOException, AuthenticationException {
// If the request servlet path is in the whitelist,
// skip Kerberos authentication and return anonymous token.
final String path = r... | @Test
public void testRequestWithIncompleteAuthorization() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
.thenReturn(KerberosAuthenti... |
Mono<NotificationContent> inferenceTemplate(Reason reason, Subscriber subscriber,
Locale locale) {
var reasonTypeName = reason.getSpec().getReasonType();
return getReasonType(reasonTypeName)
.flatMap(reasonType -> notificationTemplateSelector.select(reasonTypeName, locale)
... | @Test
public void testInferenceTemplate() {
final var spyNotificationCenter = spy(notificationCenter);
final var reasonType = mock(ReasonType.class);
var reason = new Reason();
reason.setMetadata(new Metadata());
reason.getMetadata().setName("reason-a");
reason.setS... |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldFindUnknownConsumerPropertyIfNotStrict() {
// Given:
final String configName = StreamsConfig.CONSUMER_PREFIX
+ "custom.interceptor.config";
// Then:
assertThat(resolver.resolve(configName, false), is(unresolvedItem(configName)));
} |
@Override
public Collection<String> resolve(Class<? extends AnalysisIndexer> clazz) {
if (clazz.isAssignableFrom(IssueIndexer.class)) {
return changedIssuesRepository.getChangedIssuesKeys();
}
throw new UnsupportedOperationException("Unsupported indexer: " + clazz);
} | @Test
public void resolve_whenUnsupportedIndexer_shouldThrowUPE() {
when(changedIssuesRepository.getChangedIssuesKeys()).thenReturn(Set.of("key1", "key2","key3"));
assertThatThrownBy(() ->underTest.resolve(ProjectMeasuresIndexer.class))
.isInstanceOf(UnsupportedOperationException.class)
.hasMessag... |
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) {
KafkaMetadataState currentState = metadataState;
metadataState = switch (currentState) {
case KRaft -> onKRaft(kafkaStatus);
case ZooKeeper -> onZooKeeper(kafkaStatus);
case KRaftMigration -... | @Test
public void testWarningInKRaftMigration() {
Kafka kafka = new KafkaBuilder(KAFKA)
.editMetadata()
.addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "enabled")
.endMetadata()
.withNewStatus()
.withKafkaMetadataSt... |
public static String dup(char c, int num) {
if (c == 0 || num < 1)
return "";
StringBuilder sb = new StringBuilder(num);
for (int i = 0; i < num; i++)
sb.append(c);
return sb.toString();
} | @Test
public void testDup() {
String str = StringKit.dup('c', 6);
Assert.assertEquals(6, str.length());
Assert.assertEquals("cccccc", str);
} |
@Override
protected String throwableProxyToString(IThrowableProxy tp) {
return PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX);
} | @Test
void prefixesExceptionsWithExclamationMarks() throws Exception {
assertThat(converter.throwableProxyToString(proxy))
.startsWith(String.format("! java.io.IOException: noo%n" +
"! at io.dropwizard.logging.common.PrefixedThrowableProxyCon... |
public boolean isEnabled() {
return configuration.getBoolean(ENABLED).orElse(false) &&
configuration.get(PROVIDER_ID).isPresent() &&
configuration.get(APPLICATION_ID).isPresent() &&
configuration.get(LOGIN_URL).isPresent() &&
configuration.get(CERTIFICATE).isPresent() &&
configuration.... | @Test
@UseDataProvider("settingsRequiredToEnablePlugin")
public void is_enabled_return_false_when_one_required_setting_is_missing(String setting) {
initAllSettings();
settings.setProperty(setting, (String) null);
assertThat(underTest.isEnabled()).isFalse();
} |
RunMapperResult mapRun(Run run) {
if (run.getResults().isEmpty()) {
return new RunMapperResult();
}
String driverName = getToolDriverName(run);
Map<String, Result.Level> ruleSeveritiesByRuleId = detectRulesSeverities(run, driverName);
Map<String, Result.Level> ruleSeveritiesByRuleIdForNewCCT ... | @Test
public void mapRun_shouldNotFail_whenExtensionsDontHaveRules() {
when(run.getTool().getDriver().getRules()).thenReturn(Set.of(rule));
ToolComponent extension = mock(ToolComponent.class);
when(extension.getRules()).thenReturn(null);
when(run.getTool().getExtensions()).thenReturn(Set.of(extension)... |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
public void rename(
Iterable<String> srcFilenames, Iterable<String> destFilenames, MoveOptions... moveOptions)
throws IOException {
// Rename is implemented as a rewrite followed by deleting the source. If the new object is in
// the same location, the copy is a metadata-only operation.
Set<Move... | @Test
public void testRename() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
gcsUtil.setBatchRequestSupplier(FakeBatcher::n... |
public static URI getProxyUri(URI originalUri, URI proxyUri,
ApplicationId id) {
try {
String path = getPath(id, originalUri == null ? "/" : originalUri.getPath());
return new URI(proxyUri.getScheme(), proxyUri.getAuthority(), path,
originalUri == null ? null : originalUri.getQuery(),
... | @Test
void testGetProxyUriNull() throws Exception {
URI originalUri = null;
URI proxyUri = new URI("http://proxy.net:8080/");
ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5);
URI expected = new URI("http://proxy.net:8080/proxy/application_6384623_0005/");
URI result = ProxyUriUtils.g... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final String resourceId = fileid.getFileId(file);
final UiFsModel uiFsModel = new ListResourceApi(new EueApiClient(session)).resourceR... | @Test
public void testReadInterrupt() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final byte[] content = RandomUtils.nextBytes(32769);
final Path container = new EueDirectoryFeature(session, fileid).mkdir(
new Path(new Alphanume... |
public void unregister(String name) {
HealthCheck healthCheck;
synchronized (lock) {
healthCheck = healthChecks.remove(name);
if (healthCheck instanceof AsyncHealthCheckDecorator) {
((AsyncHealthCheckDecorator) healthCheck).tearDown();
}
}
... | @Test
public void asyncHealthCheckIsCanceledOnRemove() {
registry.unregister("ahc");
verify(af).cancel(true);
} |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) {
list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file));
}
... | @Test
public void testPlaceholder() {
assertTrue(
new S3UrlProvider(session, Collections.emptyMap()).toUrl(new Path("/test-eu-west-1-cyberduck/test", EnumSet.of(Path.Type.directory))).filter(DescriptiveUrl.Type.signed).isEmpty());
} |
@Nullable
public String ensureBuiltinRole(String roleName, String description, Set<String> expectedPermissions) {
Role previousRole = null;
try {
previousRole = roleService.load(roleName);
if (!previousRole.isReadOnly() || !expectedPermissions.equals(previousRole.getPermissio... | @Test
public void ensureBuiltinRoleWithSaveError() throws Exception {
when(roleService.load("test-role")).thenThrow(NotFoundException.class);
when(roleService.save(any(Role.class))).thenThrow(DuplicateKeyException.class); // Throw database error
assertThat(migrationHelpers.ensureBuiltinRole... |
@Override
@Nullable
protected ObjectStatus getObjectStatus(String key) {
try {
ObjectMetadata meta = mClient.getObjectMetadata(mBucketName, key);
Date lastModifiedDate = meta.getLastModified();
Long lastModifiedTime = lastModifiedDate == null ? null : lastModifiedDate.getTime();
return n... | @Test
public void getNullLastModifiedTime() throws IOException {
Mockito.when(
mClient.getObjectMetadata(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenReturn(new ObjectMetadata());
// throw NPE before https://github.com/Alluxio/alluxio/pull/14641
mS3UnderFileSystem.getO... |
public String migrate(String oldJSON, int targetVersion) {
LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON);
Chainr transform = getTransformerFor(targetVersion);
Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion));
... | @Test
void shouldMigrateV1ToV2_ByChangingEnablePipelineLockingFalse_To_LockBehaviorNone() {
ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother();
String oldJSON = documentMother.versionOneWithLockingSetTo(false);
String transformedJSON = migrator.migrate(oldJSON, 2);
... |
public static Schema schemaFromPojoClass(
TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) {
return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier);
} | @Test
public void testNestedArray() {
Schema schema =
POJOUtils.schemaFromPojoClass(
new TypeDescriptor<NestedArrayPOJO>() {}, JavaFieldTypeSupplier.INSTANCE);
SchemaTestUtils.assertSchemaEquivalent(NESTED_ARRAY_POJO_SCHEMA, schema);
} |
@Bean
public SonarUserHome provide(ScannerProperties scannerProps) {
Path home = findSonarHome(scannerProps);
LOG.debug("Sonar User Home: {}", home);
return new SonarUserHome(home);
} | @Test
void should_consider_scanner_property_over_env_and_user_home(@TempDir Path userHome, @TempDir Path sonarUserHomeFromEnv, @TempDir Path sonarUserHomeFromProps) {
when(system.envVariable("SONAR_USER_HOME")).thenReturn(sonarUserHomeFromEnv.toString());
when(system.property("user.home")).thenReturn(userHome... |
@POST
@ZeppelinApi
public Response createNote(String message) throws IOException {
String user = authenticationService.getPrincipal();
LOGGER.info("Creating new note by JSON {}", message);
NewNoteRequest request = GSON.fromJson(message, NewNoteRequest.class);
String defaultInterpreterGroup = request... | @Test
void testCreateNote() throws Exception {
LOG.info("Running testCreateNote");
String message1 = "{\n\t\"name\" : \"test1\",\n\t\"addingEmptyParagraph\" : true\n}";
CloseableHttpResponse post1 = httpPost("/notebook/", message1);
assertThat(post1, isAllowed());
Map<String, Object> resp1 = gson... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void conditionalAnd() {
assertUnifiesAndInlines(
"true && false",
UBinary.create(
Kind.CONDITIONAL_AND, ULiteral.booleanLit(true), ULiteral.booleanLit(false)));
} |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_dry_run() {
properties.put(Constants.EXECUTION_DRY_RUN_PROPERTY_NAME, "true");
RuntimeOptions options = cucumberPropertiesParser.parse(properties).build();
assertThat(options.isDryRun(), equalTo(true));
} |
@Override
protected void customAnalyze( GetXMLDataMeta meta, IMetaverseNode node ) throws MetaverseAnalyzerException {
super.customAnalyze( meta, node );
// Add the XPath Loop to the step node
node.setProperty( "loopXPath", meta.getLoopXPath() );
} | @Test
public void testCustomAnalyze() throws Exception {
when( meta.getLoopXPath() ).thenReturn( "file/xpath/name" );
analyzer.customAnalyze( meta, node );
verify( node ).setProperty( "loopXPath", "file/xpath/name" );
} |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.2");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportClients() throws IOException {
ClientDetailsEntity client1 = new ClientDetailsEntity();
client1.setId(1L);
client1.setAccessTokenValiditySeconds(3600);
client1.setClientId("client1");
client1.setClientSecret("clientsecret1");
client1.setRedirectUris(ImmutableSet.of("http://foo.c... |
public String getConfigClass(String className) {
return getHeader() + "\n\n" + //
getRootClassDeclaration(root, className) + "\n\n" + //
indentCode(INDENTATION, getFrameworkCode()) + "\n\n" + //
ConfigGenerator.generateContent(INDENTATION, root, true) + "\n" + //
... | @Disabled
@Test
void visual_inspection_of_generated_class() {
final String testDefinition =
"namespace=test\n" + //
"p path\n" + //
"pathArr[] path\n" + //
"u url\n" + //
"urlArr[] url\n" + //... |
public void updatePet(Pet body) throws RestClientException {
updatePetWithHttpInfo(body);
} | @Test
public void updatePetTest() {
Pet body = null;
api.updatePet(body);
// TODO: test validations
} |
static String createUniqueSymbol(CNode node, String basis) {
Set<String> usedSymbols = Arrays.stream(node.getChildren()).map(CNode::getName).collect(Collectors.toSet());
Random rng = new Random();
for (int i = 1;; i++) {
String candidate = (i < basis.length()) ? basis.substring(0, i... | @Test
void testCreateUniqueSymbol() {
final String testDefinition =
"namespace=test\n" + //
"m int\n" + //
"n int\n";
InnerCNode root = new DefParser("test", new StringReader(testDefinition)).getTree();
assertEquals("f", create... |
public static OpenOptions defaults() {
return new OpenOptions();
} | @Test
public void defaults() throws IOException {
OpenOptions options = OpenOptions.defaults();
assertEquals(0, options.getOffset());
} |
private <T> T newPlugin(Class<T> klass) {
// KAFKA-8340: The thread classloader is used during static initialization and must be
// set to the plugin's classloader during instantiation
try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) {
return Utils.newInstance(kl... | @Test
public void shouldThrowIfStaticInitializerThrowsServiceLoader() {
assertThrows(ConnectException.class, () -> plugins.newPlugin(
TestPlugin.BAD_PACKAGING_STATIC_INITIALIZER_THROWS_REST_EXTENSION.className(),
new AbstractConfig(new ConfigDef(), Collections.emptyMap()),
... |
public String getScope() {
return (String) context.getRequestAttribute(OidcConfiguration.SCOPE)
.or(() -> Optional.ofNullable(configuration.getScope()))
.orElse("openid profile email");
} | @Test
public void shouldResolveScopeWhenOverriddenFromRequest() {
var webContext = MockWebContext.create();
webContext.setRequestAttribute(OidcConfiguration.SCOPE, "openid profile email phone");
var oidcConfiguration = new OidcConfiguration();
var oidcConfigurationContext = new Oid... |
@Description("value raised to the power of exponent")
@ScalarFunction(alias = "pow")
@SqlType(StandardTypes.DOUBLE)
public static double power(@SqlType(StandardTypes.DOUBLE) double num, @SqlType(StandardTypes.DOUBLE) double exponent)
{
return Math.pow(num, exponent);
} | @Test
public void testPower()
{
for (long left : intLefts) {
for (long right : intRights) {
assertFunction("power(" + left + ", " + right + ")", DOUBLE, Math.pow(left, right));
}
}
for (int left : intLefts) {
for (int right : intRights... |
public OkHttpClient get(boolean keepAlive, boolean skipTLSVerify) {
try {
return cache.get(Parameters.fromBoolean(keepAlive, skipTLSVerify));
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | @Test
@Disabled("Not enabled by default")
public void testWithSystemDefaultTruststore() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
final ParameterizedHttpClientProvider provider = new ParameterizedHttpClientProvider(client(null));
final OkHttpClient... |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertParallelDecodeWithTx() {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("INSERT");
tableData.setColumnsName(new String[]{"data"});
tableData.setColumnsType(new String[]{"raw"});
tableData.setCol... |
@Override
public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) {
traceIfNecessary(grpcRequest, true);
String type = grpcRequest.getMetadata().getType();
long startTime = System.nanoTime();
//server is on starting.
if (!Applicati... | @Test
void testNoRequestHandler() {
ApplicationUtils.setStarted(true);
RequestMeta metadata = new RequestMeta();
metadata.setClientIp("127.0.0.1");
metadata.setConnectionId(connectId);
InstanceRequest instanceRequest = new InstanceRequest();
instanceRequest.setRequest... |
@Override
public Optional<JavaClass> tryResolve(String typeName) {
String typeFile = typeName.replace(".", "/") + ".class";
Optional<URI> uri = tryGetUriOf(typeFile);
return uri.isPresent() ? classUriImporter.tryImport(uri.get()) : Optional.empty();
} | @Test
@UseDataProvider("urls_with_spaces")
public void is_resilient_against_wrongly_encoded_ClassLoader_resource_URLs(URL urlReturnedByClassLoader, URI expectedUriDerivedFromUrl) {
// it seems like some OSGI ClassLoaders incorrectly return URLs with unencoded spaces.
// This lead to `url.toURI()... |
public void setAuthResult(Object authResult) {
this.authResult = authResult;
} | @Test
void testSetAuthResult() {
assertNull(authContext.getAuthResult());
authContext.setAuthResult(true);
assertTrue((boolean) authContext.getAuthResult());
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<ch.cyberduck.core.Path> paths = new AttributedList<>();
final java.nio.file.Path p = session.toPath(directory);
if(!Files.exists(p)) {
... | @Test(expected = NotfoundException.class)
public void testListFile() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCall... |
public static boolean isBeanPropertyWriteMethod(Method method) {
return method != null
&& Modifier.isPublic(method.getModifiers())
&& !Modifier.isStatic(method.getModifiers())
&& method.getDeclaringClass() != Object.class
&& method.getParameterType... | @Test
void testIsBeanPropertyWriteMethod() throws Exception {
Method method = EmptyClass.class.getMethod("setProperty", EmptyProperty.class);
assertTrue(ReflectUtils.isBeanPropertyWriteMethod(method));
method = EmptyClass.class.getMethod("setSet", boolean.class);
assertTrue(ReflectUt... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
return FEELFnResult.ofResult( BigDecimal.valueOf( list.size() ) );
} | @Test
void invokeParamArrayEmpty() {
FunctionTestUtil.assertResult(countFunction.invoke(new Object[]{}), BigDecimal.ZERO);
} |
public void xor(Bitmap other)
{
requireNonNull(other, "cannot combine with null Bitmap");
checkArgument(length() == other.length(), "cannot XOR two bitmaps of different size");
bitSet.xor(other.bitSet);
} | @Test
public static void testXor()
{
Bitmap bitmapA = Bitmap.fromBytes(100 * 8, BYTE_STRING_A);
Bitmap bitmapB = Bitmap.fromBytes(100 * 8, BYTE_STRING_B);
Bitmap bitmapC = bitmapA.clone();
bitmapC.xor(bitmapB);
for (int i = 0; i < 100 * 8; i++) {
assertEquals... |
@Bean
@ConditionalOnMissingBean(ServerEndpointExporter.class)
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} | @Test
public void testServerEndpointExporter() {
WebSocketSyncConfiguration websocketListener = new WebSocketSyncConfiguration();
assertNotNull(websocketListener.serverEndpointExporter());
} |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testOneMoreThanFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
history.add(3);
history.add(4);
int[] expectedHistorySnapshot = {2, 3, 4};
testHistory(history, expectedHistorySnapshot);
} |
@VisibleForTesting
int getReturnCode() {
int successCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode();
if ( getResult().getNrErrors() != 0 ) {
getLog().logError( BaseMessages.getString( getPkgClazz(), "Kitchen.Error.FinishedWithErrors" ) );
return CommandExecutorCodes.Kitchen.ERRORS_DURING_P... | @Test
public void testReturnCodeSuccess() {
when( mockedKitchenCommandExecutor.getResult() ).thenReturn( result );
when( result.getResult() ).thenReturn( true );
assertEquals( mockedKitchenCommandExecutor.getReturnCode(), CommandExecutorCodes.Kitchen.SUCCESS.getCode() );
} |
@Override
public long getPreferredBlockSize() {
return HeaderFormat.getPreferredBlockSize(header);
} | @Test
public void testInodeIdBasedPaths() throws Exception {
Configuration conf = new Configuration();
conf.setInt(DFSConfigKeys.DFS_BLOCK_SIZE_KEY,
DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT);
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true);
MiniDFSCluster cluster = null;... |
public void setExpectedValue(String expectedValue) {
setProperty(EXPECTEDVALUE, expectedValue);
} | @Test
void testSetExpectedValue() {
String expectedValue = "some value";
JSONPathAssertion instance = new JSONPathAssertion();
instance.setExpectedValue(expectedValue);
assertEquals(expectedValue, instance.getExpectedValue());
} |
public boolean fileExists(String path) throws IOException, InvalidTokenException {
String url;
try {
url =
getUriBuilder()
.setPath(API_PATH_PREFIX + "/mounts/primary/files/info")
.setParameter("path", path)
.build()
.toString();
} catc... | @Test
public void testFileExistsTokenExpired() throws Exception {
when(credentialFactory.refreshCredential(credential))
.then(
(InvocationOnMock invocation) -> {
final Credential cred = invocation.getArgument(0);
cred.setAccessToken("acc1");
return cre... |
@Override
public Health checkNode() {
return nodeHealthChecks.stream()
.map(NodeHealthCheck::check)
.reduce(Health.GREEN, HealthReducer::merge);
} | @Test
public void check_returns_green_status_without_any_cause_when_there_is_no_NodeHealthCheck() {
HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0]);
assertThat(underTest.checkNode()).isEqualTo(Health.GREEN);
} |
public static String format( String xml ) {
XMLStreamReader rd = null;
XMLStreamWriter wr = null;
StringWriter result = new StringWriter();
try {
rd = INPUT_FACTORY.createXMLStreamReader( new StringReader( xml ) );
synchronized ( OUTPUT_FACTORY ) {
// BACKLOG-18743: This object was... | @Test
public void test1() throws Exception {
String inXml, expectedXml;
try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterIn1.xml" ) ) {
inXml = IOUtils.toString( in );
}
try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterExpected1.xml" ... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
String methodName) throws Throwable {
RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter);
Object returnValue = proceedingJoinPoint.proceed();
return executeR... | @Test
public void testRxTypes() throws Throwable {
RateLimiter rateLimiter = RateLimiter.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(
rxJava3RateLimiterAspectExt.handle(proceedingJoinPoint, rateLimiter, "testMethod"))
... |
@Override
public void run() {
doHealthCheck();
} | @Test
void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException {
injectInstance(true, System.currentTimeMillis());
Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME);
InstanceMetadata metadata = new InstanceMetadata();
metadata.getExtend... |
@Override
public <T> void storeObject(
String accountName,
ObjectType objectType,
String objectKey,
T obj,
String filename,
boolean isAnUpdate) {
if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) {
var draftRecord = new SqlCanaryArchive();
draftRecord.setId(o... | @Test
public void testStoreObjectWhenMetricSetPairs() {
var testAccountName = UUID.randomUUID().toString();
var testObjectType = ObjectType.METRIC_SET_PAIR_LIST;
var testObjectKey = UUID.randomUUID().toString();
var testMetricSetPair = createTestMetricSetPair();
sqlStorageService.storeObject(
... |
protected List<ProviderInfo> directUrl2IpUrl(ProviderInfo providerInfo, List<ProviderInfo> originList) {
List<ProviderInfo> result = new ArrayList<>();
try {
String originHost = providerInfo.getHost();
String originUrl = providerInfo.getOriginUrl();
InetAddress[] addr... | @Test
public void testDirectUrl2IpUrl() {
ProviderInfo providerInfo = ProviderHelper.toProviderInfo("bolt://alipay.com:12200");
List<ProviderInfo> providerInfos = domainRegistry.directUrl2IpUrl(providerInfo, null);
assertTrue(providerInfos.size() > 0);
String host = providerInfos.get... |
@VisibleForTesting
StreamConfig getConfig(
OperatorID operatorID,
StateBackend stateBackend,
Configuration additionalConfig,
StreamOperator<TaggedOperatorSubtaskState> operator) {
// Eagerly perform a deep copy of the configuration, otherwise it will result in... | @Test
public void testStreamConfig() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> input = env.fromData("");
StateBootstrapTransformation<String> transformation =
OperatorTransformation.bootstrapWith(input)
... |
@Converter(fallback = true)
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
if (NodeInfo.class.isAssignableFrom(value.getClass())) {
// use a fallback type converter so we can convert the embedded body if the value is NodeInfo
... | @Test
public void convertToByteArray() {
byte[] ba = context.getTypeConverter().convertTo(byte[].class, exchange, doc);
assertNotNull(ba);
String string = context.getTypeConverter().convertTo(String.class, exchange, ba);
assertEquals(CONTENT, string);
} |
public boolean acquire(final Object o) {
if (Objects.isNull(o)) {
throw new NullPointerException();
}
if (memory.sum() >= memoryLimit) {
return false;
}
acquireLock.lock();
try {
final long sum = memory.sum();
final long obj... | @Test
public void testAcquireWhenEqualToLimit() {
MemoryLimiter memoryLimiter = new MemoryLimiter(testObjectSize, instrumentation);
assertFalse(memoryLimiter.acquire(testObject));
} |
@Override
public RemoveMembersFromConsumerGroupResult removeMembersFromConsumerGroup(String groupId,
RemoveMembersFromConsumerGroupOptions options) {
String reason = options.reason() == null || options.reason().isEmpty() ?
... | @Test
public void testRemoveMembersFromGroupNumRetries() throws Exception {
final Cluster cluster = mockCluster(3, 0);
final Time time = new MockTime();
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster,
AdminClientConfig.RETRIES_CONFIG, "0")) {
... |
@Deprecated
public static Method findMethodByMethodName(Class<?> clazz, String methodName)
throws NoSuchMethodException, ClassNotFoundException {
return findMethodByMethodSignature(clazz, methodName, null);
} | @Test
void testFindMethodByMethodName2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ReflectUtils.findMethodByMethodName(Foo2.class, "hello");
});
} |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final Stacker contextStacker = buildContext.buildNodeContext(getId().toString());
return schemaKStreamFactory.create(
buildContext,
dataSource,
contextStacker.push(SOURCE_OP_NAME)
);
} | @Test
public void shouldBuildSourceStreamWithCorrectTimestampIndex() {
// Given:
givenNodeWithMockSource();
// When:
node.buildStream(buildContext);
// Then:
verify(schemaKStreamFactory).create(any(), any(), any());
} |
@Override
public RedisClusterNode clusterGetNodeForSlot(int slot) {
Iterable<RedisClusterNode> res = clusterGetNodes();
for (RedisClusterNode redisClusterNode : res) {
if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) {
return redisCluster... | @Test
public void testClusterGetNodeForSlot() {
RedisClusterNode node1 = connection.clusterGetNodeForSlot(1);
RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000);
assertThat(node1.getId()).isNotEqualTo(node2.getId());
} |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds);
intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub);
for (String feature : FEATURES_IN_ORDER)
{
... | @Test
void testApplyTransforms_pres()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(284,294,314,315);
// when
List<Integer> result = gsubWorkerForGujarati.applyTransforms(getGlyphIds("ગ્નટ્ટપ્તલ્લ"));
// then
assertEquals(glyphsAfterGsub, result);
... |
@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 testNonTrivialSelectorsIntent() {
Set<FilteredConnectPoint> ingress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1),
DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("100")).build()),
... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterminismList() {
assertDeterministic(AvroCoder.of(StringList.class));
assertDeterministic(AvroCoder.of(StringArrayList.class));
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void fail_when_not_double() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("ten").build()),
emptySet());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value 'ten' is not a nu... |
public static byte buildHigh2Low6Bytes(byte high2, byte low6) {
return (byte) ((high2 << 6) + low6);
} | @Test
public void buildHigh2Low6Bytes() {
byte bs = CodecUtils.buildHigh2Low6Bytes((byte) 1, (byte) 53);
Assert.assertEquals(bs, (byte) 117);
} |
@Nonnull
public List<String> value() {
return parsedValue;
} | @Test
void valueWithoutProtocol() {
final RemoteReindexAllowlist allowlist = new RemoteReindexAllowlist(URI.create("http://example.com:9200"), "example.com:9200");
Assertions.assertThat(allowlist.value())
.containsExactly("example.com:9200");
} |
@Override public boolean parseClientIpAndPort(Span span) {
if (parseClientIpFromXForwardedFor(span)) return true;
return span.remoteIpAndPort(delegate.getRemoteAddr(), delegate.getRemotePort());
} | @Test void parseClientIpAndPort_prefersXForwardedFor() {
when(span.remoteIpAndPort("1.2.3.4", 0)).thenReturn(true);
when(request.getHeader("X-Forwarded-For")).thenReturn("1.2.3.4");
wrapper.parseClientIpAndPort(span);
verify(span).remoteIpAndPort("1.2.3.4", 0);
verifyNoMoreInteractions(span);
} |
public int allocate(final String label)
{
return allocate(label, DEFAULT_TYPE_ID);
} | @Test
void shouldStoreLabels()
{
final int counterId = manager.allocate("abc");
reader.forEach(consumer);
verify(consumer).accept(counterId, "abc");
} |
@Override
@Private
public boolean isApplicationActive(ApplicationId id) throws YarnException {
ApplicationReport report = null;
try {
report = client.getApplicationReport(id);
} catch (ApplicationNotFoundException e) {
// the app does not exist
return false;
} catch (IOException e)... | @Test
void testRunningApp() throws Exception {
YarnClient client = createCheckerWithMockedClient();
ApplicationId id = ApplicationId.newInstance(1, 1);
// create a report and set the state to an active one
ApplicationReport report = new ApplicationReportPBImpl();
report.setYarnApplicationState(Ya... |
public synchronized boolean isServing() {
return mWebServer != null && mWebServer.getServer().isRunning();
} | @Test
public void primaryOnlyTest() {
Configuration.set(PropertyKey.STANDBY_MASTER_WEB_ENABLED, false);
WebServerService webService =
WebServerService.Factory.create(mWebAddress, mMasterProcess);
Assert.assertTrue(webService instanceof PrimaryOnlyWebServerService);
Assert.assertTrue(waitForFre... |
static ConfusionMatrixTuple tabulate(ImmutableOutputInfo<MultiLabel> domain, List<Prediction<MultiLabel>> predictions) {
// this just keeps track of how many times [class x] was predicted to be [class y]
DenseMatrix confusion = new DenseMatrix(domain.size(), domain.size());
Set<MultiLabel> obse... | @Test
public void testTabulateUnexpectedMultiLabel() {
MultiLabel a = label("a");
MultiLabel bc = label("b","c");
MultiLabel abd = label("a","b","d");
ImmutableOutputInfo<MultiLabel> domain = mkDomain(a,bc,abd);
List<Prediction<MultiLabel>> predictions = Arrays.asList(
... |
public static <T> T loginWithKerberos(
Configuration configuration,
String krb5FilePath,
String kerberosPrincipal,
String kerberosKeytabPath,
LoginFunction<T> action)
throws IOException, InterruptedException {
if (!configuration.get("hadoop... | @Test
void loginWithKerberos_success() throws Exception {
miniKdc.createPrincipal(new File(workDir, "tom.keytab"), "tom");
UserGroupInformation userGroupInformation =
HadoopLoginFactory.loginWithKerberos(
createConfiguration(),
null,
... |
@Override
public void await() throws InterruptedException {
_delegate.await();
} | @Test
public void testAwait() throws InterruptedException {
final SettablePromise<String> delegate = Promises.settable();
final Promise<String> promise = new DelegatingPromise<String>(delegate);
final String value = "value";
delegate.done(value);
assertTrue(promise.await(20, TimeUnit.MILLISECOND... |
@Override
public Object read(final MySQLPacketPayload payload, final boolean unsigned) {
if (unsigned) {
return payload.getByteBuf().readUnsignedByte();
}
return payload.getByteBuf().readByte();
} | @Test
void assertRead() {
when(payload.getByteBuf()).thenReturn(Unpooled.wrappedBuffer(new byte[]{1, 1}));
assertThat(new MySQLInt1BinaryProtocolValue().read(payload, false), is((byte) 1));
assertThat(new MySQLInt1BinaryProtocolValue().read(payload, true), is((short) 1));
} |
public String getStartTimeStr() {
String str = NA;
if (startTime >= 0) {
str = new Date(startTime).toString();
}
return str;
} | @Test
public void testGetStartTimeStr() {
JobReport jobReport = mock(JobReport.class);
when(jobReport.getStartTime()).thenReturn(-1L);
Job job = mock(Job.class);
when(job.getReport()).thenReturn(jobReport);
when(job.getName()).thenReturn("TestJobInfo");
when(job.getState()).thenReturn(JobStat... |
@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 testEvalAndSet() {
run("eval-and-set.feature");
} |
public static String createJobName(String prefix) {
return createJobName(prefix, 0);
} | @Test
public void testCreateJobNameWithUppercaseSuffix() {
assertThat(createJobName("testWithUpperCase", 8))
.matches("test-with-upper-case-\\d{17}-[a-z0-9]{8}");
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullsFirst() {
assertThat(CompareUtils.compareTo(1, null, OrderDirection.ASC, NullsOrderType.FIRST, caseSensitive), is(1));
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefin... | @Test
public void testConvertTimestamp() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("timestamp")
.dataType("timestamp")
.build();
Column col... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testJsonConversionForComplexType() throws Exception {
ComplexType complexType = new ComplexType();
complexType.stringField = "stringField";
complexType.intField = 12;
complexType.innerType = InnerType.of(12);
complexType.genericType = ImmutableList.of(InnerType.of(16234), InnerTy... |
private void updateControllerAddr() {
if (brokerConfig.isFetchControllerAddrByDnsLookup()) {
List<String> adders = brokerOuterAPI.dnsLookupAddressByDomain(this.brokerConfig.getControllerAddr());
if (CollectionUtils.isNotEmpty(adders)) {
this.controllerAddresses = adders;
... | @Test
public void testUpdateControllerAddr() throws Exception {
final String controllerAddr = "192.168.1.1";
brokerConfig.setFetchControllerAddrByDnsLookup(true);
when(brokerOuterAPI.dnsLookupAddressByDomain(anyString())).thenReturn(Lists.newArrayList(controllerAddr));
Method method ... |
static JavaInput reorderModifiers(String text) throws FormatterException {
return reorderModifiers(
new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length())));
} | @Test
public void simple() throws FormatterException {
assertThat(ModifierOrderer.reorderModifiers("static abstract class InnerClass {}").getText())
.isEqualTo("abstract static class InnerClass {}");
} |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionMap)
throws InterruptedException {
return accessNativeLib();
} | @Test
public void nativeLibPresent() throws Exception {
File testLibDir = ValidationTestUtils.createTemporaryDirectory();
String testLibPath = testLibDir.getPath();
String libPath = testLibPath;
System.setProperty(NativeLibValidationTask.NATIVE_LIB_PATH, libPath);
NativeLibValidationTask task = ... |
public static String parsePath(String uri, Map<String, String> patterns) {
if (uri == null) {
return null;
} else if (StringUtils.isBlank(uri)) {
return String.valueOf(SLASH);
}
CharacterIterator ci = new StringCharacterIterator(uri);
StringBuilder pathBuf... | @Test(description = "parse two part path with one param")
public void parseTwoPartPathWithOneParam() {
final Map<String, String> regexMap = new HashMap<String, String>();
final String path = PathUtils.parsePath("/api/{itemId: [0-9]{4}/[0-9]{2,4}/[A-Za-z0-9]+}", regexMap);
assertEquals(path, ... |
@Override
public void createService(Service service) {
checkNotNull(service, ERR_NULL_SERVICE);
checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()),
ERR_NULL_SERVICE_UID);
k8sServiceStore.createService(service);
log.info(String.format(MSG_SERVICE, s... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateService() {
target.createService(SERVICE);
target.createService(SERVICE);
} |
public String failureMessage(
int epoch,
OptionalLong deltaUs,
boolean isActiveController,
long lastCommittedOffset
) {
StringBuilder bld = new StringBuilder();
if (deltaUs.isPresent()) {
bld.append("event failed with ");
} else {
bld.a... | @Test
public void testNotLeaderExceptionFailureMessage() {
assertEquals("event unable to start processing because of NotLeaderException (treated as " +
"NotControllerException) at epoch 123. Renouncing leadership and reverting to the " +
"last committed offset 456. Exception message:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.