focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAME... | @Test
void testInitNamespaceFromJvmNamespaceWithCloudParsing() {
String expect = "jvm_namespace";
System.setProperty(PropertyKeyConst.NAMESPACE, expect);
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String ns = InitUtils.initNamespaceForNaming(pr... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void fabricMissingMinecraft() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/fabric-minecraft.txt")),
CrashReportAnalyzer.Rule.MOD_RESOLUTION_MISSING_MINECRAFT);
assertEquals("fabric",... |
public static List<String> validateJsonMessage(JsonNode specificationNode, JsonNode jsonNode,
String messagePathPointer) {
return validateJsonMessage(specificationNode, jsonNode, messagePathPointer, null);
} | @Test
void testFullProcedureFromSwaggerResource() {
String openAPIText = null;
String jsonText = "{\n" + " \"name\": \"Rodenbach\",\n" + " \"country\": \"Belgium\",\n"
+ " \"type\": \"Fruit\",\n" + " \"rating\": 4.3,\n" + " \"status\": \"available\"\n" + "}";
JsonNode openAPISpec =... |
@VisibleForTesting
static void checkAuthorization(ReqContext reqContext, IAuthorizer auth, String operation, String function)
throws AuthorizationException {
checkAuthorization(reqContext, auth, operation, function, true);
} | @Test
public void testNotStrict() throws Exception {
ReqContext jt = new ReqContext(new Subject());
SingleUserPrincipal jumpTopo = new SingleUserPrincipal("jump_topo");
jt.subject().getPrincipals().add(jumpTopo);
ReqContext jc = new ReqContext(new Subject());
SingleUserPrinc... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false);
if (shouldAuth) {
Authenticator authenticator = applicationModel
.... | @Test
void testAuthSuccessfully() {
String service = "org.apache.dubbo.DemoService";
String method = "test";
long currentTimeMillis = System.currentTimeMillis();
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.setServiceInterface(service)
.addParame... |
public static <T> KNN<T> fit(T[] x, int[] y, Distance<T> distance) {
return fit(x, y, 1, distance);
} | @Test
public void testBreastCancer() {
System.out.println("Breast Cancer");
MathEx.setSeed(19650218); // to get repeatable results.
ClassificationValidations<KNN<double[]>> result = CrossValidation.classification(10, BreastCancer.x, BreastCancer.y,
(x, y) -> KNN.fit(x, y, 3)... |
@Override
public ByteBuf slice() {
return slice(readerIndex, readableBytes());
} | @Test
public void testSliceAfterRelease2() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().slice(0, 1);
}
});
} |
public static Map<String, ServiceInfo> read(String cacheDir) {
Map<String, ServiceInfo> domMap = new HashMap<>(16);
try {
File[] files = makeSureCacheDirExists(cacheDir).listFiles();
if (files == null || files.length == 0) {
return domMap;
}
... | @Test
void testReadCacheForAllSituation() {
String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test";
Map<String, ServiceInfo> actual = DiskCache.read(dir);
assertEquals(2, actual.size());
assertTrue(actual.containsKey("legal@@no_name@@file"));
assertE... |
public static <InputT, OutputT> Growth<InputT, OutputT, OutputT> growthOf(
Growth.PollFn<InputT, OutputT> pollFn, Requirements requirements) {
return new AutoValue_Watch_Growth.Builder<InputT, OutputT, OutputT>()
.setTerminationPerInput(Growth.never())
.setPollFn(Contextful.of(pollFn, requirem... | @Test
public void testPollingGrowthTrackerUsesElementTimestampIfNoWatermarkProvided() throws Exception {
Instant now = Instant.now();
Watch.Growth<String, String, String> growth =
Watch.growthOf(
new Watch.Growth.PollFn<String, String>() {
@Override
... |
@SneakyThrows // compute() doesn't throw checked exceptions
public static String sha256Hex(String string) {
return sha256DigestCache.get(string, () -> compute(string, DigestObjectPools.SHA_256));
} | @Test
public void shouldComputeForAGivenStringUsingSHA_256() {
String fingerprint = "Some String";
String digest = sha256Hex(fingerprint);
assertEquals(DigestUtils.sha256Hex(fingerprint), digest);
} |
public static byte[] compress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
return Zstd.compress(bytes);
} | @Test
public void test_compress() {
Assertions.assertThrows(NullPointerException.class, () -> {
ZstdUtil.compress(null);
});
} |
public boolean isGlobalOrderingEnabled() {
return globalOrderingEnabled;
} | @Test
public void testIsGlobalOrderingEnabled() {
TopicConfig topicConfig = new TopicConfig();
assertFalse(topicConfig.isGlobalOrderingEnabled());
} |
public abstract void broadcastEmit(T record) throws IOException; | @TestTemplate
void testBroadcastEmitRecord(@TempDir Path tempPath) throws Exception {
final int numberOfSubpartitions = 4;
final int bufferSize = 32;
final int numValues = 8;
final int serializationLength = 4;
final ResultPartition partition = createResultPartition(bufferSiz... |
public StatusInfo getStatusInfo() {
StatusInfo.Builder builder = StatusInfo.Builder.newBuilder();
// Add application level status
int upReplicasCount = 0;
StringBuilder upReplicas = new StringBuilder();
StringBuilder downReplicas = new StringBuilder();
StringBuilder repl... | @Test
public void testGetStatusInfoUnhealthy() {
StatusUtil statusUtil = getStatusUtil(5, 3, 4);
assertFalse(statusUtil.getStatusInfo().isHealthy());
} |
public Database getDb(String dbName) {
return metastore.getDb(dbName);
} | @Test
public void testGetDb() {
Database database = hmsOps.getDb("db1");
Assert.assertEquals("db1", database.getFullName());
try {
hmsOps.getDb("db2");
Assert.fail();
} catch (Exception e) {
Assert.assertTrue(e instanceof StarRocksConnectorExcepti... |
@Override
public AppResponse process(Flow flow, ActivateAppRequest body) {
String decodedPin = ChallengeService.decodeMaskedPin(appSession.getIv(), appAuthenticator.getSymmetricKey(), body.getMaskedPincode());
if ((decodedPin == null || !Pattern.compile("\\d{5}").matcher(decodedPin).matches())) {
... | @Test
void processNOKRequestAccountAndAppFlow(){
Map<String, String> finishRegistrationResponse = Map.of(lowerUnderscore(STATUS), "ERROR");
when(switchService.digidAppSwitchEnabled()).thenReturn(true);
when(digidClientMock.finishRegistration(TEST_REGISTRATION_ID, TEST_ACCOUNT_ID, RequestAcc... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnInvalidQueryParamAnnotationTypeRef() {
@RestLiCollection(name = "brokenParam")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> {
@Finder("brokenParam")
public void brokenParam(@QueryParam(value = "... |
public static void main(String[] args) {
LOGGER.info("Librarian begins their work.");
// Defining genre book functions
Book.AddAuthor fantasyBookFunc = Book.builder().withGenre(Genre.FANTASY);
Book.AddAuthor horrorBookFunc = Book.builder().withGenre(Genre.HORROR);
Book.AddAuthor scifiBookFunc = Boo... | @Test
void executesWithoutExceptions() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public <T> boolean execute(final Predicate<T> predicate, final T arg) {
do {
if (predicate.test(arg)) {
return true;
}
} while (!isTimeout());
return false;
} | @Test
void assertExecute() {
assertTrue(new RetryExecutor(5L, 2L).execute(value -> value > 0, 1));
} |
public String register(Namespace ns) {
return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "register");
} | @Test
public void testRegister() {
Namespace ns = Namespace.of("ns");
assertThat(withPrefix.register(ns)).isEqualTo("v1/ws/catalog/namespaces/ns/register");
assertThat(withoutPrefix.register(ns)).isEqualTo("v1/namespaces/ns/register");
} |
@Override
protected void doUpdate(final List<AppAuthData> dataList) {
dataList.forEach(appAuthData -> authDataSubscribers.forEach(authDataSubscriber -> authDataSubscriber.onSubscribe(appAuthData)));
} | @Test
public void testDoUpdate() {
List<AppAuthData> appAuthDataList = createFakerAppAuthDataObjects(4);
authDataHandler.doUpdate(appAuthDataList);
appAuthDataList.forEach(appAuthData ->
authDataSubscribers.forEach(authDataSubscriber -> verify(authDataSubscriber).onSubscribe(... |
public static String prepareDomain(final String domain) {
// A typical issue is regular expressions that also capture a whitespace at the beginning or the end.
String trimmedDomain = domain.trim();
// Some systems will capture DNS requests with a trailing '.'. Remove that for the lookup.
... | @Test
public void testPrepareDomain() throws Exception {
// Trimming.
assertEquals("example.org", Domain.prepareDomain("example.org "));
assertEquals("example.org", Domain.prepareDomain(" example.org"));
assertEquals("example.org", Domain.prepareDomain(" example.org "));
// ... |
static void setEntryValue( StepInjectionMetaEntry entry, RowMetaAndData row, SourceStepField source )
throws KettleValueException {
// A standard attribute, a single row of data...
//
Object value = null;
switch ( entry.getValueType() ) {
case ValueMetaInterface.TYPE_STRING:
value = ro... | @Test
public void setEntryValue_number() throws KettleValueException {
StepInjectionMetaEntry entry = mock( StepInjectionMetaEntry.class );
doReturn( ValueMetaInterface.TYPE_NUMBER ).when( entry ).getValueType();
RowMetaAndData row = createRowMetaAndData( new ValueMetaNumber( TEST_FIELD ), 1D );
Sourc... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) {
if ( n == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null"));
}
if ( scale == null ) {
return FEEL... | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(decimalFunction.invoke((BigDecimal) null, null),
InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(decimalFunction.invoke(BigDecimal.ONE, null), InvalidParametersEvent.class);
... |
@Override
public synchronized NMResourceInfo getNMResourceInfo() throws YarnException {
final GpuDeviceInformation gpuDeviceInformation;
if (gpuDiscoverer.isAutoDiscoveryEnabled()) {
//At this point the gpu plugin is already enabled
checkGpuResourceHandler();
checkErrorCount();
try{
... | @Test(expected = YarnException.class)
public void testResourceHandlerNotInitialized() throws YarnException {
GpuDiscoverer gpuDiscoverer = createMockDiscoverer();
GpuNodeResourceUpdateHandler gpuNodeResourceUpdateHandler =
mock(GpuNodeResourceUpdateHandler.class);
GpuResourcePlugin target =
... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void parensWithLiteral() {
String inputExpression = "(10.5 )";
BaseNode number = parse( inputExpression );
assertThat( number).isInstanceOf(NumberNode.class);
assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat( number.getText()).isEqualTo("10... |
public ConnectionFactory connectionFactory(ConnectionFactory connectionFactory) {
// It is common to implement both interfaces
if (connectionFactory instanceof XAConnectionFactory) {
return (ConnectionFactory) xaConnectionFactory((XAConnectionFactory) connectionFactory);
}
return TracingConnection... | @Test void connectionFactory_wrapsInput() {
assertThat(jmsTracing.connectionFactory(mock(ConnectionFactory.class)))
.isInstanceOf(TracingConnectionFactory.class);
} |
public static CloseableIterable<CombinedScanTask> planTasks(
CloseableIterable<FileScanTask> splitFiles, long splitSize, int lookback, long openFileCost) {
validatePlanningArguments(splitSize, lookback, openFileCost);
// Check the size of delete file as well to avoid unbalanced bin-packing
Function<... | @Test
public void testPlanTaskWithDeleteFiles() {
List<FileScanTask> testFiles =
tasksWithDataAndDeleteSizes(
Arrays.asList(
Pair.of(150L, new Long[] {50L, 100L}),
Pair.of(50L, new Long[] {1L, 50L}),
Pair.of(50L, new Long[] {100L}),
... |
@VisibleForTesting
void validateNameUnique(List<MemberLevelDO> list, Long id, String name) {
for (MemberLevelDO levelDO : list) {
if (ObjUtil.notEqual(levelDO.getName(), name)) {
continue;
}
if (id == null || !id.equals(levelDO.getId())) {
... | @Test
public void testCreateLevel_nameUnique() {
// 准备参数
String name = randomString();
// mock 数据
memberlevelMapper.insert(randomLevelDO(o -> o.setName(name)));
// 调用,校验异常
List<MemberLevelDO> list = memberlevelMapper.selectList();
assertServiceException(() -... |
@Override
public ServerGroup servers() {
return cache.get();
} | @Test
public void one_down_endpoint_is_up() {
NginxHealthClient service = createClient("nginx-health-output-policy-up.json");
assertTrue(service.servers().isHealthy("gateway.prod.music.vespa.us-east-2.prod"));
} |
public boolean isFound() {
return found;
} | @Test
public void testCalcInstructionsRoundaboutDirectExit() {
roundaboutGraph.inverse3to9();
Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc);
Path p = new Dijkstra(roundaboutGraph.g, weighting, TraversalMode.NODE_BASED)
.calcPath(6, 8);
assertTrue(p.isFoun... |
@Override
public Optional<Track<T>> clean(Track<T> track) {
TreeSet<Point<T>> points = new TreeSet<>(track.points());
Optional<Point<T>> firstNonNull = firstPointWithAltitude(points);
if (!firstNonNull.isPresent()) {
return Optional.empty();
}
SortedSet<Point<T... | @Test
public void testFillingMissingAltitude() {
Track<NoRawData> testTrack = trackWithSingleMissingAltitude();
Track<NoRawData> cleanedTrack = (new FillMissingAltitudes<NoRawData>()).clean(testTrack).get();
ArrayList<Point<NoRawData>> points = new ArrayList<>(cleanedTrack.points());
... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var msgDataAsJsonNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
processFieldsData(ctx, msg, msg.getOriginator(), msgDataAsJsonNode, config.isIgnoreN... | @Test
public void givenValidMsgAndFetchToData_whenOnMsg_thenShouldTellSuccessAndFetchToData() throws TbNodeException, ExecutionException, InterruptedException {
// GIVEN
var device = new Device();
device.setId(DUMMY_DEVICE_ORIGINATOR);
device.setName("Test device");
device.se... |
public static AuthorizationsCollector parse(File file) throws ParseException {
if (file == null) {
LOG.warn("parsing NULL file, so fallback on default configuration!");
return AuthorizationsCollector.emptyImmutableCollector();
}
if (!file.exists()) {
LOG.warn(... | @Test
public void testParseValidComment() throws ParseException {
Reader conf = new StringReader("#simple comment");
AuthorizationsCollector authorizations = ACLFileParser.parse(conf);
// Verify
assertTrue(authorizations.isEmpty());
} |
public MethodBuilder reliable(Boolean reliable) {
this.reliable = reliable;
return getThis();
} | @Test
void reliable() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.reliable(true);
Assertions.assertTrue(builder.build().isReliable());
} |
private void wrapCorsResponse(final HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader... | @Test
public void testWrapCorsResponse() {
try {
Method testMethod = statelessAuthFilter.getClass().getDeclaredMethod("wrapCorsResponse", HttpServletResponse.class);
testMethod.setAccessible(true);
testMethod.invoke(statelessAuthFilter, httpServletResponse);
v... |
@Override
protected int poll() throws Exception {
// must reset for each poll
shutdownRunningTask = null;
pendingExchanges = 0;
List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call();
// okay we have some response from aws so lets mark the cons... | @Test
void shouldRequest18MessagesWithTwoReceiveRequestWithoutSorting() throws Exception {
// given
generateSequenceNumber = false;
var expectedMessages = IntStream.range(0, 18).mapToObj(Integer::toString).toList();
expectedMessages.stream().map(this::message).forEach(sqsClientMock::... |
@Override
public void deleteAll() {
} | @Test
public void deleteAll() {
mSensorsAPI.deleteAll();
} |
public static <T> CloseableIterator<T> from(Iterator<T> iterator) {
// early fail
requireNonNull(iterator);
checkArgument(!(iterator instanceof AutoCloseable), "This method does not support creating a CloseableIterator from an Iterator which is Closeable");
return new RegularIteratorWrapper<>(iterator);... | @Test(expected = IllegalArgumentException.class)
public void from_iterator_throws_IAE_if_arg_is_a_CloseableIterator() {
CloseableIterator.from(new SimpleCloseableIterator());
} |
@Override
public SQLXML getSQLXML(final int columnIndex) throws SQLException {
return (SQLXML) mergeResultSet.getValue(columnIndex, SQLXML.class);
} | @Test
void assertGetSQLXMLWithColumnIndex() throws SQLException {
SQLXML sqlxml = mock(SQLXML.class);
when(mergeResultSet.getValue(1, SQLXML.class)).thenReturn(sqlxml);
assertThat(shardingSphereResultSet.getSQLXML(1), is(sqlxml));
} |
public DecisionTree prune(DataFrame test) {
return prune(test, formula, classes);
} | @Test
public void testPrune() {
System.out.println("USPS");
// Overfitting with very large maxNodes and small nodeSize
DecisionTree model = DecisionTree.fit(USPS.formula, USPS.train, SplitRule.ENTROPY, 20, 3000, 1);
System.out.println(model);
double[] importance = model.imp... |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.3");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportAuthenticationHolders() throws IOException {
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
new HashSet<String>(), null);
Authentication moc... |
@Override
public long count() {
return coll.count();
} | @Test
@MongoDBFixtures("OutputServiceImplTest.json")
public void countReturnsNumberOfOutputs() {
assertThat(outputService.count()).isEqualTo(2L);
} |
@Override
public int getRowCount() {
return _rowsArray.size();
} | @Test
public void testGetRowCount() {
// Run the test
final int result = _resultTableResultSetUnderTest.getRowCount();
// Verify the results
assertEquals(2, result);
} |
public boolean isInstalled() {
return mTrigger != null;
} | @Test
public void testImeInstalledWhenMixedVoice() {
addInputMethodInfo(List.of("keyboard", "keyboard", "handwriting"));
addInputMethodInfo(List.of("handwriting"));
addInputMethodInfo(List.of("handwriting", "keyboard", "voice", "keyboard", "keyboard"));
Assert.assertTrue(ImeTrigger.isInstalled(mMockI... |
@Override
public boolean supportsTableCorrelationNames() {
return false;
} | @Test
void assertSupportsTableCorrelationNames() {
assertFalse(metaData.supportsTableCorrelationNames());
} |
public void setConstructor(boolean constructor) {
this.constructor = constructor;
} | @Test
void testSetConstructor() {
Method method = new Method("Bar");
assertFalse(method.isConstructor());
method.setConstructor(true);
assertTrue(method.isConstructor());
} |
public void checkExecutePrerequisites(final ExecutionContext executionContext) {
ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext)));
} | @Test
void assertCheckExecutePrerequisitesWhenExecuteDDLInBaseTransaction() {
when(transactionRule.getDefaultType()).thenReturn(TransactionType.BASE);
ExecutionContext executionContext = new ExecutionContext(
new QueryContext(createMySQLCreateTableStatementContext(), "", Collections.... |
@SuppressWarnings({"unchecked", "rawtypes"})
public static Object compatibleTypeConvert(Object value, Class<?> type) {
if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
return value;
}
if (value instanceof String) {
String string = (Stri... | @SuppressWarnings("unchecked")
@Test
void testCompatibleTypeConvert() throws Exception {
Object result;
{
Object input = new Object();
result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class);
assertSame(input, result);
result = Comp... |
public static List<GsonEmail> parse(String json) {
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<List<GsonEmail>>() {
});
} | @Test
public void parse() {
List<GsonEmail> underTest = GsonEmail.parse(
"[\n" +
" {\n" +
" \"email\": \"octocat@github.com\",\n" +
" \"verified\": true,\n" +
" \"primary\": true\n" +
" },\n" +
" {\n" +
" \"email\": \"support@github.com\... |
public static Node build(final List<JoinInfo> joins) {
Node root = null;
for (final JoinInfo join : joins) {
if (root == null) {
root = new Leaf(join.getLeftSource());
}
if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) {
throw new K... | @Test
public void shouldThrowOnMissingSource() {
// Given:
when(j1.getLeftSource()).thenReturn(a);
when(j1.getRightSource()).thenReturn(b);
when(j2.getLeftSource()).thenReturn(c);
when(j2.getRightSource()).thenReturn(d);
final List<JoinInfo> joins = ImmutableList.of(j1, j2);
// When:
... |
public static String getKeyTenant(String dataId, String group, String tenant) {
return doGetKey(dataId, group, tenant);
} | @Test
void testGetKeyTenantByPlusThreeParams() {
// Act
final String actual = GroupKey.getKeyTenant("3", "1", ",");
// Assert result
assertEquals("3+1+,", actual);
} |
@Override
public String decryptAES(String content) {
return AESSecretManager.getInstance().decryptAES(content);
} | @Test
public void decryptAES() {
SAHelper.initSensors(mApplication);
SAEncryptAPIImpl encryptAPIImpl = new SAEncryptAPIImpl(SensorsDataAPI.sharedInstance(mApplication).getSAContextManager());
final String Identity = "Identity";
String encrypt = encryptAPIImpl.encryptAES(Identity);
... |
@Override
public JobStatus getState() {
return jobStatus;
} | @Test
void getState() {
final JobStatusStore store = new JobStatusStore(0L);
store.jobStatusChanges(new JobID(), JobStatus.RUNNING, 1L);
assertThat(store.getState(), is(JobStatus.RUNNING));
} |
public static byte[] copyOf(byte[] src, int length) {
byte[] dest = new byte[length];
System.arraycopy(src, 0, dest, 0, Math.min(src.length, length));
return dest;
} | @Test
public void copyOf() {
byte[] bs = new byte[] { 1, 2, 3, 5 };
byte[] cp = CodecUtils.copyOf(bs, 3);
Assert.assertArrayEquals(cp, new byte[] { 1, 2, 3 });
cp = CodecUtils.copyOf(bs, 5);
Assert.assertArrayEquals(cp, new byte[] { 1, 2, 3, 5, 0 });
} |
@Override
public Void execute(Context context) {
KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
Collection<?> objects = ksession.getObjects(new ConditionFilter(factToCheck));
if (!objects.isEmpty()) {
factToCheck.forEach(fact -> fact.getScenarioResult... | @Test
public void execute_setResultIsCalled() {
when(kieSession.getObjects(any(ObjectFilter.class))).thenReturn(Collections.singleton(null));
validateFactCommand.execute(registryContext);
verify(scenarioResult, times(1)).setResult(anyBoolean());
} |
@Override
public String getName() {
return name;
} | @Test
public void testEqualsAndHashCode() {
assumeDifferentHashCodes();
EqualsVerifier.forClass(ReplicatedMapConfig.class)
.suppress(Warning.NONFINAL_FIELDS)
.withPrefabValues(MergePolicyConfig.class,
new MergePolicyConfig(PutIfAbsentMergePolic... |
private static int getNumSlots(final Configuration config) {
return config.get(TaskManagerOptions.NUM_TASK_SLOTS);
} | @Test
void testConfigNumSlots() {
final int numSlots = 5;
Configuration conf = new Configuration();
conf.set(TaskManagerOptions.NUM_TASK_SLOTS, numSlots);
validateInAllConfigurations(
conf,
taskExecutorProcessSpec ->
assertTha... |
@Override
public void init(Properties config) throws ServletException {
acceptAnonymous = Boolean.parseBoolean(config.getProperty(ANONYMOUS_ALLOWED, "false"));
} | @Test
public void testInit() throws Exception {
PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler();
try {
Properties props = new Properties();
props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false");
handler.init(props);
Assert.assertEquals(false,... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.MAIL_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteMailTemplate(Long id) {
// 校验是否存在
validateMailTemplateExists(id);
// 删除
mailTemplateMapper.deleteById(id);
} | @Test
public void testDeleteMailTemplate_success() {
// mock 数据
MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailTemplate.getId();
// 调用
mailTemplateServic... |
public List<String> scanPlugins(ClassLoader classLoader, String path) throws IOException {
final List<String> files = new LinkedList<>();
scanner.scan(classLoader, path, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
Clas... | @Test
public void testScanPlugins() throws Exception {
ClassPathAnnotationScanner scanner = new ClassPathAnnotationScanner(Plugin.class.getName(), new ClassPathScanner());
assertArrayEquals("Plugin discovered", new String[]{SimplePlugin.class.getName()},
scanner.scanPlugins(getClass... |
private void initializePartition(Set<TrackerClient> trackerClients, int partitionId, long clusterGenerationId)
{
if (!_partitionLoadBalancerStateMap.containsKey(partitionId))
{
PartitionState partitionState = new PartitionState(partitionId,
new DelegatingRingFactory<>(_relativeStrategyProperti... | @Test(dataProvider = "partitionId")
public void testInitializePartition(int partitionId)
{
setup(new D2RelativeStrategyProperties(), new ConcurrentHashMap<>());
List<TrackerClient> trackerClients = TrackerClientMockHelper.mockTrackerClients(2,
Arrays.asList(20, 20), Arrays.asList(10, 10), Arrays.as... |
@Override
public void validatePostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得岗位信息
List<PostDO> posts = postMapper.selectBatchIds(ids);
Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId);
// 校验
ids.forEach(id ... | @Test
public void testValidatePostList_notFound() {
// 准备参数
List<Long> ids = singletonList(randomLongId());
// 调用, 并断言异常
assertServiceException(() -> postService.validatePostList(ids), POST_NOT_FOUND);
} |
@Override
public <T> List<T> getExtensions(Class<T> type) {
return getExtensions(type, currentPluginId);
} | @Test
public void getExtensions() {
pluginManager.loadPlugins();
pluginManager.startPlugins();
assertEquals(1, wrappedPluginManager.getExtensions(TestExtensionPoint.class).size());
assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.getExtensions(TestExtensionPoint.cla... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("list", concurrency);
try {
final String prefix = this.createPrefix(directory);
if(log.isDebugEnabl... | @Test
public void testList() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(new Path(container, new AlphanumericRandomSt... |
int sendBackups0(BackupAwareOperation backupAwareOp) {
int requestedSyncBackups = requestedSyncBackups(backupAwareOp);
int requestedAsyncBackups = requestedAsyncBackups(backupAwareOp);
int requestedTotalBackups = requestedTotalBackups(backupAwareOp);
if (requestedTotalBackups == 0) {
... | @Test(expected = IllegalArgumentException.class)
public void backup_whenNegativeAsyncBackupCount() {
setup(BACKPRESSURE_ENABLED);
BackupAwareOperation op = makeOperation(0, -1);
backupHandler.sendBackups0(op);
} |
public ExecutionStateTracker create() {
return new ExecutionStateTracker();
} | @Test
public void testTrackerReuse() throws Exception {
MillisProvider clock = mock(MillisProvider.class);
ExecutionStateSampler sampler =
new ExecutionStateSampler(
PipelineOptionsFactory.fromArgs("--experiments=state_sampling_period_millis=10")
.create(),
cloc... |
public static Optional<URLArgumentLine> parse(final String line) {
Matcher matcher = PLACEHOLDER_PATTERN.matcher(line);
if (!matcher.find()) {
return Optional.empty();
}
String[] parsedArg = matcher.group(1).split(KV_SEPARATOR, 2);
return Optional.of(new URLArgumentLi... | @Test
void assertParseWithInvalidPattern() {
assertFalse(URLArgumentLine.parse("invalid").isPresent());
} |
public static String byte2FitMemoryString(final long byteNum) {
if (byteNum < 0) {
return "shouldn't be less than zero!";
} else if (byteNum < MemoryConst.KB) {
return String.format("%d B", byteNum);
} else if (byteNum < MemoryConst.MB) {
return String.format(... | @Test
public void byte2FitMemoryStringKB() {
Assert.assertEquals(
"1 KB",
ConvertKit.byte2FitMemoryString(1024)
);
} |
@Override
public String getAnonymousId() {
return null;
} | @Test
public void getAnonymousId() {
Assert.assertNull(mSensorsAPI.getAnonymousId());
} |
@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 shouldIgnoreSessionsThatStartAtUpperBoundIfUpperBoundOpen() {
// Given:
final Range<Instant> startBounds = Range.closedOpen(
LOWER_INSTANT,
UPPER_INSTANT
);
givenSingleSession(UPPER_INSTANT, UPPER_INSTANT.plusMillis(1));
// When:
final Iterator<WindowedRow> rowI... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
if (tradingRecord != null && !tradingRecord.isClosed()) {
Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice();
Num currentPrice = this.referencePrice.getValue(index);
N... | @Test
public void testLongPositionStopLoss() {
ZonedDateTime initialEndDateTime = ZonedDateTime.now();
for (int i = 0; i < 10; i++) {
series.addBar(initialEndDateTime.plusDays(i), 100, 105, 95, 100);
}
AverageTrueRangeStopLossRule rule = new AverageTrueRangeStopLossRule... |
public WriteResult<T, K> update(Bson filter, T object, boolean upsert, boolean multi) {
return update(filter, object, upsert, multi, delegate.getWriteConcern());
} | @Test
void updateWithBsonVariants() {
final var collection = spy(jacksonCollection("simple", Simple.class));
final DBQuery.Query query = DBQuery.empty();
final DBUpdate.Builder update = new DBUpdate.Builder().set("name", "foo");
collection.update(query, update);
verify(coll... |
void removeWatchers() {
List<NamespaceWatcher> localEntries = Lists.newArrayList(entries);
while (localEntries.size() > 0) {
NamespaceWatcher watcher = localEntries.remove(0);
if (entries.remove(watcher)) {
try {
log.debug("Removing watcher for... | @Test
public void testSameWatcherDifferentPaths1Triggered() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
try {
client.start();
WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client... |
boolean contains(DatanodeDescriptor node) {
if (node==null) {
return false;
}
String ipAddr = node.getIpAddr();
hostmapLock.readLock().lock();
try {
DatanodeDescriptor[] nodes = map.get(ipAddr);
if (nodes != null) {
for(DatanodeDescriptor containedNode:nodes) {
... | @Test
public void testContains() throws Exception {
DatanodeDescriptor nodeNotInMap =
DFSTestUtil.getDatanodeDescriptor("3.3.3.3", "/d1/r4");
for (int i = 0; i < dataNodes.length; i++) {
assertTrue(map.contains(dataNodes[i]));
}
assertFalse(map.contains(null));
assertFalse(map.contains... |
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {INT, BIGINT}, returnType = INT)
public static ConstantOperator bitShiftRightLogicalInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(first.getInt() >>> second.getBigint());
} | @Test
public void bitShiftRightLogicalInt() {
assertEquals(1, ScalarOperatorFunctions.bitShiftRightLogicalInt(O_INT_10, O_BI_3).getInt());
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
// {"code":400,"message":"Bad Request","debugInfo":"Node ID must be positive.","errorCode":-80001}
final PathAttributes attributes = new PathAtt... | @Test
public void testFindRoot() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final SDSAttributesFinderFeature f = new SDSAttributesFinderFeature(session, nodeid);
final PathAttributes attributes = f.find(new Path("/", EnumSet.of(Path.Type.volume, Path.... |
public List<String> build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
switch (dialect.getId()) {
case PostgreSql.ID:
return createPostgresQuery();
case Oracle.ID:
return createOracleQuery();
default:
return ... | @Test
public void update_columns_on_h2() {
assertThat(createSampleBuilder(new H2()).build())
.containsOnly(
"ALTER TABLE issues ALTER COLUMN value DOUBLE NULL",
"ALTER TABLE issues ALTER COLUMN name VARCHAR (10) NULL");
} |
@Override
public List<TypeInfo> getColumnTypes(Configuration conf) throws HiveJdbcDatabaseAccessException {
return getColumnMetadata(conf, typeInfoTranslator);
} | @Test
public void testGetColumnTypes_fieldListQuery() throws HiveJdbcDatabaseAccessException {
Configuration conf = buildConfiguration();
conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select name,referrer from test_strategy");
DatabaseAccessor accessor = DatabaseAccessorFactory.getAccessor(conf);
... |
public MetricsBuilder collectorSyncPeriod(Integer collectorSyncPeriod) {
this.collectorSyncPeriod = collectorSyncPeriod;
return getThis();
} | @Test
void collectorSyncPeriod() {
MetricsBuilder builder = MetricsBuilder.newBuilder();
builder.collectorSyncPeriod(10);
Assertions.assertEquals(10, builder.build().getCollectorSyncPeriod());
} |
@Override
public Stream<ColumnName> resolveSelectStar(
final Optional<SourceName> sourceName
) {
return getSource().resolveSelectStar(sourceName)
.map(name -> aliases.getOrDefault(name, name));
} | @Test
public void shouldNotAddAliasOnResolveSelectStarWhenNotAliased() {
// Given:
final ColumnName unknown = ColumnName.of("unknown");
when(source.resolveSelectStar(any()))
.thenReturn(ImmutableList.of(K, unknown).stream());
// When:
final Stream<ColumnName> result = projectNode.resolve... |
@PutMapping
@Secured(resource = AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE)
public Object updateUser(@RequestParam String username, @RequestParam String newPassword,
HttpServletResponse response, HttpServletRequest request) throws IOException {
// admin or same use... | @Test
void testUpdateUser6() throws IOException, AccessException {
RequestContextHolder.getContext().getAuthContext().getIdentityContext()
.setParameter(AuthConstants.NACOS_USER_KEY, null);
when(authConfigs.isAuthEnabled()).thenReturn(true);
when(authenticationManager.authent... |
public static void checkMetaDir() throws InvalidMetaDirException,
IOException {
// check meta dir
// if metaDir is the default config: StarRocksFE.STARROCKS_HOME_DIR + "/meta",
// we should check whether both the new default dir (STARROCKS_HOME_DI... | @Test
public void testUseOldMetaDir() throws IOException,
InvalidMetaDirException {
Config.start_with_incomplete_meta = false;
new MockUp<System>() {
@Mock
public String getenv(String name) {
return testDir;
}
};
mkdir(... |
public int ndots() {
return ndots;
} | @Test
void ndotsBadValues() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> builder.ndots(-2))
.withMessage("ndots must be greater or equal to -1");
} |
public DateTime getStartedAt() {
return startedAt;
} | @Test
public void testGetStartedAt() throws Exception {
assertNotNull(status.getStartedAt());
} |
@Override
public void clear() {
history.clear();
} | @Test
void testClear() {
TreeMapLogHistory<String> history = new TreeMapLogHistory<>();
history.addAt(100, "100");
history.addAt(200, "200");
history.clear();
assertEquals(Optional.empty(), history.lastEntry());
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testOnWindowExpirationMultipleAnnotation() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Found multiple methods annotated with @OnWindowExpiration");
thrown.expectMessage("bar()");
thrown.expectMessage("baz()");
thrown.expectMessage(getCl... |
public void publishExpired(Cache<K, V> cache, K key, V value) {
publish(cache, EventType.EXPIRED, key, /* hasOldValue */ true,
/* oldValue */ value, /* newValue */ value, /* quiet */ false);
} | @Test
public void publishExpired() {
var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run);
registerAll(dispatcher);
dispatcher.publishExpired(cache, 1, 2);
verify(expiredListener, times(4)).onExpired(any());
assertThat(dispatcher.pending.get()).hasSize(2);
assertThat(dispatch... |
public void setTransactionAnnotation(GlobalTransactional transactionAnnotation) {
this.transactionAnnotation = transactionAnnotation;
} | @Test
public void testSetTransactionAnnotation()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
MethodDesc methodDesc = getMethodDesc();
assertThat(methodDesc.getTransactionAnnotation()).isNotNull();
methodDesc.setTransactionAnnotation(null);
... |
public String getLocation() {
String location = properties.getProperty(NACOS_LOGGING_CONFIG_PROPERTY);
if (StringUtils.isBlank(location)) {
if (isDefaultLocationEnabled()) {
return defaultLocation;
}
return null;
}
return location;
... | @Test
void testGetLocationForSpecifiedWithDefault() {
properties.setProperty("nacos.logging.config", "classpath:specified-test.xml");
assertEquals("classpath:specified-test.xml", loggingProperties.getLocation());
} |
public URLNormalizer secureScheme() {
Matcher m = PATTERN_SCHEMA.matcher(url);
if (m.find()) {
String schema = m.group(1);
if ("http".equalsIgnoreCase(schema)) {
url = m.replaceFirst(schema + "s$2");
}
}
return this;
} | @Test
public void testSecureScheme() {
s = "https://www.example.com/secure.html";
t = "https://www.example.com/secure.html";
assertEquals(t, n(s).secureScheme().toString());
s = "HTtP://www.example.com/secure.html";
t = "HTtPs://www.example.com/secure.html";
assertEqu... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void testStringToBooleanRandomStringError() {
final TypedExpression left = expr(THIS_PLACEHOLDER + ".getBooleanValue", Boolean.class);
final TypedExpression right = expr("\"randomString\"", String.class);
assertThatThrownBy(() -> new CoercedExpression(left, right, false).coerce(... |
public boolean canRebalance() {
return PREPARING_REBALANCE.validPreviousStates().contains(state);
} | @Test
public void testCanRebalanceWhenStable() {
assertTrue(group.canRebalance());
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testParseNewStyleResourceMemoryNegativeWithSpaces()
throws Exception {
expectNegativeValueOfResource("memory");
parseResourceConfigValue("memory-mb=-5120, vcores=2");
} |
public void changeStrategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
} | @Test
void testChangeStrategy() {
final var initialStrategy = mock(DragonSlayingStrategy.class);
final var dragonSlayer = new DragonSlayer(initialStrategy);
dragonSlayer.goToBattle();
verify(initialStrategy).execute();
final var newStrategy = mock(DragonSlayingStrategy.class);
dragonSlayer.c... |
DataTableType lookupTableTypeByType(Type type) {
return lookupTableTypeByType(type, Function.identity());
} | @Test
void null_string_transformed_to_null() {
DataTableTypeRegistry registry = new DataTableTypeRegistry(Locale.ENGLISH);
DataTableType dataTableType = registry.lookupTableTypeByType(LIST_OF_LIST_OF_STRING);
assertEquals(
singletonList(singletonList(null)),
dataTable... |
@Override
public List<String> findConfigInfoTags(final String dataId, final String group, final String tenant) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoTagMapper configInfoTagMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
... | @Test
void testFindConfigInfoTags() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
List<String> mockedTags = Arrays.asList("tags1", "tags11", "tags111");
Mockito.when(jdbcTemplate.queryForList(anyString(), eq(new Object[] {dataId, grou... |
public FloatArrayAsIterable usingExactEquality() {
return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_containsExactly_primitiveFloatArray_success() {
assertThat(array(1.0f, 2.0f, 3.0f))
.usingExactEquality()
.containsExactly(array(2.0f, 1.0f, 3.0f));
} |
public static Object getFieldValue(Object obj, String fieldName) {
try {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | @Test
void testGetFieldValue() {
Object elementData = ReflectUtils.getFieldValue(listStr, "elementData");
assertTrue(elementData instanceof Object[]);
assertEquals(2, ((Object[]) elementData).length);
} |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void addDuplicateField() {
Schema schema = Schema.builder().addStringField("field1").build();
thrown.expect(IllegalArgumentException.class);
pipeline
.apply(Create.of(Row.withSchema(schema).addValue("value").build()).withRowSchema(schema))
.apply... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.