focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
final St... | @Test
public void testExecute() throws SubCommandException {
QueryMsgTraceByIdSubCommand cmd = new QueryMsgTraceByIdSubCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {String.format("-i %s", MSG_ID),
String.format("-... |
public void measureAccountEnvelopeUuidMismatches(final Account account,
final MessageProtos.Envelope envelope) {
if (envelope.hasDestinationUuid()) {
try {
measureAccountDestinationUuidMismatches(account, ServiceIdentifier.valueOf(envelope.getDestinationUuid()));
} catch (final IllegalArgu... | @Test
void measureAccountEnvelopeUuidMismatches() {
final MessageProtos.Envelope envelopeToAci = createEnvelope(new AciServiceIdentifier(aci));
messageMetrics.measureAccountEnvelopeUuidMismatches(account, envelopeToAci);
Optional<Counter> counter = findCounter(simpleMeterRegistry);
assertTrue(counte... |
public void undelete() {
// make a copy because the selected trash items changes as soon as trashService.undelete is called
List<UIDeletedObject> selectedTrashFileItemsSnapshot = new ArrayList<UIDeletedObject>( selectedTrashFileItems );
if ( selectedTrashFileItemsSnapshot != null && selectedTrashFileItemsSn... | @Test
public void testExceptionNotHandle() throws Exception {
RuntimeException runtimeException = new RuntimeException( "Exception handle" );
when( selectedTrashFileItemsMock.toArray() )
.thenReturn( new TrashBrowseController.UIDeletedObject[] { uiDirectoryObjectMock } );
doThrow( runtimeException... |
@Override
public void confirmLeadership(UUID leaderSessionID, String leaderAddress) {
parentService.confirmLeadership(componentId, leaderSessionID, leaderAddress);
} | @Test
void testLeaderConfirmation() throws Exception {
final AtomicReference<String> componentIdRef = new AtomicReference<>();
final AtomicReference<UUID> leaderSessionIDRef = new AtomicReference<>();
final AtomicReference<String> leaderAddressRef = new AtomicReference<>();
final Def... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testChemistryUsed3()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", USED_AMULET_OF_CHEMISTRY_3_DOSES, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_AMULET_OF_... |
public static VersionSet parse(ImmutableList<String> versionAndRangesList) {
checkNotNull(versionAndRangesList);
checkArgument(!versionAndRangesList.isEmpty(), "Versions and ranges list cannot be empty.");
VersionSet.Builder versionSetBuilder = VersionSet.builder();
for (String versionOrRangeString : ... | @Test
public void parse_withEmptyInputList_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> VersionSet.parse(ImmutableList.of()));
assertThat(exception).hasMessageThat().isEqualTo("Versions and ranges list cannot be empty.");
... |
public static void setupClientId(Configuration conf) {
if (OptionsResolver.isMultiWriter(conf)) {
// explicit client id always has higher priority
if (!conf.contains(FlinkOptions.WRITE_CLIENT_ID)) {
try (ClientIds clientIds = ClientIds.builder().conf(conf).build()) {
String clientId = ... | @Test
void testSetupClientId() throws Exception {
Configuration conf = getConf();
conf.setString(FlinkOptions.WRITE_CLIENT_ID, "2");
OptionsInference.setupClientId(conf);
assertThat("Explicit client id has higher priority",
conf.getString(FlinkOptions.WRITE_CLIENT_ID), is("2"));
for (int ... |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldReturnWindowStoreWhenItExists() {
assertNotNull(storeProvider.getStore(StoreQueryParameters.fromNameAndType(windowStore, QueryableStoreTypes.windowStore())));
} |
@Override
public int getOrder() {
return PluginEnum.URI.getCode();
} | @Test
public void testGetOrder() {
assertEquals(uriPlugin.getOrder(), PluginEnum.URI.getCode());
} |
public static Configuration loadConfiguration(
String workingDirectory, Configuration dynamicParameters, Map<String, String> env) {
final Configuration configuration =
GlobalConfiguration.loadConfiguration(workingDirectory, dynamicParameters);
final String keytabPrincipal = ... | @Test
void testRestPortOptionsUnspecified() throws IOException {
final Configuration initialConfiguration = new Configuration();
final Configuration configuration = loadConfiguration(initialConfiguration);
// having not specified the ports should set the rest bind port to 0
assertT... |
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
// note fullPath will check that paths are relative to this FileSystem.
// Hence both are in same file system and a rename is valid
return super.rename(fullPath(src), fullPath(dst));
} | @Test
public void testRename() throws IOException {
// Rename a file
fileSystemTestHelper.createFile(fSys, "/newDir/foo");
fSys.rename(new Path("/newDir/foo"), new Path("/newDir/fooBar"));
Assert.assertFalse(fSys.exists(new Path("/newDir/foo")));
Assert.assertFalse(fSysTarget.exists(new Path(chroo... |
protected static LinkedHashMap<String, KiePMMLProbabilityConfidence> getProbabilityConfidenceMap(final List<KiePMMLScoreDistribution> kiePMMLScoreDistributions,
final double missingValuePenalty) {
return (kiePMM... | @Test
void getProbabilityConfidenceMap() {
LinkedHashMap<String, KiePMMLProbabilityConfidence> retrieved = KiePMMLNode.getProbabilityConfidenceMap(null, 1.0);
assertThat(retrieved).isNotNull();
assertThat(retrieved).isEmpty();
retrieved = KiePMMLNode.getProbabilityConfidenceMap(Colle... |
@Override
public boolean onTouchEvent(@NonNull MotionEvent nativeMotionEvent) {
if (mKeyboard == null) {
// I mean, if there isn't any keyboard I'm handling, what's the point?
return false;
}
final int action = nativeMotionEvent.getActionMasked();
final int pointerCount = nativeMotionEven... | @Test
public void testWithLongPressOutputLongPressKeyPressState() {
final AnyKeyboard.AnyKey key = findKey('f');
key.longPressCode = 'z';
KeyDrawableStateProvider provider =
new KeyDrawableStateProvider(
R.attr.key_type_function,
R.attr.key_type_action,
R.attr.a... |
public static Read<JmsRecord> read() {
return new AutoValue_JmsIO_Read.Builder<JmsRecord>()
.setMaxNumRecords(Long.MAX_VALUE)
.setCoder(SerializableCoder.of(JmsRecord.class))
.setCloseTimeout(DEFAULT_CLOSE_TIMEOUT)
.setRequiresDeduping(false)
.setMessageMapper(
ne... | @Test
public void testAuthenticationRequired() {
pipeline.apply(JmsIO.read().withConnectionFactory(connectionFactory).withQueue(QUEUE));
String errorMessage =
this.connectionFactoryClass == ActiveMQConnectionFactory.class
? "User name [null] or password is invalid."
: "Client f... |
@Override
public EncryptRule build(final EncryptRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType,
final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceContext... | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void assertBuild() {
EncryptRuleConfiguration ruleConfig = mock(EncryptRuleConfiguration.class);
DatabaseRuleBuilder builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class, Collections.singleton(ruleConfig)).get(ruleConfig);
as... |
public static String unescape(String uri) {
return uri.replace("%2F", "/").replace("%2E", ".").replace("%25", "%");
} | @Test
public void testUnescape() {
AlluxioURI localUri1 = new AlluxioURI("/foo/alluxio/underFSStorage");
String localUriEscaped1 = MetricsSystem.escape(localUri1);
String localUriUnescaped1 = MetricsSystem.unescape(localUriEscaped1);
assertEquals(localUri1.toString(), localUriUnescaped1);
Alluxio... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testDeploymentMetadata() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final Deployment resultDeployment = this.kubernetesJobMa... |
@Udf(description = "Returns the base 10 logarithm of an INT value.")
public Double log(
@UdfParameter(
value = "value",
description = "the value get the base 10 logarithm of."
) final Integer value
) {
return log(value == null ? null : value.doubleValue())... | @Test
public void shouldHandlePositiveValueAndBase() {
assertThat(udf.log(1), closeTo(0.0, 0.000000000000001));
assertThat(udf.log(1L), closeTo(0.0, 0.000000000000001));
assertThat(udf.log(1.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.log(13), closeTo(2.5649493574615367, 0.000000000000001));
... |
@Override
protected Byte parseSerializeType(String serialization) {
Byte serializeType;
if (SERIALIZE_HESSIAN.equals(serialization)
|| SERIALIZE_HESSIAN2.equals(serialization)) {
serializeType = RemotingConstants.SERIALIZE_CODE_HESSIAN;
} else if (SERIALIZE_PROTOBUF.e... | @Test
public void testParseSerializeType() throws Exception {
ConsumerConfig consumerConfig = new ConsumerConfig().setProtocol("bolt");
ConsumerBootstrap bootstrap = Bootstraps.from(consumerConfig);
BoltClientProxyInvoker invoker = new BoltClientProxyInvoker(bootstrap);
byte actual =... |
public SecApduResponse generateSecureAPDUsRestService(SecApduRequest request, String clientIp) {
SecApduResponse response = new SecApduResponse();
EidSession session = initSession(request, clientIp, response);
if (session == null) return response;
// 1a. check that the content of ef.car... | @Test
public void generateSecureAPDUsRestServiceTest() {
EidSession session = new EidSession();
session.setAtReference("SSSSSSSSSSSSSSSS");
session.setEphemeralKey(ephemeralKey);
session.setKeyReference(2);
session.setTaVersion(2);
session.setPaceVersion(2);
s... |
public Unmarshaller createUnmarshaller(Class<?> clazz) throws JAXBException {
Unmarshaller unmarshaller = getContext(clazz).createUnmarshaller();
if (unmarshallerEventHandler != null) {
unmarshaller.setEventHandler(unmarshallerEventHandler);
}
unmarshaller.setSchema(unmashallerSchema);
return ... | @Test
void buildsUnmarshallerWithCustomEventHandler() throws Exception {
ValidationEventHandler handler = event -> false;
JAXBContextFactory factory =
new JAXBContextFactory.Builder().withUnmarshallerEventHandler(handler).build();
Unmarshaller unmarshaller = factory.createUnmarshaller(Object.clas... |
@Override
public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) {
final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build();
mutableGraph.addNode(entityDescriptor);
final ModelId modelId = entityDescriptor.id();
try {
... | @Test
@MongoDBFixtures("PipelineFacadeTest/pipelines.json")
public void resolve() {
final Stage stage = Stage.builder()
.stage(0)
.match(Stage.Match.EITHER)
.ruleReferences(ImmutableList.of("debug", "no-op"))
.build();
RuleDao rule... |
public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize)
{
// sort ranges by start offset
List<DiskRange> ranges = new ArrayList<>(diskRanges);
Collections.sort(ranges, new Comparator<DiskRange>()
{
... | @Test
public void testMergeGap()
{
List<DiskRange> consistent10ByteGap = ImmutableList.of(new DiskRange(100, 90), new DiskRange(200, 90), new DiskRange(300, 90));
assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(0, BYTE), new DataSize(1, GIGABYTE)), consistent10ByteGap);
... |
public static <
EventTypeT,
EventKeyTypeT,
ResultTypeT,
StateTypeT extends MutableState<EventTypeT, ResultTypeT>>
OrderedEventProcessor<EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT> create(
OrderedProcessingHandler<EventTypeT, EventKeyTypeT, StateTypeT, Resu... | @Test
public void testPerfectOrderingProcessing() throws CannotProvideCoderException {
Event[] events = {
Event.create(0, "id-1", "a"),
Event.create(1, "id-1", "b"),
Event.create(2, "id-1", "c"),
Event.create(3, "id-1", "d"),
Event.create(0, "id-2", "a"),
Event.create(1, "id-2"... |
protected boolean tryProcess2(@Nonnull Object item) throws Exception {
return tryProcess(2, item);
} | @Test
public void when_tryProcess2_then_delegatesToTryProcess() throws Exception {
// When
boolean done = p.tryProcess2(MOCK_ITEM);
// Then
assertTrue(done);
p.validateReceptionOfItem(ORDINAL_2, MOCK_ITEM);
} |
public <T extends BuildableManifestTemplate> ManifestTemplate getManifestListTemplate(
Class<T> manifestTemplateClass) throws IOException {
Preconditions.checkArgument(
manifestTemplateClass == V22ManifestTemplate.class,
"Build an OCI image index is not yet supported");
Preconditions.check... | @Test
public void testGetManifestListTemplate() throws IOException {
// Expected Manifest List JSON
// {
// "schemaVersion":2,
// "mediaType":"application/vnd.docker.distribution.manifest.list.v2+json",
// "manifests":[
// {
// "mediaType":"application/vnd.docker.distribution.... |
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException {
lock.lock();
try {
checkArgument(!req.completed, () ->
"given SendRequest has already been completed");
log.info("Completing send tx with {} outputs totalling {} ... | @Test(expected = Wallet.DustySendRequested.class)
public void sendDustAndMessageWithValueTest() throws Exception {
// Tests sending dust and OP_RETURN with value, should throw DustySendRequested
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
tx.addOutput(... |
public static void verify(NetworkParameters params, Block block, int height, EnumSet<VerifyFlag> flags) throws VerificationException {
verifyHeader(block);
verifyTransactions(params, block, height, flags);
} | @Test
public void testBlockVerification() {
Block.verify(TESTNET, block700000, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
} |
@Override
public void notify(final ConfigChangeEvent value) {
if (value.getEventType().equals(EventType.DELETE)) {
ruleSetting = null;
grouping.setEndpointGroupingRule(new QuickUriGroupingRule());
} else {
ruleSetting = value.getNewValue();
grouping.se... | @Test
public void testWatcher() throws FileNotFoundException {
EndpointNameGrouping endpointNameGrouping = new EndpointNameGrouping();
EndpointNameGroupingRuleWatcher watcher = new EndpointNameGroupingRuleWatcher(
new ModuleProvider() {
@Override
public S... |
@Override
public ByteBuf setMedium(int index, int value) {
throw new ReadOnlyBufferException();
} | @Test
public void shouldRejectSetMedium() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
unmodifiableBuffer(EMPTY_BUFFER).setMedium(0, 0);
}
});
} |
@Override
public WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(Integer userType, String phoneCode) {
WxMaService service = getWxMaService(userType);
try {
return service.getUserService().getPhoneNoInfo(phoneCode);
} catch (WxErrorException e) {
log.error("[getPhoneNoInfo... | @Test
public void testGetWxMaPhoneNumberInfo_exception() throws WxErrorException {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String phoneCode = randomString();
// mock 方法
WxMaUserService userService = mock(WxMaUserService.class);
when(wxMaS... |
public static void extendActiveLock(Duration lockAtMostFor, Duration lockAtLeastFor) {
SimpleLock lock = locks().peekLast();
if (lock == null) throw new NoActiveLockException();
Optional<SimpleLock> newLock = lock.extend(lockAtMostFor, lockAtLeastFor);
if (newLock.isPresent()) {
... | @Test
void shouldFailIfNoActiveLock() {
assertThatThrownBy(() -> LockExtender.extendActiveLock(ofSeconds(1), ofSeconds(0)))
.isInstanceOf(NoActiveLockException.class);
} |
public byte[] toBytes() {
String authzid = authorizationId.isEmpty() ? "" : "a=" + authorizationId;
String extensions = extensionsMessage();
if (!extensions.isEmpty())
extensions = SEPARATOR + extensions;
String message = String.format("n,%s,%sauth=Bearer %s%s%s%s", authzid,... | @Test
public void testBuildClientResponseToBytes() throws Exception {
String expectedMessage = "n,,\u0001auth=Bearer 123.345.567\u0001nineteen=42\u0001\u0001";
Map<String, String> extensions = new HashMap<>();
extensions.put("nineteen", "42");
OAuthBearerClientInitialResponse respon... |
@Override
public Class<? extends MinLabeledStorageBuilder> builder() {
return MinLabeledStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1);
function.calculate();
StorageBuilder<MinLabeledFunction> storageBuilder = function.builder().newInstance();
... |
public void pickSuggestionManually(int index, CharSequence suggestion) {
pickSuggestionManually(index, suggestion, mAutoSpace);
} | @Test
public void testNextWordDeleteAfterPick() {
mAnySoftKeyboardUnderTest.simulateTextTyping("hello face hello face hello face hello face ");
mAnySoftKeyboardUnderTest.simulateTextTyping("hello ");
verifySuggestions(true, "face");
mAnySoftKeyboardUnderTest.pickSuggestionManually(0, "face");
Test... |
public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter(
NetworkService networkService) {
return tsunamiPlugins.entrySet().stream()
.filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT))
.filter(entry -> hasMatchingServiceName(networkService,... | @Test
public void getServiceFingerprinter_whenNoFingerprinterMatches_returnsEmpty() {
NetworkService httpsService =
NetworkService.newBuilder()
.setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80))
.setTransportProtocol(TransportProtocol.TCP)
.setService... |
public final void isIn(Range<T> range) {
if (!range.contains(checkNotNull(actual))) {
failWithActual("expected to be in range", range);
}
} | @Test
public void isInRange() {
Range<Integer> oneToFive = Range.closed(1, 5);
assertThat(4).isIn(oneToFive);
expectFailureWhenTestingThat(6).isIn(oneToFive);
assertThat(expectFailure.getFailure())
.factValue("expected to be in range")
.isEqualTo(oneToFive.toString());
} |
public static String[] tokenizeOnSpace(String s)
{
return Arrays.stream(s.split("(?<=" + StringUtil.PATTERN_SPACE + ")|(?=" + StringUtil.PATTERN_SPACE + ")"))
.toArray(String[]::new);
} | @Test
void testTokenizeOnSpace_happyPath()
{
String[] result = StringUtil.tokenizeOnSpace("a b c");
assertArrayEquals(new String[] {"a", " ", "b", " ", "c"}, result);
} |
public static SerializableFunction<Row, byte[]> getRowToProtoBytesFromSchema(
String schemaString, String messageName) {
Descriptors.Descriptor descriptor = getDescriptorFromProtoSchema(schemaString, messageName);
ProtoDynamicMessageSchema<DynamicMessage> protoDynamicMessageSchema =
ProtoDynamic... | @Test
public void testRowToProtoSchemaWithPackageFunction() {
Row row =
Row.withSchema(SCHEMA)
.withFieldValue("id", 1234)
.withFieldValue("name", "Doe")
.withFieldValue("active", false)
.withFieldValue("address.city", "seattle")
.withFieldValue(... |
public boolean ifNodeExist(String path) {
return zkClient.ifNodeExist(path);
} | @Test
public void testIfNodeExist() {
boolean result = zooKeeperBufferedClient.ifNodeExist(PARENT_PATH);
Assert.assertTrue(result);
} |
public FEELFnResult<TemporalAmount> invoke(@ParameterName("from") Temporal from, @ParameterName("to") Temporal to) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
if ( to == null ) {
return FEELF... | @Test
void invokeUnsupportedTemporal() {
FunctionTestUtil.assertResultError(yamFunction.invoke(Instant.EPOCH, Instant.EPOCH),
InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(yamFunction.invoke(LocalDate.of(2017, 1, 1), Instant.EPOCH),
... |
public boolean isCipherColumn(final String columnName) {
return columns.values().stream().anyMatch(each -> each.getCipher().getName().equalsIgnoreCase(columnName));
} | @Test
void assertIsCipherColumn() {
assertTrue(encryptTable.isCipherColumn("CipherColumn"));
} |
public List<String> getDeletedIds() {
return deletedIds;
} | @Test
public void testGetDeletedIds() {
List<String> ids = roleDOList
.stream()
.map(BaseDO::getId)
.collect(Collectors.toList());
assertEquals(ids, batchRoleDeletedEventTest.getDeletedIds());
List<String> emptyIds = emptyRoleDOList
... |
@Override
public Object getField(final String reference) {
final Object unconverted = getUnconvertedField(FieldReference.from(reference));
return unconverted == null ? null : Javafier.deep(unconverted);
} | @Test
public void testGetFieldList() throws Exception {
Map<String, Object> data = new HashMap<>();
List<Object> l = new ArrayList<>();
data.put("foo", l);
l.add(1);
Event e = new Event(data);
assertEquals(1L, e.getField("[foo][0]"));
} |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testEnumSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(EnumMessage.class));
assertEquals(ENUM_SCHEMA, schema);
} |
@ApiOperation(value = "Get a deployment resource", tags = { "Deployment" }, notes = "Replace ** by ResourceId")
/*
* @ApiImplicitParams({
*
* @ApiImplicitParam(name = "resourceId", dataType = "string", value =
* "The id of the resource to get. Make sure you URL-encode the resourceId in case it ... | @Test
public void testGetDeploymentResource() throws Exception {
try {
String rawResourceName = "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml";
Deployment deployment = repositoryService.createDeployment().name("Deployment 1").addClasspathResource(rawResourceName... |
protected BaseNode getNullNode() {
return parseNotEmptyInput("null");
} | @Test
void getNullNode() {
assertThat(rangeFunction.getNullNode()).isInstanceOf(NullNode.class);
} |
public static boolean instanceOfToolbar(Object view) {
return ReflectUtil.isInstance(view, "androidx.appcompat.widget.Toolbar", "android.support.v7.widget.Toolbar", "android.widget.Toolbar");
} | @Test
public void instanceOfToolbar() {
CheckBox textView1 = new CheckBox(mApplication);
textView1.setText("child1");
Assert.assertFalse(SAViewUtils.instanceOfToolbar(textView1));
} |
public static Map<String, String> getKiePMMLTreeModelSourcesMap(final TreeCompilationDTO compilationDTO) {
logger.trace("getKiePMMLTreeModelSourcesMap {} {} {}", compilationDTO.getFields(),
compilationDTO.getModel(),
compilationDTO.getPackageName());
String clas... | @Test
void getKiePMMLTreeModelSourcesMap() {
CommonCompilationDTO<TreeModel> source = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmml1,
... |
@Override
public List<ImportValidationFeedback> verifyRule( Object subject ) {
List<ImportValidationFeedback> feedback = new ArrayList<>();
if ( !isEnabled() || !( subject instanceof TransMeta ) ) {
return feedback;
}
TransMeta transMeta = (TransMeta) subject;
String description = transMe... | @Test
public void testVerifyRule_NullDescription_DisabledRule() {
TransformationHasDescriptionImportRule importRule = getImportRule( 10, false );
TransMeta transMeta = new TransMeta();
transMeta.setDescription( null );
List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null );
... |
@Override
public boolean assign(final Map<ProcessId, ClientState> clients,
final Set<TaskId> allTaskIds,
final Set<TaskId> statefulTaskIds,
final RackAwareTaskAssignor rackAwareTaskAssignor,
final AssignmentConfi... | @Test
public void shouldViolateBalanceToPreserveActiveTaskStickiness() {
final ClientState c1 = createClientWithPreviousActiveTasks(PID_1, 1, TASK_0_0, TASK_0_1, TASK_0_2);
final ClientState c2 = createClient(PID_2, 1);
final List<TaskId> taskIds = asList(TASK_0_0, TASK_0_1, TASK_0_2);
... |
public long put(final K key, final V value, final long timestamp) {
if (timestampedStore != null) {
timestampedStore.put(key, ValueAndTimestamp.make(value, timestamp));
return PUT_RETURN_CODE_IS_LATEST;
}
if (versionedStore != null) {
return versionedStore.put... | @Test
public void shouldPutToTimestampedStore() {
givenWrapperWithTimestampedStore();
final long putReturnCode = wrapper.put(KEY, VALUE_AND_TIMESTAMP.value(), VALUE_AND_TIMESTAMP.timestamp());
assertThat(putReturnCode, equalTo(PUT_RETURN_CODE_IS_LATEST));
verify(timestampedStore).p... |
public static GenericRecord convertToAvro(Schema schema, Message message) {
return AvroSupport.convert(schema, message);
} | @Test
public void oneOfSchema() throws IOException {
Schema.Parser parser = new Schema.Parser();
Schema convertedSchema = parser.parse(getClass().getClassLoader().getResourceAsStream("schema-provider/proto/oneof_schema.avsc"));
WithOneOf input = WithOneOf.newBuilder().setLong(32L).build();
GenericReco... |
Getter getGetter(Object targetObject, String attributeName, boolean failOnMissingReflectiveAttribute) {
Getter getter = getterCache.getGetter(targetObject.getClass(), attributeName);
if (getter == null) {
getter = instantiateGetter(targetObject, attributeName, failOnMissingReflectiveAttribut... | @Test
public void when_getGetterExtractor_then_getterInCacheWithProperType() {
// GIVEN
AttributeConfig config
= new AttributeConfig("gimmePower", "com.hazelcast.query.impl.getters.ExtractorsTest$PowerExtractor");
Extractors extractors = createExtractors(config);
// ... |
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
final BigDecimal amount, final String currency, final String returnUrl,
final String cancelUrl, final String locale) {
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePayme... | @Test
void createPayPalOneTimePayment() {
final HttpResponse<Object> response = mock(HttpResponse.class);
when(httpClient.sendAsync(any(), any()))
.thenReturn(CompletableFuture.completedFuture(response));
final String paymentId = "PAYID-AAA1AAAA1A11111AA111111A";
when(response.body())
... |
@Override
public void forEachEventTimeTimer(BiConsumerWithException<N, Long, Exception> consumer) {
throw new UnsupportedOperationException(
"The BatchExecutionInternalTimeService should not be used in State Processor API.");
} | @Test
void testForEachProcessingTimeTimerUnsupported() {
BatchExecutionInternalTimeService<Object, Object> timeService =
new BatchExecutionInternalTimeService<>(
new TestProcessingTimeService(),
LambdaTrigger.eventTimeTrigger(timer -> {}));
... |
private int getDatanodeInfo(String[] argv, int i) throws IOException {
ClientDatanodeProtocol dnProxy = getDataNodeProxy(argv[i]);
try {
DatanodeLocalInfo dnInfo = dnProxy.getDatanodeInfo();
System.out.println(dnInfo.getDatanodeLocalReport());
} catch (IOException ioe) {
throw new IOExcept... | @Test(timeout = 30000)
public void testGetDatanodeInfo() throws Exception {
redirectStream();
final DFSAdmin dfsAdmin = new DFSAdmin(conf);
for (int i = 0; i < cluster.getDataNodes().size(); i++) {
resetStream();
final DataNode dn = cluster.getDataNodes().get(i);
final String addr = Str... |
public ImportedProject importProject(ImportProjectRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
checkNewCodeDefinitionParam(request.newCodeDefinitionType(), request.newCodeDefinitionValue());
AlmSettingDto almSetting = dbClient.almSettingDao().selectByUuid(dbSession, reque... | @Test
void createdImportedProject_whenAlmSettingDoesntExist_throws() {
userSession.logIn().addPermission(PROVISION_PROJECTS);
DbSession dbSession = mockDbSession();
when(dbClient.almSettingDao().selectByUuid(dbSession, ALM_SETTING_ID)).thenReturn(Optional.empty());
ImportProjectRequest request = new ... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComFieldListPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_FIELD_LIST, payload, connectionSession), instanceOf(MySQLComFieldListPacket.class));
} |
@VisibleForTesting
ImmutableList<EventWithContext> eventsFromAggregationResult(EventFactory eventFactory, AggregationEventProcessorParameters parameters, AggregationResult result)
throws EventProcessorException {
final ImmutableList.Builder<EventWithContext> eventsWithContext = ImmutableList.bui... | @Test
public void testEventsFromAggregationResultWithConditions() throws EventProcessorException {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.minusHours(1).plusMillis(SEARCH_WINDOW_MS));
// We expect to ge... |
@Override
public void onChange(List<JobRunrMetadata> metadataList) {
if (this.serversWithLongGCCyclesMetadataList == null || this.serversWithLongGCCyclesMetadataList.size() != metadataList.size()) {
problems.removeProblemsOfType(CpuAllocationIrregularityProblem.PROBLEM_TYPE);
if (!me... | @Test
void ifCpuAllocationIrregularitiesIsDeletedThenProblemIsRemoved() {
final JobRunrMetadata jobRunrMetadata = new JobRunrMetadata(CpuAllocationIrregularityNotification.class.getSimpleName(), "BackgroundJobServer " + UUID.randomUUID(), "23");
cpuAllocationIrregularityProblemHandler.onChange(asLis... |
public static String getGroupedNameOptional(final String serviceName, final String groupName) {
return groupName + Constants.SERVICE_INFO_SPLITER + serviceName;
} | @Test
void testGetGroupedNameOptional() {
String onlyGroupName = NamingUtils.getGroupedNameOptional(StringUtils.EMPTY, "groupA");
assertEquals("groupA@@", onlyGroupName);
String onlyServiceName = NamingUtils.getGroupedNameOptional("serviceA", StringUtils.EMPTY);
assertEquals... |
public String extractVersion(String rawXml) {
Matcher m = p.matcher(rawXml);
if (m.find()) {
return m.group(1);
}
throw new IllegalArgumentException("Impossible to extract version from the file");
} | @Test
public void extractVersionWhenMoreVersionAttributesArePresent() {
String version = instance.extractVersion("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ScenarioSimulationModel version=\"1.2\">\n" +
... |
public Comparator<?> getValueComparator(int column) {
return valueComparators[column];
} | @Test
public void getDefaultComparatorForIntegerClass() {
ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("integer", Integer.class));
assertThat(sorter.getValueComparator(0), is(CoreMatchers.notNullValue()));
} |
@VisibleForTesting
public static JobGraph createJobGraph(StreamGraph streamGraph) {
return new StreamingJobGraphGenerator(
Thread.currentThread().getContextClassLoader(),
streamGraph,
null,
Runnable::run)
... | @Test
void testDisabledCheckpointing() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromData(0).print();
StreamGraph streamGraph = env.getStreamGraph();
assertThat(streamGraph.getCheckpointConfig().isCheckpointingEnable... |
public static Option<String> getRawValueWithAltKeys(Configuration conf,
ConfigProperty<?> configProperty) {
String value = conf.get(configProperty.key());
if (value != null) {
return Option.of(value);
}
for (String alternative : configProperty.... | @Test
public void testGetRawValueWithAltKeysFromHadoopConf() {
Configuration conf = new Configuration();
assertEquals(Option.empty(), getRawValueWithAltKeys(conf, TEST_BOOLEAN_CONFIG_PROPERTY));
boolean setValue = !Boolean.parseBoolean(TEST_BOOLEAN_CONFIG_PROPERTY.defaultValue());
conf.setBoolean(TES... |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldResolveConsumerConfig() {
assertThat(resolver.resolve(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, true),
is(resolvedItem(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, CONSUMER_CONFIG_DEF)));
} |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
var now = clock.instant();
var bearerToken = requestBearerToken(req).orElse(null);
if (bearerToken == null) {
log.fine("Missing bearer token");
return Optional.of(new ErrorResponse(Response.St... | @Test
void rejects_tokens_on_empty_clients() {
var req = FilterTestUtils.newRequestBuilder()
.withMethod(Method.GET)
.withHeader("Authorization", "Bearer " + UNKNOWN_TOKEN.secretTokenString())
.build();
var responseHandler = new MockResponseHandler();
... |
@SuppressWarnings("checkstyle:MissingSwitchDefault")
@Override
protected void doCommit(TableMetadata base, TableMetadata metadata) {
int version = currentVersion() + 1;
CommitStatus commitStatus = CommitStatus.FAILURE;
/* This method adds no fs scheme, and it persists in HTS that way. */
final Stri... | @Test
void testDoCommitCherryPickFirstSnapshot() throws IOException {
List<Snapshot> testWapSnapshots = IcebergTestUtil.getWapSnapshots().subList(0, 1);
// add 1 staged snapshot to the base metadata
TableMetadata base =
TableMetadata.buildFrom(BASE_TABLE_METADATA).addSnapshot(testWapSnapshots.get(... |
public static boolean isRuleActiveVersionPath(final String rulePath) {
Pattern pattern = Pattern.compile(getRuleNameNode() + "/(\\w+)" + ACTIVE_VERSION_SUFFIX, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(rulePath);
return matcher.find();
} | @Test
void assertIsRuleActiveVersionPath() {
assertTrue(GlobalNodePath.isRuleActiveVersionPath("/rules/transaction/active_version"));
} |
public static <T> boolean isReferringTo(final Reference<T> ref, final T obj)
{
return ref.get() == obj;
} | @Test
void validateIsReferringTo()
{
final Long objOne = 42L;
final Long objTwo = 43L; // Need different value to make sure it is a different instance...
final WeakReference<Long> ref = new WeakReference<>(objOne);
assertTrue(References.isReferringTo(ref, objOne));
assert... |
public Optional<EndpointCertificateSecrets> readEndpointCertificateSecrets(EndpointCertificateMetadata metadata) {
return Optional.of(readFromSecretStore(metadata));
} | @Test
void returns_missing_when_cert_version_not_found() {
DefaultEndpointCertificateSecretStore defaultEndpointCertificateSecretStore = new DefaultEndpointCertificateSecretStore(new MockSecretStore());
TestEndpointCertificateSecretStore zerosslStore = new TestEndpointCertificateSecretStore(null, nu... |
public static String[] convertToStringArray(Object value) {
if (value == null) {
return null;
}
String text = value.toString();
if (text == null || text.length() == 0) {
return null;
}
StringTokenizer stok = new StringTokenizer(text, ",");
... | @Test
public void testConvertToStringArray() throws Exception {
assertNull(StringArrayConverter.convertToStringArray(null));
assertNull(StringArrayConverter.convertToStringArray(""));
String[] array = StringArrayConverter.convertToStringArray("foo");
assertEquals(1, array.length);
... |
@Override
public String toString() {
if (command != null) {
return "SmppMessage: " + command;
} else {
return "SmppMessage: " + getBody();
}
} | @Test
public void toStringShouldReturnTheBodyIfTheCommandIsNull() {
message = new SmppMessage(camelContext, null, new SmppConfiguration());
assertEquals("SmppMessage: null", message.toString());
} |
public static String from(Path path) {
return from(path.toString());
} | @Test
void testJavascriptContentType() {
assertThat(ContentType.from(Path.of("javascript.js"))).isEqualTo(TEXT_JAVASCRIPT);
} |
@Override
public Map<String, String> generationCodes(Long tableId) {
// 校验是否已经存在
CodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
List<CodegenColumnDO> columns = codegenColumnMapper.se... | @Test
public void testGenerationCodes_tableNotExists() {
assertServiceException(() -> codegenService.generationCodes(randomLongId()),
CODEGEN_TABLE_NOT_EXISTS);
} |
public static String toStr(Object value, String defaultValue) {
return convertQuietly(String.class, value, defaultValue);
} | @Test
public void toStrTest4() {
// 被当作八进制
@SuppressWarnings("OctalInteger") final String result = Convert.toStr(001200);
assertEquals("640", result);
} |
@Override
public SortedSet<BrokerStatus> getAvailablePrimaryBrokers(SortedSet<BrokerStatus> primaryCandidates) {
SortedSet<BrokerStatus> availablePrimaries = new TreeSet<BrokerStatus>();
for (BrokerStatus status : primaryCandidates) {
if (this.autoFailoverPolicy.isBrokerAvailable(status)... | @Test
public void testGetAvailablePrimaryBrokers() throws Exception {
NamespaceIsolationPolicyImpl defaultPolicy = this.getDefaultPolicy();
SortedSet<BrokerStatus> brokerStatus = new TreeSet<>();
SortedSet<BrokerStatus> expectedAvailablePrimaries = new TreeSet<>();
for (int i = 0; i ... |
@Udf
public String lcase(
@UdfParameter(description = "The string to lower-case") final String input) {
if (input == null) {
return null;
}
return input.toLowerCase();
} | @Test
public void shouldRetainLowerCaseInput() {
final String result = udf.lcase("foo");
assertThat(result, is("foo"));
} |
@Override
public Iterator<Text> search(String term) {
if (invertedFile.containsKey(term)) {
ArrayList<Text> hits = new ArrayList<>(invertedFile.get(term));
return hits.iterator();
} else {
return Collections.emptyIterator();
}
} | @Test
public void testSearchRomanticComedy() {
System.out.println("search 'romantic comedy'");
String[] terms = {"romantic", "comedy"};
Iterator<Relevance> hits = corpus.search(new BM25(), terms);
int n = 0;
while (hits.hasNext()) {
n++;
Relevance hit ... |
public static BaggageField constant(String name, @Nullable String value) {
return new BaggageField(name, new Constant(value));
} | @Test void constant() {
BaggageField constant = BaggageFields.constant("foo", "bar");
assertThat(constant.getValue(context)).isEqualTo("bar");
assertThat(constant.getValue(extracted)).isEqualTo("bar");
BaggageField constantNull = BaggageFields.constant("foo", null);
assertThat(constantNull.getValue... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processHighlightings(lineBuilder);
} catch (RangeOffsetConverterException e) {
readError = new ReadError(HIGHLIGHTING, lineBuilder.getLine());
LOG.debug(format("In... | @Test
public void keep_existing_processed_highlighting_when_range_offset_converter_throw_RangeOffsetConverterException() {
TextRange textRange2 = newTextRange(LINE_2, LINE_2);
doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange2, LINE_2, DEFAULT_LINE_LENGTH);
T... |
@Override
public void checkBeforeUpdate(final DropReadwriteSplittingRuleStatement sqlStatement) {
if (!sqlStatement.isIfExists()) {
checkToBeDroppedRuleNames(sqlStatement);
}
checkToBeDroppedInUsed(sqlStatement);
} | @Test
void assertCheckSQLStatementWithoutToBeDroppedRule() throws RuleDefinitionException {
ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class);
when(rule.getConfiguration()).thenReturn(new ReadwriteSplittingRuleConfiguration(Collections.emptyList(), Collections.emptyMap()));
ex... |
@Override
public List<DeptDO> getChildDeptList(Long id) {
List<DeptDO> children = new LinkedList<>();
// 遍历每一层
Collection<Long> parentIds = Collections.singleton(id);
for (int i = 0; i < Short.MAX_VALUE; i++) { // 使用 Short.MAX_VALUE 避免 bug 场景下,存在死循环
// 查询当前层,所有的子部门
... | @Test
public void testGetChildDeptList() {
// mock 数据(1 级别子节点)
DeptDO dept1 = randomPojo(DeptDO.class, o -> o.setName("1"));
deptMapper.insert(dept1);
DeptDO dept2 = randomPojo(DeptDO.class, o -> o.setName("2"));
deptMapper.insert(dept2);
// mock 数据(2 级子节点)
De... |
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId,
serviceName, instance);
if (instance.isEphemeral()) {
... | @Test
void testDeregisterServiceForEphemeral() throws Exception {
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate");
nacosRestTemplateField.setAccessible(true);
n... |
public Preference<Boolean> getBoolean(@StringRes int prefKey, @BoolRes int defaultValue) {
return mRxSharedPreferences.getBoolean(
mResources.getString(prefKey), mResources.getBoolean(defaultValue));
} | @Test
public void testConvertTheme() {
SharedPrefsHelper.setPrefsValue(
"settings_key_keyboard_theme_key", "28860f10-cf16-11e1-9b23-0800200c9a66");
SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 10);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedP... |
static <T> T getWildcardMappedObject(final Map<String, T> mapping, final String query) {
T value = mapping.get(query);
if (value == null) {
for (String key : mapping.keySet()) {
// Turn the search key into a regex, using all characters but the * as a literal.
... | @Test
public void testSubdirWildcardExtensionConcat() throws Exception
{
// Setup test fixture.
final Map<String, Object> haystack = Map.of("myplugin/baz/*.jsp", new Object());
// Execute system under test.
final Object result = PluginServlet.getWildcardMappedObject(haystack, "m... |
@Override
public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Error... | @Test
public void testRebalanceMetricsOnSuccessfulRebalance() {
ShareMembershipManager membershipManager = createMembershipManagerJoiningGroup();
ShareGroupHeartbeatResponse heartbeatResponse = createShareGroupHeartbeatResponse(new ShareGroupHeartbeatResponseData.Assignment());
membershipMan... |
public static RuleDescriptionSectionDtoBuilder builder() {
return new RuleDescriptionSectionDtoBuilder();
} | @Test
void setKey_whenDefaultAlreadySet_shouldThrow() {
RuleDescriptionSectionDto.RuleDescriptionSectionDtoBuilder builderWithDefault = RuleDescriptionSectionDto.builder()
.setDefault();
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> builderWithDefault.key("balbal"))
... |
public boolean isValidatedPath(final String path) {
return pathPattern.matcher(path).find();
} | @Test
void assertIsValidPathWithNullParentNode() {
UniqueRuleItemNodePath uniqueRuleItemNodePath = new UniqueRuleItemNodePath(new RuleRootNodePath("foo"), "test_path");
assertTrue(uniqueRuleItemNodePath.isValidatedPath("/word1/word2-/rules/foo/test_path/versions/1234"));
} |
@Override
public int getattr(String path, FileStat stat) {
return AlluxioFuseUtils.call(
LOG, () -> getattrInternal(path, stat), FuseConstants.FUSE_GETATTR, "path=%s", path);
} | @Test
public void getattr() throws Exception {
// set up status
FileInfo info = new FileInfo();
info.setLength(4 * Constants.KB + 1);
info.setLastAccessTimeMs(1000);
info.setLastModificationTimeMs(1000);
String userName = System.getProperty("user.name");
info.setOwner(userName);
Option... |
void generate(MessageSpec message) throws Exception {
if (message.struct().versions().contains(Short.MAX_VALUE)) {
throw new RuntimeException("Message " + message.name() + " does " +
"not specify a maximum version.");
}
structRegistry.register(message);
schema... | @Test
public void testInvalidNullDefaultForPotentiallyNonNullableArray() throws Exception {
MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList(
"{",
" \"type\": \"request\",",
" \"name\": \"FooBar\",",
... |
@Override
@PublicAPI(usage = ACCESS)
public JavaClass toErasure() {
return erasure;
} | @Test
public void erased_unbound_type_variable_is_java_lang_Object() {
@SuppressWarnings("unused")
class ClassWithUnboundTypeParameter<T> {
}
JavaTypeVariable<JavaClass> type = new ClassFileImporter().importClass(ClassWithUnboundTypeParameter.class).getTypeParameters().get(0);
... |
public static <T, IdT> Deduplicate.WithRepresentativeValues<T, IdT> withRepresentativeValueFn(
SerializableFunction<T, IdT> representativeValueFn) {
return new Deduplicate.WithRepresentativeValues<T, IdT>(
DEFAULT_TIME_DOMAIN, DEFAULT_DURATION, representativeValueFn, null, null);
} | @Test
public void withLambdaRepresentativeValuesFnNoTypeDescriptorShouldThrow() {
Multimap<Integer, String> predupedContents = HashMultimap.create();
predupedContents.put(3, "foo");
predupedContents.put(4, "foos");
predupedContents.put(6, "barbaz");
predupedContents.put(6, "bazbar");
PCollect... |
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) {
return drlxParse(patternType, bindingId, expression, false);
} | @Test
public void bigDecimalInWithBD() {
SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "(money in (100B, 200B))");
assertThat(result.getExpr().toString()).isEqualTo("D.eval(org.drools.model.operators.InOperator.INSTANCE, _this.getMoney(), new java.mat... |
@Override
public List<RemoteInstance> queryRemoteNodes() {
List<RemoteInstance> remoteInstances = new ArrayList<>();
try {
HealthClient healthClient = client.healthClient();
// Discover only "passing" nodes
List<ServiceHealth> nodes = healthClient.getHealthyServic... | @Test
public void queryRemoteNodes() {
registerSelfRemote();
List<ServiceHealth> serviceHealths = mockHealth();
when(consulResponse.getResponse()).thenReturn(serviceHealths);
List<RemoteInstance> remoteInstances = coordinator.queryRemoteNodes();
assertEquals(2, remoteInstance... |
@Override
public ExecuteContext after(ExecuteContext context) {
if (InvokeUtils.isRocketMqInvokeBySermant(Thread.currentThread().getStackTrace())) {
return context;
}
DefaultLitePullConsumerWrapper wrapper = RocketMqPullConsumerController
.getPullConsumerWrapper((... | @Test
public void testAfter() {
ExecuteContext context = ExecuteContext.forMemberMethod(pullConsumer, null, new Object[]{messageQueues},
null, null);
// wrapper为null
interceptor.after(context);
Assert.assertEquals(PullConsumerLocalInfoUtils.getSubscriptionType().name... |
@VisibleForTesting
static VertexParallelismStore computeVertexParallelismStoreForExecution(
JobGraph jobGraph,
SchedulerExecutionMode executionMode,
Function<JobVertex, Integer> defaultMaxParallelismFunc) {
if (executionMode == SchedulerExecutionMode.REACTIVE) {
... | @Test
void testComputeVertexParallelismStoreForExecutionInDefaultMode() {
JobVertex v1 = createNoOpVertex("v1", 1, 50);
JobVertex v2 = createNoOpVertex("v2", 50, 50);
JobGraph graph = streamingJobGraph(v1, v2);
VertexParallelismStore parallelismStore =
AdaptiveSchedu... |
@Override
public Iterator<ConfigDataEnvironmentContributor> iterator() {
return this.root.iterator();
} | @Test
void iteratorWhenSingleContributorReturnsSingletonIterator() {
ConfigDataEnvironmentContributor contributor = createBoundContributor("a");
assertThat(asLocationsList(contributor.iterator())).containsExactly("a");
} |
public void merge() {
if (conditions.size() > 1) {
Collection<ShardingCondition> result = new LinkedList<>();
result.add(conditions.remove(conditions.size() - 1));
while (!conditions.isEmpty()) {
findUniqueShardingCondition(result, conditions.remove(conditions... | @Test
void assertMerge() {
ShardingConditions multipleShardingConditions = createMultipleShardingConditions();
multipleShardingConditions.merge();
assertThat(multipleShardingConditions.getConditions().size(), is(2));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.