focal_method string | test_case string |
|---|---|
@Override
public void run() {
try {
PushDataWrapper wrapper = generatePushData();
ClientManager clientManager = delayTaskEngine.getClientManager();
for (String each : getTargetClientIds()) {
Client client = clientManager.getClient(each);
if... | @Test
void testRunFailedWithRetry() {
PushDelayTask delayTask = new PushDelayTask(service, 0L);
PushExecuteTask executeTask = new PushExecuteTask(service, delayTaskExecuteEngine, delayTask);
pushExecutor.setShouldSuccess(false);
pushExecutor.setFailedException(new RuntimeException())... |
@Override
protected void notifyFirstSampleAfterLoopRestart() {
log.debug("notifyFirstSampleAfterLoopRestart called "
+ "with config(httpclient.reset_state_on_thread_group_iteration={})",
RESET_STATE_ON_THREAD_GROUP_ITERATION);
JMeterVariables jMeterVariables = JMeterC... | @Test
public void testNotifyFirstSampleAfterLoopRestartWhenThreadIterationIsSameUser() {
jmvars.putObject(SAME_USER, true);
jmctx.setVariables(jmvars);
HTTPSamplerBase sampler = (HTTPSamplerBase) new HttpTestSampleGui().createTestElement();
sampler.setThreadContext(jmctx);
HT... |
@VisibleForTesting
static Duration parseToDuration(String timeStr) {
final Matcher matcher = Pattern.compile("(?<value>\\d+)\\s*(?<time>[dhms])").matcher(timeStr);
if (!matcher.matches()) {
throw new IllegalArgumentException("Expected a time specification in the form <number>[d,h,m,s], e... | @Test(expected = IllegalArgumentException.class)
public void testParseToDurationWithBadDurationFormatThrowsAnError() {
AbstractPipelineExt.parseToDuration("+3m");
} |
@ExecuteOn(TaskExecutors.IO)
@Put(uri = "{namespace}/files")
@Operation(tags = {"Files"}, summary = "Move a file or directory")
public void move(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The internal storage uri to move from") @Qu... | @Test
void move() throws IOException {
storageInterface.createDirectory(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test")));
client.toBlocking().exchange(HttpRequest.PUT("/api/v1/namespaces/" + NAMESPACE + "/files?from=/test&to=/foo", null));
FileAttributes res = storageInterface.g... |
public static Method getApplyMethod(ScalarFn scalarFn) {
Class<? extends ScalarFn> clazz = scalarFn.getClass();
Collection<Method> matches =
ReflectHelpers.declaredMethodsWithAnnotation(
ScalarFn.ApplyMethod.class, clazz, ScalarFn.class);
if (matches.isEmpty()) {
throw new Illegal... | @Test
public void testNonPublicMethodThrowsIllegalArgumentException() {
thrown.expect(instanceOf(IllegalArgumentException.class));
thrown.expectMessage("not public");
ScalarFnReflector.getApplyMethod(new IncrementFnWithProtectedMethod());
} |
@Override
public String toString() {
return name;
} | @Test
void testToString() {
List.of("Gandalf", "Dumbledore", "Oz", "Merlin")
.forEach(name -> assertEquals(name, new Wizard(name).toString()));
} |
@VisibleForTesting
void doClean(String rootUuid, List<Filter> filters, DbSession session) {
List<PurgeableAnalysisDto> history = new ArrayList<>(selectAnalysesOfComponent(rootUuid, session));
for (Filter filter : filters) {
filter.log();
List<PurgeableAnalysisDto> toDelete = filter.filter(history)... | @Test
void doClean() {
PurgeDao dao = mock(PurgeDao.class);
DbSession session = mock(DbSession.class);
when(dao.selectProcessedAnalysisByComponentUuid("uuid_123", session)).thenReturn(Arrays.asList(
new PurgeableAnalysisDto().setAnalysisUuid("u999").setDate(System2.INSTANCE.now()),
new Purgeab... |
public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit)
{
if (isClosed)
{
return 0;
}
int fragmentsRead = 0;
long initialPosition = subscriberPosition.get();
int initialOffset = (int)initialPosition & termLengthMask;
... | @Test
void shouldPollFragmentsToControlledFragmentHandlerOnContinue()
{
final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID);
position.setOrdered(initialPosition);
final Image image = createImage();
insertDataFrame(INITIAL_TER... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof MirroringName) {
final MirroringName that = (MirroringName) obj;
return this.getClass() == that.getClass() &&
Objects.equals(this.name, t... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(name1, sameAsName1)
.addEqualityGroup(name2)
.testEquals();
} |
@Override
public boolean isTenantIdSet() {
return tenantId.get() != null;
} | @Test
void isTenantIdSet() {
assertThat(underTest.isTenantIdSet()).isFalse();
underTest.setTenantId("flowable");
assertThat(underTest.isTenantIdSet()).isTrue();
underTest.clearTenantId();
assertThat(underTest.isTenantIdSet()).isFalse();
underTest.setTenantId(null);... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testLessThan() {
Evaluator evaluator = new Evaluator(STRUCT, lessThan("x", 7));
assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null, null))).as("7 < 7 => false").isFalse();
assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null, null))).as("6 < 7 => true").isTrue();
Evaluator s... |
@Override
public Map<String, String> getHeaders(ConnectorSession session)
{
if (isUseIdentityThriftHeader(session)) {
return ImmutableMap.of(PRESTO_CONNECTOR_IDENTITY_USER, session.getUser());
}
return ImmutableMap.of();
} | @Test
public void testWithIdentityHeaders()
{
ThriftConnectorConfig config = new ThriftConnectorConfig()
.setUseIdentityThriftHeader(true);
ThriftSessionProperties properties = new ThriftSessionProperties(config);
TestingConnectorSession session = new TestingConnectorSess... |
public static URI getURIFromRequestUrl(String source) {
// try without encoding the URI
try {
return new URI(source);
} catch (URISyntaxException ignore) {
System.out.println("Source is not encoded, encoding now");
}
try {
URL url = new URL(sou... | @Test
public void testGetURIFromRequestUrlShouldEncode() {
final String testUrl = "http://example.com/this is not encoded";
final String expected = "http://example.com/this%20is%20not%20encoded";
assertEquals(expected, UriUtil.getURIFromRequestUrl(testUrl).toString());
} |
public Map<Service, ServiceMetadata> getServiceMetadataSnapshot() {
ConcurrentMap<Service, ServiceMetadata> result = new ConcurrentHashMap<>(serviceMetadataMap.size());
result.putAll(serviceMetadataMap);
return result;
} | @Test
void testGetServiceMetadataSnapshot() {
Map<Service, ServiceMetadata> serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot();
assertEquals(1, serviceMetadataSnapshot.size());
} |
@Override
public Response cancelDelegationToken(HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException, Exception {
try {
// get Caller UserGroupInformation
Configuration conf = federationFacade.getConf();
UserGroupInformation callerUGI = getKerberosUserGr... | @Test
public void testCancelDelegationToken() throws Exception {
DelegationToken token = new DelegationToken();
token.setRenewer(TEST_RENEWER);
Principal principal = mock(Principal.class);
when(principal.getName()).thenReturn(TEST_RENEWER);
HttpServletRequest request = mock(HttpServletRequest.cl... |
@Override
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
AuthPaginationHelper<PermissionInfo> helper = createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM permissions WHERE ";
String sqlFetchRows = "SELECT role,resource,action F... | @Test
void testGetPermissions() {
Page<PermissionInfo> role = externalPermissionPersistService.getPermissions("role", 1, 10);
assertNotNull(role);
} |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(d... | @Test
public void speedOnly() {
// 50km/h -> 72s per km, 100km/h -> 36s per km
EdgeIteratorState edge = graph.edge(0, 1).setDistance(1000).set(avSpeedEnc, 50, 100);
CustomModel customModel = createSpeedCustomModel(avSpeedEnc)
.setDistanceInfluence(0d);
Weighting weigh... |
public static ParseResult parse(String text) {
Map<String, String> localProperties = new HashMap<>();
String intpText = "";
String scriptText = null;
Matcher matcher = REPL_PATTERN.matcher(text);
if (matcher.find()) {
String headingSpace = matcher.group(1);
intpText = matcher.group(2);
... | @Test
void testCassandra() {
ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse(
"%cassandra(locale=ru_RU, timeFormat=\"E, d MMM yy\", floatPrecision = 5, output=cql)\n"
+ "select * from system_auth.roles;");
assertEquals("cassandra", parseResult.getIntpTex... |
public static void refreshTargetServiceInstances(String serviceName) {
refreshTargetServiceInstances(serviceName, null);
} | @Test
public void refreshTargetServiceInstances() {
try (final MockedStatic<PluginConfigManager> pluginConfigManagerMockedStatic = Mockito.mockStatic(PluginConfigManager.class);){
pluginConfigManagerMockedStatic.when(() -> PluginConfigManager.getPluginConfig(GraceConfig.class))
... |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testCharLiteralFromJLS() {
assertThat( getLiteral( char.class.getCanonicalName(), "'a'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'%'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\t'" ) ).isNotNull();
ass... |
public final Logger getLogger(final Class<?> clazz) {
return getLogger(clazz.getName());
} | @Test
public void testStatusWithUnconfiguredContext() {
Logger logger = lc.getLogger(LoggerContextTest.class);
for (int i = 0; i < 3; i++) {
logger.debug("test");
}
logger = lc.getLogger("x.y.z");
for (int i = 0; i < 3; i++) {
logger.debug("test");
... |
@GetMapping("/apps")
public List<AppDTO> find(@RequestParam(value = "name", required = false) String name,
Pageable pageable) {
List<App> app = null;
if (StringUtils.isBlank(name)) {
app = appService.findAll(pageable);
} else {
app = appService.findByName(name);
... | @Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFind() {
AppDTO dto = generateSampleDTOData();
App app = BeanUtils.transform(App.class, dto);
app = appRepository.save(app);
AppDTO result = restTemplate.getForObject(getBaseAppUrl() +... |
@Override
public DefaultLogicalVertex getProducer() {
return vertexRetriever.apply(intermediateDataSet.getProducer().getID());
} | @Test
public void testGetProducer() {
assertVertexInfoEquals(producerVertex, logicalResult.getProducer());
} |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testUnderscorePlacement1() {
assertThat( getLiteral( long.class.getCanonicalName(), "1234_5678_9012_3456L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "999_99_9999L" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "3.14_1... |
public static <T> CompressedSerializedValue<T> fromBytes(byte[] compressedSerializedData) {
return new CompressedSerializedValue<>(compressedSerializedData);
} | @Test
void testFromEmptyBytes() {
assertThatThrownBy(() -> CompressedSerializedValue.fromBytes(new byte[0]))
.isInstanceOf(IllegalArgumentException.class);
} |
@Override
public short getTypeCode() {
return MessageType.TYPE_SEATA_MERGE;
} | @Test
public void getTypeCode() {
MergedWarpMessage mergedWarpMessage = new MergedWarpMessage();
assertThat(mergedWarpMessage.getTypeCode()).isEqualTo(MessageType.TYPE_SEATA_MERGE);
} |
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
... | @Test
public void testMergeAclEntriesEmptyAclSpec() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ_WRITE))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, MASK, ALL)... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final CloudBlobContainer container = session.getClient().getContainerReference(containerService.getContainer(directory).getName());
final Attribute... | @Test
public void testListLexicographicSortOrderAssumption() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path directory = new AzureDirectoryFeature(session, null).mkdir(
new Path(container, new Alphanumeric... |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeEndpointUriNoParam() throws Exception {
String out1 = URISupport.normalizeUri("direct:foo");
String out2 = URISupport.normalizeUri("direct:foo");
assertEquals(out1, out2);
out1 = URISupport.normalizeUri("direct://foo");
out2 = URISupport.normal... |
Flux<Post> allPosts() {
return client.get()
.uri("/posts")
.accept(MediaType.APPLICATION_JSON)
.exchangeToFlux(response -> response.bodyToFlux(Post.class));
} | @SneakyThrows
@Test
public void testGetAllPosts() {
var data = List.of(
new Post(UUID.randomUUID(), "title1", "content1", Status.DRAFT, LocalDateTime.now()),
new Post(UUID.randomUUID(), "title2", "content2", Status.PUBLISHED, LocalDateTime.now())
);
stubFo... |
@Override
public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) {
return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer);
} | @Test
void testUpdate3() {
List<ModifyRequest> modifyRequests = new ArrayList<>();
ModifyRequest modifyRequest1 = new ModifyRequest();
String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;";
modifyRequest1.setSql(sql);
Object[] args = new Object[] {1};
m... |
@PublicAPI(usage = ACCESS)
public JavaClasses importClasses(Class<?>... classes) {
return importClasses(Arrays.asList(classes));
} | @Test
public void imports_enclosing_method_of_local_class() throws ClassNotFoundException {
@SuppressWarnings("unused")
class ClassCreatingLocalClassInMethod {
void someMethod() {
class SomeLocalClass {
}
}
}
String localClassNa... |
public final <KIn, VIn, KOut, VOut> void addProcessor(final String name,
final ProcessorSupplier<KIn, VIn, KOut, VOut> supplier,
final String... predecessorNames) {
Objects.requireNonNull(name, "n... | @Test
public void testAddProcessorWithBadSupplier() {
final Processor<Object, Object, Object, Object> processor = new MockApiProcessor<>();
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> builder.addProcessor("processor", () ... |
Converter<E> compile() {
head = tail = null;
for (Node n = top; n != null; n = n.next) {
switch (n.type) {
case Node.LITERAL:
addToList(new LiteralConverter<E>((String) n.getValue()));
break;
case Node.COMPOSITE_KEYWORD:
CompositeNode cn = (CompositeNode) n;
... | @Test
public void testUnknownWord() throws Exception {
Parser<Object> p = new Parser<Object>("%unknown");
p.setContext(context);
Node t = p.parse();
p.compile(t, converterMap);
StatusChecker checker = new StatusChecker(context.getStatusManager());
checker
.assertContainsMatch("\\[u... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertChar() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("VARCHAR")
.dataType("VARCHAR")
.length(1L)
.... |
public Encoding encode(String text) { return encode(text, Language.UNKNOWN); } | @Test
void pads_to_max_length() throws IOException {
var builder = new HuggingFaceTokenizer.Builder()
.setTruncation(true)
.addDefaultModel(decompressModelFile(tmp, "bert-base-uncased"))
.addSpecialTokens(true).setMaxLength(32);
String input = "what wa... |
@Override
public void dropPartition(String dbName, String tableName, List<String> partValues, boolean deleteData) {
client.dropPartition(dbName, tableName, partValues, deleteData);
} | @Test
public void testDropPartition() {
HiveMetaClient client = new MockedHiveMetaClient();
HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS);
metastore.dropPartition("db", "table", Lists.newArrayList("k1=1"), false);
} |
@Override
public RLESparseResourceAllocation getAvailableResourceOverTime(String user,
ReservationId oldId, long start, long end, long period)
throws PlanningException {
readLock.lock();
try {
// for non-periodic return simple available resources
if (period == 0) {
// create ... | @Test(expected = PlanningException.class)
public void testOutOfRange() throws PlanningException {
maxPeriodicity = 100;
Plan plan = new InMemoryPlan(queueMetrics, policy, agent, totalCapacity, 1L,
resCalc, minAlloc, maxAlloc, planName, replanner, true, maxPeriodicity,
context, new UTCClock());... |
@Override
public V remove(Object key) {
return execute(key, this::removeKey, null /* default value */);
} | @Test
public void testRemove() {
PartitionMap<String> map = PartitionMap.create(SPECS);
map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v1");
map.put(BY_DATA_SPEC.specId(), Row.of("bbb"), "v2");
map.removeKey(BY_DATA_SPEC.specId(), Row.of("aaa"));
assertThat(map).doesNotContainKey(Pair.of(BY_DAT... |
@Override
protected void updateData(SummaryInfo info, Sample sample) {
// Initialize overall data if they don't exist
SummaryInfo overallInfo = getOverallInfo();
Long overallData = overallInfo.getData();
if (overallData == null) {
overallData = ZERO;
}
ove... | @Test
public void testErrorSampleCounter() {
ErrorsSummaryConsumer consumer = new ErrorsSummaryConsumer();
Sample sample = createSample(false);
AbstractSummaryConsumer<Long>.SummaryInfo info = consumer.new SummaryInfo(false);
assertNull(info.getData());
consumer.updateData(in... |
@VisibleForTesting
public Path getAllocationFile(Configuration conf)
throws UnsupportedFileSystemException {
String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE,
FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE);
Path allocPath = new Path(allocFilePath);
String alloc... | @Test
public void testGetAllocationFileFromClasspath() {
try {
FileSystem fs = FileSystem.get(conf);
conf.set(FairSchedulerConfiguration.ALLOCATION_FILE,
TEST_FAIRSCHED_XML);
AllocationFileLoaderService allocLoader =
new AllocationFileLoaderService(scheduler);
Path allo... |
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
... | @Test
public void testSubmitReservationInvalidRR() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(0, 0, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTest... |
static boolean willCreateNewThreadPool(CamelContext camelContext, DynamicRouterConfiguration cfg, boolean useDefault) {
ObjectHelper.notNull(camelContext.getExecutorServiceManager(), ESM_NAME, camelContext);
return Optional.ofNullable(cfg.getExecutorServiceBean())
.map(esb -> false)
... | @Test
void testWillCreateNewThreadPoolWithExecutorServiceBean() {
when(camelContext.getExecutorServiceManager()).thenReturn(manager);
when(mockConfig.getExecutorServiceBean()).thenReturn(existingThreadPool);
assertFalse(DynamicRouterRecipientListHelper.willCreateNewThreadPool(camelContext, m... |
@Override
public void seek(long position) throws IOException
{
throw new IOException(getClass().getName() + ".seek isn't supported.");
} | @Test
void testSeekEOF() throws IOException
{
byte[] inputValues = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ByteArrayInputStream bais = new ByteArrayInputStream(inputValues);
try (NonSeekableRandomAccessReadInputStream randomAccessSource = new NonSeekableRandomAccessReadInputStream(
... |
public String getRuntimeAndMaybeAddRuntime(final QueryId queryId,
final Collection<String> sourceTopics,
final KsqlConfig config) {
if (idToRuntime.containsKey(queryId)) {
return idToRuntime.get(queryId);
}
final... | @Test
public void shouldNotGetSameRuntimeForDifferentQueryIdAndSameSources() {
final String runtime = runtimeAssignor.getRuntimeAndMaybeAddRuntime(
query2,
sourceTopics1,
KSQL_CONFIG
);
assertThat(runtime, not(equalTo(firstRuntime)));
} |
public String getName() {
return name;
} | @Test
public void testGetName() {
Model instance = new Model();
instance.setName("");
String expResult = "";
String result = instance.getName();
assertEquals(expResult, result);
} |
@Override
public void setSpool(final Writer writer) {
spool.ifPresent(ignored -> {
throw new KsqlException("Cannot set two spools! Please issue SPOOL OFF.");
});
spool = Optional.of(new Spool(writer, terminal.writer()));
} | @Test
public void shouldThrowOnTwoSpools() {
// Given:
final Writer spool = mock(Writer.class);
terminal.setSpool(spool);
// When:
final KsqlException e = assertThrows(
KsqlException.class,
() -> terminal.setSpool(spool)
);
// Then:
assertThat(e.getMessage(), contains... |
@Override
public void initialize(ServiceConfiguration config) throws IOException {
this.allowedAudiences = validateAllowedAudiences(getConfigValueAsSet(config, ALLOWED_AUDIENCES));
this.roleClaim = getConfigValueAsString(config, ROLE_CLAIM, ROLE_CLAIM_DEFAULT);
this.isRoleClaimNotSubject = !... | @Test
public void ensureEmptyIssuersWithK8sTrustedIssuerEnabledPassesInitialization() throws Exception {
@Cleanup
AuthenticationProviderOpenID provider = new AuthenticationProviderOpenID();
Properties props = new Properties();
props.setProperty(AuthenticationProviderOpenID.ALLOWED_AU... |
public long getEndOffset() {
return getEndOffsetFromTopicPartition(commandConsumer, commandTopicPartition);
} | @Test
public void shouldGetEndOffsetCorrectly() {
// Given:
when(commandConsumer.endOffsets(any()))
.thenReturn(Collections.singletonMap(TOPIC_PARTITION, 123L));
// When:
final long endOff = commandTopic.getEndOffset();
// Then:
assertThat(endOff, equalTo(123L));
verify(commandCo... |
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<ResourceNameAndAction> resourceMapping =
requestResourceMapper.getResourceNameAndAction(request);
log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", r... | @Test
void reports_metrics_for_rejected_requests() {
MetricMock metric = new MetricMock();
AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of(), metric, null);
MockResponseHandler responseHandler = new MockResponseHandler();
DiscFilterRequest request = createRe... |
@Override
public synchronized String toString() {
return toStringHelper(ByteKeyRangeTracker.class)
.add("range", range)
.add("position", position)
.toString();
} | @Test
public void testToString() {
ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE);
String expected = String.format("ByteKeyRangeTracker{range=%s, position=null}", INITIAL_RANGE);
assertEquals(expected, tracker.toString());
tracker.tryReturnRecordAt(true, INITIAL_START_KEY);
t... |
@Override
public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception {
Map<String, FeishuSettings> settingsMap = alarmRulesWatcher.getFeishuSettings();
if (settingsMap == null || settingsMap.isEmpty()) {
return;
}
Map<String, List<AlarmMessage>> groupedMessage... | @Test
public void testFeishuWebhookWithSign() throws Exception {
CHECK_SIGN.set(true);
List<FeishuSettings.WebHookUrl> webHooks = new ArrayList<>();
webHooks.add(new FeishuSettings.WebHookUrl(secret, "http://127.0.0.1:" + SERVER.httpPort() + "/feishuhook/receiveAlarm?token=dummy_token"));
... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testToaPbEntry()
{
when(client.getVarbitValue(Varbits.TOA_MEMBER_1_HEALTH)).thenReturn(24);
when(client.getVarbitValue(Varbits.TOA_MEMBER_2_HEALTH)).thenReturn(15);
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Challenge complete: The Wardens. Duration: <col=ef1020>9:40</c... |
protected void mergeAndRevive(ConsumeReviveObj consumeReviveObj) throws Throwable {
ArrayList<PopCheckPoint> sortList = consumeReviveObj.genSortList();
POP_LOGGER.info("reviveQueueId={}, ck listSize={}", queueId, sortList.size());
if (sortList.size() != 0) {
POP_LOGGER.info("reviveQu... | @Test
public void testReviveMsgFromCk_messageFound_writeRetryFailed_rewriteCK_end() throws Throwable {
brokerConfig.setSkipWhenCKRePutReachMaxTimes(true);
PopCheckPoint ck = buildPopCheckPoint(0, 0, 0);
ck.setRePutTimes("17");
PopReviveService.ConsumeReviveObj reviveObj = new PopRevi... |
public void playbackMovie(String movie) {
VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie);
videoStreamingService.doProcessing();
} | @Test
void testBusinessDelegate() {
// setup a client object
var client = new MobileClient(businessDelegate);
// action
client.playbackMovie("Die hard");
// verifying that the businessDelegate was used by client during playbackMovie() method.
verify(businessDelegate).playbackMovie(anyString... |
public BranchStatus branchCommit(String xid, long branchId, String resourceId) {
Phase2Context context = new Phase2Context(xid, branchId, resourceId);
addToCommitQueue(context);
return BranchStatus.PhaseTwo_Committed;
} | @Test
void branchCommit() {
BranchStatus status = worker.branchCommit("test", 0, null);
assertEquals(BranchStatus.PhaseTwo_Committed, status, "should return PhaseTwo_Committed");
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
Long typeDefineLength = typeDefine.getLength();
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.get... | @Test
public void testConvertInt() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("int").dataType("int").build();
Column column = IrisTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.get... |
@Override
public String toString() {
String str = null;
if (allAllowed) {
str = "All users are allowed";
}
else if (users.isEmpty() && groups.isEmpty()) {
str = "No users are allowed";
}
else {
String usersStr = null;
String groupsStr = null;
if (!users.isEmpty()... | @Test
public void testAclString() {
AccessControlList acl;
acl = new AccessControlList("*");
assertThat(acl.toString()).isEqualTo("All users are allowed");
validateGetAclString(acl);
acl = new AccessControlList(" ");
assertThat(acl.toString()).isEqualTo("No users are allowed");
acl = ne... |
@InvokeOnHeader(Web3jConstants.ETH_NEW_BLOCK_FILTER)
void ethNewBlockFilter(Message message) throws IOException {
Request<?, EthFilter> request = web3j.ethNewBlockFilter();
setRequestId(message, request);
EthFilter response = request.send();
boolean hasError = checkForError(message, ... | @Test
public void ethNewBlockFilterTest() throws Exception {
EthFilter response = Mockito.mock(EthFilter.class);
Mockito.when(mockWeb3j.ethNewBlockFilter()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInte... |
@Override
public E next(E reuse) throws IOException {
/* There are three ways to handle object reuse:
* 1) reuse and return the given object
* 2) ignore the given object and return a new object
* 3) exchange the given object for an existing object
*
* The first o... | @Test
void testMergeOfTenStreams() throws Exception {
// iterators
List<MutableObjectIterator<Tuple2<Integer, String>>> iterators = new ArrayList<>();
iterators.add(
newIterator(new int[] {1, 2, 17, 23, 23}, new String[] {"A", "B", "C", "D", "E"}));
iterators.add(
... |
@Override
protected Map<Region, AccountInfo> operate(final PasswordCallback callback, final Path file) throws BackgroundException {
final Map<Region, AccountInfo> accounts = new ConcurrentHashMap<>();
for(Region region : session.getClient().getRegions()) {
try {
final Acc... | @Test
public void testOperate() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
assertFalse(new SwiftAccountLoader(session).operate(new DisabledLoginCallback(), container).isEmpty());
} |
@Override
public void swap(int i, int j) {
final int segmentNumberI = i / this.recordsPerSegment;
final int segmentOffsetI = (i % this.recordsPerSegment) * this.recordSize;
final int segmentNumberJ = j / this.recordsPerSegment;
final int segmentOffsetJ = (j % this.recordsPerSegment)... | @Test
void testSwap() throws Exception {
final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
final List<MemorySegment> memory =
this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
FixedLengthRecordSorter<IntPair> sorter = newSortBuffer(memory);
R... |
@Override
@MethodNotAvailable
public void set(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testSet() {
adapter.set(23, "test");
} |
public static ConfigProperty defineProperty(String name, Type type,
String defaultValue,
String description) {
return new ConfigProperty(name, type, description, defaultValue, defaultValue, false);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(defineProperty("foo", STRING, "bar", "Desc"),
defineProperty("foo", STRING, "goo", "Desc"))
.addEqualityGroup(defineProperty("bar", STRING, "bar", "Desc"),
... |
public static String generateApplyOrDefault(
final String inputCode,
final String mapperCode,
final String defaultValueCode,
final Class<?> returnType
) {
return "(" + returnType.getSimpleName() + ")" + NullSafe.class.getSimpleName()
+ ".applyOrDefault(" + inputCode + "," + mapperC... | @Test
public void shouldGenerateApplyOrDefault() {
// Given:
final String mapperCode = LambdaUtil
.toJavaCode("val", Long.class, "val.longValue() + 1");
// When:
final String javaCode = NullSafe
.generateApplyOrDefault("arguments.get(\"input\")", mapperCode, "99L", Long.class);
/... |
@Operation(summary = "Get single certificate")
@GetMapping(value = "{id}", produces = "application/json")
@ResponseBody
public Certificate getById(@PathVariable("id") Long id) {
return certificateService.getCertificate(id);
} | @Test
public void getCertificateById() {
when(certificateServiceMock.getCertificate(anyLong())).thenReturn(getCertificate());
Certificate result = controllerMock.getById(anyLong());
verify(certificateServiceMock, times(1)).getCertificate(anyLong());
assertEquals("test", result.getC... |
@Override
public R get(Object key) {
if (key instanceof Integer) {
int n = (Integer) key;
return get(n);
}
return super.get(key);
} | @Test
public void lookupWithBogusKeyType() {
assertNull(a.get(null));
// don't inline, otherwise some IDEs will immediately complain about the wrong key type
Object badKey = "foo";
assertNull(a.get(badKey));
badKey = this;
assertNull(a.get(badKey));
} |
public static double find(Function func, double x1, double x2, double tol, int maxIter) {
if (tol <= 0.0) {
throw new IllegalArgumentException("Invalid tolerance: " + tol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid maximum number of iterations: " ... | @Test
public void testNewton() {
System.out.println("Newton");
Function func = new DifferentiableFunction() {
@Override
public double f(double x) {
return x * x * x + x * x - 5 * x + 3;
}
@Override
public double g(double x... |
public void useBundles(List<String> bundlePaths) {
if (hasLoadedBundles) {
log.log(Level.FINE, () -> "Platform bundles have already been installed." +
"\nInstalled bundles: " + installedBundles +
"\nGiven files: " + bundlePaths);
return;
}
... | @Test
void bundles_are_installed_and_started() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
assertEquals(1, osgi.getInstalledBundles().size());
// The bundle is installed and started
TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0);
assertEqua... |
public Mono<Void> createProducerAcl(KafkaCluster cluster, CreateProducerAclDTO request) {
return adminClientService.get(cluster)
.flatMap(ac -> createAclsWithLogging(ac, createProducerBindings(request)))
.then();
} | @Test
void createsProducerDependantAcls() {
ArgumentCaptor<Collection<AclBinding>> createdCaptor = ArgumentCaptor.forClass(Collection.class);
when(adminClientMock.createAcls(createdCaptor.capture()))
.thenReturn(Mono.empty());
var principal = UUID.randomUUID().toString();
var host = UUID.rand... |
public Map<String, String> parse(String body) {
final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder();
final String[] lines = body.split(lineSeparator);
for (String line : lines) {
if (line.startsWith(this.ignorechar)) {
continue;
... | @Test
public void parseQuotedStrings() throws Exception {
final String input = "# Sample file for testing\n" +
"\"foo\":\"23\"\n" +
"\"bar\":\"42\"\n" +
"\"baz\":\"17\"\n" +
"\"qux\":\"42:23\"\n" +
"\"qu:ux\":\"42\"";
fi... |
@Override
public void truncate(SequenceNumber to) {
LOG.debug("truncate {} to sqn {} (excl.)", logId, to);
checkArgument(to.compareTo(activeSequenceNumber) <= 0);
lowestSequenceNumber = to;
notUploaded.headMap(lowestSequenceNumber, false).clear();
Map<SequenceNumber, UploadR... | @Test
void testTruncate() {
assertThatThrownBy(
() ->
withWriter(
(writer, uploader) -> {
SequenceNumber sqn = append(writer, getBytes());
... |
static String getConfigValueAsString(ServiceConfiguration conf,
String configProp) throws IllegalArgumentException {
String value = getConfigValueAsStringImpl(conf, configProp);
log.info("Configuration for [{}] is [{}]", configProp, value);
return ... | @Test
public void testGetConfigValueAsStringWithDefaultWorks() {
Properties props = new Properties();
props.setProperty("prop1", "audience");
ServiceConfiguration config = new ServiceConfiguration();
config.setProperties(props);
String actual = ConfigUtils.getConfigValueAsStr... |
public int positionBitsToShift()
{
return positionBitsToShift;
} | @Test
void shouldOverridePositionBitsToShift()
{
final int positionBitsToShift = -6;
final int newPositionBitsToShift = 20;
final Header header = new Header(42, positionBitsToShift);
assertEquals(positionBitsToShift, header.positionBitsToShift());
header.positionBitsToSh... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldCloseIterator() {
// When:
table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS);
// Then:
verify(fetchIterator).close();
} |
static int readHeapBuffer(InputStream f, ByteBuffer buf) throws IOException {
int bytesRead = f.read(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
if (bytesRead < 0) {
// if this resulted in EOF, don't update position
return bytesRead;
} else {
buf.position(buf.positio... | @Test
public void testHeapRead() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocate(20);
MockInputStream stream = new MockInputStream();
int len = DelegatingSeekableInputStream.readHeapBuffer(stream, readBuffer);
Assert.assertEquals(10, len);
Assert.assertEquals(10, readBuffer.positi... |
@Override
public Expression getExpression(String tableName, Alias tableAlias) {
// 只有有登陆用户的情况下,才进行数据权限的处理
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
if (loginUser == null) {
return null;
}
// 只有管理员类型的用户,才进行数据权限的处理
if (ObjectUtil.notEqual(... | @Test // 全部数据权限
public void testGetExpression_allDeptDataPermission() {
try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock
= mockStatic(SecurityFrameworkUtils.class)) {
// 准备参数
String tableName = "t_user";
Alias tableAlias = new Alia... |
public static List<String> fromPartitionKey(PartitionKey key) {
// get string value from partitionKey
List<LiteralExpr> literalValues = key.getKeys();
List<String> values = new ArrayList<>(literalValues.size());
for (LiteralExpr value : literalValues) {
if (value instanceof N... | @Test
public void testFromPartitionKey() {
PartitionKey partitionKey = new PartitionKey();
LiteralExpr boolTrue1 = new BoolLiteral(true);
partitionKey.pushColumn(boolTrue1, PrimitiveType.BOOLEAN);
Assert.assertEquals(Lists.newArrayList("true"), fromPartitionKey(partitionKey));
} |
@Override
public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) {
if (!(sqlStatementContext instanceof InsertStatementContext)) {
return false;
}
Optional<InsertColumnsSegment> insertColumnsSegment = ((InsertStatementContext) sqlStatementContext).getSql... | @Test
void assertIsNotGenerateSQLTokenWithNotInsertStatement() {
assertFalse(generator.isGenerateSQLToken(mock(SelectStatementContext.class)));
} |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(co... | @Test
void assertConvertDateValueSuccess() throws SQLException {
Date now = new Date();
assertThat(ResultSetUtils.convertValue(now, Date.class), is(now));
assertThat(ResultSetUtils.convertValue(now, java.sql.Date.class), is(now));
assertThat(ResultSetUtils.convertValue(now, Time.clas... |
public MailConfiguration getConfiguration() {
if (configuration == null) {
configuration = new MailConfiguration(getCamelContext());
}
return configuration;
} | @Test
public void testDefaultPOP3Configuration() {
MailEndpoint endpoint = checkEndpoint("pop3://james@myhost?password=secret");
MailConfiguration config = endpoint.getConfiguration();
assertEquals("pop3", config.getProtocol(), "getProtocol()");
assertEquals("myhost", config.getHost(... |
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
BlockingQueue<Runnable> workQueue = executor.getQueue();
Runnable firstWork = workQueue.poll();
boolean newTaskAdd = workQueue.offer(r);
... | @Test
public void testRejectedExecutionWhenATaskIsInTheQueueTheExecutorShouldNotExecute() {
when(threadPoolExecutor.isShutdown()).thenReturn(false);
when(threadPoolExecutor.getQueue()).thenReturn(workQueue);
when(workQueue.poll()).thenReturn(runnableInTheQueue);
when(workQueue.offer(... |
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request)
throws Exception {
BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder();
BundleProcessor bundleProcessor =
bundleProcessorCache.get(
request,
... | @Test
public void testInstructionIsUnregisteredFromBeamFnDataClientOnSuccess() throws Exception {
BeamFnApi.ProcessBundleDescriptor processBundleDescriptor =
BeamFnApi.ProcessBundleDescriptor.newBuilder()
.putTransforms(
"2L",
RunnerApi.PTransform.newBuilder()
... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testCharSeqValue() {
StructType struct = StructType.of(required(34, "s", Types.StringType.get()));
Evaluator evaluator = new Evaluator(struct, equal("s", "abc"));
assertThat(evaluator.eval(TestHelpers.Row.of(new Utf8("abc"))))
.as("string(abc) == utf8(abc) => true")
.isTr... |
public static TransformerFactory getTransformerFactory() {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
setAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_DTD);
setAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
return trans... | @Test
public void testGetTransformerFactory() {
TransformerFactory transformerFactory = XmlUtil.getTransformerFactory();
assertNotNull(transformerFactory);
assertThrows(IllegalArgumentException.class, () -> XmlUtil.setAttribute(transformerFactory, "test://no-such-property"));
ignoreX... |
public static boolean isStrictProjectionOf(Schema sourceSchema, Schema targetSchema) {
return isProjectionOfInternal(sourceSchema, targetSchema, Objects::equals);
} | @Test
public void testIsStrictProjection() {
Schema sourceSchema = new Schema.Parser().parse(SOURCE_SCHEMA);
Schema projectedNestedSchema = new Schema.Parser().parse(PROJECTED_NESTED_SCHEMA_STRICT);
// Case #1: Validate proper (nested) projected record schema
assertTrue(AvroSchemaUtils.isStrictProje... |
@SuppressWarnings("unchecked")
void unite(final T id1, final T... idList) {
for (final T id2 : idList) {
unitePair(id1, id2);
}
} | @Test
public void testUnite() {
final QuickUnion<Long> qu = new QuickUnion<>();
final long[] ids = {
1L, 2L, 3L, 4L, 5L
};
for (final long id : ids) {
qu.add(id);
}
assertEquals(5, roots(qu, ids).size());
qu.unite(1L, 2L);
a... |
public PullResult processPullResult(final MessageQueue mq, final PullResult pullResult,
final SubscriptionData subscriptionData) {
PullResultExt pullResultExt = (PullResultExt) pullResult;
this.updatePullFromWhichNode(mq, pullResultExt.getSuggestWhichBrokerId());
if (PullStatus.FOUND ==... | @Test
public void testProcessPullResult() throws Exception {
PullResultExt pullResult = mock(PullResultExt.class);
when(pullResult.getPullStatus()).thenReturn(PullStatus.FOUND);
when(pullResult.getMessageBinary()).thenReturn(MessageDecoder.encode(createMessageExt(), false));
Subscrip... |
public SymbolTableMetadata extractMetadata(String fullName)
{
int index = fullName.indexOf(SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR);
// If no separator char was found, we assume it's a local table.
if (index == -1)
{
return new SymbolTableMetadata(null, fullName, false);
}
if (index... | @Test
public void testExtractTableInfoRemoteTable()
{
SymbolTableMetadata metadata =
new SymbolTableMetadataExtractor().extractMetadata("https://Host:100/service|Prefix-1000");
Assert.assertEquals(metadata.getServerNodeUri(), "https://Host:100/service");
Assert.assertEquals(metadata.getSymbolTab... |
public static GestureTrailTheme fromThemeResource(
@NonNull Context askContext,
@NonNull Context themeContext,
@NonNull AddOn.AddOnResourceMapping mapper,
@StyleRes int resId) {
// filling in the defaults
TypedArray defaultValues =
askContext.obtainStyledAttributes(
... | @Test
public void testFromThemeResource() {
GestureTrailTheme underTest =
GestureTrailTheme.fromThemeResource(
ApplicationProvider.getApplicationContext(),
ApplicationProvider.getApplicationContext(),
new AddOn.AddOnResourceMapping() {
@Override
... |
@Nonnull
@Override
public Optional<Mode> parse(
@Nullable final String str, @Nonnull final DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
// get explicit block size
Optional<BlockSize> optionalBlockSize =
... | @Test
void base() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaModeMapper jcaModeMapper = new JcaModeMapper();
Optional<Mode> modeOptional = jcaModeMapper.parse("CCM", testDetectionLocation);
a... |
static ClassDef buildClassDef(
ClassResolver classResolver, Class<?> type, List<Field> fields, boolean isObjectType) {
List<FieldInfo> fieldInfos = buildFieldsInfo(classResolver, fields);
Map<String, List<FieldInfo>> classLayers = getClassFields(type, fieldInfos);
fieldInfos = new ArrayList<>(fieldInf... | @Test
public void testBigMetaEncoding() {
for (Class<?> type :
new Class[] {
MapFields.class, BeanA.class, Struct.createStructClass("TestBigMetaEncoding", 5)
}) {
Fury fury = Fury.builder().withMetaShare(true).build();
ClassDef classDef = ClassDef.buildClassDef(fury, type);
... |
@SuppressWarnings("unchecked")
@Override
public final void remove() {
remove(InternalThreadLocalMap.getIfSet());
} | @Test
void testRemove() {
final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>();
internalThreadLocal.set(1);
Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!");
internalThreadLocal.remove();
Assertions.asser... |
@CheckForNull
@Override
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path projectBaseDir, Set<Path> changedFiles) {
return branchChangedLinesWithFileMovementDetection(targetBranchName, projectBaseDir, toChangedFileByPathsMap(changedFiles));
} | @Test
public void branchChangedLines_returns_empty_set_for_files_with_lines_removed_only() throws GitAPIException, IOException {
String fileName = "file-in-first-commit.xoo";
git.branchCreate().setName("b1").call();
git.checkout().setName("b1").call();
removeLineInFile(fileName, 2);
commit(fileNa... |
public static ShardingSphereDatabase create(final String databaseName, final DatabaseConfiguration databaseConfig,
final ConfigurationProperties props, final ComputeNodeInstanceContext computeNodeInstanceContext) throws SQLException {
return ShardingSphereDatabase... | @Test
void assertCreateSingleDatabase() throws SQLException {
DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.emptyMap(), Collections.emptyList());
ShardingSphereDatabase actual = ExternalMetaDataFactory.create("foo_db", databaseConfig, new Configuratio... |
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) {
validateGroupName(name);
checkNameDoesNotExist(dbSession, name);
GroupDto group = new GroupDto()
.setUuid(uuidFactory.create())
.setName(name)
.setDescription(description);
return gro... | @Test
public void createGroup_whenGroupExist_throws() {
GroupDto group = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME)).thenReturn(Optional.of(group));
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.createGroup(dbSession, GROUP_NA... |
public static List<String> split(@Nullable String input, String delimiter) {
if (isNullOrEmpty(input)) {
return Collections.emptyList();
}
return Stream.of(input.split(delimiter)).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
} | @Test
public void testSplit() {
assertEquals(new ArrayList<>(), StringUtils.split(null, ","));
assertEquals(new ArrayList<>(), StringUtils.split("", ","));
assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b, c", ","));
assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b,, ... |
public boolean cleanupExpiredOffsets(String groupId, List<CoordinatorRecord> records) {
TimelineHashMap<String, TimelineHashMap<Integer, OffsetAndMetadata>> offsetsByTopic =
offsets.offsetsByGroup.get(groupId);
if (offsetsByTopic == null) {
return true;
}
// We e... | @Test
public void testCleanupExpiredOffsets() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
Group group = mock(Group.class);
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder()
.withGroupMetadataManager(grou... |
@Override
public boolean revokeToken(String clientId, String accessToken) {
// 先查询,保证 clientId 时匹配的
OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken);
if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) {
retur... | @Test
public void testRevokeToken_success() {
// 准备参数
String clientId = randomString();
String accessToken = randomString();
// mock 方法(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class).setClientId(clientId);
when(oauth2TokenService.getAc... |
public static void hookIntentGetBroadcast(Context context, int requestCode, Intent intent, int flags) {
hookIntent(intent);
} | @Test
public void hookIntentGetBroadcast() {
PushAutoTrackHelper.hookIntentGetBroadcast(mApplication, 100, MockDataTest.mockJPushIntent(), 100);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.