focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public List<String> build() {
return switch (dialect.getId()) {
case Oracle.ID -> forOracle(tableName);
case H2.ID, PostgreSql.ID -> singletonList("drop table if exists " + tableName);
case MsSql.ID ->
// "if exists" is supported only since MSSQL 2016.
singletonList("drop table " +... | @Test
public void drop_tables_on_mssql() {
assertThat(new DropTableBuilder(new MsSql(), "issues")
.build()).containsOnly("drop table issues");
} |
Mono<ResponseEntity<Void>> save(Post post) {
return client.post()
.uri("/posts")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(post)
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.CREATED)) {
... | @SneakyThrows
@Test
public void testCreatePost() {
var id = UUID.randomUUID();
var data = new Post(null, "title1", "content1", Status.DRAFT, null);
stubFor(post("/posts")
.willReturn(
aResponse()
.withHeader("Locati... |
static void populateOutputFields(final PMML4Result toUpdate,
final ProcessingDTO processingDTO) {
logger.debug("populateOutputFields {} {}", toUpdate, processingDTO);
for (KiePMMLOutputField outputField : processingDTO.getOutputFields()) {
Object variable... | @Test
void populateTransformedOutputFieldWithApplyWithConstants() {
// <Apply function="/">
// <Constant>100.0</Constant>
// <Constant>5.0</Constant>
// </Apply>
KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant(PARAM_1, Collections.emptyList(), va... |
public static String storeChangelogTopic(final String prefix, final String storeName, final String namedTopology) {
if (namedTopology == null) {
return prefix + "-" + storeName + STATE_CHANGELOG_TOPIC_SUFFIX;
} else {
return prefix + "-" + namedTopology + "-" + storeName + STATE_... | @Test
public void shouldReturnDefaultChangelogTopicName() {
final String applicationId = "appId";
final String storeName = "store";
assertThat(
ProcessorStateManager.storeChangelogTopic(applicationId, storeName, null),
is(applicationId + "-" + storeName + "-changelog... |
@Override
protected void route(List<SendingMailbox> sendingMailboxes, TransferableBlock block)
throws Exception {
sendBlock(sendingMailboxes.get(0), block);
} | @Test
public void shouldRouteSingleton()
throws Exception {
// Given:
ImmutableList<SendingMailbox> destinations = ImmutableList.of(_mailbox1);
// When:
new SingletonExchange(destinations, TransferableBlockUtils::splitBlock).route(destinations, _block);
// Then:
ArgumentCaptor<Transfer... |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldParseFullLocalDateWithPartialSeconds() {
// Given
final String format = "yyyy-MM-dd HH:mm:ss:SSS";
final String timestamp = "1605-11-05 10:10:10:010";
// When
final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID);
// Then
assertTh... |
@Override
public Timer timer(String name) {
return NoopTimer.INSTANCE;
} | @Test
public void accessingACustomTimerRegistersAndReusesIt() {
final MetricRegistry.MetricSupplier<Timer> supplier = () -> timer;
final Timer timer1 = registry.timer("thing", supplier);
final Timer timer2 = registry.timer("thing", supplier);
assertThat(timer1).isExactlyInstanceOf(N... |
public static String escapeString(String str) {
return escapeString(str, ESCAPE_CHAR, COMMA);
} | @Test (timeout = 30000)
public void testEscapeString() throws Exception {
assertEquals(NULL_STR, StringUtils.escapeString(NULL_STR));
assertEquals(EMPTY_STR, StringUtils.escapeString(EMPTY_STR));
assertEquals(STR_WO_SPECIAL_CHARS,
StringUtils.escapeString(STR_WO_SPECIAL_CHARS));
assertEquals(E... |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null;
taskId = context.taskId();
initStoreSerde(context);
s... | @Test
public void testMetrics() {
store.init((StateStoreContext) context, store);
final JmxReporter reporter = new JmxReporter();
final MetricsContext metricsContext = new KafkaMetricsContext("kafka.streams");
reporter.contextChange(metricsContext);
metrics.addReporter(repor... |
public static String getPartitionPath(TieredStoragePartitionId partitionId, String basePath) {
if (basePath == null) {
return null;
}
while (basePath.endsWith("/") && basePath.length() > 1) {
basePath = basePath.substring(0, basePath.length() - 1);
}
retu... | @Test
void testGetPartitionPath() {
TieredStoragePartitionId partitionId =
TieredStorageIdMappingUtils.convertId(new ResultPartitionID());
String partitionPath =
SegmentPartitionFile.getPartitionPath(partitionId, tempFolder.getPath());
File partitionFile =
... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_PlusMinusZero() {
expectFailureWhenTestingThat(array(0.0d)).isEqualTo(array(-0.0d));
assertFailureValue("expected", "[-0.0]");
assertFailureValue("but was", "[0.0]");
} |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldLoadInvertFilterForScmMaterial() throws Exception {
String content = config(
"""
<scms>
<scm id="abcd" name="scm_name">
<pluginConfiguration id="GitPathMaterial" version="1" />
... |
public static boolean isBlankChar(char c) {
return isBlankChar((int) c);
} | @Test
public void trimTest() {
//此字符串中的第一个字符为不可见字符: '\u202a'
final String str = "C:/Users/maple/Desktop/tone.txt";
assertEquals('\u202a', str.charAt(0));
assertTrue(CharUtil.isBlankChar(str.charAt(0)));
} |
public static StrimziPodSet createPodSet(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
ResourceTemplate template,
int replicas,
Map<String, String> annotations,
Labels selectorLabels,
... | @Test
public void testCreateStrimziPodSetWithNullTemplate() {
List<Integer> podIds = new ArrayList<>();
StrimziPodSet sps = WorkloadUtils.createPodSet(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
null,
RE... |
public static PTransformMatcher createViewWithViewFn(final Class<? extends ViewFn> viewFnType) {
return application -> {
if (!(application.getTransform() instanceof CreatePCollectionView)) {
return false;
}
CreatePCollectionView<?, ?> createView =
(CreatePCollectionView<?, ?>) ap... | @Test
public void createViewWithViewFnNotCreatePCollectionView() {
PCollection<Integer> input = p.apply(Create.of(1));
PCollectionView<Iterable<Integer>> view = input.apply(View.asIterable());
PTransformMatcher matcher =
PTransformMatchers.createViewWithViewFn(view.getViewFn().getClass());
ass... |
@Override
public DeviceCredentials findByDeviceId(TenantId tenantId, UUID deviceId) {
return DaoUtil.getData(deviceCredentialsRepository.findByDeviceId(deviceId));
} | @Test
public void testFindByDeviceId() {
DeviceCredentials foundedDeviceCredentials = deviceCredentialsDao.findByDeviceId(SYSTEM_TENANT_ID, neededDeviceCredentials.getDeviceId().getId());
assertNotNull(foundedDeviceCredentials);
assertEquals(neededDeviceCredentials.getId(), foundedDeviceCred... |
@Override
public JooqEndpoint getEndpoint() {
return (JooqEndpoint) super.getEndpoint();
} | @Test
public void testConsumerDelete() throws InterruptedException {
MockEndpoint mockResult = getMockEndpoint("mock:resultAuthorRecord");
MockEndpoint mockInserted = getMockEndpoint("mock:insertedAuthorRecord");
mockResult.expectedMessageCount(1);
mockInserted.expectedMessageCount(1... |
public static String showControlCharacters(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) {
char c = str.charAt(i);
switch (c) {
case '\b':
sb.append("\\b");
... | @Test
void testControlCharacters() {
String testString = "\b \t \n \f \r default";
String controlString = StringUtils.showControlCharacters(testString);
assertThat(controlString).isEqualTo("\\b \\t \\n \\f \\r default");
} |
public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position) {
if (position >= collection.size() || position < 0) {
return null;
}
if (collection instanceof List) {
return ((List<T>) collection).get(position);
}
Iterator<T> iterator ... | @Test
public void testGetItemAtPositionOrNull_whenNegativePosition_thenReturnNull() {
Object obj = new Object();
Collection<Object> src = new ArrayList<>();
src.add(obj);
Object result = getItemAtPositionOrNull(src, -1);
assertNull(result);
} |
@Override
public String buildContext() {
final SelectorDO after = (SelectorDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the namespace [%s] selector [%s] is %s", after.getNamespaceId(), after.getName(), StringUtils.lowerCase(getType().getType().toString()));
... | @Test
void buildContextAndBeforeNotNullAndAllChange() {
SelectorChangedEvent selectorChangedEvent
= new SelectorChangedEvent(before, after, EventTypeEnum.SELECTOR_CREATE, "test-operator");
SelectorDO before = (SelectorDO) selectorChangedEvent.getBefore();
SelectorDO after = ... |
public static String sanitizeDescription(String javadoc, boolean summary) {
if (isNullOrEmpty(javadoc)) {
return null;
}
// lets just use what java accepts as identifiers
StringBuilder sb = new StringBuilder();
// split into lines
String[] lines = javadoc.sp... | @Test
public void testSanitizeJavaDocLink() throws Exception {
String s = " * Provides methods to create, delete, find, and update {@link Customer}\n"
+ " * objects. This class does not need to be instantiated directly. Instead, use";
String s2 = JavadocHelper.sanitizeDescription(... |
@Override
protected int rsv(WebSocketFrame msg) {
return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame?
msg.rsv() | WebSocketExtension.RSV1 : msg.rsv();
} | @Test
public void testSelectivityCompressionSkip() {
WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() {
@Override
public boolean mustSkip(WebSocketFrame frame) {
return (frame instanceof TextWebSocketFrame || frame instanceof Bin... |
public static <K, V> StoreBuilder<KeyValueStore<K, V>> keyValueStoreBuilder(final KeyValueBytesStoreSupplier supplier,
final Serde<K> keySerde,
final Serde<V> v... | @Test
public void shouldThrowIfSupplierIsNullForKeyValueStoreBuilder() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.keyValueStoreBuilder(null, Serdes.ByteArray(), Serdes.ByteArray()));
assertEquals("supplier cannot be null", e.getMessage());
} |
@Override
public DenyUserStatement getSqlStatement() {
return (DenyUserStatement) super.getSqlStatement();
} | @Test
void assertNewInstance() {
SQLServerDenyUserStatement sqlStatement = new SQLServerDenyUserStatement();
SimpleTableSegment table = new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("tbl_1")));
sqlStatement.setTable(table);
DenyUserStatementContext actual = ne... |
@SuppressWarnings("unchecked")
@Udf
public <T> List<T> union(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> combined ... | @Test
public void shouldUnionArraysBothContainingNulls() {
final List<String> input1 = Arrays.asList(null, "foo", "bar");
final List<String> input2 = Arrays.asList("foo", null);
final List<String> result = udf.union(input1, input2);
assertThat(result, contains((String) null, "foo", "bar"));
} |
@SuppressWarnings("unchecked")
@Override
public boolean canHandleReturnType(Class returnType) {
return rxSupportedTypes.stream()
.anyMatch(classType -> classType.isAssignableFrom(returnType));
} | @Test
public void testCheckTypes() {
assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue();
assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Single.class)).isTrue();
} |
@Override
public boolean addIfExists(Duration ttl, V object) {
return get(addIfExistsAsync(ttl, object));
} | @Test
public void testAddIfExists() throws InterruptedException {
RSetCache<String> cache = redisson.getSetCache("list");
cache.add("a", 1, TimeUnit.SECONDS);
assertThat(cache.addIfExists(Duration.ofSeconds(2), "a")).isTrue();
Thread.sleep(1500);
assertThat(cache.contains("a... |
@Override
public void submit(ManagedQueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor)
{
checkState(configurationManager.get() != null, "configurationManager not set");
createGroupIfNecessary(selectionContext, executor);
groups.get(selectionContext.ge... | @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = ".*Presto server is still initializing.*")
public void testQueryFailsWithInitializingConfigurationManager()
{
InternalResourceGroupManager<ImmutableMap<Object, Object>> internalResourceGroupManager = new InternalResource... |
@Override
public TopicAssignment place(
PlacementSpec placement,
ClusterDescriber cluster
) throws InvalidReplicationFactorException {
RackList rackList = new RackList(random, cluster.usableBrokers());
throwInvalidReplicationFactorIfNonPositive(placement.numReplicas());
t... | @Test
public void testEvenDistribution() {
MockRandom random = new MockRandom();
StripedReplicaPlacer placer = new StripedReplicaPlacer(random);
TopicAssignment topicAssignment = place(placer, 0, 200, (short) 2, Arrays.asList(
new UsableBroker(0, Optional.empty(), false),
... |
public boolean isService(Object bean, String beanName) {
for (RemotingParser remotingParser : allRemotingParsers) {
if (remotingParser.isService(bean, beanName)) {
return true;
}
}
return false;
} | @Test
public void testIsServiceFromClass() {
assertTrue(remotingParser.isService(SimpleRemoteBean.class));
} |
@Override
public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
if (errorLog == null) {
throw exception(API_ERROR_LOG_NOT_FOUND);
}
if (!ApiErrorLogProcessStatusEnum.INIT.getSt... | @Test
public void testUpdateApiErrorLogProcess_notFound() {
// 准备参数
Long id = randomLongId();
Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus();
Long processUserId = randomLongId();
// 调用,并断言异常
assertServiceException(() ->
... |
public static GrpcUpstream buildAliveGrpcUpstream(final String upstreamUrl) {
return GrpcUpstream.builder().upstreamUrl(upstreamUrl).weight(50)
.timestamp(System.currentTimeMillis()).build();
} | @Test
public void buildAliveGrpcUpstream() {
GrpcUpstream grpcUpstream = CommonUpstreamUtils.buildAliveGrpcUpstream(HOST);
Assert.assertNotNull(grpcUpstream);
Assert.assertEquals(HOST, grpcUpstream.getUpstreamUrl());
Assert.assertNull(grpcUpstream.getProtocol());
} |
@Override
public void createPod(Pod pod) {
checkNotNull(pod, ERR_NULL_POD);
checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()),
ERR_NULL_POD_UID);
k8sPodStore.createPod(pod);
log.info(String.format(MSG_POD, pod.getMetadata().getName(), MSG_CREATED));
... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicatePod() {
target.createPod(POD);
target.createPod(POD);
} |
@Override
public AuthenticationDataSource getAuthDataSource() {
return authenticationDataSource;
} | @Test
void getAuthDataOnAuthStateShouldBeNullIfNotAuthenticated() {
AuthenticationStateOpenID state = new AuthenticationStateOpenID(null, null, null);
assertNull(state.getAuthDataSource());
} |
public static Expression substituteBoolExpression(ConfigVariableExpander cve, Expression expression) {
try {
if (expression instanceof BinaryBooleanExpression) {
BinaryBooleanExpression binaryBoolExp = (BinaryBooleanExpression) expression;
Expression substitutedLeftEx... | @Test
public void basicBinaryBooleanSubstitution() throws InvalidIRException {
SourceWithMetadata swm = new SourceWithMetadata("proto", "path", 1, 8, "if \"${SMALL}\" == 1 { add_tag => \"pass\" }");
ValueExpression left = new ValueExpression(swm, "${SMALL}");
ValueExpression right = new Valu... |
public <T> Flux<PushNotificationExperimentSample<T>> getSamples(final String experimentName, final Class<T> stateClass) {
return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#experiment = :experiment")
... | @Test
void getSamples() throws JsonProcessingException {
final String experimentName = "test-experiment";
final UUID initialSampleAccountIdentifier = UUID.randomUUID();
final byte initialSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID);
final boolean initialSampleI... |
@Override
public Map<String, String> getMetadata() {
return metadata;
} | @Test
public void testGetNacosMetadata() {
String clusterName = "cluster";
when(nacosContextProperties.getClusterName()).thenReturn(clusterName);
Map<String, String> metadata = polarisRegistration1.getMetadata();
assertThat(metadata).isNotNull();
assertThat(metadata).isNotEmpty();
assertThat(metadata.size(... |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final SoftwareVersionData version = this.softwareVersion();
final Matcher matcher = Pattern.compile(VERSION_REGEX).matcher(version.getRestApiVersion());
if(matcher.matches()) {
... | @Test(expected = LoginCanceledException.class)
public void testLoginOAuthExpiredRefreshToken() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SDSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
... |
public static boolean hasCauseOf(Throwable t, Class<? extends Throwable> causeType) {
return Throwables.getCausalChain(t)
.stream()
.anyMatch(c -> causeType.isAssignableFrom(c.getClass()));
} | @Test
public void hasCauseOf_returnsTrueIfTheCauseIsSubtypeOfTheProvidedType() {
assertThat(ExceptionUtils.hasCauseOf(
new RuntimeException("parent", new SocketTimeoutException("asdasd")), IOException.class)).isTrue();
assertThat(ExceptionUtils.hasCauseOf(
new Runtim... |
public Map<String, BulkOperationResponse> removeCustomMappingForFields(final List<String> fieldNames,
final Set<String> indexSetsIds,
final boolean rotateImmediately) {
... | @Test
void testMappingsRemoval() {
doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set");
final Map<String, BulkOperationResponse> response = toTest.removeCustomMappingForFields(
List.of("existing_field", "unexisting_field"),
Set.of("... |
public static InstanceAssignmentConfig getInstanceAssignmentConfig(TableConfig tableConfig,
InstancePartitionsType instancePartitionsType) {
Preconditions.checkState(allowInstanceAssignment(tableConfig, instancePartitionsType),
"Instance assignment is not allowed for the given table config");
// ... | @Test
public void testGetInstanceAssignmentConfigWhenInstanceAssignmentConfigIsNotPresentAndPartitionColumnPresent() {
TagOverrideConfig tagOverrideConfig = new TagOverrideConfig("broker", "Server");
Map<InstancePartitionsType, String> instancePartitionsTypeStringMap = new HashMap<>();
instancePartition... |
public EndpointConfig setSocketKeepCount(int socketKeepCount) {
Preconditions.checkPositive("socketKeepCount", socketKeepCount);
Preconditions.checkTrue(socketKeepCount < MAX_SOCKET_KEEP_COUNT,
"socketKeepCount value " + socketKeepCount + " is outside valid range 1 - 127");
this.... | @Test
public void testKeepCountValidation() {
EndpointConfig endpointConfig = new EndpointConfig();
Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepCount(0));
Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepCount(128... |
@Override
public boolean isAuthenticatedBrowserSession() {
return false;
} | @Test
public void isAuthenticatedGuiSession_isAlwaysFalse() {
assertThat(githubWebhookUserSession.isAuthenticatedBrowserSession()).isFalse();
} |
@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 testRequestWithoutAuthorization() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Assert.assertNull(handler.authenticate(request, response));
Mockito.verify(response).setH... |
public void register(GracefulShutdownHook shutdownHook) {
if (isShuttingDown.get()) {
// Avoid any changes to the shutdown hooks set when the shutdown is already in progress
throw new IllegalStateException("Couldn't register shutdown hook because shutdown is already in progress");
... | @Test
public void registerAndShutdown() throws Exception {
final AtomicBoolean hook1Called = new AtomicBoolean(false);
final AtomicBoolean hook2Called = new AtomicBoolean(false);
shutdownService.register(() -> hook1Called.set(true));
shutdownService.register(() -> hook2Called.set(tr... |
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto)
throws ProtoParsingException {
return Parsers.fromProto(proto);
} | @Test
public void legacyConvertFromProto() throws Exception {
alluxio.grpc.WorkerIdentity identityProto = alluxio.grpc.WorkerIdentity.newBuilder()
.setVersion(0)
.setIdentifier(ByteString.copyFrom(Longs.toByteArray(2L)))
.build();
WorkerIdentity identity = new WorkerIdentity(Longs.toBy... |
@Override
public Object get(String key) {
return this.map.get(key);
} | @Test
public void keyWithDifferentCase() {
map.put("key", "value");
CamelMessagingHeadersExtractAdapter adapter = new CamelMessagingHeadersExtractAdapter(map, true);
assertEquals("value", adapter.get("KeY"));
} |
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
String s = getClass().getName();
builder.append(s.substring(s.lastIndexOf('.') + 1));
List<? extends Coder<?>> componentCoders = getComponents();
if (!componentCoders.isEmpty()) {
builder.append('(');
bo... | @Test
public void testToString() {
assertThat(
new ObjectIdentityBooleanCoder().toString(),
CoreMatchers.equalTo("StructuredCoderTest$ObjectIdentityBooleanCoder"));
ObjectIdentityBooleanCoder coderWithArgs =
new ObjectIdentityBooleanCoder() {
@Override
public List<... |
public PathSpecSet copyWithScope(PathSpec parent)
{
if (this.isAllInclusive())
{
return PathSpecSet.of(parent);
}
if (this.isEmpty())
{
return PathSpecSet.empty();
}
Builder builder = newBuilder();
this.getPathSpecs().stream()
.map(childPathSpec -> {
Li... | @Test(dataProvider = "copyWithScopeProvider")
public void testCopyWithScope(PathSpecSet input, PathSpec parent, PathSpecSet expected) {
Assert.assertEquals(input.copyWithScope(parent), expected);
} |
public boolean isCollecting() {
return (state & MASK_COLLECTING) != 0;
} | @Test
public void isCollecting() {
LacpState state = new LacpState((byte) 0x10);
assertTrue(state.isCollecting());
} |
@Override
@Nullable
public short[] readShortArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, SHORT_ARRAY, super::readShortArray);
} | @Test
public void testReadShortArray() throws Exception {
assertNull(reader.readShortArray("NO SUCH FIELD"));
} |
public synchronized Topology addSource(final String name,
final String... topics) {
internalTopologyBuilder.addSource(null, name, null, null, null, topics);
return this;
} | @Test
public void shouldNotAllowToAddSourcesWithSameName() {
topology.addSource("source", "topic-1");
try {
topology.addSource("source", "topic-2");
fail("Should throw TopologyException for duplicate source name");
} catch (final TopologyException expected) { }
} |
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors(
ReconnaissanceReport reconnaissanceReport) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> isVulnDetector(entry.getKey()))
.map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc... | @Test
public void getVulnDetectors_whenOsFilterHasMatchingClass_returnsMatches() {
NetworkService wordPressService =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80))
.setTransportProtocol(TransportProtocol.TCP)
.setServic... |
public PartitionMetadata from(Struct row) {
return PartitionMetadata.newBuilder()
.setPartitionToken(row.getString(COLUMN_PARTITION_TOKEN))
.setParentTokens(Sets.newHashSet(row.getStringList(COLUMN_PARENT_TOKENS)))
.setStartTimestamp(row.getTimestamp(COLUMN_START_TIMESTAMP))
.setEndT... | @Test
public void testMapPartitionMetadataFromResultSetWithNulls() {
final Struct row =
Struct.newBuilder()
.set(COLUMN_PARTITION_TOKEN)
.to("token")
.set(COLUMN_PARENT_TOKENS)
.toStringArray(Collections.singletonList("parentToken"))
.set(COLUMN_... |
public SubscriptionData findSubscriptionData(final String group, final String topic) {
return findSubscriptionData(group, topic, true);
} | @Test
public void findSubscriptionDataTest() {
register();
final SubscriptionData subscriptionData = consumerManager.findSubscriptionData(GROUP, TOPIC);
Assertions.assertThat(subscriptionData).isNotNull();
} |
@Override
public BitString newInstance() {
return new BitString(bits.length, fitness, crossover, crossoverRate, mutationRate);
} | @Test
public void testNewInstance() {
System.out.println("newInstance");
byte[] father = {1,1,1,0,1,0,0,1,0,0,0};
int length = father.length;
BitString instance = new BitString(father, null, Crossover.SINGLE_POINT, 1.0, 0.0);
BitString result = instance.newInstance();
... |
boolean shouldReplicateAcl(AclBinding aclBinding) {
return !(aclBinding.entry().permissionType() == AclPermissionType.ALLOW
&& aclBinding.entry().operation() == AclOperation.WRITE);
} | @Test
public void testAclFiltering() {
MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"),
new DefaultReplicationPolicy(), x -> true, getConfigPropertyFilter());
assertFalse(connector.shouldReplicateAcl(
new AclBinding(new Reso... |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
ResponseHeader responseHeader = proxyBackendHandler.execute();
if (responseHeader instanceof QueryResponseHeader) {
return processQuery((QueryResponseHeader) responseHeader);
}
responseType = Resp... | @Test
void assertIsQueryResponse() throws SQLException, NoSuchFieldException, IllegalAccessException {
MySQLComQueryPacketExecutor mysqlComQueryPacketExecutor = new MySQLComQueryPacketExecutor(packet, connectionSession);
MemberAccessor accessor = Plugins.getMemberAccessor();
accessor.set(MyS... |
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
throws IOException {
EthCall ethCall =
web3j.ethCall(
Transaction.createEthCallTransaction(fromAddress, to, data),
... | @Test
public void sendCallRevertedTest() throws IOException {
when(response.isReverted()).thenReturn(true);
when(response.getRevertReason()).thenReturn(OWNER_REVERT_MSG_STR);
when(service.send(any(), any())).thenReturn(response);
ReadonlyTransactionManager readonlyTransactionManager... |
@Nonnull
public <T> T getInstance(@Nonnull Class<T> type) {
return getInstance(new Key<>(type));
} | @Test
public void whenDefaultSpecified_shouldUseSameInstance() throws Exception {
Thing thing = injector.getInstance(Thing.class);
assertThat(injector.getInstance(Thing.class)).isSameInstanceAs(thing);
} |
@Override
public void merge(NormalSketch other) {
Preconditions.checkArgument(data.length == other.data.length,
"Trying to merge sketch with one of different size. Expected %s, actual %s", data.length, other.data.length);
for (int i = 0; i < data.length; i++) {
data[i] = ... | @Test
public void requireThatMergeDoesElementWiseMax() {
NormalSketch s1 = new NormalSketch(2);
setSketchValues(s1, 0, 1, 1, 3);
NormalSketch s2 = new NormalSketch(2);
setSketchValues(s2, 2, 1, 1, 0);
s1.merge(s2);
assertBucketEquals(s1, 0, 2);
assertBucketEq... |
public static UNewClass create(
UExpression enclosingExpression,
List<? extends UExpression> typeArguments,
UExpression identifier,
List<UExpression> arguments,
@Nullable UClassDecl classBody) {
return new AutoValue_UNewClass(
enclosingExpression,
ImmutableList.copyOf(t... | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UNewClass.create(UClassIdent.create("java.lang.String"), ULiteral.stringLit("123")))
.addEqualityGroup(
UNewClass.create(UClassIdent.create("java.math.BigInteger"), ULiteral.stringLit("123")))
.add... |
@Override
public synchronized boolean tryReturnRecordAt(
boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) {
if (lastGroupStart == null && !isAtSplitPoint) {
throw new IllegalStateException(
String.format("The first group [at %s] must be at a split point", groupStart.toString()))... | @Test
public void testTryReturnRecordWithNonSplitPoints() throws Exception {
GroupingShuffleRangeTracker tracker =
new GroupingShuffleRangeTracker(ofBytes(1, 0, 0), ofBytes(5, 0, 0));
assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3)));
assertTrue(tracker.tryReturnRecordAt(false, ofBytes... |
@Override
@MethodNotAvailable
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor,
Object... arguments) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testInvokeAll() {
Set<Integer> keys = new HashSet<>(asList(23, 65, 88));
adapter.invokeAll(keys, new ICacheReplaceEntryProcessor(), "value", "newValue");
} |
static void readFullyDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
int nextReadLength = Math.min(buf.remaining(), temp.length);
int bytesRead = 0;
while (nextReadLength > 0 && (bytesRead = f.read(temp, 0, nextReadLength)) >= 0) {
buf.put(temp, 0, bytesRead);
next... | @Test
public void testDirectReadFullySmallBuffer() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocateDirect(8);
MockInputStream stream = new MockInputStream();
DelegatingSeekableInputStream.readFullyDirectBuffer(stream, readBuffer, TEMP.get());
Assert.assertEquals(8, readBuffer.position(... |
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (read(b, 0, 1) != 1) {
return -1;
} else {
return b[0];
}
} | @Test
public void testRead() throws Exception {
DistributedLogManager dlm = mock(DistributedLogManager.class);
LogReader reader = mock(LogReader.class);
when(dlm.getInputStream(any(DLSN.class))).thenReturn(reader);
byte[] data = "test-read".getBytes(StandardCharsets.UTF_8);
... |
@Override
public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException {
final TransferStatus status = super.prepare(file, local, parent, progress);
if(status.isExists()) {
final String filename... | @Test
public void testPrepare() throws Exception {
RenameFilter f = new RenameFilter(new DisabledUploadSymlinkResolver(), new NullSession(new Host(new TestProtocol())));
final Path t = new Path("t", EnumSet.of(Path.Type.file));
f.prepare(t, new NullLocal("t"), new TransferStatus(), new Disab... |
private static CPUResource getCpuCores(final Configuration config) {
return getCpuCoresWithFallback(config, -1.0);
} | @Test
void testConfigCpuCores() {
final double cpuCores = 1.0;
Configuration conf = new Configuration();
conf.set(TaskManagerOptions.CPU_CORES, cpuCores);
validateInAllConfigurations(
conf,
taskExecutorProcessSpec ->
assertTha... |
@NonNull
public static List<VideoStream> getSortedStreamVideosList(
@NonNull final Context context,
@Nullable final List<VideoStream> videoStreams,
@Nullable final List<VideoStream> videoOnlyStreams,
final boolean ascendingOrder,
final boolean preferVideoO... | @Test
public void getSortedStreamVideosListTest() {
List<VideoStream> result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, true,
VIDEO_STREAMS_TEST_LIST, VIDEO_ONLY_STREAMS_TEST_LIST, true, false);
List<String> expected = List.of("144p", "240p", "360p", "480p", "720p", ... |
public String toLoggableString(ApiMessage message) {
MetadataRecordType type = MetadataRecordType.fromId(message.apiKey());
switch (type) {
case CONFIG_RECORD: {
if (!configSchema.isSensitive((ConfigRecord) message)) {
return message.toString();
... | @Test
public void testUserScramCredentialRecordToString() {
assertEquals("UserScramCredentialRecord(name='bob', mechanism=0, " +
"salt=(redacted), storedKey=(redacted), serverKey=(redacted), iterations=128)",
REDACTOR.toLoggableString(new UserScramCredentialRecord().
... |
public DockerImage get(Node node) {
Optional<DockerImage> requestedImage = node.allocation()
.flatMap(allocation -> allocation.membership().cluster().dockerImageRepo());
NodeType nodeType = node.type().isHost() ? node.type().childNodeType() : node.type(... | @Test
public void image_selection() {
DockerImage defaultImage = DockerImage.fromString("different.example.com/vespa/default");
DockerImage tenantImage = DockerImage.fromString("registry.example.com/vespa/tenant");
DockerImage gpuImage = DockerImage.fromString("registry.example.com/vespa/ten... |
static KiePMMLCompoundPredicate getKiePMMLCompoundPredicate(final CompoundPredicate compoundPredicate,
final List<Field<?>> fields) {
final BOOLEAN_OPERATOR booleanOperator =
BOOLEAN_OPERATOR.byName(compoundPredicate.getBooleanOpera... | @Test
void getKiePMMLCompoundPredicate() {
List<Field<?>> fields = IntStream.range(0, 3).mapToObj(i -> getRandomDataField()).collect(Collectors.toList());
final CompoundPredicate toConvert = getRandomCompoundPredicate(fields);
final KiePMMLCompoundPredicate retrieved =
KiePMM... |
public WorkflowActionResponse activate(String workflowId, String version, User caller) {
Checks.notNull(
caller, "caller cannot be null to activate workflow [%s][%s]", workflowId, version);
WorkflowVersionUpdateJobEvent jobEvent =
(WorkflowVersionUpdateJobEvent) workflowDao.activate(workflowId, ... | @Test
public void testActivateError() {
AssertHelper.assertThrows(
"caller cannot be null to activate workflow",
NullPointerException.class,
"caller cannot be null to activate workflow [sample-minimal-wf][1]",
() -> actionHandler.activate("sample-minimal-wf", "1", null));
when(... |
@Override
public Result run(GoPluginDescriptor pluginDescriptor, Map<String, List<String>> extensionsInfoOfPlugin) {
final ValidationResult validationResult = validate(pluginDescriptor, extensionsInfoOfPlugin);
return new Result(validationResult.hasError(), validationResult.toErrorMessage());
} | @Test
void shouldConsiderPluginValidWhenOneOfTheExtensionVersionUsedByThePluginIsSupportedByGoCD() {
final PluginPostLoadHook.Result validationResult = pluginExtensionsAndVersionValidator.run(descriptor, Map.of(ELASTIC_AGENT_EXTENSION, List.of("a.b", "2.0")));
assertThat(validationResult.isAFailure... |
public static void copy(int[] src, long[] dest, int length) {
for (int i = 0; i < length; i++) {
dest[i] = src[i];
}
} | @Test
public void testCopyFromStringArray() {
ArrayCopyUtils.copy(STRING_ARRAY, INT_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(STRING_ARRAY, LONG_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(STRING_ARRAY, FLOAT_BUFFER, COPY_LENGTH);
ArrayCopyUtils.copy(STRING_ARRAY, DOUBLE_BUFFER, COPY_LENGTH);
for (i... |
@Override
public Encoder getValueEncoder() {
return encoder;
} | @Test
public void shouldSerializeValueCorrectly() throws Exception {
assertThat(valueCodec.getValueEncoder().encode(value).toString(CharsetUtil.UTF_8))
.isEqualTo("{\"value\":\"test\"}");
} |
public static <E> BoundedList<E> newArrayBacked(int maxLength) {
return new BoundedList<>(maxLength, new ArrayList<>());
} | @Test
public void testInitialCapacityMustNotBeZero() {
assertEquals("Invalid non-positive initialCapacity of 0",
assertThrows(IllegalArgumentException.class,
() -> BoundedList.newArrayBacked(100, 0)).getMessage());
} |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testStaticMemberRejoinAsFollowerWithUnknownMemberId() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinAndReba... |
public static BookmarkCollection defaultCollection() {
return FAVORITES_COLLECTION;
} | @Test
public void testDefault() {
assertNotNull(BookmarkCollection.defaultCollection());
} |
@Override
public <VR> KStream<K, VR> flatMapValues(final ValueMapper<? super V, ? extends Iterable<? extends VR>> mapper) {
return flatMapValues(withKey(mapper));
} | @Test
public void shouldNotAllowNullNameOnFlatMapValues() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatMapValues(v -> Collections.emptyList(), null));
assertThat(exception.getMessage(), equalTo("named can't be null"))... |
private RemotingCommand queryTopicConsumeByWho(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
QueryTopicConsumeByWhoRequestHeader requestHeader =
(QueryTopicConsumeByW... | @Test
public void testQueryTopicConsumeByWho() throws RemotingCommandException {
QueryTopicConsumeByWhoRequestHeader requestHeader = new QueryTopicConsumeByWhoRequestHeader();
requestHeader.setTopic("topic");
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_TO... |
@Override
public String toString() {
return "MutableLong{value=" + value + '}';
} | @Test
public void testToString() {
MutableLong mutableLong = new MutableLong();
String s = mutableLong.toString();
assertEquals("MutableLong{value=0}", s);
} |
public Stream<NoSqlMigration> getMigrations() {
NoSqlMigrationProvider migrationProvider = getMigrationProvider();
return getMigrations(migrationProvider);
} | @Test
void testNoSqlDatabaseMigrationsAreSortedCorrectly() {
final NoSqlDatabaseMigrationsProvider databaseCreator = new NoSqlDatabaseMigrationsProvider(asList(MongoDBStorageProvider.class, AmazonDocumentDBStorageProvider.class));
final Stream<NoSqlMigration> databaseSpecificMigrations = databaseCre... |
public static YamlMapAccessor empty() {
return new YamlMapAccessor(new LinkedHashMap<>());
} | @Test
public void testEmpty() {
YamlMapAccessor yamlMapAccessor = YamlMapAccessor.empty();
Optional<Object> optional = yamlMapAccessor.get("/");
assertNotNull(optional);
assertTrue(optional.isPresent());
assertTrue(optional.get() instanceof Map);
Map<Object, Object> m... |
public OALScripts parse() throws IOException {
OALScripts scripts = new OALScripts();
CommonTokenStream tokens = new CommonTokenStream(lexer);
OALParser parser = new OALParser(tokens);
ParseTree tree = parser.root();
ParseTreeWalker walker = new ParseTreeWalker();
wal... | @Test
public void testParse() throws IOException {
ScriptParser parser = ScriptParser.createFromScriptText(
"endpoint_resp_time = from(Endpoint.latency).longAvg(); //comment test" + "\n" + "Service_avg = from(Service.latency).longAvg()",
TEST_SOURCE_PACKAGE
);
List<An... |
public static Future<Void> reconcileJmxSecret(Reconciliation reconciliation, SecretOperator secretOperator, SupportsJmx cluster) {
return secretOperator.getAsync(reconciliation.namespace(), cluster.jmx().secretName())
.compose(currentJmxSecret -> {
Secret desiredJmxSecret = ... | @Test
public void testDisabledJmxWithExistingSecret(VertxTestContext context) {
KafkaClusterSpec spec = new KafkaClusterSpecBuilder().build();
JmxModel jmx = new JmxModel(NAMESPACE, NAME, LABELS, OWNER_REFERENCE, spec);
SecretOperator mockSecretOps = mock(SecretOperator.class);
when... |
@Override
public void validateNameUniqueness(Map<CaseInsensitiveString, AbstractMaterialConfig> map) {
if (StringUtils.isBlank(packageId)) {
return;
}
if (map.containsKey(new CaseInsensitiveString(packageId))) {
AbstractMaterialConfig material = map.get(new CaseInsens... | @Test
public void shouldAddErrorIfMaterialNameUniquenessValidationFails() throws Exception {
PackageMaterialConfig packageMaterialConfig = new PackageMaterialConfig("package-id");
Map<CaseInsensitiveString, AbstractMaterialConfig> nameToMaterialMap = new HashMap<>();
PackageMaterialConfig e... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListProperties> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final KsqlConfigResolver resolver = new KsqlConfigResolver()... | @Test
public void shouldContainLevelField() {
// When:
final PropertiesList properties = (PropertiesList) CustomExecutors.LIST_PROPERTIES.execute(
engine.configure("LIST PROPERTIES;"),
mock(SessionProperties.class),
engine.getEngine(),
engine.getServiceContext()
).getEntity... |
@Override
public RemoteEnvironment createEnvironment(Environment environment, String workerId)
throws Exception {
Preconditions.checkState(
environment
.getUrn()
.equals(BeamUrns.getUrn(RunnerApi.StandardEnvironments.Environments.PROCESS)),
"The passed environment doe... | @Test
public void createsMultipleEnvironments() throws Exception {
Environment fooEnv =
Environments.createProcessEnvironment("", "", "foo", Collections.emptyMap());
RemoteEnvironment fooHandle = factory.createEnvironment(fooEnv, "workerId");
assertThat(fooHandle.getEnvironment(), is(equalTo(fooEn... |
public static String getMinInstantTime(String fileName) {
Matcher fileMatcher = ARCHIVE_FILE_PATTERN.matcher(fileName);
if (fileMatcher.matches()) {
return fileMatcher.group(1);
} else {
throw new HoodieException("Unexpected archival file name: " + fileName);
}
} | @Test
void testParseMinInstantTime() {
String fileName = "001_002_0.parquet";
String minInstantTime = LSMTimeline.getMinInstantTime(fileName);
assertThat(minInstantTime, is("001"));
assertThrows(HoodieException.class, () -> LSMTimeline.getMinInstantTime("invalid_file_name.parquet"));
} |
@Override
@NonNull
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = exchange.getResponse();
H... | @Test
public void testOriginRegex() {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest
.get("http://localhost:8080")
.header("Origin", "http://abc.com")
.build());
ServerHttpResponse exchangeResponse = exchange.getResponse(... |
public static Guess performGuess(List<Date> releaseDates) {
if (releaseDates.size() <= 1) {
return new Guess(Schedule.UNKNOWN, null, null);
} else if (releaseDates.size() > MAX_DATA_POINTS) {
releaseDates = releaseDates.subList(releaseDates.size() - MAX_DATA_POINTS, releaseDates.... | @Test
public void testEdgeCases() {
ArrayList<Date> releaseDates = new ArrayList<>();
assertEquals(ReleaseScheduleGuesser.Schedule.UNKNOWN, performGuess(releaseDates).schedule);
releaseDates.add(makeDate("2024-01-01 16:30"));
assertEquals(ReleaseScheduleGuesser.Schedule.UNKNOWN, perf... |
public void assignRoles( List<Object> rolesToAssign ) {
List<UIRepositoryObjectAcl> acls = new ArrayList<UIRepositoryObjectAcl>();
for ( Object role : rolesToAssign ) {
if ( role instanceof String ) {
String roleToAssign = (String) role;
acls.add( assignRole( roleToAssign ) );
}
... | @Test
public void testAssignRoles() {
UIRepositoryObjectAcl selectedRoleAcl = new UIRepositoryObjectAcl( createRoleAce( ROLE1 ) );
repositoryObjectAcls.addAcl( selectedRoleAcl );
repositoryObjectAclModel.setAclsList( null, defaultRoleNameList );
List<Object> objectRoleList = Arrays.asList( new Object... |
@Override
public void addTask(Object key, AbstractDelayTask newTask) {
lock.lock();
try {
AbstractDelayTask existTask = tasks.get(key);
if (null != existTask) {
newTask.merge(existTask);
}
tasks.put(key, newTask);
} finally {
... | @Test
void testRemoveProcessor() throws InterruptedException {
when(taskProcessor.process(abstractTask)).thenReturn(true);
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.removeProcessor("test");
nacosDelayTaskExecuteEngine.addTask("te... |
public void delete(final String name) {
dynamoDbClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_NAME, AttributeValues.fromString(name)))
.build());
} | @Test
void testDelete() {
remoteConfigs.set(new RemoteConfig("android.stickers", 50, Set.of(AuthHelper.VALID_UUID), "FALSE", "TRUE", null));
remoteConfigs.set(new RemoteConfig("ios.stickers", 50, Set.of(), "FALSE", "TRUE", null));
remoteConfigs.set(new RemoteConfig("ios.stickers", 75, Set.of(), "FALSE", "... |
@Override
public int hashCode() {
return Objects.hash(type, name, host, port, startedAt);
} | @Test
public void hashcode_is_based_on_content() {
NodeDetails.Builder builder = testSupport.randomNodeDetailsBuilder();
NodeDetails underTest = builder.build();
assertThat(builder.build().hashCode())
.isEqualTo(underTest.hashCode());
} |
@Override
public ScannerReport.Component readComponent(int componentRef) {
ensureInitialized();
return delegate.readComponent(componentRef);
} | @Test
public void readComponent_is_not_cached() {
writer.writeComponent(COMPONENT);
assertThat(underTest.readComponent(COMPONENT_REF)).isNotSameAs(underTest.readComponent(COMPONENT_REF));
} |
@Override
public Map<SubClusterId, List<ResourceRequest>> splitResourceRequests(
List<ResourceRequest> resourceRequests,
Set<SubClusterId> timedOutSubClusters) throws YarnException {
if (homeSubcluster == null) {
throw new FederationPolicyException("No home subcluster available");
}
Map... | @Test
public void testHomeSubclusterNotActive() throws YarnException {
// We setup the home subcluster to a non-existing one
initializePolicyContext(getPolicy(), mock(WeightedPolicyInfo.class),
getActiveSubclusters(), "badsc");
// Verify the request fails because the home subcluster is not avail... |
@Override
public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
if (!location.hasPrefix(PREFIX)) {
return false;
}
boolean contextEnabled = context.getBinder()
.bind("spring.cloud.polaris.enabled", Boolean.class)
.orElse(true);
boolean configEnabled ... | @Test
public void testIsResolvable() {
when(context.getBinder()).thenReturn(environmentBinder);
assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("configserver:"))).isFalse();
assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))).isTrue();
assertThat(th... |
@Deprecated
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype)
throws IllegalStateException {
return Types.resolveLastTypeParameter(genericContext, supertype);
} | @Test
void resolveLastTypeParameterWhenNotSubtype() throws Exception {
Type context =
LastTypeParameter.class.getDeclaredField("PARAMETERIZED_LIST_STRING").getGenericType();
Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType();
Type last = resolveLastTypeP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.