focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String toJson(MetadataUpdate metadataUpdate) {
return toJson(metadataUpdate, false);
} | @Test
public void testSetSnapshotRefTagToJsonAllFields() {
long snapshotId = 1L;
SnapshotRefType type = SnapshotRefType.TAG;
String refName = "hank";
Integer minSnapshotsToKeep = null;
Long maxSnapshotAgeMs = null;
Long maxRefAgeMs = 1L;
String expected =
"{\"action\":\"set-snapsho... |
public MonitorBuilder address(String address) {
this.address = address;
return getThis();
} | @Test
void address() {
MonitorBuilder builder = MonitorBuilder.newBuilder();
builder.address("address");
Assertions.assertEquals("address", builder.build().getAddress());
} |
@Override
protected void close() {
// FIXME Kafka needs to add a timeout parameter here for us to properly obey the timeout
// passed in
try {
task.stop();
} catch (Throwable t) {
log.warn("Could not stop task", t);
}
taskStopped = true;
... | @Test
public void testMetricsGroup() {
SinkTaskMetricsGroup group = new SinkTaskMetricsGroup(taskId, metrics);
SinkTaskMetricsGroup group1 = new SinkTaskMetricsGroup(taskId1, metrics);
for (int i = 0; i != 10; ++i) {
group.recordRead(1);
group.recordSend(2);
... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeOutRangeScale() {
FunctionTestUtil.assertResultError(ceilingFunction.invoke(BigDecimal.valueOf(1.5), BigDecimal.valueOf(6177)),
InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(ceilingFunction.invoke(BigDecimal.valueOf(1.5)... |
@Override
public ResourceId getCurrentDirectory() {
if (isDirectory()) {
return this;
}
return fromComponents(scheme, getBucket(), key.substring(0, key.lastIndexOf('/') + 1));
} | @Test
public void testGetCurrentDirectory() {
// Tests s3 paths.
assertEquals(
S3ResourceId.fromUri("s3://my_bucket/tmp dir/"),
S3ResourceId.fromUri("s3://my_bucket/tmp dir/").getCurrentDirectory());
// Tests path with unicode.
assertEquals(
S3ResourceId.fromUri("s3://my_bucke... |
public void isEqualTo(@Nullable Object expected) {
standardIsEqualTo(expected);
} | @Test
public void isEqualToWithSameObject() {
Object a = new Object();
Object b = a;
assertThat(a).isEqualTo(b);
} |
public void setCliProperty(final String name, final Object value) {
try {
config = config.with(name, value);
} catch (final ConfigException e) {
terminal.writer().println(e.getMessage());
}
} | @Test
public void shouldThrowOnInvalidCliProperty() {
// When:
console.setCliProperty("FOO", "BAR");
// Then:
assertThat(terminal.getOutputString(),
containsString("Undefined property: FOO. Valid properties are"));
} |
@Bean
public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties,
EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry,
RegistryEventConsumer<Retry> retryRegistryEventConsumer,
@Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCus... | @Test
public void testRetryRegistry() {
InstanceProperties instanceProperties1 = new InstanceProperties();
instanceProperties1.setMaxAttempts(3);
InstanceProperties instanceProperties2 = new InstanceProperties();
instanceProperties2.setMaxAttempts(2);
RetryConfigurationProper... |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws
RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final EndTransactionRequestHeader requestHeader =
(EndTransactionReq... | @Test
public void testProcessRequest_RejectCommitMessage() throws RemotingCommandException {
when(transactionMsgService.commitMessage(any(EndTransactionRequestHeader.class))).thenReturn(createRejectResponse());
RemotingCommand request = createEndTransactionMsgCommand(MessageSysFlag.TRANSACTION_COMMI... |
@Override
public Optional<InetAddress> toInetAddress(String hostOrAddress) {
try {
if (InetAddresses.isInetAddress(hostOrAddress)) {
return Optional.of(InetAddresses.forString(hostOrAddress));
}
return Optional.of(InetAddress.getByName(hostOrAddress));
} catch (UnknownHostException e... | @Test
public void toInetAddress_returns_empty_on_unvalid_IP_and_hostname() {
assertThat(underTest.toInetAddress(randomAlphabetic(32))).isEmpty();
} |
public void setDefault() {
fileName = "file";
extension = "xml";
stepNrInFilename = false;
doNotOpenNewFileInit = false;
dateInFilename = false;
timeInFilename = false;
addToResultFilenames = false;
zipped = false;
splitEvery = 0;
encoding = Const.XML_ENCODING;
nameSpace = ""... | @Test
public void testSetDefault() throws Exception {
XMLOutputMeta xmlOutputMeta = new XMLOutputMeta();
xmlOutputMeta.setDefault();
assertEquals( "file", xmlOutputMeta.getFileName() );
assertEquals( "xml", xmlOutputMeta.getExtension() );
assertFalse( xmlOutputMeta.isStepNrInFilename() );
asse... |
public static double[] rowMeans(double[][] matrix) {
double[] x = new double[matrix.length];
for (int i = 0; i < x.length; i++) {
x[i] = mean(matrix[i]);
}
return x;
} | @Test
public void testRowMeans() {
System.out.println("rowMeans");
double[][] A = {
{0.7220180, 0.07121225, 0.6881997},
{-0.2648886, -0.89044952, 0.3700456},
{-0.6391588, 0.44947578, 0.6240573}
};
double[] r = {0.4938100, -0.2617642, 0.1447914};
... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
try {
final Ds3Client client = new SpectraClientBuilder().wrap(session.getClient(), session.getHost());
final Map<Path, TransferSta... | @Test
public void testDeleteContainer() throws Exception {
final Path container = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.volume, Path.Type.directory));
container.attributes().setRegion("US");
new SpectraDirectoryFeature(session, new SpectraWriteFeature(... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldNotTryToResolveNonStringAttributes() {//this tests replacement doesn't fail when non-string config-attributes are present, and non opt-out annotated
MailHost mailHost = new MailHost("host", 25, "loser", "passwd", true, false, "boozer@loser.com", "root@loser.com");
new ParamRe... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testDefaultMethodIgnoresDefaultImplementation() {
OptionsWithDefaultMethod optsWithDefault =
PipelineOptionsFactory.as(OptionsWithDefaultMethod.class);
assertThat(optsWithDefault.getValue(), nullValue());
optsWithDefault.setValue(12.25);
assertThat(optsWithDefault.getValue()... |
Double calculateMedian(List<Double> durationEntries) {
if (durationEntries.isEmpty()) {
return 0.0;
}
Collections.sort(durationEntries);
int middle = durationEntries.size() / 2;
if (durationEntries.size() % 2 == 1) {
return durationEntries.get(middle);
... | @Test
void calculateMedianOfOddNumberOfEntries() {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
Double result = usageFormatter
.calculateMedian(asList(1.0, 2.0, 3.0));
assertThat(result, is(closeTo(2.0, EPSIL... |
public Set<Path> getAllowedAuxiliaryPaths() {
return allowedAuxiliaryPaths;
} | @Test
public void testAllowedAuxiliaryPaths() throws ValidationException, RepositoryException {
HashMap<String, String> validProperties = new HashMap<>();
validProperties.put("allowed_auxiliary_paths", "/permitted-dir,/another-valid-dir");
PathConfiguration configuration = ConfigurationHelp... |
public Boolean setSeckillEndFlag(long seckillId, String taskId) {
return stringRedisTemplate.opsForValue().setIfAbsent("goodskill:seckill:end:notice" + seckillId + ":" + taskId, "1");
} | @Test
void testSetSeckillEndFlag() {
ValueOperations valueOperations = mock(ValueOperations.class);
when(stringRedisTemplate.opsForValue()).thenReturn(valueOperations);
Boolean result = redisService.setSeckillEndFlag(0L, "1");
Assertions.assertEquals(Boolean.FALSE, result);
} |
@SuppressWarnings("unchecked")
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, CircuitBreaker circuitBreaker,
String methodName) throws Throwable {
CircuitBreakerOperator circuitBreakerOperator = CircuitBreakerOperator.of(circuitBreaker);
Object returnValue = proc... | @Test
public void testRxTypes() throws Throwable {
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava3CircuitBreakerAspectExt
.handle(proceedingJoinPoint, circuitBreaker, "test... |
@SuppressWarnings("OptionalGetWithoutIsPresent")
public StatementExecutorResponse execute(
final ConfiguredStatement<DescribeConnector> configuredStatement,
final SessionProperties sessionProperties,
final KsqlExecutionContext ksqlExecutionContext,
final ServiceContext serviceContext
) {
... | @Test
public void shouldNotWarnClientOnMissingTopicsEndpoint() {
// Given:
when(connectClient.topics(any())).thenReturn(ConnectResponse.failure("not found",
HttpStatus.SC_NOT_FOUND));
// When:
final Optional<KsqlEntity> entity = executor
.execute(describeStatement, mock(SessionPropert... |
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException {
byte[] bytes = pollEntryBytes(timeout);
if (bytes == null) {
return null;
}
return DLQEntry.deserialize(bytes);
} | @Test
public void testWriteReadRandomEventSize() throws Exception {
Event event = new Event(Collections.emptyMap());
int maxEventSize = BLOCK_SIZE * 2; // 64kb
int eventCount = 1024; // max = 1000 * 64kb = 64mb
long startTime = System.currentTimeMillis();
try(DeadLetterQueue... |
@Override
public ActionResult apply(Agent agent, Map<String, String> input) {
log.debug("Fetching url {} for agent {}", input.get("url"), agent.getId());
String url = input.get("url");
if (url == null || url.isEmpty()) {
return errorResult("An error occurred while attempting to ... | @Test
void testApplyWithBrowsingException() {
String url = "http://example.com";
String query = "What is this page about?";
Map<String, String> input = new HashMap<>();
input.put("url", url);
input.put("query", query);
when(browserContext.newPage()).thenReturn(page);... |
@Override
protected void processOptions(LinkedList<String> args)
throws IOException {
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE,
OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN,
OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE,
OPTION_MTIME, OPTION_SIZE, OPTION_A... | @Test
public void processPathDirOrderMtimeYears() throws IOException {
TestFile testfile01 = new TestFile("testDirectory", "testFile01");
TestFile testfile02 = new TestFile("testDirectory", "testFile02");
TestFile testfile03 = new TestFile("testDirectory", "testFile03");
TestFile testfile04 = new Test... |
public static boolean privateKeyMatchesPublicKey(PrivateKey privateKey, PublicKey publicKey) {
byte[] someRandomData = new byte[64];
new Random().nextBytes(someRandomData);
Signature signer = SignatureUtils.createSigner(privateKey);
Signature verifier = SignatureUtils.createVerifier(pub... | @Test
void verifies_matching_cert_and_key() {
KeyPair ecKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair ecKeypairB = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair rsaKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 1024);
KeyPair rsaKeypairB = KeyUti... |
@Override
@MethodNotAvailable
public void close() {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testClose() {
adapter.close();
} |
public Struct put(String fieldName, Object value) {
Field field = lookupField(fieldName);
return put(field, value);
} | @Test
public void testInvalidArrayFieldElements() {
assertThrows(DataException.class,
() -> new Struct(NESTED_SCHEMA).put("array", Collections.singletonList("should fail since elements should be int8s")));
} |
@Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity == null) return;
switch (v.getId()) {
case R.id.ask_for_contact_permissions_action -> enableContactsDictionary();
case R.id.disable_contacts_dictionary -> {
mSharedPref... | @Test
@Config(sdk = Build.VERSION_CODES.TIRAMISU)
public void testHidesNotificationGroupIfNotGrantedButSkipped() {
var fragment = startFragment();
var group = fragment.getView().findViewById(R.id.notification_permission_group);
Assert.assertEquals(View.VISIBLE, group.getVisibility());
View skipLink... |
public static boolean isValidProjectKey(String keyCandidate) {
return VALID_PROJECT_KEY_REGEXP.matcher(keyCandidate).matches();
} | @Test
public void invalid_project_key() {
assertThat(ComponentKeys.isValidProjectKey("0123")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("ab/12")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("코드품질")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("")).isFalse();
asser... |
@Override
public AlterReplicaLogDirsResult alterReplicaLogDirs(Map<TopicPartitionReplica, String> replicaAssignment, final AlterReplicaLogDirsOptions options) {
final Map<TopicPartitionReplica, KafkaFutureImpl<Void>> futures = new HashMap<>(replicaAssignment.size());
for (TopicPartitionReplica repl... | @Test
public void testAlterReplicaLogDirsLogDirNotFound() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
createAlterLogDirsResponse(env, env.cluster().nodeById(0), Errors.NONE, 0);
createAlterLogDirsResponse(env, env.cluster().nodeById(1), Errors.LOG_DIR_NOT_... |
@Override
public FileClient getFileClient(Long id) {
return clientCache.getUnchecked(id);
} | @Test
public void testGetFileClient() {
// mock 数据
FileConfigDO fileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(fileConfig);
// 准备参数
Long id = fileConfig.getId();
// mock 获得 Client
FileClient fileClient = new LocalFileClient(id, new... |
public static Set<Member> selectTargetMembers(Collection<Member> members, Predicate<Member> filter) {
return members.stream().filter(filter).collect(Collectors.toSet());
} | @Test
void testSelectTargetMembers() {
Collection<Member> input = new HashSet<>();
input.add(originalMember);
Member member = buildMember();
member.setIp("2.2.2.2");
input.add(member);
Set<Member> actual = MemberUtil.selectTargetMembers(input, member1 -> member1.getIp... |
@ScalarOperator(ADD)
@SqlType(StandardTypes.SMALLINT)
public static long add(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right)
{
try {
return Shorts.checkedCast(left + right);
}
catch (IllegalArgumentException e) {
throw ... | @Test
public void testAdd()
{
assertFunction("SMALLINT'37' + SMALLINT'37'", SMALLINT, (short) (37 + 37));
assertFunction("SMALLINT'37' + SMALLINT'17'", SMALLINT, (short) (37 + 17));
assertFunction("SMALLINT'17' + SMALLINT'37'", SMALLINT, (short) (17 + 37));
assertFunction("SMALLI... |
public MapConfig setBackupCount(final int backupCount) {
this.backupCount = checkBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test
public void setBackupCount_whenItsZero() {
MapConfig config = new MapConfig();
config.setBackupCount(0);
} |
@Override
public void abortCheckpointOnBarrier(long checkpointId, CheckpointException cause)
throws IOException {
if (isCurrentSyncSavepoint(checkpointId)) {
throw new FlinkRuntimeException("Stop-with-savepoint failed.");
}
subtaskCheckpointCoordinator.abortCheckpoint... | @Test
void testSavepointSuspendedAborted() {
assertThatThrownBy(
() ->
testSyncSavepointWithEndInput(
(task, id) ->
task.abortCheckpointOnBarrier(
... |
public List<RowMetaInterface> getRecommendedIndexes() {
List<RowMetaInterface> indexes = new ArrayList<RowMetaInterface>();
// First index : ID_BATCH if any is used.
if ( isBatchIdUsed() ) {
indexes.add( addFieldsToIndex( getKeyField() ) );
}
// The next index includes : ERRORS, STATUS, TRANS... | @Test
public void getRecommendedIndexes() {
List<RowMetaInterface> indexes = jobLogTable.getRecommendedIndexes();
String[] expected = new String[]{ "JOBNAME", "LOGDATE" };
assertTrue( "No indicies present", indexes.size() > 0 );
boolean found = false;
for ( RowMetaInterface rowMeta : indexes ) {
... |
public MetricSampleCompleteness<G, E> completeness(long from, long to, AggregationOptions<G, E> options) {
_windowRollingLock.lock();
try {
long fromWindowIndex = Math.max(windowIndex(from), _oldestWindowIndex);
long toWindowIndex = Math.min(windowIndex(to), _currentWindowIndex - 1);
if (fromW... | @Test
public void testAggregationOption4() {
MetricSampleAggregator<String, IntegerEntity> aggregator = prepareCompletenessTestEnv();
// Change the option to have 0.5 as minValidEntityGroupRatio. This will exclude window index 3, 4, 20.
AggregationOptions<String, IntegerEntity> options =
new Aggre... |
public void addLongPollingClient(HttpServletRequest req, HttpServletResponse rsp, Map<String, String> clientMd5Map,
int probeRequestSize) {
String noHangUpFlag = req.getHeader(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER);
long start = System.currentTimeMillis();
... | @Test
void testRejectByConnectionLimit() throws Exception {
//mock connection no limit
ConnectionCheckResponse connectionCheckResponse = new ConnectionCheckResponse();
connectionCheckResponse.setSuccess(false);
Mockito.when(connectionControlManager.check(any())).thenReturn(connection... |
public static int getXpForLevel(int level)
{
if (level < 1 || level > MAX_VIRT_LEVEL)
{
throw new IllegalArgumentException(level + " is not a valid level");
}
// XP_FOR_LEVEL[0] is XP for level 1
return XP_FOR_LEVEL[level - 1];
} | @Test(expected = IllegalArgumentException.class)
public void testGetXpForLowLevel()
{
int xp = Experience.getXpForLevel(0);
} |
public static Map<String, String> parseParameters(String rawParameters) {
if (StringUtils.isBlank(rawParameters)) {
return Collections.emptyMap();
}
Matcher matcher = PARAMETERS_PATTERN.matcher(rawParameters);
if (!matcher.matches()) {
return Collections.emptyMap(... | @Test
void testParseParameters() {
String legalStr = "[{key1:value1},{key2:value2}]";
Map<String, String> legalMap = StringUtils.parseParameters(legalStr);
assertEquals(2, legalMap.size());
assertEquals("value2", legalMap.get("key2"));
String str = StringUtils.encodeParamete... |
@Override
public Set<Link> getEgressLinks(ConnectPoint connectPoint) {
checkNotNull(connectPoint, CONNECT_POINT_NULL);
return manager.getVirtualLinks(this.networkId())
.stream()
.filter(link -> (connectPoint.equals(link.dst())))
.collect(Collectors.toS... | @Test(expected = NullPointerException.class)
public void testGetEgressLinksByNullId() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
LinkService linkService = manager.get(virtualN... |
public ZkService chooseService() {
if (zkService != null) {
return zkService;
}
synchronized (this) {
if (zkService == null) {
final String version = lbConfig.getZkServerVersion();
if (version.startsWith(VERSION_34_PREFIX)) {
... | @Test(expected = IllegalArgumentException.class)
public void chooseServiceWithNoVersion() {
lbConfig.setZkServerVersion("9.9.9");
final ZkServiceManager zkServiceManager = new ZkServiceManager();
zkServiceManager.chooseService();
} |
public static Object decodeToJson(ExecutionContext ctx, List<Byte> bytesList) throws IOException {
return TbJson.parse(ctx, bytesToString(bytesList));
} | @Test
public void parseStringDecodeToJson() throws IOException {
String expectedStr = "{\"hello\": \"world\"}";
ExecutionHashMap<String, Object> expectedJson = new ExecutionHashMap<>(1, ctx);
expectedJson.put("hello", "world");
Object actualJson = TbUtils.decodeToJson(ctx, expectedSt... |
@Override
public CodegenTableDO getCodegenTable(Long id) {
return codegenTableMapper.selectById(id);
} | @Test
public void testGetCodegenTable() {
// mock 数据
CodegenTableDO tableDO = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene()));
codegenTableMapper.insert(tableDO);
// 准备参数
Long id = tableDO.getId();
// 调用
CodegenTableDO res... |
@Override
public int getPartitionId() {
return partitionId;
} | @Test
public void testGetPartitionId() {
assertEquals(1, batchEventData.getPartitionId());
assertEquals(1, batchEventDataSameAttribute.getPartitionId());
assertEquals(1, batchEventDataOtherSource.getPartitionId());
assertEquals(2, batchEventDataOtherPartitionId.getPartitionId());
... |
public AnnouncerHostPrefixGenerator(String hostName)
{
if (hostName == null)
{
_hostName = null;
}
else
{
// Since just want to use the machine name for pre-fix and not the entire FQDN to reduce the size of name
int machineNameEndIndex = hostName.indexOf('.');
_hostName = m... | @Test(dataProvider = "prefixGeneratorDataProvider")
public void testAnnouncerHostPrefixGenerator(String hostName, String expectedPrefix)
{
AnnouncerHostPrefixGenerator prefixGenerator = new AnnouncerHostPrefixGenerator(hostName);
String actualPrefix = prefixGenerator.generatePrefix();
Assert.assertEqual... |
public static Tags fromString(String tagsString) {
if (tagsString == null || tagsString.isBlank()) return empty();
return new Tags(Set.of(tagsString.trim().split(" +")));
} | @Test
public void testDeserialization() {
assertEquals(new Tags(Set.of("tag1", "tag2")), Tags.fromString(" tag1 tag2 "));
} |
@Override
public Iterator<String> iterator() {
return Arrays.asList(getPathComponents()).iterator();
} | @Test
public void testIterator() {
List<String> queuePathCollection = ImmutableList.copyOf(TEST_QUEUE_PATH.iterator());
List<String> queuePathWithEmptyPartCollection = ImmutableList.copyOf(
QUEUE_PATH_WITH_EMPTY_PART.iterator());
List<String> rootPathCollection = ImmutableList.copyOf(ROOT_PATH.ite... |
public static String getSIntA( int... intA ) {
//
String Info = "";
//
if ( intA == null ) return "?";
if ( intA.length == 0 ) return "?";
//
for ( int K = 0; K < intA.length; K ++ ) {
//
Info += ( Info.isEmpty() )? "" : ", ";
Info += BTools.getSInt( intA[ K ] );
}
//
return Info;
... | @Test
public void testgetSIntA() throws Exception {
//
assertEquals( "?", BTools.getSIntA( null ) );
assertEquals( "?", BTools.getSIntA( ) );
assertEquals( "0", BTools.getSIntA( 0 ) );
assertEquals( "5, 6, 7", BTools.getSIntA( 5, 6, 7 ) );
int[] intA = { 2, 3, 4, 5, 6 };
assertEquals( "2, 3, 4, 5, 6", B... |
public Resource getIncrementAllocation() {
Long memory = null;
Integer vCores = null;
Map<String, Long> others = new HashMap<>();
ResourceInformation[] resourceTypes = ResourceUtils.getResourceTypesArray();
for (int i=0; i < resourceTypes.length; ++i) {
String name = resourceTypes[i].getName()... | @Test
public void testAllocationIncrementCustomResource() {
try {
initResourceTypes();
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RESOURCE_TYPES + ".a-custom-resource" +
FairSchedulerConfiguration.INCREMENT_ALLOCATION, "10");
FairSchedulerConfiguration f... |
public ReferenceBuilder<T> client(String client) {
this.client = client;
return getThis();
} | @Test
void client() {
ReferenceBuilder builder = new ReferenceBuilder();
builder.client("client");
Assertions.assertEquals("client", builder.build().getClient());
} |
@Override
public List<Class<? extends Event>> subscribeTypes() {
return new LinkedList<>(interestedEvents.keySet());
} | @Test
void testSubscribeTypes() {
List<Class<? extends Event>> actual = combinedTraceSubscriber.subscribeTypes();
assertEquals(10, actual.size());
assertTrue(actual.contains(RegisterInstanceTraceEvent.class));
assertTrue(actual.contains(DeregisterInstanceTraceEvent.class));
a... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testArrayOnLhs() {
run(
"match [] == '#[]'"
);
} |
public final void isLessThan(int other) {
isLessThan((double) other);
} | @Test
public void isLessThan_int() {
expectFailureWhenTestingThat(2.0).isLessThan(2);
assertThat(2.0).isLessThan(3);
} |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testGettersAnnotatedWithInconsistentDefaultValue() throws Exception {
// Initial construction is valid.
GetterWithDefault options = PipelineOptionsFactory.as(GetterWithDefault.class);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
... |
public static Font createFont() {
return new Font(null);
} | @Test
public void createFontTest(){
final Font font = FontUtil.createFont();
assertNotNull(font);
} |
@Override
public boolean dropNamespace(Namespace namespace) {
if (!isValidateNamespace(namespace)) {
return false;
}
try {
clients.run(client -> {
client.dropDatabase(namespace.level(0),
false /* deleteData */,
false /* ignoreUnknownDb */,
false /* ... | @Test
public void dropNamespace() {
Namespace namespace = Namespace.of("dbname_drop");
TableIdentifier identifier = TableIdentifier.of(namespace, "table");
Schema schema = getTestSchema();
catalog.createNamespace(namespace, meta);
catalog.createTable(identifier, schema);
Map<String, String> n... |
private void syncFromAddressUrl() throws Exception {
RestResult<String> result = restTemplate
.get(addressServerUrl, Header.EMPTY, Query.EMPTY, genericType.getType());
if (result.ok()) {
isAddressServerHealth = true;
Reader reader = new StringReader(result.getData... | @Test
void testSyncFromAddressUrl() throws Exception {
RestResult<String> result = restTemplate.get(addressServerUrl, Header.EMPTY, Query.EMPTY, genericType.getType());
assertEquals("1.1.1.1:8848", result.getData());
} |
@Override
public int indexOf(int fromIndex, int toIndex, byte value) {
if (fromIndex <= toIndex) {
return ByteBufUtil.firstIndexOf(this, fromIndex, toIndex, value);
}
return ByteBufUtil.lastIndexOf(this, fromIndex, toIndex, value);
} | @Test
public void testIndexOf() {
buffer.clear();
// Ensure the buffer is completely zero'ed.
buffer.setZero(0, buffer.capacity());
buffer.writeByte((byte) 1);
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 3);
buffer.writeByte((byte) 2);
buffer.... |
public static <S> S loadFirst(final Class<S> clazz) {
final ServiceLoader<S> loader = loadAll(clazz);
final Iterator<S> iterator = loader.iterator();
if (!iterator.hasNext()) {
throw new IllegalStateException(String.format(
"No implementation defined in /META-INF/... | @Test
public void testLoadFirstNoDefined() {
assertThrows(IllegalStateException.class, () -> SpiLoadFactory.loadFirst(List.class));
} |
protected DurationSerializer() {
super(Duration.class);
} | @Test
void testDurationSerializer() throws IOException {
Duration duration = Duration.ofNanos(323567890098765L);
JsonGenerator jsonGenerator = mock(JsonGenerator.class);
durationSerializer.serialize(duration, jsonGenerator, null);
ArgumentCaptor<String> argumentCaptor = ArgumentCap... |
protected boolean setActive(String appName) {
try {
File active = appFile(appName, "active");
createParentDirs(active);
return active.createNewFile() && updateTime(appName);
} catch (IOException e) {
log.warn("Unable to mark app {} as active", appName, e);... | @Test(expected = ApplicationException.class)
@Ignore("No longer needed")
public void setBadActive() throws IOException {
aar.setActive("org.foo.BAD");
} |
public <T extends Output<T>> void save(Path csvPath, Dataset<T> dataset, String responseName) throws IOException {
save(csvPath, dataset, Collections.singleton(responseName));
} | @Test
public void testSave() throws IOException {
URL path = CSVSaverTest.class.getResource("/org/tribuo/data/csv/test.csv");
Set<String> responses = Collections.singleton("RESPONSE");
//
// Load the csv
CSVLoader<MockOutput> loader = new CSVLoader<>(new MockOutputFactory());... |
@Override
public ExecuteContext onThrow(ExecuteContext context) {
ThreadLocalUtils.removeRequestTag();
return context;
} | @Test
public void testOnThrow() {
ThreadLocalUtils.addRequestTag(Collections.singletonMap("bar", Collections.singletonList("foo")));
Assert.assertNotNull(ThreadLocalUtils.getRequestTag());
// Test the onThrow method to verify if thread variables are released
interceptor.onThrow(cont... |
@Override
public Decorator findById(String decoratorId) throws NotFoundException {
final Decorator result = coll.findOneById(decoratorId);
if (result == null) {
throw new NotFoundException("Decorator with id " + decoratorId + " not found.");
}
return result;
} | @Test
public void findByIdThrowsNotFoundExceptionForMissingDecorator() throws NotFoundException {
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Decorator with id 588bcafebabedeadbeef0001 not found.");
decoratorService.findById("588bcafebabedeadbeef0001"... |
public void run(String[] args) {
if (!parseArguments(args)) {
showOptions();
return;
}
if (command == null) {
System.out.println("Error: Command is empty");
System.out.println();
showOptions();
return;
}
if ... | @Test
public void testMissingInput() {
Main main = new Main();
assertDoesNotThrow(() -> main.run("-c encrypt -p secret".split(" ")));
} |
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
JsonNode jsonValue;
// This handles a tombstone message
if (value == null) {
return SchemaAndValue.NULL;
}
try {
jsonValue = deserializer.deserialize(topic, value);
}... | @Test
public void arrayToConnect() {
byte[] arrayJson = "{ \"schema\": { \"type\": \"array\", \"items\": { \"type\" : \"int32\" } }, \"payload\": [1, 2, 3] }".getBytes();
assertEquals(new SchemaAndValue(SchemaBuilder.array(Schema.INT32_SCHEMA).build(), Arrays.asList(1, 2, 3)), converter.toConnectDat... |
public Duration cacheMaxTimeToLive() {
return cacheMaxTimeToLive;
} | @Test
void cacheMaxTimeToLive() {
assertThat(builder.build().cacheMaxTimeToLive()).isEqualTo(DEFAULT_CACHE_MAX_TIME_TO_LIVE);
Duration cacheMaxTimeToLive = Duration.ofSeconds(5);
builder.cacheMaxTimeToLive(cacheMaxTimeToLive);
assertThat(builder.build().cacheMaxTimeToLive()).isEqualTo(cacheMaxTimeToLive);
} |
@Override
public InterpreterResult interpret(final String st, final InterpreterContext context)
throws InterpreterException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("st:\n{}", st);
}
final FormType form = getFormType();
RemoteInterpreterProcess interpreterProcess = null;
try {
... | @Test
void testFailToLaunchInterpreterProcess_ErrorInRunner() {
try {
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER.getVarName(),
zeppelinHome.getAbsolutePath() + "/zeppelin-zengine/src/test/resources/bin/interpreter_invalid.sh");
final Interpreter... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeRuntimeFlags() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("runtimeFlags", "-Dfoo=bar2");
FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig... |
@Override
public Integer addAndGetRevRank(double score, V object) {
return get(addAndGetRevRankAsync(score, object));
} | @Test
public void testAddAndGetRevRank() {
RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple");
Integer res = set.addAndGetRevRank(0.3, 1);
assertThat(res).isEqualTo(0);
Integer res2 = set.addAndGetRevRank(0.4, 2);
assertThat(res2).isEqualTo(0);
Inte... |
@Override
public String toString() { return toString(false); } | @Test
void testToString() {
assertEquals("HTTP 200/OK", new HttpResult().setContent("Foo").toString());
assertEquals("HTTP 200/OK\n\nFoo", new HttpResult().setContent("Foo").toString(true));
assertEquals("HTTP 200/OK", new HttpResult().toString(true));
assertEquals("HTTP 200/OK", new... |
@SuppressWarnings("deprecation")
public static void setClasspath(Map<String, String> environment,
Configuration conf) throws IOException {
boolean userClassesTakesPrecedence =
conf.getBoolean(MRJobConfig.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, false);
String classpathEnvVar =
conf.getBoolean(M... | @Test
@Timeout(120000)
public void testSetClasspathWithJobClassloader() throws IOException {
Configuration conf = new Configuration();
conf.setBoolean(MRConfig.MAPREDUCE_APP_SUBMISSION_CROSS_PLATFORM, true);
conf.setBoolean(MRJobConfig.MAPREDUCE_JOB_CLASSLOADER, true);
Map<String, String> env = new ... |
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
boolean cancelled = original.cancel(mayInterruptIfRunning);
try {
return peel().cancel(mayInterruptIfRunning);
} catch (CancellationException e) {
// ignore; cancelled before scheduled-in
ign... | @Test
public void cancel_twice() {
ScheduledFuture<Future<Integer>> original = taskScheduler.schedule(new SimpleCallableTestTask(), 10, TimeUnit.SECONDS);
ScheduledFuture stripper = new DelegatingScheduledFutureStripper<Future<Integer>>(original);
stripper.cancel(true);
stripper.can... |
public void resetOffsetsTo(final Consumer<byte[], byte[]> client,
final Set<TopicPartition> inputTopicPartitions,
final Long offset) {
final Map<TopicPartition, Long> endOffsets = client.endOffsets(inputTopicPartitions);
final Map<TopicPartit... | @Test
public void testResetToSpecificOffsetWhenAfterEndOffset() {
final Map<TopicPartition, Long> endOffsets = new HashMap<>();
endOffsets.put(topicPartition, 3L);
consumer.updateEndOffsets(endOffsets);
final Map<TopicPartition, Long> beginningOffsets = new HashMap<>();
begi... |
@Override
public Object pageListService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize,
String instancePattern, boolean ignoreEmptyService) throws NacosException {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
List<ServiceView> serviceViews =... | @Test
void testPageListServiceNotSpecifiedName() throws NacosException {
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHosts(Collections.singletonList(new Instance()));
Mockito.when(serviceStorage.getData(Mockito.any())).thenReturn(serviceInfo);
ServiceMetadata metadata... |
protected boolean shouldOverwrite( OverwritePrompter prompter, Props props, String message, String rememberMessage ) {
boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false;
boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : tru... | @Test
public void testShouldOverwrite() {
assertTrue( meta.shouldOverwrite( null, null, null, null ) );
Props.init( Props.TYPE_PROPERTIES_EMPTY );
assertTrue( meta.shouldOverwrite( null, Props.getInstance(), "message", "remember" ) );
Props.getInstance().setProperty( Props.STRING_ASK_ABOUT_REPLACING_... |
@Override
public boolean isDetected() {
// https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project
// JENKINS_URL is not enough to identify Jenkins. It can be easily used on a non-Jenkins job.
return isNotBlank(system.envVariable("JENKINS_URL")) && isNotBlank(system.envVariable("EXECUTOR_N... | @Test
public void isDetected() {
setEnvVariable("JENKINS_URL", "http://foo");
setEnvVariable("EXECUTOR_NUMBER", "12");
assertThat(underTest.isDetected()).isTrue();
setEnvVariable("JENKINS_URL", null);
setEnvVariable("EXECUTOR_NUMBER", "12");
assertThat(underTest.isDetected()).isFalse();
... |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchInt8() {
assertThrows(DataException.class,
() -> ConnectSchema.validateValue(Schema.INT8_SCHEMA, 1));
} |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastStringRoundDown() {
// When:
final BigDecimal decimal = DecimalUtil.cast("1.12", 2, 1);
// Then:
assertThat(decimal, is(new BigDecimal("1.1")));
} |
public static HttpResponseStatus parseLine(CharSequence line) {
return (line instanceof AsciiString) ? parseLine((AsciiString) line) : parseLine(line.toString());
} | @Test
public void parseLineStringMalformedCodeWithPhrase() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
parseLine("200a foo");
}
});
} |
private static Timestamp fromLong(Long elapsedSinceEpoch, TimestampPrecise precise) throws IllegalArgumentException {
final long seconds;
final int nanos;
switch (precise) {
case Millis:
seconds = Math.floorDiv(elapsedSinceEpoch, (long) THOUSAND);
nanos = (int) Math.floorMod(elapsedSinceEpo... | @Test
void timestampMillisConversionSecondsLowerLimit() throws Exception {
assertThrows(IllegalArgumentException.class, () -> {
TimestampMillisConversion conversion = new TimestampMillisConversion();
long exceeded = (ProtoConversions.SECONDS_LOWERLIMIT - 1) * 1000;
conversion.fromLong(exceeded, ... |
public static <T> ValueOnlyWindowedValueCoder<T> getValueOnlyCoder(Coder<T> valueCoder) {
return ValueOnlyWindowedValueCoder.of(valueCoder);
} | @Test
public void testValueOnlyWindowedValueCoderIsSerializableWithWellKnownCoderType() {
CoderProperties.coderSerializable(WindowedValue.getValueOnlyCoder(GlobalWindow.Coder.INSTANCE));
} |
protected ProducerService getProducerService() {
return service;
} | @Test
void testStartDoesNotCreateNewProducerService() {
// setup
testObj.start();
ProducerService expectedService = testObj.getProducerService();
testObj.start();
// act
ProducerService result = testObj.getProducerService();
// assert
assertEquals(ex... |
LoadImbalance updateImbalance() {
clearWorkingImbalance();
updateNewWorkingImbalance();
updateNewFinalImbalance();
printDebugTable();
return imbalance;
} | @Test
public void testUpdateImbalance() throws Exception {
MigratablePipeline owner1Pipeline1 = mock(MigratablePipeline.class);
when(owner1Pipeline1.load()).thenReturn(0L)
.thenReturn(100L);
when(owner1Pipeline1.owner())
.thenReturn(owner1);
loadTracke... |
public static String replaceFirst(String input, String from, String to) {
if (from == null || to == null) {
return input;
}
int pos = input.indexOf(from);
if (pos != -1) {
int len = from.length();
return input.substring(0, pos) + to + input.substring(p... | @Test
public void testReplaceFirst() {
assertEquals("jms:queue:bar", replaceFirst("jms:queue:bar", "foo", "bar"));
assertEquals("jms:queue:bar", replaceFirst("jms:queue:foo", "foo", "bar"));
assertEquals("jms:queue:bar?blah=123", replaceFirst("jms:queue:foo?blah=123", "foo", "bar"));
... |
public void handleSend(HttpServerResponse response, Span span) {
handleFinish(response, span);
} | @Test void handleSend_oneOfResponseError() {
brave.Span span = mock(brave.Span.class);
assertThatThrownBy(() -> handler.handleSend(null, span))
.isInstanceOf(NullPointerException.class)
.hasMessage("response == null");
} |
@Override
public void clear() {
throw MODIFICATION_ATTEMPT_ERROR;
} | @Test
void testClear() throws IOException {
long value = valueState.value();
assertThat(value).isEqualTo(42L);
assertThatThrownBy(() -> valueState.clear())
.isInstanceOf(UnsupportedOperationException.class);
} |
public String getAgentStatusReport(String pluginId, JobIdentifier jobIdentifier, String elasticAgentId, Map<String, String> cluster) {
LOGGER.debug("Processing get plugin status report for plugin: {} with job-identifier: {} with elastic-agent-id: {} and cluster: {}", pluginId, jobIdentifier, elasticAgentId, clu... | @Test
public void shouldTalkToExtensionToGetAgentStatusReport() {
final JobIdentifier jobIdentifier = new JobIdentifier();
elasticAgentPluginRegistry.getAgentStatusReport(PLUGIN_ID, jobIdentifier, "some-id", null);
verify(elasticAgentExtension, times(1)).getAgentStatusReport(PLUGIN_ID, job... |
@Override
public void checkVersion() {
// Does nothing. (Version is always compatible since it's in memory)
} | @Test
public void checkVersion() {
try {
confStore.checkVersion();
} catch (Exception e) {
fail("checkVersion threw exception");
}
} |
@Override
public Optional<ResultDecorator<EncryptRule>> newInstance(final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database,
final EncryptRule encryptRule, final ConfigurationProperties props, final SQLStatementContext sqlStatementCo... | @Test
void assertNewInstanceWithOtherStatement() {
EncryptResultDecoratorEngine engine = (EncryptResultDecoratorEngine) OrderedSPILoader.getServices(ResultProcessEngine.class, Collections.singleton(rule)).get(rule);
assertFalse(engine.newInstance(mock(RuleMetaData.class), database, rule, mock(Config... |
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) {
Objects.requireNonNull(pred, "pred cannot be null");
Objects.requireNonNull(columns, "columns cannot be null");
return pred.accept(new StatisticsFilter(columns));
} | @Test
public void testUdp() {
FilterPredicate pred = userDefined(intColumn, SevensAndEightsUdp.class);
FilterPredicate invPred = LogicalInverseRewriter.rewrite(not(userDefined(intColumn, SevensAndEightsUdp.class)));
FilterPredicate udpDropMissingColumn = userDefined(missingColumn2, DropNullUdp.class);
... |
public void registerEndpoint(final Class<?> pojo) {
ShenyuServerEndpoint annotation = AnnotatedElementUtils.findMergedAnnotation(pojo, ShenyuServerEndpoint.class);
if (annotation == null) {
throw new ShenyuException("Class missing annotation ShenyuServerEndpoint! class name: " + pojo.getName... | @Test
public void registerEndpointTest() throws DeploymentException {
exporter.registerEndpoint(pojoWithAnnotation.getClass());
verify(serverContainer).addEndpoint(any(ServerEndpointConfig.class));
} |
public static void main(String[] args) throws InterruptedException {
var taskSet = new TaskSet();
var taskHandler = new TaskHandler();
var workCenter = new WorkCenter();
workCenter.createWorkers(4, taskSet, taskHandler);
execute(workCenter, taskSet);
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public void getMetrics(MetricsCollector collector, boolean all) {
StartupProgressView prog = startupProgress.createView();
MetricsRecordBuilder builder = collector.addRecord(
STARTUP_PROGRESS_METRICS_INFO);
builder.addCounter(info("ElapsedTime", "overall elapsed time"),
prog.getElap... | @Test
public void testInitialState() {
MetricsRecordBuilder builder = getMetrics(metrics, true);
assertCounter("ElapsedTime", 0L, builder);
assertGauge("PercentComplete", 0.0f, builder);
assertCounter("LoadingFsImageCount", 0L, builder);
assertCounter("LoadingFsImageElapsedTime", 0L, builder);
... |
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
checkBackupLevel(backupUser, BackupLevel.MESSAGES);
return backupsDb
// Try to swap out the backupDir for the user
.scheduleBackupDeletion(backupUser)
// If there was already a pending swap, try... | @Test
public void deleteEntireBackup() {
final AuthenticatedBackupUser original = backupUser(TestRandomUtil.nextBytes(16), BackupLevel.MEDIA);
testClock.pin(Instant.ofEpochSecond(10));
// Deleting should swap the backupDir for the user
backupManager.deleteEntireBackup(original).join();
verifyNoI... |
protected List<String> parse(final int response, final String[] reply) {
final List<String> result = new ArrayList<String>(reply.length);
for(final String line : reply) {
// Some servers include the status code for every line.
if(line.startsWith(String.valueOf(response))) {
... | @Test
public void testParse8006() throws Exception {
final List<String> lines = Arrays.asList(
"212-Status of /cgi-bin:",
" drwxr-xr-x 3 1564466 15000 4 Jan 19 19:56 .",
" drwxr-x--- 13 1564466 15000 44 Jun 13 18:36 ..",
" drwxr-xr-x ... |
public static Object[] toArray(Object arrayObj) {
if (arrayObj == null) {
return null;
}
if (!arrayObj.getClass().isArray()) {
throw new ClassCastException("'arrayObj' is not an array, can't cast to Object[]");
}
int length = Array.getLength(arrayObj);
... | @Test
public void testToArray() {
Assertions.assertNull(ArrayUtils.toArray(null));
Object obj = new String[]{"1", "2", "3"};
Object[] array = ArrayUtils.toArray(obj);
Assertions.assertArrayEquals(new String[]{"1", "2", "3"}, array);
Object obj1 = new String[]{};
Obj... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) {
// 校验存在
validateFileConfigExists(id);
// 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新
fileConfigMapper.updateById(new Fi... | @Test
public void testUpdateFileConfigMaster_success() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
FileConfigDO masterFileConfig = randomFileConfigDO().setMaster(true);
fileConfigMa... |
public boolean relaxedOffer(E e) {
return offer(e);
} | @Test(dataProvider = "empty")
public void relaxedOffer_whenEmpty(MpscGrowableArrayQueue<Integer> queue) {
assertThat(queue.relaxedOffer(1)).isTrue();
assertThat(queue).hasSize(1);
} |
@Override
public Page<User> getUsers(int pageNo, int pageSize, String username) {
AuthPaginationHelper<User> helper = createPaginationHelper();
String sqlCountRows = "SELECT count(*) FROM users ";
String sqlFetchRows = "SELECT username,password FROM users ";
... | @Test
void testGetUsers() {
Page<User> users = externalUserPersistService.getUsers(1, 10, "nacos");
assertNotNull(users);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.