focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public synchronized int getEndOfBlockIndex() {
return endOfBlockIndex;
} | @Test
public void tesGgetEndOfBlockIndex() {
int expected = -1;
assertEquals(expected, instance.getEndOfBlockIndex(), "Unexpected initial value");
expected = 0;
instance.endOfBlockIndex = expected;
assertEquals(expected, instance.getEndOfBlockIndex());
expected = 5;... |
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String mainBranchUuid,
String defaultBranchName, String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) {
boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent()... | @Test
public void createNewCodeDefinition_throw_IAE_if_days_is_invalid() {
assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH_UUID, MAIN_BRANCH, NUMBER_OF_DAYS.name(), "unknown"))
.isInstanceOf(IllegalArgumentException.class)
.hasMess... |
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
// will transform to topN
LogicalLimitOperator limit = (LogicalLimitOperator) input.getOp();
LogicalTopNOperator sort = (LogicalTopNOperator) input.getInputs().get(0).getOp();
long minLim... | @Test
public void transform() {
OptExpression limit = new OptExpression(LogicalLimitOperator.init(10, 2));
OptExpression sort = new OptExpression(new LogicalTopNOperator(
Lists.newArrayList(new Ordering(new ColumnRefOperator(1, Type.INT, "name", true), false, false))));
limi... |
@Override
public CompletableFuture<Map<String, BrokerLookupData>> filterAsync(Map<String, BrokerLookupData> brokers,
ServiceUnitId serviceUnit,
LoadManagerContext context) ... | @Test
public void testDisabledFilter() throws BrokerFilterException, ExecutionException, InterruptedException {
LoadManagerContext context = getContext();
ServiceConfiguration configuration = new ServiceConfiguration();
configuration.setPreferLaterVersions(false);
doReturn(configurat... |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public GenericRow apply(
final GenericKey k,
final GenericRow rowValue,
final GenericRow aggRowValue
) {
final GenericRow result = GenericRow.fromList(aggRowValue.values());
for (int idx = 0; idx < nonAggColumnCount; idx++) {
... | @Test
public void shouldNotMutateParametersOnApply() {
// Given:
final GenericRow value = GenericRow.genericRow(1, 2L);
final GenericRow agg = GenericRow.genericRow(1, 2L, 3);
// When:
final GenericRow result = aggregator.apply(key, value, agg);
// Then:
assertThat(value, is(GenericRow.g... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testExpeditiousCheck1()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_EXPEDITIOUS_BRACELET_1, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_EXPEDITIOUS... |
public static <T extends Message> ProtoCoder<T> of(Class<T> protoMessageClass) {
return new ProtoCoder<>(protoMessageClass, ImmutableSet.of());
} | @Test
public void encodeNullThrowsCoderException() throws Exception {
thrown.expect(CoderException.class);
thrown.expectMessage("cannot encode a null MessageA");
CoderUtils.encodeToBase64(ProtoCoder.of(MessageA.class), null);
} |
public boolean existsCreatedStep() {
return 0 != getCreatedStepCount();
} | @Test
public void testExistsCreatedStep() throws Exception {
WorkflowRuntimeOverview overview =
loadObject(
"fixtures/instances/sample-workflow-runtime-overview.json",
WorkflowRuntimeOverview.class);
assertTrue(overview.existsCreatedStep());
overview.setTotalStepCount(2);
... |
KafkaBasedLog<String, byte[]> setupAndCreateKafkaBasedLog(String topic, final WorkerConfig config) {
String clusterId = config.kafkaClusterId();
Map<String, Object> originals = config.originals();
Map<String, Object> producerProps = new HashMap<>(baseProducerProps);
producerProps.put(Co... | @Test
public void testConsumerPropertiesOverrideUserSuppliedValuesWithExactlyOnceSourceEnabled() {
props.put(EXACTLY_ONCE_SOURCE_SUPPORT_CONFIG, "enabled");
props.put(ISOLATION_LEVEL_CONFIG, IsolationLevel.READ_UNCOMMITTED.toString());
createStore();
configStorage.setupAndCreateKafk... |
@Override
@Transactional
public boolean checkForPreApproval(Long userId, Integer userType, String clientId, Collection<String> requestedScopes) {
// 第一步,基于 Client 的自动授权计算,如果 scopes 都在自动授权中,则返回 true 通过
OAuth2ClientDO clientDO = oauth2ClientService.validOAuthClientFromCache(clientId);
Asse... | @Test
public void checkForPreApproval_clientAutoApprove() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
List<String> requestedScopes = Lists.newArrayList("read");
// mock 方法
... |
@Override
public void run() {
final Instant now = time.get();
try {
final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries();
final Optional<Double> saturation = queries.stream()
.collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId))
... | @Test
public void shouldCleanupThreadMetric() {
// Given:
final Instant start = Instant.now();
when(clock.get()).thenReturn(start);
givenMetrics(kafkaStreams1)
.withThreadStartTime("t1", start)
.withBlockedTime("t1", Duration.ofMinutes(0));
collector.run();
when(clock.get()).th... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void timeWindowAnonymousStoreTypeMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.windowedBy(TimeWindows.of(ofMillis(1)))
.count(Materialized.as(Mate... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testParseCorruptedRecord() throws Exception {
buildFetcher();
assignFromUser(singleton(tp0));
ByteBuffer buffer = ByteBuffer.allocate(1024);
DataOutputStream out = new DataOutputStream(new ByteBufferOutputStream(buffer));
byte magic = RecordBatch.MAGIC_VAL... |
public void reset() {
this.next = this.initial;
this.mandatoryStopMade = false;
} | @Test
public void basicTest() {
Clock mockClock = Clock.fixed(Instant.EPOCH, ZoneId.systemDefault());
Backoff backoff = new Backoff(5, TimeUnit.MILLISECONDS, 60, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, mockClock);
assertTrue(checkExactAndDecrementTimer(backoff, 5));
assertTrue(within... |
public static byte[] fromHexString(final String values) {
return fromHexString(values, ":");
} | @Test(expected = NumberFormatException.class)
public void testFromHexStringError() {
String invalidStr = "00:00:00:00:00:00:ffff";
HexString.fromHexString(invalidStr);
fail("HexString.fromHexString() should have thrown a NumberFormatException");
} |
public static String getCurrentTimeStr() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
return DateFormatUtils.format(c.getTime(), YYYYMMMDDHHMMSS);
} | @Test
void testGetCurrentTimeStr() throws ParseException {
Date date1 = new Date(TimeUtils.getCurrentTime().getTime());
assertNotNull(date1.toString());
Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(TimeUtils.getCurrentTimeStr());
assertNotNull(date... |
@Override
@SuppressWarnings("unchecked")
public void init() throws ServiceException {
timersSize = getServiceConfig().getInt(CONF_TIMERS_SIZE, 10);
counterLock = new ReentrantLock();
timerLock = new ReentrantLock();
variableLock = new ReentrantLock();
samplerLock = new ReentrantLock();
Map<S... | @Test
public void sampler() throws Exception {
final long value[] = new long[1];
Instrumentation.Variable<Long> var = new Instrumentation.Variable<Long>() {
@Override
public Long getValue() {
return value[0];
}
};
InstrumentationService.Sampler sampler = new InstrumentationS... |
@Override
public boolean containsKey(K key) {
begin();
boolean result = transactionalMap.containsKey(key);
commit();
return result;
} | @Test
public void testContainsKey() {
map.put(23, "value-23");
assertTrue(adapter.containsKey(23));
assertFalse(adapter.containsKey(42));
} |
public static boolean isSecond(long ts) {
return (ts & SECOND_MASK) == 0;
} | @Test
public void testIsSecond() {
Assert.assertFalse(TimeUtils.isSecond(System.currentTimeMillis()));
Assert.assertTrue(TimeUtils.isSecond(System.currentTimeMillis() / 1000));
} |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final Void options, final PasswordCallback callback) throws BackgroundException {
try {
if(log.isDebugEnabled()) {
log.debug(String.format("Create temporary link for %s", file));
}
... | @Test
public void testToUrl() throws Exception {
final DropboxTemporaryUrlProvider provider = new DropboxTemporaryUrlProvider(session);
final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new Dr... |
public static <T> T readJsonSR(
@Nonnull final byte[] jsonWithMagic,
final ObjectMapper mapper,
final Class<? extends T> clazz
) throws IOException {
if (!hasMagicByte(jsonWithMagic)) {
// don't log contents of jsonWithMagic to avoid leaking data into the logs
throw new KsqlException... | @Test()
public void shouldThrowOnStandardJsonConversion() {
// Given:
byte[] json = new byte[]{/* data */ 0x01};
// When:
final Exception e = assertThrows(
Exception.class,
() -> JsonSerdeUtils.readJsonSR(json, mapper, Object.class)
);
// Then:
assertThat(e.getMessage(), ... |
public SaslExtensions extensions() {
return saslExtensions;
} | @Test
public void testNoExtensionsFromTokenAndNullExtensions() throws Exception {
OAuthBearerClientInitialResponse response = new OAuthBearerClientInitialResponse("token", null);
assertTrue(response.extensions().map().isEmpty());
} |
@Override
public PageResult<MailAccountDO> getMailAccountPage(MailAccountPageReqVO pageReqVO) {
return mailAccountMapper.selectPage(pageReqVO);
} | @Test
public void testGetMailAccountPage() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class, o -> { // 等会查询到
o.setMail("768@qq.com");
o.setUsername("yunai");
});
mailAccountMapper.insert(dbMailAccount);
// 测试 mail 不匹配
m... |
@Override
public int delete(String id) {
return this.coll.removeById(id).getN();
} | @Test
public void deleteThrowsIllegalArgumentExceptionForInvalidObjectId() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("state should be: hexString has 24 characters");
decoratorService.delete("NOPE");
} |
@Override
public void connectToResourceManager(ResourceManagerGateway resourceManagerGateway) {
assertHasBeenStarted();
resourceRequirementServiceConnectionManager.connect(
resourceRequirements ->
resourceManagerGateway.declareRequiredResources(
... | @Test
void testConnectToResourceManagerDeclaresRequiredResources() throws Exception {
final Collection<ResourceRequirement> requiredResources =
Arrays.asList(
ResourceRequirement.create(ResourceProfile.UNKNOWN, 2),
ResourceRequirement.create(Re... |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowDb() throws AnalysisException, DdlException {
ctx.setCurrentUserIdentity(UserIdentity.ROOT);
ctx.setCurrentRoleIds(Sets.newHashSet(PrivilegeBuiltinConstants.ROOT_ROLE_ID));
ShowDbStmt stmt = new ShowDbStmt(null);
ShowResultSet resultSet = ShowExecutor.exec... |
@Override
public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
Path target;
if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) {
// De... | @Test
public void testMoveWithServerSideEncryptionBucketPolicy() throws Exception {
final Path container = new Path("sse-test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.... |
@Override
public ParDoFn create(
PipelineOptions options,
CloudObject cloudUserFn,
@Nullable List<SideInputInfo> sideInputInfos,
TupleTag<?> mainOutputTag,
Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices,
DataflowExecutionContext<?> executionContext,
DataflowOperat... | @Test
public void testCleanupRegistered() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
CounterSet counters = new CounterSet();
DoFn<?, ?> initialFn = new TestStatefulDoFn();
CloudObject cloudObject =
getCloudObject(
initialFn,
WindowingS... |
@Operation(description = "Return openId configuration")
@GetMapping(value = "/jwks", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> jwks() {
return Map.of("keys", Arrays.asList(provider.generateJWK()));
} | @Test
void jwks() {
var response = controller.jwks();
List list = (List) response.get("keys");
Map<String, String> key = (Map<String,String>) list.get(0);
assertEquals(1, list.size());
assertEquals("RSA", key.get("kty"));
assertEquals("sig", key.get("use"));
... |
@Override
public List<String> extractPartitionValuesInPath(String partitionPath) {
// If the partitionPath is empty string( which means none-partition table), the partition values
// should be empty list.
if (partitionPath.isEmpty()) {
return Collections.emptyList();
}
String[] splits = part... | @Test
public void testMultiPartExtractor() {
MultiPartKeysValueExtractor valueExtractor = new MultiPartKeysValueExtractor();
// Test extract empty partitionPath
assertEquals(new ArrayList<>(), valueExtractor.extractPartitionValuesInPath(""));
List<String> expected = new ArrayList<>();
expected.add... |
@Transient
public String getFlinkTableWith(String flinkConfig) {
if (Asserts.isNotNullString(flinkConfig)) {
Map<String, String> replacements = new HashMap<>();
replacements.put("schemaName", schema);
replacements.put("tableName", name);
return SqlUtil.replac... | @Test
void getFlinkTableWith() {
String result = table.getFlinkTableWith(flinkConfig);
assertThat(
result,
equalTo("SchemaOrigin=schemaName, TableNameOrigin=tableName, #{abc}=abc, #{}=null, " + "bcd=bcd"));
} |
@GetMapping("/addVGroup")
public Result<?> addVGroup(@RequestParam String vGroup, @RequestParam String unit) {
Result<?> result = new Result<>();
MappingDO mappingDO = new MappingDO();
mappingDO.setNamespace(Instance.getInstance().getNamespace());
mappingDO.setCluster(Instance.getIns... | @Test
void addVGroup() {
namingController.addVGroup("group1","unit1");
} |
public static boolean safeCollectionEquals(final Collection<Comparable<?>> sources, final Collection<Comparable<?>> targets) {
List<Comparable<?>> all = new ArrayList<>(sources);
all.addAll(targets);
Optional<Class<?>> clazz = getTargetNumericType(all);
if (!clazz.isPresent()) {
... | @Test
void assertSafeCollectionEqualsForFloat() {
List<Comparable<?>> sources = Arrays.asList(10.01F, 12.01F);
List<Comparable<?>> targets = Arrays.asList(10.01F, 12.01F);
assertTrue(SafeNumberOperationUtils.safeCollectionEquals(sources, targets));
} |
@Override
public Map<String, String> apply(ServerWebExchange exchange) {
StainingRule stainingRule = stainingRuleManager.getStainingRule();
if (stainingRule == null) {
return Collections.emptyMap();
}
return ruleStainingExecutor.execute(exchange, stainingRule);
} | @Test
public void testNoStainingRule() {
RuleStainingProperties ruleStainingProperties = new RuleStainingProperties();
ruleStainingProperties.setNamespace(testNamespace);
ruleStainingProperties.setGroup(testGroup);
ruleStainingProperties.setFileName(testFileName);
ConfigFile configFile = Mockito.mock(Config... |
static void createCompactedTopic(String topicName, short partitions, short replicationFactor, Admin admin) {
NewTopic topicDescription = TopicAdmin.defineTopic(topicName).
compacted().
partitions(partitions).
replicationFactor(replicationFactor).
b... | @Test
public void testCreateCompactedTopicAssumeTopicAlreadyExistsWithClusterAuthorizationException() throws Exception {
Map<String, KafkaFuture<Void>> values = Collections.singletonMap(TOPIC, future);
when(future.get()).thenThrow(new ExecutionException(new ClusterAuthorizationException("not authori... |
static String prettyPrintException(Throwable throwable) {
if (throwable == null)
return "Null exception.";
if (throwable.getMessage() != null) {
return throwable.getClass().getSimpleName() + ": " + throwable.getMessage();
}
return throwable.getClass().getSimpleNam... | @Test
public void testPrettyPrintException() {
assertEquals("Null exception.", KafkaAdminClient.prettyPrintException(null));
assertEquals("TimeoutException", KafkaAdminClient.prettyPrintException(new TimeoutException()));
assertEquals("TimeoutException: The foobar timed out.",
... |
ByteArrayOutputStream createConnectivityRequest(String uuid, FlowRule rule) {
/*
{
"tapi-connectivity:connectivity-service":[
{
"uuid":"ffb006d4-349e-4d2f-817e-0906c88458d0",
"service-layer":"PHOTONIC_MEDIA",
"servic... | @Test
public void createConnRequest() {
String output = tapiFrp.createConnectivityRequest(CONNECTION_UUID, FLOW_RULE).toString();
System.out.println(output);
assertEquals("Json to create network connectivity is wrong", CONNECTIVITY_REQUEST, output);
} |
@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_vatu()
{
// given
List<Integer> glyphsAfterGsub = Arrays.asList(517,593,601,665);
// when
List<Integer> result = gsubWorkerForDevanagari.applyTransforms(getGlyphIds("श्रत्रस्रघ्र"));
// then
assertEquals(glyphsAfterGsub, result);
... |
void prioritizeCopiesAndShiftUps(List<MigrationInfo> migrations) {
for (int i = 0; i < migrations.size(); i++) {
prioritize(migrations, i);
}
if (logger.isFinestEnabled()) {
StringBuilder s = new StringBuilder("Migration order after prioritization: [");
int i... | @Test
public void testCopyPrioritizationAgainstMove()
throws UnknownHostException {
List<MigrationInfo> migrations = new ArrayList<>();
final MigrationInfo migration1 = new MigrationInfo(0, null, new PartitionReplica(new Address("localhost", 5701), uuids[0]), -1, -1, -1, 0);
fina... |
@Override
public InvokerWrapper getInvokerWrapper() {
return invokerWrapper;
} | @Test(expected = UnsupportedOperationException.class)
public void testInvokerWrapper_invoke() {
context.getInvokerWrapper().invoke(null, false);
} |
@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 shouldReturnNullForAllNullInputs() {
final List<Long> result = udf.union((List<Long>) null, (List<Long>) null);
assertThat(result, is(nullValue()));
} |
public static int hash(Client client) {
if (!(client instanceof IpPortBasedClient)) {
return 0;
}
return Objects.hash(client.getClientId(),
client.getAllPublishedService().stream()
.map(s -> {
InstancePublishInfo ip ... | @Test
void performanceTestOfHash() {
long start = System.nanoTime();
for (int i = 0; i < N; i++) {
DistroUtils.hash(client1);
}
System.out.printf("Distro Verify Hash Performance: %.2f ivk/ns\n", ((double) System.nanoTime() - start) / N);
} |
public <T> HttpRestResult<T> post(String url, Header header, Query query, Object body, Type responseType)
throws Exception {
return execute(url, HttpMethod.POST, new RequestHttpEntity(header, query, body), responseType);
} | @Test
void testPost() throws Exception {
when(requestClient.execute(any(), eq("POST"), any())).thenReturn(mockResponse);
when(mockResponse.getStatusCode()).thenReturn(200);
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
HttpRestResult<String> re... |
@Override
public Write.Append append(final Path file, final TransferStatus status) throws BackgroundException {
return new Write.Append(status.isExists()).withStatus(status);
} | @Test
public void testAppend() throws Exception {
final Path workdir = new SFTPHomeDirectoryService(session).find();
final Path test = new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new SFTPTouchFeature(session).touch(test, new TransferStatus()... |
@Activate
protected void activate() {
this.loadConfigs();
log.info("Started");
} | @Test
public void basics() throws IOException {
stageTestResource("basic.json");
loader.activate();
assertEquals("incorrect component", FOO_COMPONENT, service.component);
} |
@Override
public Map<String, Object> processCsvFile(String encodedCsvData, boolean dryRun) throws JsonProcessingException {
services = new HashMap<>();
serviceParentChildren = new HashMap<>();
Map<String, Object> result = super.processCsvFile(encodedCsvData, dryRun);
if (!services.is... | @Test
void processCsvFileSuccessCreationServiceTest() throws IOException {
String csvData = """SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS... |
public void mergeWith(DynamicFilterStats other)
{
if (other == null) {
return;
}
producerNodeIds.addAll(other.getProducerNodeIds());
} | @Test
public void testMergeWith()
{
final PlanNodeId[] planNodes1 = new PlanNodeId[] {new PlanNodeId("1"), new PlanNodeId("2")};
Set<PlanNodeId> planNodeSet1 = new HashSet<>(Arrays.asList(planNodes1));
DynamicFilterStats stats1 = new DynamicFilterStats(planNodeSet1);
assertEquals... |
@Override
public Long clusterCountKeysInSlot(int slot) {
RedisClusterNode node = clusterGetNodeForSlot(slot);
MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort()));
RFuture<Long> f = executorService.readAsync(entry, St... | @Test
public void testClusterCountKeysInSlot() {
Long t = connection.clusterCountKeysInSlot(1);
assertThat(t).isZero();
} |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testExpiredIterator() throws InterruptedException {
RMapCacheNative<String, String> cache = redisson.getMapCacheNative("simple");
cache.put("0", "8");
cache.put("1", "6", Duration.ofSeconds(1));
cache.put("2", "4", Duration.ofSeconds(3));
cache.put("3", "2",... |
@Override
public Port port(String portId) {
checkArgument(!Strings.isNullOrEmpty(portId), ERR_NULL_PORT_ID);
return osNetworkStore.port(portId);
} | @Test
public void testGetPortById() {
createBasicNetworks();
assertTrue("Port did not match", target.port(PORT_ID) != null);
assertTrue("Port did not match", target.port(UNKNOWN_ID) == null);
} |
@Override
public String getImage() {
if ( isLocked() ) {
return "ui/images/lock.svg"; //$NON-NLS-1$
}
return "ui/images/jobrepo.svg"; //$NON-NLS-1$
} | @Test
public void testGetImage() {
String image = uiJob.getImage();
assertNotNull( image );
File f = new File( image );
when( mockEERepositoryObject.getLock() ).thenReturn( mockRepositoryLock );
String image2 = uiJob.getImage();
assertNotNull( image2 );
f = new File( image2 );
assert... |
public static void addSecurityProvider(Properties properties) {
properties.keySet().stream()
.filter(key -> key.toString().matches("security\\.provider(\\.\\d+)?"))
.sorted(Comparator.comparing(String::valueOf)).forEach(key -> addSecurityProvider(properties.get(key).toString()));... | @Test
void addSecurityProviderTest() {
removeAllDummyProviders();
Provider[] providers = Security.getProviders();
int providersCountBefore = providers.length;
SecurityProviderLoader.addSecurityProvider(DummyProvider.class.getName());
Provider[] providersAfter = Security.get... |
public void setWisdom(int wizard, int amount) {
wizards[wizard].setWisdom(amount);
} | @Test
void testSetWisdom() {
var wizardNumber = 0;
var bytecode = new int[5];
bytecode[0] = LITERAL.getIntValue();
bytecode[1] = wizardNumber;
bytecode[2] = LITERAL.getIntValue();
bytecode[3] = 50; // wisdom amount
bytecode[4] = SET_WISDOM.getIntValue();
var vm ... |
public void convert(FSConfigToCSConfigConverterParams params)
throws Exception {
validateParams(params);
this.clusterResource = getClusterResource(params);
this.convertPlacementRules = params.isConvertPlacementRules();
this.outputDirectory = params.getOutputDirectory();
this.rulesToFile = para... | @Test
public void testConvertFSConfigurationClusterResourceInvalid2()
throws Exception {
FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
.withClusterResource("vcores=20, memmmm=240")
.build();
expectedException.expect(ConversionException.class);
expectedExcep... |
public static boolean isValidMetaKey(String key) {
return META_KEY_PATTERN.matcher(key).matches();
} | @Test
public void testMetaKey() {
Assert.assertTrue(ConsulUtils.isValidMetaKey("tags"));
Assert.assertTrue(ConsulUtils.isValidMetaKey("TAGS"));
Assert.assertTrue(ConsulUtils.isValidMetaKey("TAGS1"));
Assert.assertTrue(ConsulUtils.isValidMetaKey("TAGS-1"));
Assert.assertTrue(C... |
public static String toArgumentString(Object[] args) {
StringBuilder buf = new StringBuilder();
for (Object arg : args) {
if (buf.length() > 0) {
buf.append(COMMA_SEPARATOR);
}
if (arg == null || ReflectUtils.isPrimitives(arg.getClass())) {
... | @Test
void testToArgumentString() throws Exception {
String s = StringUtils.toArgumentString(new Object[] {"a", 0, Collections.singletonMap("enabled", true)});
assertThat(s, containsString("a,"));
assertThat(s, containsString("0,"));
assertThat(s, containsString("{\"enabled\":true}")... |
@Override
public void initialize(URI uri, Configuration conf)
throws IOException
{
requireNonNull(uri, "uri is null");
requireNonNull(conf, "conf is null");
super.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAut... | @Test
public void testCompatibleStaticCredentials()
throws Exception
{
Configuration config = new Configuration();
config.set(S3_ACCESS_KEY, "test_secret_access_key");
config.set(S3_SECRET_KEY, "test_access_key_id");
config.set(S3_ENDPOINT, "test.example.endpoint.com"... |
public void changeMethod(StealingMethod method) {
this.method = method;
} | @Test
void testChangeMethod() {
final var initialMethod = spy(StealingMethod.class);
final var thief = new HalflingThief(initialMethod);
thief.steal();
verify(initialMethod).steal();
String target = verify(initialMethod).pickTarget();
verify(initialMethod).confuseTarget(target);
verify(in... |
public DefaultProbe(Map<String, String> props) {
this("Default probe: IP presence", props);
} | @Test
public void testDefaultProbe() {
// component instance has a good hostname, so probe will eventually succeed
// whether or not DNS checking is enabled
ComponentInstance componentInstance =
createMockComponentInstance("example.com");
checkPingResults(probe, componentInstance, false);
... |
@Override
public String toString()
{
return "id: " + super.toString() + ", entity: " + (_entity == null ? "" : _entity);
} | @Test
public void testToString()
{
IdEntityResponse<Long, AnyRecord> longIdEntityResponse = new IdEntityResponse<>(6L, new AnyRecord());
Assert.assertEquals(longIdEntityResponse.toString(), "id: 6, entity: {}");
IdEntityResponse<Long, AnyRecord> nullIdEntityResponse = new IdEntityResponse<>(null, new A... |
public static TunnelId valueOf(String value) {
return new TunnelId(value);
} | @Test
public void testConstruction() {
final String tunnelIdValue = "7777";
final TunnelId tunnelId = TunnelId.valueOf(tunnelIdValue);
assertThat(tunnelId, is(notNullValue()));
assertThat(tunnelId.id(), is(tunnelIdValue));
} |
@Override
protected void delete(Collection<HadoopResourceId> resourceIds) throws IOException {
for (HadoopResourceId resourceId : resourceIds) {
// ignore response as issues are surfaced with exception
final Path resourcePath = resourceId.toPath();
resourcePath.getFileSystem(configuration).delet... | @Test
public void testDeleteNonExisting() throws Exception {
fileSystem.delete(ImmutableList.of(testPath("MissingFile")));
} |
public static UserOperatorConfig buildFromMap(Map<String, String> map) {
Map<String, String> envMap = new HashMap<>(map);
envMap.keySet().retainAll(UserOperatorConfig.keyNames());
Map<String, Object> generatedMap = ConfigParameter.define(envMap, CONFIG_VALUES);
return new UserOperatorC... | @Test
public void testFromMapInvalidScramPasswordLengthThrows() {
Map<String, String> envVars = new HashMap<>(UserOperatorConfigTest.ENV_VARS);
envVars.put(UserOperatorConfig.SCRAM_SHA_PASSWORD_LENGTH.key(), "not_an_integer");
assertThrows(InvalidConfigurationException.class, () -> UserOpe... |
public static Expression fromJson(String json) {
return fromJson(json, null);
} | @Test
public void invalidTerm() {
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"not\",\n"
+ " \"child\" : {\n"
+ " \"type\" : \"lt\",\n"
... |
@Secured(action = ActionTypes.READ)
@GetMapping("/services")
public Object listDetail(@RequestParam(required = false) boolean withInstances,
@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam(required = false) int pageNo, @RequestParam(required... | @Test
void testListDetail() {
try {
when(catalogServiceV2.pageListServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME, 1,
10)).thenReturn(Collections.emptyList());
Object res = catalogController.listDetail(true, Constants.DEFAULT_NAMES... |
public static boolean cleanDirectory(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
if (children != null) {
for (String aChildren : children) {
boolean success = cleanDirectory(new File(dir, aChildren));
if (!s... | @Test
public void cleanDirectory() throws Exception {
String filePath = System.getProperty("java.io.tmpdir") + File.separator
+ "FileTest" + 1;
FileUtils.string2File(new File(filePath, "xx.tmp"), "helloworld!");
Assert.assertTrue(new File(filePath, "xx.tmp").exists());
S... |
public SegmentLineage(String tableNameWithType) {
_tableNameWithType = tableNameWithType;
_lineageEntries = new HashMap<>();
} | @Test
public void testSegmentLineage() {
SegmentLineage segmentLineage = new SegmentLineage("test_OFFLINE");
String id = SegmentLineageUtils.generateLineageEntryId();
segmentLineage.addLineageEntry(id,
new LineageEntry(Arrays.asList("s1", "s2", "s3"), Arrays.asList("s4", "s5"), LineageEntryState.C... |
public static Map<String, String> getSegmentationSourcesMap(final MiningModelCompilationDTO compilationDTO,
final List<KiePMMLModel> nestedModels) {
logger.debug("getSegmentationSourcesMap {}", compilationDTO.getModel().getSegmentation());
... | @Test
void getSegmentationSourcesMap() {
final List<KiePMMLModel> nestedModels = new ArrayList<>();
final CommonCompilationDTO<MiningModel> source =
CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
... |
public static HostInfo parseHostInfo(final String applicationServerId) {
if (applicationServerId == null || applicationServerId.trim().isEmpty()) {
return StreamsMetadataState.UNKNOWN_HOST;
}
final String serverId = applicationServerId.endsWith("/")
? applicationServerId.substring(0, applicat... | @Test
public void shouldReturnServerPortWithTrailingSlash() {
// When:
final HostInfo hostInfo = ServerUtil.parseHostInfo("http://localhost:8088/");
// Then:
assertThat(hostInfo.port(), Matchers.is(8088));
} |
@Override
public GlobalCommitResponseProto convert2Proto(GlobalCommitResponse globalCommitResponse) {
final short typeCode = globalCommitResponse.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNumber(type... | @Test
public void convert2Proto() {
GlobalCommitResponse globalCommitResponse = new GlobalCommitResponse();
globalCommitResponse.setGlobalStatus(GlobalStatus.AsyncCommitting);
globalCommitResponse.setMsg("msg");
globalCommitResponse.setResultCode(ResultCode.Failed);
globalCo... |
@Override
public MigratablePipeline findPipelineToMigrate(LoadImbalance imbalance) {
Set<? extends MigratablePipeline> candidates = imbalance.getPipelinesOwnedBy(imbalance.srcOwner);
long migrationThreshold = (long) ((imbalance.maximumLoad - imbalance.minimumLoad)
* MAXIMUM_NO_OF_EVE... | @Test
public void testFindPipelineToMigrate() {
NioThread srcOwner = mock(NioThread.class);
NioThread dstOwner = mock(NioThread.class);
imbalance.srcOwner = srcOwner;
imbalance.dstOwner = dstOwner;
imbalance.minimumLoad = 100;
MigratablePipeline pipeline1 = mock(Migr... |
public Optional<User> login(String nameOrEmail, String password) {
if (nameOrEmail == null || password == null) {
return Optional.empty();
}
User user = userDAO.findByName(nameOrEmail);
if (user == null) {
user = userDAO.findByEmail(nameOrEmail);
}
if (user != null && !user.isDisabled()) {
boolean... | @Test
void callingLoginShouldNotReturnUserObjectIfCouldNotFindUserByNameOrEmail() {
Mockito.when(userDAO.findByName("test@test.com")).thenReturn(null);
Mockito.when(userDAO.findByEmail("test@test.com")).thenReturn(null);
Optional<User> user = userService.login("test@test.com", "password");
Assertions.assertF... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDa... | @Test
void assertRangeDoShardingWithoutUpperBound() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3", "t_order_4", "t_order_5");
Collection<String> actual = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue... |
@Override
public Long createNotifyMessage(Long userId, Integer userType,
NotifyTemplateDO template, String templateContent, Map<String, Object> templateParams) {
NotifyMessageDO message = new NotifyMessageDO().setUserId(userId).setUserType(userType)
.setTe... | @Test
public void testCreateNotifyMessage_success() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class);
String templateContent = randomString();
Map<Str... |
@Override
public ListenableFuture<?> execute(CreateMaterializedView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, Session session, List<Expression> parameters, WarningCollector warningCollector)
{
QualifiedObjectName viewName = createQualifiedObjectNam... | @Test
public void testCreateMaterializedViewNotExistsTrue()
{
SqlParser parser = new SqlParser();
String sql = String.format("CREATE MATERIALIZED VIEW IF NOT EXISTS %s AS SELECT 2021 AS col_0 FROM %s", MATERIALIZED_VIEW_A, TABLE_A);
CreateMaterializedView statement = (CreateMaterializedV... |
static String toJavaName(String opensslName) {
if (opensslName == null) {
return null;
}
Matcher matcher = PATTERN.matcher(opensslName);
if (matcher.matches()) {
String group1 = matcher.group(1);
if (group1 != null) {
return group1.toUp... | @Test
public void testInvalid() {
assertNull(SignatureAlgorithmConverter.toJavaName("ThisIsSomethingInvalid"));
} |
@Override
public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
result.setOrder(true);
List<MessageExt> msgs = new ArrayList<>();
msgs.add(msg);
MessageQueue m... | @Test
public void testConsumeMessageDirectly_WithException() {
MessageListenerOrderly listenerOrderly = new MessageListenerOrderly() {
@Override
public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
throw new RuntimeExcepti... |
public String getLogicColumnByCipherColumn(final String cipherColumnName) {
for (Entry<String, EncryptColumn> entry : columns.entrySet()) {
if (entry.getValue().getCipher().getName().equalsIgnoreCase(cipherColumnName)) {
return entry.getValue().getName();
}
}
... | @Test
void assertGetLogicColumnByCipherColumn() {
assertThat(encryptTable.getLogicColumnByCipherColumn("cipherColumn"), is("logicColumn"));
} |
public static String toHex(long value) {
return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
} | @Test
public void toHex() throws Exception {
assertEquals("0f", Tools.toHex(15, 2));
assertEquals("ffff", Tools.toHex(65535, 4));
assertEquals("1000", Tools.toHex(4096, 4));
assertEquals("000000000000000f", Tools.toHex(15));
assertEquals("ffffffffffffffff", Tools.toHex(0xffff... |
public boolean getBooleanProperty(String key, boolean defaultValue) {
return getBooleanProperty(key, defaultValue, false);
} | @Test
public void testBooleanProperty() {
TypedProperties p = createProperties();
assertEquals(true, p.getBooleanProperty("boolean", false));
assertEquals(true, p.getBooleanProperty("boolean_put_str", false));
assertEquals(true, p.getBooleanProperty("boolean_invalid", true));
assertEqua... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldHandleEmpty() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of();
// When:
final Result result = CoercionUtil.coerceUserList(expressions, typeManager);
// Then:
assertThat(result.commonType(), is(Optional.empty()));
assertThat(result.expr... |
OrcBulkWriter(Vectorizer<T> vectorizer, Writer writer) {
this.vectorizer = checkNotNull(vectorizer);
this.writer = checkNotNull(writer);
this.rowBatch = vectorizer.getSchema().createRowBatch();
// Configure the vectorizer with the writer so that users can add
// metadata on the ... | @Test
void testOrcBulkWriter(@TempDir File outDir) throws Exception {
final Properties writerProps = new Properties();
writerProps.setProperty("orc.compress", "LZ4");
final OrcBulkWriterFactory<Record> writer =
new OrcBulkWriterFactory<>(
new RecordVe... |
@Override
public AlterConfigsResult incrementalAlterConfigs(Map<ConfigResource, Collection<AlterConfigOp>> configs,
final AlterConfigsOptions options) {
final Map<ConfigResource, KafkaFutureImpl<Void>> allFutures = new HashMap<>();
// BROKER_LOGG... | @Test
public void testIncrementalAlterConfigs() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
//test error scenarios
IncrementalAlterConfigsResponseData responseData = new Increme... |
@Override
public synchronized List<PersistFile> pollFilesToPersist(long workerId)
throws InvalidPathException, AccessControlException {
List<PersistFile> filesToPersist = new ArrayList<>();
List<Long> fileIdsToPersist = new ArrayList<>();
if (!mWorkerToAsyncPersistFiles.containsKey(workerId)) {
... | @Test
public void persistenceFileWithBlocksOnMultipleWorkers() throws Exception {
DefaultAsyncPersistHandler handler =
new DefaultAsyncPersistHandler(new FileSystemMasterView(mFileSystemMaster));
AlluxioURI path = new AlluxioURI("/test");
List<FileBlockInfo> blockInfoList = new ArrayList<>();
... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testThreeMoreThanFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
history.add(3);
history.add(4);
history.add(5);
history.add(6);
int[] expectedHistorySnapshot = {4, 5, 6};
testHistory(history, expectedHistory... |
public void registerStrategy(BatchingStrategy<?, ?, ?> strategy) {
_strategies.add(strategy);
} | @Test
public void testBatchAndFailedSingleton() {
RecordingStrategy<Integer, Integer, String> strategy =
new RecordingStrategy<>((key, promise) -> {
if (key % 2 == 0) {
promise.done(String.valueOf(key));
} else {
promise.fail(new Exception());
}
... |
@Override
public Set<Interface> getInterfacesByIp(IpAddress ip) {
return interfaces.values()
.stream()
.flatMap(Collection::stream)
.filter(intf -> intf.ipAddressesList()
.stream()
.anyMatch(ia -> ia.ipAddress().... | @Test
public void testGetInterfacesByIp() throws Exception {
IpAddress ip = Ip4Address.valueOf("192.168.2.1");
Set<Interface> byIp = Collections.singleton(createInterface(2));
assertEquals(byIp, interfaceManager.getInterfacesByIp(ip));
} |
public static Throwable stripException(
Throwable throwableToStrip, Class<? extends Throwable> typeToStrip) {
while (typeToStrip.isAssignableFrom(throwableToStrip.getClass())
&& throwableToStrip.getCause() != null) {
throwableToStrip = throwableToStrip.getCause();
... | @Test
void testInvalidExceptionStripping() {
final FlinkException expectedException =
new FlinkException(new RuntimeException(new FlinkException("inner exception")));
final Throwable strippedException =
ExceptionUtils.stripException(expectedException, RuntimeException... |
@Override
public void closeRewardActivity(Long id) {
// 校验存在
RewardActivityDO dbRewardActivity = validateRewardActivityExists(id);
if (dbRewardActivity.getStatus().equals(PromotionActivityStatusEnum.CLOSE.getStatus())) { // 已关闭的活动,不能关闭噢
throw exception(REWARD_ACTIVITY_CLOSE_FAIL_... | @Test
public void testCloseRewardActivity() {
// mock 数据
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id ... |
@Override
public void aggregate(Iterable<Integer> hashValues) {
for (int hash: hashValues) {
aggregate(hash);
}
} | @Test
public void requireThatSerializationRetainAllData() {
SparseSketch from = new SparseSketch();
from.aggregate(42);
from.aggregate(1337);
SparseSketch to = new SparseSketch();
BufferSerializer buffer = new BufferSerializer();
from.serialize(buffer);
buff... |
public static String keyToString(Object key,
URLEscaper.Escaping escaping,
UriComponent.Type componentType,
boolean full,
ProtocolVersion version)
{
if (version.compareTo(All... | @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "longKey")
public void testLongKeyToString(ProtocolVersion version, String expected)
{
Long longKey = 6L;
String longKeyString = URIParamUtils.keyToString(longKey, NO_ESCAPING, null, true, version);
Assert.assertEquals(longKeyString, expect... |
@Override
public CloseableHttpClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws ConnectionCanceledException {
final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
authorizationService = new OAuth2... | @Test
public void testConnect() throws Exception {
assertNotEquals(StringUtils.EMPTY, session.getHost().getCredentials().getUsername());
} |
public void hasLength(int expectedLength) {
checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength);
check("length()").that(checkNotNull(actual).length()).isEqualTo(expectedLength);
} | @Test
public void hasLengthNegative() {
try {
assertThat("kurt").hasLength(-1);
fail();
} catch (IllegalArgumentException expected) {
}
} |
@Override
public void writeBundleDataOnZooKeeper() {
updateBundleData();
// Write the bundle data to metadata store.
List<CompletableFuture<Void>> futures = new ArrayList<>();
// use synchronized to protect bundleArr.
synchronized (bundleArr) {
int updateBundleCo... | @Test
public void testFilterBundlesWhileWritingToMetadataStore() throws Exception {
Map<String, PulsarService> pulsarServices = new HashMap<>();
pulsarServices.put(pulsar1.getWebServiceAddress(), pulsar1);
pulsarServices.put(pulsar2.getWebServiceAddress(), pulsar2);
MetadataCache<Bun... |
public PaginationContext createPaginationContext(final TopProjectionSegment topProjectionSegment, final Collection<ExpressionSegment> expressions, final List<Object> params) {
Collection<AndPredicate> andPredicates = expressions.stream().flatMap(each -> ExpressionExtractUtils.getAndPredicates(each).stream()).co... | @Test
void assertCreatePaginationContextWhenParameterMarkerRowNumberValueSegment() {
String name = "rowNumberAlias";
ColumnSegment left = new ColumnSegment(0, 10, new IdentifierValue(name));
ParameterMarkerExpressionSegment right = new ParameterMarkerExpressionSegment(0, 10, 0);
Bina... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testCorrectHandlingOfDuplicateSequenceError() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerId(producerId, Errors.NO... |
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
} | @Test
public void testSetCfgContext() throws NoSuchFieldException {
final ConfigurableApplicationContext cfgContext = mock(ConfigurableApplicationContext.class);
springBeanUtilsUnderTest.setApplicationContext(cfgContext);
assertNotNull(springBeanUtilsUnderTest.getClass().getDeclaredField("ap... |
public void addValueProviders(final String segmentName,
final RocksDB db,
final Cache cache,
final Statistics statistics) {
if (storeToValueProviders.isEmpty()) {
logger.debug("Adding metrics record... | @Test
public void shouldThrowIfValueProvidersForASegmentHasBeenAlreadyAdded() {
recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1);
final Throwable exception = assertThrows(
IllegalStateException.class,
() -> recorder.addValueProviders(... |
public static RateLimiterRegistry of(Configuration configuration, CompositeCustomizer<RateLimiterConfigCustomizer> customizer){
CommonRateLimiterConfigurationProperties rateLimiterProperties = CommonsConfigurationRateLimiterConfiguration.of(configuration);
Map<String, RateLimiterConfig> rateLimiterConfi... | @Test
public void testRateLimiterRegistryFromYamlFile() throws ConfigurationException {
Configuration config = CommonsConfigurationUtil.getConfiguration(YAMLConfiguration.class, TestConstants.RESILIENCE_CONFIG_YAML_FILE_NAME);
RateLimiterRegistry registry = CommonsConfigurationRateLimiterRegistry.o... |
public static boolean seemDuplicates(FeedItem item1, FeedItem item2) {
if (sameAndNotEmpty(item1.getItemIdentifier(), item2.getItemIdentifier())) {
return true;
}
FeedMedia media1 = item1.getMedia();
FeedMedia media2 = item2.getMedia();
if (media1 == null || media2 ==... | @Test
public void testNoMediaType() {
assertTrue(FeedItemDuplicateGuesser.seemDuplicates(
item("id1", "Title", "example.com/episode1", 2 * DAYS, 5 * MINUTES, ""),
item("id2", "Title", "example.com/episode2", 2 * DAYS, 5 * MINUTES, "")));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.