focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void setDeepLinkCallback(SensorsDataDeepLinkCallback deepLinkCallback) {
} | @Test
public void setDeepLinkCallback() {
mSensorsAPI.setDeepLinkCompletion(new SensorsDataDeferredDeepLinkCallback() {
@Override
public boolean onReceive(SADeepLinkObject saDeepLinkObject) {
Assert.fail();
return false;
}
});
} |
public static InstrumentedScheduledExecutorService newScheduledThreadPool(
int corePoolSize, MetricRegistry registry, String name) {
return new InstrumentedScheduledExecutorService(
Executors.newScheduledThreadPool(corePoolSize), registry, name);
} | @Test
public void testNewScheduledThreadPool() throws Exception {
final ScheduledExecutorService executorService = InstrumentedExecutors.newScheduledThreadPool(2, registry, "xs");
executorService.schedule(new NoopRunnable(), 0, TimeUnit.SECONDS);
assertThat(registry.meter("xs.scheduled.once... |
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
if(file.isDirectory()) {
try (final Directory entry = share.get().openDirectory(new SMBPa... | @Test
public void testTimestampDirectory() throws Exception {
final TransferStatus status = new TransferStatus();
final Path home = new DefaultHomeFinderService(session).find();
final Path f = new SMBDirectoryFeature(session).mkdir(
new Path(home, new AlphanumericRandomString... |
static void quoteExternalName(StringBuilder sb, String externalName) {
List<String> parts = splitByNonQuotedDots(externalName);
for (int i = 0; i < parts.size(); i++) {
String unescaped = unescapeQuotes(parts.get(i));
String unquoted = unquoteIfQuoted(unescaped);
DIAL... | @Test
public void quoteExternalName_with_hyphen() {
String externalName = "schema-with-hyphen.table-with-hyphen";
StringBuilder sb = new StringBuilder();
MappingHelper.quoteExternalName(sb, externalName);
assertThat(sb.toString()).isEqualTo("\"schema-with-hyphen\".\"table-with-hyphen... |
public static Bip39Wallet generateBip39WalletFromMnemonic(
String password, String mnemonic, File destinationDirectory)
throws CipherException, IOException {
byte[] seed = MnemonicUtils.generateSeed(mnemonic, password);
ECKeyPair privateKey = ECKeyPair.create(sha256(seed));
... | @Test
public void testGenerateBip39WalletFromMnemonic() throws Exception {
Bip39Wallet wallet =
WalletUtils.generateBip39WalletFromMnemonic(PASSWORD, MNEMONIC, tempDir);
byte[] seed = MnemonicUtils.generateSeed(wallet.getMnemonic(), PASSWORD);
Credentials credentials = Creden... |
public static OpenAction getOpenAction(int flag) {
// open flags must contain one of O_RDONLY(0), O_WRONLY(1), O_RDWR(2)
// O_ACCMODE is mask of read write(3)
// Alluxio fuse only supports read-only for completed file
// and write-only for file that does not exist or contains open flag O_TRUNC
// O_... | @Test
public void readWrite() {
int[] readFlags = new int[]{0x8002, 0x9002, 0xc002};
for (int readFlag : readFlags) {
Assert.assertEquals(AlluxioFuseOpenUtils.OpenAction.READ_WRITE,
AlluxioFuseOpenUtils.getOpenAction(readFlag));
}
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void unpinAllChatMessages() {
BaseResponse response = bot.execute(new UnpinAllChatMessages(groupId));
assertTrue(response.isOk());
} |
public StatementExecutorResponse execute(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext executionContext,
final KsqlSecurityContext securityContext
) {
final String commandRunnerWarningString = commandRunnerWarning.get();
if (!commandRunnerWarningString... | @Test
public void shouldInferSchemas() {
// When:
distributor.execute(CONFIGURED_STATEMENT, executionContext, securityContext);
// Then:
verify(schemaInjector, times(1)).inject(eq(CONFIGURED_STATEMENT));
} |
public Stream<Flow> keepLastVersion(Stream<Flow> stream) {
return keepLastVersionCollector(stream);
} | @Test
void sameRevisionWithDeletedOrdered() {
Stream<Flow> stream = Stream.of(
create("test", "test", 1),
create("test", "test2", 2),
create("test", "test2", 2).toDeleted(),
create("test", "test2", 4)
);
List<Flow> collect = flowService.keepLa... |
public static String getSrcUserName(HttpServletRequest request) {
IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext();
String result = StringUtils.EMPTY;
if (null != identityContext) {
result = (String) identityContext.getParamete... | @Test
void testGetSrcUserNameFromContext() {
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID, "test");
RequestContextHolder.getContext().getAuthContext().setIdentityContext(identityCon... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetFloatSchemaForDoublePrimitiveClassVariadic() {
assertThat(
UdfUtil.getVarArgsSchemaFromType(double.class),
equalTo(ParamTypes.DOUBLE)
);
} |
public Result fetchArtifacts(String[] uris) {
checkArgument(uris != null && uris.length > 0, "At least one URI is required.");
ArtifactUtils.createMissingParents(baseDir);
List<File> artifacts =
Arrays.stream(uris)
.map(FunctionUtils.uncheckedFunction(thi... | @Test
void testFileSystemFetchWithAdditionalUri() throws Exception {
File sourceFile = TestingUtils.getClassFile(getClass());
String uriStr = "file://" + sourceFile.toURI().getPath();
File additionalSrcFile = getFlinkClientsJar();
String additionalUriStr = "file://" + additionalSrcFi... |
public File createTmpFileForWrite(String pathStr, long size,
Configuration conf) throws IOException {
AllocatorPerContext context = obtainContext(contextCfgItemName);
return context.createTmpFileForWrite(pathStr, size, conf);
} | @Test (timeout = 30000)
public void testNoSideEffects() throws IOException {
assumeNotWindows();
String dir = buildBufferDir(ROOT, 0);
try {
conf.set(CONTEXT, dir);
File result = dirAllocator.createTmpFileForWrite(FILENAME, -1, conf);
assertTrue(result.delete());
assertTrue(result.... |
public static byte[] getNullableSizePrefixedArray(final ByteBuffer buffer) {
final int size = buffer.getInt();
return getNullableArray(buffer, size);
} | @Test
public void getNullableSizePrefixedArrayRemainder() {
byte[] input = {0, 0, 0, 2, 1, 0, 9};
final ByteBuffer buffer = ByteBuffer.wrap(input);
final byte[] array = Utils.getNullableSizePrefixedArray(buffer);
assertArrayEquals(new byte[] {1, 0}, array);
assertEquals(6, bu... |
@Override
public RexNode visit(CallExpression call) {
boolean isBatchMode = unwrapContext(relBuilder).isBatchMode();
for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) {
Optional<RexNode> converted = rule.convert(call, newFunctionContext());
if (conve... | @Test
void testIntervalDayTime() {
Duration value = Duration.ofDays(3).plusMillis(21);
RexNode rex = converter.visit(valueLiteral(value));
assertThat(((RexLiteral) rex).getValueAs(BigDecimal.class))
.isEqualTo(BigDecimal.valueOf(value.toMillis()));
assertThat(rex.getT... |
public static SparkClusterResourceSpec buildResourceSpec(
final SparkCluster cluster, final SparkClusterSubmissionWorker worker) {
Map<String, String> confOverrides = new HashMap<>();
SparkClusterResourceSpec spec = worker.getResourceSpec(cluster, confOverrides);
ClusterDecorator decorator = new Clust... | @Test
void testOwnerReference() {
SparkCluster cluster = new SparkCluster();
cluster.setMetadata(
new ObjectMetaBuilder().withNamespace("test-namespace").withName("my-cluster").build());
SparkClusterSubmissionWorker mockWorker = mock(SparkClusterSubmissionWorker.class);
when(mockWorker.getReso... |
@Override
public Path.Type detect(final String path) {
if(StringUtils.isBlank(path)) {
return Path.Type.directory;
}
if(path.endsWith(String.valueOf(Path.DELIMITER))) {
return Path.Type.directory;
}
if(StringUtils.isBlank(Path.getExtension(path))) {
... | @Test
public void testDetect() {
DefaultPathKindDetector d = new DefaultPathKindDetector();
assertEquals(Path.Type.directory, d.detect(null));
assertEquals(Path.Type.directory, d.detect("/"));
assertEquals(Path.Type.directory, d.detect("/a"));
assertEquals(Path.Type.directory... |
@Override
public double distanceBtw(Point p1, Point p2) {
numCalls++;
confirmRequiredDataIsPresent(p1);
confirmRequiredDataIsPresent(p2);
Duration timeDelta = Duration.between(p1.time(), p2.time()); //can be positive of negative
timeDelta = timeDelta.abs();
Double... | @Test
public void testDistanceComputation_Altitude() {
PointDistanceMetric metric = new PointDistanceMetric(1.0, 1.0);
PointDistanceMetric metric2 = new PointDistanceMetric(1.0, 2.0);
Point p1 = new PointBuilder()
.latLong(0.0, 0.0)
.altitude(Distance.ofFeet(0.0))
... |
@Override
public InputStream fetch(String fetchKey, Metadata metadata, ParseContext parseContext) throws IOException, TikaException {
HttpFetcherConfig additionalHttpFetcherConfig = getAdditionalHttpFetcherConfig(parseContext);
HttpGet get = new HttpGet(fetchKey);
RequestConfig requestConfig... | @Test
@Disabled("requires network connectivity")
public void testRange() throws Exception {
String url = "https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2020-45/segments/1603107869785.9/warc/CC-MAIN-20201020021700-20201020051700-00529.warc.gz";
long start = 969596307;
long end =... |
@Override
public void writeShort(final int v) throws IOException {
ensureAvailable(SHORT_SIZE_IN_BYTES);
MEM.putShort(buffer, ARRAY_BYTE_BASE_OFFSET + pos, (short) v);
pos += SHORT_SIZE_IN_BYTES;
} | @Test
public void testWriteShortForPositionV() throws Exception {
short expected = 100;
out.writeShort(1, expected);
short actual = Bits.readShort(out.buffer, 1, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
assertEquals(expected, actual);
} |
@Override
public int compare( TransMeta t1, TransMeta t2 ) {
return super.compare( t1, t2 );
} | @Test
public void testCompare() {
TransMeta transMeta = new TransMeta( "aFile", "aName" );
TransMeta transMeta2 = new TransMeta( "aFile", "aName" );
assertEquals( 0, transMeta.compare( transMeta, transMeta2 ) );
transMeta2.setVariable( "myVariable", "myValue" );
assertEquals( 0, transMeta.compare(... |
@Override
public SQLParserRule build(final SQLParserRuleConfiguration ruleConfig, final Map<String, ShardingSphereDatabase> databases, final ConfigurationProperties props) {
return new SQLParserRule(ruleConfig);
} | @Test
void assertBuild() {
SQLParserRuleConfiguration ruleConfig = new SQLParserRuleConfiguration(new CacheOption(2, 5L), new CacheOption(4, 7L));
SQLParserRule actualResult = new SQLParserRuleBuilder().build(ruleConfig, Collections.emptyMap(), new ConfigurationProperties(new Properties()));
... |
public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
} | @Test
void testDelimitedListToStringArrayWithEmptyDelimiter() {
String testCase = "a,b";
String[] actual = StringUtils.delimitedListToStringArray(testCase, "", "");
assertEquals(3, actual.length);
assertEquals("a", actual[0]);
assertEquals(",", actual[1]);
assertEqual... |
public String get(String key) {
return properties.getProperty(key);
} | @Test
public void testGet_whenValueNotString() {
// given a "compromised" Properties object
Properties props = new Properties();
props.put("key", 1);
// HazelcastProperties.get returns null
HazelcastProperties hzProperties = new HazelcastProperties(props);
assertNull... |
public boolean isExcluded(Path absolutePath, Path relativePath, InputFile.Type type) {
PathPattern[] exclusionPatterns = InputFile.Type.MAIN == type ? mainExclusionsPattern : testExclusionsPattern;
for (PathPattern pattern : exclusionPatterns) {
if (pattern.match(absolutePath, relativePath)) {
re... | @Test
public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestExclusions() {
settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java");
settings.setProperty(PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters... |
@Override
public ShardingAutoTableRuleConfiguration swapToObject(final YamlShardingAutoTableRuleConfiguration yamlConfig) {
ShardingSpherePreconditions.checkNotNull(yamlConfig.getLogicTable(), () -> new MissingRequiredShardingConfigurationException("Sharding Logic table"));
ShardingAutoTableRuleConf... | @Test
void assertSwapToObject() {
YamlShardingAutoTableRuleConfigurationSwapper swapper = new YamlShardingAutoTableRuleConfigurationSwapper();
ShardingAutoTableRuleConfiguration actual = swapper.swapToObject(createYamlShardingAutoTableRuleConfiguration());
assertThat(actual.getShardingStrate... |
public static CompleteFilePOptions completeFileDefaults() {
return CompleteFilePOptions.newBuilder()
.setCommonOptions(FileSystemOptionsUtils.commonDefaults(Configuration.global()))
.setUfsLength(0)
.build();
} | @Test
public void completeFileDefaultsTest() {
CompleteFilePOptions options = FileSystemMasterOptions.completeFileDefaults();
Assert.assertNotNull(options);
Assert.assertEquals(0, options.getUfsLength());
} |
@Bean
public ShenyuPlugin jwtPlugin() {
return new JwtPlugin();
} | @Test
public void testJwtPlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JwtPluginConfiguration.class))
.withBean(JwtPluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
ShenyuPlu... |
@Override
public Long sendSingleMailToMember(String mail, Long userId,
String templateCode, Map<String, Object> templateParams) {
// 如果 mail 为空,则加载用户编号对应的邮箱
if (StrUtil.isEmpty(mail)) {
mail = memberService.getMemberUserEmail(userId);
}
... | @Test
public void testSendSingleMailToMember() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// ... |
static MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) {
LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName);
MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName);
if (result == null) {
... | @Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistryByType() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MetricRegistry.class)).thenReturn(Collections.singleton(metricRegistry));
MetricRegistry result ... |
static String getScheme( String[] schemes, String fileName ) {
for (String scheme : schemes) {
if ( fileName.startsWith( scheme + ":" ) ) {
return scheme;
}
}
return null;
} | @Test
public void testCheckForSchemeIfBlank() {
String[] schemes = {"file"};
String vfsFilename = " ";
assertNull( KettleVFS.getScheme( schemes, vfsFilename ) );
} |
@Override
public ArrayNode encode(Iterable<MeasurementOption> entities,
CodecContext context) {
ArrayNode an = context.mapper().createArrayNode();
entities.forEach(node -> an.add(node.name()));
return an;
} | @Test
public void testEncodeIterableOfMeasurementOptionCodecContext() {
List<MeasurementOption> moList = new ArrayList<>();
moList.add(MeasurementOption.FRAME_DELAY_BACKWARD_MAX);
moList.add(MeasurementOption.FRAME_DELAY_FORWARD_BINS);
ArrayNode an =
context.codec(Me... |
public BlobOperationResponse listBlobs(final Exchange exchange) {
final ListBlobsOptions listBlobOptions = configurationProxy.getListBlobOptions(exchange);
final Duration timeout = configurationProxy.getTimeout(exchange);
final String regex = configurationProxy.getRegex(exchange);
List<B... | @Test
void testListBlobWithRegex() {
BlobConfiguration myConfiguration = new BlobConfiguration();
myConfiguration.setAccountName("cameldev");
myConfiguration.setContainerName("awesome2");
myConfiguration.setRegex(".*\\.pdf");
when(client.listBlobs(any(), any())).thenReturn(... |
public static Schema getOutputSchema(
Schema inputSchema, FieldAccessDescriptor fieldAccessDescriptor) {
return getOutputSchemaTrackingNullable(inputSchema, fieldAccessDescriptor, false);
} | @Test
public void testNullableSchema() {
FieldAccessDescriptor fieldAccessDescriptor1 =
FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_NULLABLE_SCHEMA);
Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
Schema expectedSchema1 = Sc... |
public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart,
final CharSequence substring, final int start, final int length) {
if (cs instanceof String && substring instanceof String) {
return ((String) cs).regionMatches(ignoreCase, thisStart... | @Test
void testRegionMatchesEqualsCaseInsensitiveForNonString() {
assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xabc", 1, 3));
assertTrue(StringUtils.regionMatches(new StringBuilder("abc"), true, 0, "xAbc", 1, 3));
} |
@Override
public void write(final int b) throws IOException {
throw new IOException(new UnsupportedOperationException());
} | @Test
public void testWriteWithChunkSize() throws Exception {
final CryptoVault vault = this.getVault();
final ByteArrayOutputStream cipherText = new ByteArrayOutputStream();
final FileHeader header = vault.getFileHeaderCryptor().create();
final CryptoOutputStream stream = new Crypto... |
@Subscribe
public void inputUpdated(InputUpdated inputUpdatedEvent) {
final String inputId = inputUpdatedEvent.id();
LOG.debug("Input updated: {}", inputId);
final Input input;
try {
input = inputService.find(inputId);
} catch (NotFoundException e) {
L... | @Test
public void inputUpdatedDoesNotStartLocalInputOnLocalNodeIfItWasNotRunning() throws Exception {
final String inputId = "input-id";
final Input input = mock(Input.class);
@SuppressWarnings("unchecked")
final IOState<MessageInput> inputState = mock(IOState.class);
when(in... |
public FEELFnResult<List> invoke(@ParameterName( "list" ) List list, @ParameterName( "position" ) BigDecimal position, @ParameterName( "newItem" ) Object newItem) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
... | @Test
void invokeListNull() {
FunctionTestUtil.assertResultError(insertBeforeFunction.invoke(null, BigDecimal.ZERO, new Object()),
InvalidParametersEvent.class);
} |
@Override
public GetWorkStream getWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
return windmillStreamFactory.createGetWorkStream(
dispatcherClient.getWindmillServiceStub(),
GetWorkRequest.newBuilder(request)
.setJobId(options.getJobId())
.setProjectId(opti... | @Test
public void testStreamingGetWork() throws Exception {
// This fake server returns an infinite stream of identical WorkItems, obeying the request size
// limits set by the client.
serviceRegistry.addService(
new CloudWindmillServiceV1Alpha1ImplBase() {
@Override
public Str... |
Map<String, Object> offsetSyncsTopicAdminConfig() {
return SOURCE_CLUSTER_ALIAS_DEFAULT.equals(offsetSyncsTopicLocation())
? sourceAdminConfig(OFFSET_SYNCS_SOURCE_ADMIN_ROLE)
: targetAdminConfig(OFFSET_SYNCS_TARGET_ADMIN_ROLE);
} | @Test
public void testAdminConfigsForOffsetSyncsTopic() {
Map<String, String> connectorProps = makeProps(
"source.admin.request.timeout.ms", "1",
"target.admin.send.buffer.bytes", "1",
"admin.reconnect.backoff.max.ms", "1",
"retries", "123"
... |
@Override
public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier... | @Test
void getVersionedProfilePniInvalidArgument() {
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toByte... |
@Override
public Type createType(List<TypeParameter> parameters)
{
checkArgument(!parameters.isEmpty(), "Row type must have at least one parameter");
checkArgument(
parameters.stream().allMatch(parameter -> parameter.getKind() == ParameterKind.NAMED_TYPE),
"Expect... | @Test
public void testTypeSignatureRoundTrip()
{
FunctionAndTypeManager functionAndTypeManager = createTestFunctionAndTypeManager();
TypeSignature typeSignature = new TypeSignature(
ROW,
TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName... |
@Override
public void setConfigAttributes(Object attributes) {
if (attributes == null) {
return;
}
super.setConfigAttributes(attributes);
Map map = (Map) attributes;
if (map.containsKey(BRANCH)) {
String branchName = (String) map.get(BRANCH);
... | @Test
void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception {
GitMaterialConfig gitMaterialConfig = git("");
Map<String, String> map = new HashMap<>();
map.put(GitMaterialConfig.PASSWORD, "secret");
map.put(GitMaterialConfig.PASSWORD_CHANGE... |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
List<KeyValue<String, Object>> templateParams) throws Throwable {
// 构建请求
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(mobile);
req... | @Test
public void tesSendSms_success() throws Throwable {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("code",... |
@Override
public ListenableFuture<?> execute(StartTransaction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.isClientTransac... | @Test
public void testStartTransactionIdleExpiration()
throws Exception
{
Session session = sessionBuilder()
.setClientTransactionSupport()
.build();
TransactionManager transactionManager = InMemoryTransactionManager.create(
new Transac... |
public static String buildUrl(boolean isHttps, String serverAddr, String... subPaths) {
StringBuilder sb = new StringBuilder();
if (isHttps) {
sb.append(HTTPS_PREFIX);
} else {
sb.append(HTTP_PREFIX);
}
sb.append(serverAddr);
String pre = null;
... | @Test
void testBuildHttpUrl1() {
String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "/v1/api/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "v1/api/test");
assertEquals(exceptUrl, targetUrl);
targetUrl = HttpUti... |
public static boolean isLog4jLogger(Class<?> clazz) {
if (clazz == null) {
return false;
}
return isLog4jLogger(clazz.getName());
} | @Test
public void testIsLog4jLogger() throws Exception {
assertFalse("False if clazz is null", GenericsUtil.isLog4jLogger((Class<?>) null));
assertTrue("The implementation is Log4j",
GenericsUtil.isLog4jLogger(TestGenericsUtil.class));
} |
public boolean hasReceivers()
{
return !lastSmTimestampNsByReceiverIdMap.isEmpty();
} | @Test
void shouldNotBeLiveIfNoReceiversAdded()
{
final ReceiverLivenessTracker receiverLivenessTracker = new ReceiverLivenessTracker();
assertFalse(receiverLivenessTracker.hasReceivers());
} |
@Override
public void delete(CacheDto nativeEntity) {
cacheService.deleteAndPostEventImmutable(nativeEntity.id());
} | @Test
@MongoDBFixtures("LookupCacheFacadeTest.json")
public void delete() {
final Optional<CacheDto> cacheDto = cacheService.get("5adf24b24b900a0fdb4e52dd");
assertThat(cacheService.findAll()).hasSize(1);
cacheDto.ifPresent(facade::delete);
assertThat(cacheService.get("5adf24b2... |
public IndicesBlockStatus getIndicesBlocksStatus(final List<String> indices) {
if (indices == null || indices.isEmpty()) {
return new IndicesBlockStatus();
} else {
return indicesAdapter.getIndicesBlocksStatus(indices);
}
} | @Test
public void testGetIndicesBlocksStatusReturnsNoBlocksOnNullIndicesList() {
final IndicesBlockStatus indicesBlocksStatus = underTest.getIndicesBlocksStatus(null);
assertNotNull(indicesBlocksStatus);
assertEquals(0, indicesBlocksStatus.countBlockedIndices());
} |
@Override
public DirectPipelineResult run(Pipeline pipeline) {
try {
options =
MAPPER
.readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class)
.as(DirectOptions.class);
} catch (IOException e) {
throw new IllegalArgumentException(
"Pipeli... | @Test
public void testNoBlockOnRunState() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
final Future handler =
executor.submit(
() -> {
PipelineOptions options =
PipelineOptionsFactory.fromArgs("--blockOnRun=false").cre... |
@Override
public <I> void foreach(List<I> data, SerializableConsumer<I> consumer, int parallelism) {
data.forEach(throwingForeachWrapper(consumer));
} | @Test
public void testForeach() {
List<Integer> mapList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = new ArrayList<>(10);
context.foreach(mapList, result::add, 2);
Assertions.assertEquals(result.size(), mapList.size());
Assertions.assertTrue(result.containsAll(mapList));... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test
public void testSiblingsOnResourceResponse() {
Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true));
OpenAPI openAPI = reader.read(SiblingsResourceResponse.class);
String yaml = "openapi: 3.1.0\n" +
"paths:\n" +
... |
public static String toJson(Message message) {
StringWriter json = new StringWriter();
try (JsonWriter jsonWriter = JsonWriter.of(json)) {
write(message, jsonWriter);
}
return json.toString();
} | @Test
public void do_not_write_null_wrapper_of_array() {
TestNullableArray msg = TestNullableArray.newBuilder()
.setLabel("world")
.build();
assertThat(msg.hasCountries()).isFalse();
// array wrapper is null
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\"}");
} |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<Path>();
// At least one entry successfully parsed
boolean success = false;
// Call hook for those im... | @Test
public void testNoChunkNotification() throws Exception {
final CompositeFileEntryParser parser = new FTPParserSelector().getParser("NETWARE Type : L8");
final AttributedList<Path> list = new FTPListResponseReader(parser).read(
new Path("/", EnumSet.of(Path.Type.directory)), Collec... |
public static HDPath parsePath(@Nonnull String path) {
List<String> parsedNodes = SEPARATOR_SPLITTER.splitToList(path);
boolean hasPrivateKey = false;
if (!parsedNodes.isEmpty()) {
final String firstNode = parsedNodes.get(0);
if (firstNode.equals(Character.toString(PREFIX... | @Test
public void testParsePath() {
Object[] tv = {
"M / 44H / 0H / 0H / 1 / 1",
HDPath.M(new ChildNumber(44, true), new ChildNumber(0, true), new ChildNumber(0, true),
new ChildNumber(1, false), new ChildNumber(1, false)),
false,
... |
public static double round( double f, int places ) {
return round( f, places, java.math.BigDecimal.ROUND_HALF_EVEN );
} | @Test
public void testRound() {
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_UP ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_DOWN ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_CEILING ) );
assertEquals( 1.0, Const.round( 1.0, 0, BigDecimal.ROUND_FLOOR ) );
... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithCommaSeparatedVsIndividual() {
expectFailureWhenTestingThat(asList("a, b")).containsExactly("a", "b");
assertFailureKeys(
"missing (2)", "#1", "#2", "", "unexpected (1)", "#1", "---", "expected", "but was");
assertFailureValueIndexed("#1", 0, "a");
... |
public static void dumpConfiguration(Configuration config,
String propertyName, Writer out) throws IOException {
if(Strings.isNullOrEmpty(propertyName)) {
dumpConfiguration(config, out);
} else if (Strings.isNullOrEmpty(config.get(propertyName))) {
throw new IllegalArgumentException("Property ... | @Test
public void testDumpConfiguration() throws IOException {
StringWriter outWriter = new StringWriter();
Configuration.dumpConfiguration(conf, outWriter);
String jsonStr = outWriter.toString();
ObjectMapper mapper = new ObjectMapper();
JsonConfiguration jconf =
mapper.readValue(jsonStr,... |
@Override
public void close() throws SQLException {
proxyBackendHandler.close();
} | @Test
void assertClose() throws SQLException, NoSuchFieldException, IllegalAccessException {
MySQLComQueryPacketExecutor actual = new MySQLComQueryPacketExecutor(packet, connectionSession);
MemberAccessor accessor = Plugins.getMemberAccessor();
accessor.set(MySQLComQueryPacketExecutor.class.... |
public static void init(Timer timer, Collector collector, String applicationType) {
if (!Parameter.UPDATE_CHECK_DISABLED.getValueAsBoolean()) {
final UpdateChecker updateChecker = new UpdateChecker(collector, applicationType,
SERVER_URL);
final TimerTask updateCheckerTimerTask = new TimerTask() {
@Over... | @Test
public void testInit() {
Utils.setProperty(Parameter.UPDATE_CHECK_DISABLED, "true");
UpdateChecker.init(null, null, null);
} |
@Override
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetRepositoryNamesMeta) smi;
data = (GetRepositoryNamesData) sdi;
if ( super.init( smi, sdi ) ) {
try {
// Get the repository objects from the repository...
//
data.list = getRepositoryO... | @Test
public void testGetRepoList_excludeNameMask() throws KettleException {
init( repo, "/", true, ".*", "Trans1.*", All, 3 );
} |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testSimpleStateIdAnonymousDoFn() throws Exception {
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<KV<String, Integer>, Long>() {
@StateId("foo")
private final StateSpec<ValueState<Integer>> bizzle =
StateSpecs.value(V... |
public void validateFilterExpression(final Expression exp) {
final SqlType type = getExpressionReturnType(exp);
if (!SqlTypes.BOOLEAN.equals(type)) {
throw new KsqlStatementException(
"Type error in " + filterType.name() + " expression: "
+ "Should evaluate to boolean but is"
... | @Test
public void shouldThrowOnBadType() {
// Given:
final Expression literal = new IntegerLiteral(10);
// When:
assertThrows("Type error in WHERE expression: "
+ "Should evaluate to boolean but is 10 (INTEGER) instead.",
KsqlException.class,
() -> validator.validateFilter... |
@Override
@MethodNotAvailable
public CompletionStage<V> putAsync(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testPutAsyncWithTtl() {
adapter.putAsync(42, "value", 1, TimeUnit.MILLISECONDS);
} |
public Certificate add(X509Certificate cert) {
final Certificate db;
try {
db = Certificate.from(cert);
} catch (CertificateEncodingException e) {
logger.error("Encoding error in certificate", e);
throw new ClientException("Encoding error in certificate", e);
... | @Test
public void shouldAllowToAddCRL() throws CertificateException, IOException {
certificateRepo.saveAndFlush(loadCertificate("test/root.crt", true));
assertDoesNotThrow(() -> service.add(readCRL("test/root.crl")));
} |
@Override
public Distribution distribute(D2CanaryDistributionStrategy strategy)
{
switch (strategy.getStrategy()) {
case TARGET_HOSTS:
return distributeByTargetHosts(strategy);
case TARGET_APPLICATIONS:
return distributeByTargetApplications(strategy);
case PERCENTAGE:
r... | @Test
public void testNormalCasesForApplicationsStrategy()
{
TargetApplicationsStrategyProperties appsProperties =
new TargetApplicationsStrategyProperties().setTargetApplications(new StringArray(Arrays.asList("appA", "appB")))
.setScope(0.4);
D2CanaryDistributionStrategy targetAppsStrat... |
@Override
public void close() throws IOException {
if (open.compareAndSet(true, false)) {
onClose.run();
Throwable thrown = null;
do {
for (Closeable resource : resources) {
try {
resource.close();
} catch (Throwable e) {
if (thrown == null) {... | @Test
public void testClose_callsOnCloseRunnable() throws IOException {
assertEquals(0, onClose.runCount);
state.close();
assertEquals(1, onClose.runCount);
} |
public static Sensor activeProcessRatioSensor(final String threadId,
final String taskId,
final StreamsMetricsImpl streamsMetrics) {
final String name = ACTIVE_TASK_PREFIX + PROCESS + RATIO_SUFFIX;
final ... | @Test
public void shouldGetActiveProcessRatioSensor() {
final String operation = "active-process-ratio";
when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO))
.thenReturn(expectedSensor);
final String ratioDescription = "The fraction of tim... |
public static void switchContextLoader(ClassLoader loader) {
try {
if (loader != null && loader != Thread.currentThread().getContextClassLoader()) {
Thread.currentThread().setContextClassLoader(loader);
}
} catch (SecurityException e) {
// ignore , For... | @Test
void switchContextLoader() {
ClassLoadUtil.switchContextLoader(Thread.currentThread().getContextClassLoader());
} |
public TriRpcStatus getStatus() {
return status;
} | @Test
void getStatus() {
Assertions.assertEquals(
TriRpcStatus.INTERNAL, ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus());
} |
@SuppressWarnings("deprecation")
static Object[] buildArgs(final Object[] positionalArguments,
final ResourceMethodDescriptor resourceMethod,
final ServerResourceContext context,
final DynamicRecordTemplate templa... | @Test(expectedExceptions = RoutingException.class, dataProvider = "positionalParameterData")
public void testPositionalParameterType(Class<?> dataType, Parameter.ParamType paramType)
{
String paramKey = "testParam";
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class... |
@Override
public Optional<Buffer> getNextBuffer(
TieredStoragePartitionId partitionId,
TieredStorageSubpartitionId subpartitionId,
int segmentId) {
// Get current segment id and buffer index.
Tuple2<Integer, Integer> bufferIndexAndSegmentId =
curre... | @Test
void testGetBuffer() {
int bufferSize = 10;
TieredStoragePartitionId partitionId =
new TieredStoragePartitionId(new ResultPartitionID());
PartitionFileReader partitionFileReader =
new TestingPartitionFileReader.Builder()
.setReadB... |
public void wrap(final byte[] buffer)
{
capacity = buffer.length;
addressOffset = ARRAY_BASE_OFFSET;
byteBuffer = null;
wrapAdjustment = 0;
if (buffer != byteArray)
{
byteArray = buffer;
}
} | @Test
void shouldWrapValidRange()
{
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[8]);
final UnsafeBuffer slice = new UnsafeBuffer();
slice.wrap(buffer);
slice.wrap(buffer, 0, 8);
slice.wrap(buffer, 1, 7);
slice.wrap(buffer, 2, 6);
slice.wrap(buff... |
static int internalEncodeLogHeader(
final MutableDirectBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final NanoClock nanoClock)
{
if (captureLength < 0 || captureLength > length || captureLength > MAX_CAPTURE_LENGTH)
{
... | @Test
void encodeLogHeaderThrowsIllegalArgumentExceptionIfCaptureLengthIsGreaterThanMaxCaptureSize()
{
assertThrows(IllegalArgumentException.class,
() -> internalEncodeLogHeader(buffer, 0, MAX_CAPTURE_LENGTH + 1, Integer.MAX_VALUE, () -> 0));
} |
@Override
public boolean offerFirst(V e) {
return get(offerFirstAsync(e));
} | @Test
public void testOfferFirst() {
RDeque<Integer> queue = redisson.getDeque("deque");
queue.offerFirst(1);
queue.offerFirst(2);
queue.offerFirst(3);
assertThat(queue).containsExactly(3, 2, 1);
} |
public URLSerializer(Fury fury, Class<URL> type) {
super(fury, type);
} | @Test(dataProvider = "furyCopyConfig")
public void testURLSerializer(Fury fury) throws MalformedURLException {
fury.registerSerializer(URL.class, URLSerializer.class);
copyCheck(fury, new URL("http://test"));
} |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldThrowWhenConfigDescriptionsDoNotContainTopicDuringValidation() {
final AdminClient admin = mock(AdminClient.class);
final InternalTopicManager topicManager = new InternalTopicManager(
time,
admin,
new StreamsConfig(config)
);
... |
public boolean cleanTable() {
boolean allRemoved = true;
Set<String> removedPaths = new HashSet<>();
for (PhysicalPartition partition : table.getAllPhysicalPartitions()) {
try {
WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr();
... | @Test
public void test(@Mocked LakeTable table,
@Mocked PhysicalPartition partition,
@Mocked MaterializedIndex index,
@Mocked LakeTablet tablet,
@Mocked LakeService lakeService) throws StarClientException {
LakeTableCleaner ... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeNewDecimal() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.NEWDECIMAL), instanceOf(MySQLStringLenencBinaryProtocolValue.class));
} |
@PostMapping("/api/v1/meetings")
public ResponseEntity<MomoApiResponse<MeetingCreateResponse>> create(
@RequestBody @Valid MeetingCreateRequest request
) {
MeetingCreateResponse response = meetingService.create(request);
String path = cookieManager.pathOf(response.uuid());
St... | @DisplayName("주최자가 확정되지 않은 약속을 취소하면 204 상태 코드를 응답 받는다.")
@Test
void cancelConfirmedMeetingNonExist() {
Meeting meeting = createLockedMovieMeeting();
Attendee host = attendeeRepository.save(AttendeeFixture.HOST_JAZZ.create(meeting));
String token = getToken(host, meeting);
RestAs... |
private static SchemaVersion getSchemaVersion(byte[] schemaVersion) {
if (schemaVersion != null) {
return BytesSchemaVersion.of(schemaVersion);
}
return BytesSchemaVersion.of(new byte[0]);
} | @Test
public void decodeDataWithNullSchemaVersion() {
Schema<GenericRecord> autoConsumeSchema = new AutoConsumeSchema();
byte[] bytes = "bytes data".getBytes();
MessageImpl<GenericRecord> message = MessageImpl.create(
new MessageMetadata(), ByteBuffer.wrap(bytes), autoConsume... |
@Override
public <T> PinotGauge<T> newGauge(PinotMetricName name, PinotGauge<T> gauge) {
return new YammerGauge<T>((YammerSettableGauge<T>)
_metricsRegistry.newGauge((MetricName) name.getMetricName(), (Gauge<T>) gauge.getGauge()));
} | @Test
public void testNewGaugeNoError() {
YammerMetricsRegistry yammerMetricsRegistry = new YammerMetricsRegistry();
YammerSettableGauge<Long> yammerSettableGauge = new YammerSettableGauge<>(1L);
YammerGauge<Long> yammerGauge = new YammerGauge<>(yammerSettableGauge);
MetricName metricName = new Metric... |
public String execService( String service, boolean retry ) throws Exception {
int tries = 0;
int maxRetries = 0;
if ( retry ) {
maxRetries = KETTLE_CARTE_RETRIES;
}
while ( true ) {
try {
return execService( service );
} catch ( Exception e ) {
if ( tries >= maxRetr... | @Test( expected = NullPointerException.class )
public void testExecService() throws Exception {
HttpGet httpGetMock = mock( HttpGet.class );
URI uriMock = new URI( "fake" );
doReturn( uriMock ).when( httpGetMock ).getURI();
doReturn( httpGetMock ).when( slaveServer ).buildExecuteServiceMethod( anyStri... |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Bui... | @Test
public void addSchema() {
int lastColumnId = 1;
when(metadata.lastColumnId()).thenReturn(lastColumnId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddSchema(new Schema(), las... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.for... | @Test
void matches_rule_with_multiple_alternatives_for_host_path_and_method() throws IOException {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(false)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.... |
@Override
public SelType call(String methodName, SelType[] args) {
methodName += args.length;
if (SUPPORTED_METHODS.containsKey(methodName)) {
return SelTypeUtil.callJavaMethod(val, args, SUPPORTED_METHODS.get(methodName), methodName);
}
throw new UnsupportedOperationException(
type()
... | @Test(expected = IllegalArgumentException.class)
public void testInvalidCallArg() {
one.call("minusYears", new SelType[] {SelType.NULL});
} |
@Override
public CompletableFuture<Void> completeTransaction(
TopicPartition tp,
long producerId,
short producerEpoch,
int coordinatorEpoch,
TransactionResult result,
Duration timeout
) {
if (!isActive.get()) {
return FutureUtils.failedFuture(E... | @Test
public void testCompleteTransactionWhenNotCoordinatorServiceStarted() {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
run... |
@Override
public boolean hasPrivileges(final String database) {
return databases.contains(AuthorityConstants.PRIVILEGE_WILDCARD) || databases.contains(database);
} | @Test
void assertHasPrivilegesWithWildcard() {
assertTrue(new DatabasePermittedPrivileges(Collections.singleton(AuthorityConstants.PRIVILEGE_WILDCARD)).hasPrivileges("foo_db"));
} |
public Future<KafkaCluster> prepareKafkaCluster(
Kafka kafkaCr,
List<KafkaNodePool> nodePools,
Map<String, Storage> oldStorage,
Map<String, List<String>> currentPods,
KafkaVersionChange versionChange,
KafkaStatus kafkaStatus,
boolean tr... | @Test
public void testSkipScaleDownCheckWithKRaft(VertxTestContext context) {
Kafka kafka = new KafkaBuilder(KAFKA)
.editMetadata()
.addToAnnotations(Annotations.ANNO_STRIMZI_IO_SKIP_BROKER_SCALEDOWN_CHECK, "true")
.endMetadata()
.build();
... |
@Override
public void setLastOffset(long offset) {
buffer.putLong(BASE_OFFSET_OFFSET, offset - lastOffsetDelta());
} | @Test
public void testSetLastOffset() {
SimpleRecord[] simpleRecords = new SimpleRecord[] {
new SimpleRecord(1L, "a".getBytes(), "1".getBytes()),
new SimpleRecord(2L, "b".getBytes(), "2".getBytes()),
new SimpleRecord(3L, "c".getBytes(), "3".getBytes())
};
... |
public void saveOrganization(Organization organization) {
organizationRepository.saveAndFlush(organization);
} | @Test
public void saveOrganization() {
when(repositoryMock.saveAndFlush(any(Organization.class))).thenReturn(newOrganization());
organizationServiceMock.saveOrganization(newOrganization());
verify(repositoryMock, times(1)).saveAndFlush(any(Organization.class));
} |
@Override
public boolean supportsOpenStatementsAcrossCommit() {
return false;
} | @Test
void assertSupportsOpenStatementsAcrossCommit() {
assertFalse(metaData.supportsOpenStatementsAcrossCommit());
} |
public void setOnKeyboardActionListener(OnKeyboardActionListener keyboardActionListener) {
mKeyboardActionListener = keyboardActionListener;
for (int childIndex = 0; childIndex < getChildCount(); childIndex++) {
View child = getChildAt(childIndex);
if (child instanceof InputViewActionsProvider) {
... | @Test
public void testSetOnKeyboardActionListener() {
AnyKeyboardView mock1 = Mockito.mock(AnyKeyboardView.class);
AnyKeyboardView mock2 = Mockito.mock(AnyKeyboardView.class);
mUnderTest.removeAllViews();
mUnderTest.addView(mock1);
Mockito.verify(mock1, Mockito.never())
.setOnKeyboardAc... |
@Override
public String getPath() {
return path;
} | @Test(expectedExceptions = FileNotFoundException.class)
public void testReadingFromDirectoryThrowsException2() throws IOException {
File dir = createDir();
fs.getInput(dir.getPath()); // should throw exception
} |
@Override
public void handleTenantMenu(TenantMenuHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户,然后获得菜单
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
Set<Long> menuIds;
if (isSystemTenant(tenan... | @Test // 系统租户的情况
public void testHandleTenantMenu_system() {
// 准备参数
TenantMenuHandler handler = mock(TenantMenuHandler.class);
// mock 未禁用
when(tenantProperties.getEnable()).thenReturn(true);
// mock 租户
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackage... |
static Date toDate(final JsonNode object) {
if (object instanceof NumericNode) {
return getDateFromEpochDays(object.asLong());
}
if (object instanceof TextNode) {
try {
return getDateFromEpochDays(Long.parseLong(object.textValue()));
} catch (final NumberFormatException e) {
... | @Test(expected = IllegalArgumentException.class)
public void shouldNotConvertIncorrectStringToDate() {
JsonSerdeUtils.toDate(JsonNodeFactory.instance.textNode("ha"));
} |
public void populateModel(HashMap<String, Object> model) {
model.put("matchers", matcher());
model.put("email", email);
model.put("emailMe", emailMe);
model.put("notificationFilters", notificationFilters);
} | @Test
void shouldPopulateEmptyListWhenMatcherDoesNotInitialized() {
user = new User("UserName", new String[]{""}, "user@mail.com", true);
HashMap<String, Object> data = new HashMap<>();
user.populateModel(data);
Object value = data.get("matchers");
assertThat(value).isEqualTo... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
ret... | @Test
void invokeArrayParamReturnNull() {
FunctionTestUtil.assertResult(nnAllFunction.invoke(new Object[]{Boolean.TRUE, null, Boolean.TRUE}), true);
} |
@Override
public boolean supports(Job job) {
if (jobActivator == null) return false;
JobDetails jobDetails = job.getJobDetails();
return !jobDetails.hasStaticFieldName() && jobActivator.activateJob(toClass(jobDetails.getClassName())) != null;
} | @Test
void doesNotSupportJobIfJobClassIsNotKnownInIoC() {
Job job = anEnqueuedJob()
.withJobDetails(defaultJobDetails().withClassName(TestServiceForIoC.class))
.build();
assertThat(backgroundIoCJobWithIocRunner.supports(job)).isFalse();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.