focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testToaPbNew() { when(client.getVarbitValue(Varbits.TOA_MEMBER_1_HEALTH)).thenReturn(27); when(client.getVarbitValue(Varbits.TOA_MEMBER_2_HEALTH)).thenReturn(30); when(client.getVarbitValue(Varbits.TOA_MEMBER_3_HEALTH)).thenReturn(20); when(client.getVarbitValue(Varbits.TOA_MEMBER_4_HEALTH))...
static <T> Optional<T> lookupByNameAndType(CamelContext camelContext, String name, Class<T> type) { return Optional.ofNullable(ObjectHelper.isEmpty(name) ? null : name) .map(n -> EndpointHelper.isReferenceParameter(n) ? EndpointHelper.resolveReferenceParameter(camelContex...
@Test void testLookupByNameAndTypeWithEmptyName() { String name = ""; Optional<Object> object = DynamicRouterRecipientListHelper.lookupByNameAndType(camelContext, name, Object.class); Assertions.assertFalse(object.isPresent()); }
public Result runExtractor(String value) { final Matcher matcher = pattern.matcher(value); final boolean found = matcher.find(); if (!found) { return null; } final int start = matcher.groupCount() > 0 ? matcher.start(1) : -1; final int end = matcher.groupCou...
@Test public void testReplacementWithOnePlaceholder() throws Exception { final Message message = messageFactory.createMessage("Test Foobar", "source", Tools.nowUTC()); final RegexReplaceExtractor extractor = new RegexReplaceExtractor( metricRegistry, "id", ...
@Override public Result detect(ChannelBuffer in) { int prefaceLen = Preface.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceLen); if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) { return Result.UNRECOGNIZED; } if (bytes...
@Test void testDetect_Unrecognized() { DubboDetector detector = new DubboDetector(); ChannelBuffer in = ChannelBuffers.wrappedBuffer(new byte[] {(byte) 0x00, (byte) 0x00}); assertEquals(DubboDetector.Result.UNRECOGNIZED, detector.detect(in)); }
public static boolean isNameCoveredByPattern( String name, String pattern ) { if ( name == null || name.isEmpty() || pattern == null || pattern.isEmpty() ) { throw new IllegalArgumentException( "Arguments cannot be null or empty." ); } final String needle = name.toLowerC...
@Test public void testNameCoverageUnequal() throws Exception { // setup final String name = "xmpp.example.org"; final String pattern = "something.completely.different"; // do magic final boolean result = DNSUtil.isNameCoveredByPattern( name, pattern ); // verify...
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testDoNotReuseForTheOtherKey() { KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); underTest.showPreviewForKey(mTestKeys[0], "y", mKeyboardView, mTheme); final PopupWindow firstPopupWindow = getLatestCreatedPopupWindow(); ...
@Override public long getExpectedInsertions() { return get(getExpectedInsertionsAsync()); }
@Test public void testNotInitializedOnExpectedInsertions() { Assertions.assertThrows(RedisException.class, () -> { RBloomFilter<String> filter = redisson.getBloomFilter("filter"); filter.getExpectedInsertions(); }); }
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testUnsupportedVersionInProduceRequest() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(producerId, Errors.NONE);...
public boolean poll(Timer timer, boolean waitForJoinGroup) { maybeUpdateSubscriptionMetadata(); invokeCompletedOffsetCommitCallbacks(); if (subscriptions.hasAutoAssignedPartitions()) { if (protocol == null) { throw new IllegalStateException("User configured " + Cons...
@Test public void testAutoCommitDynamicAssignmentRebalance() { try (ConsumerCoordinator coordinator = buildCoordinator(rebalanceConfig, new Metrics(), assignors, true, subscriptions)) { subscriptions.subscribe(singleton(topic1), Optional.of(rebalanceListener)); client.prepareResponse...
public static void checkBetaIps(String betaIps) throws NacosException { if (StringUtils.isBlank(betaIps)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, BETAIPS_INVALID_MSG); } String[] ipsArr = betaIps.split(","); for (String ip : ipsArr) { if (!...
@Test void testCheckBetaIps() throws NacosException { ParamUtils.checkBetaIps("127.0.0.1"); }
@Override public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) { Collection<Stri...
@Test void assertDecideWhenNotContainsShardingTable() { ShardingRule rule = mock(ShardingRule.class); when(rule.getShardingLogicTableNames(Arrays.asList("t_order", "t_order_item"))).thenReturn(Collections.emptyList()); when(rule.findShardingTable("t_order")).thenReturn(Optional.of(mock(Shard...
@Override public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context) throws KeySourceException { var jwksUrl = discoverJwksUrl(); try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) { return jwkSetSource.getJWKSet(null...
@Test void getJWKSet_badJwksUri(WireMockRuntimeInfo wm) { var discoveryUrl = URI.create(wm.getHttpBaseUrl()).resolve(DISCOVERY_PATH); var jwksUrl = "wut://bad?"; stubFor(get(DISCOVERY_PATH).willReturn(okJson("{\"jwks_uri\": \"%s\"}".formatted(jwksUrl)))); stubFor(get(JWKS_PATH).willReturn(serviceU...
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_emptyCluster() { NamespaceName.get("pulsar", "", "namespace"); }
public void updateAutoCommitTimer(final long currentTimeMs) { this.autoCommitState.ifPresent(t -> t.updateTimer(currentTimeMs)); }
@Test public void testAsyncAutocommitNotRetriedAfterException() { long commitInterval = retryBackoffMs * 2; CommitRequestManager commitRequestManager = create(true, commitInterval); TopicPartition tp = new TopicPartition("topic", 1); subscriptionState.assignFromUser(Collections.singl...
public Range intersect(Range other) { checkTypeCompatibility(other); if (!this.overlaps(other)) { throw new IllegalArgumentException("Cannot intersect non-overlapping ranges"); } Marker lowMarker = Marker.max(low, other.getLow()); Marker highMarker = Marker.min(hi...
@Test public void testIntersect() { assertEquals(Range.greaterThan(BIGINT, 1L).intersect(Range.lessThanOrEqual(BIGINT, 2L)), Range.range(BIGINT, 1L, false, 2L, true)); assertEquals(Range.range(BIGINT, 1L, true, 3L, false).intersect(Range.equal(BIGINT, 2L)), Range.equal(BIGINT, 2L)); asse...
public static List<String> shellSplit(CharSequence string) { List<String> tokens = new ArrayList<>(); if ( string == null ) { return tokens; } boolean escaping = false; char quoteChar = ' '; boolean quoting = false; StringBuilder current = new StringBu...
@Test public void escapedSpacesDoNotBreakUpTokens() { assertEquals(List.of("three four"), StringUtils.shellSplit("three\\ four")); }
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testMissedDoubleMatchWithInvalidValue() { StreamRule rule = getSampleRule(); rule.setValue("LOL I AM NOT EVEN A NUMBER"); Message msg = getSampleMessage(); msg.addField("something", "90000.23"); StreamRuleMatcher matcher = getMatcher(rule); assertF...
UserGroupInformation ugi() throws IOException { UserGroupInformation ugi; try { final Token<DelegationTokenIdentifier> token = params.delegationToken(); // Create nonTokenUGI when token is null regardless of security. // This makes it possible to access the data stored in secure DataNode ...
@Test public void testUGICacheInSecure() throws Exception { String uri1 = WebHdfsFileSystem.PATH_PREFIX + PATH + "?op=OPEN" + Param.toSortedString("&", new OffsetParam((long) OFFSET), new LengthParam((long) LENGTH), new UserParam("root")); String uri2 = WebHdfsFileSystem.P...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerial...
@Test void addingAnOptionalFieldsIsCompatibleAsIs() { assertThat( AvroSerializerSnapshot.resolveSchemaCompatibility( FIRST_NAME, FIRST_REQUIRED_LAST_OPTIONAL)) .is(isCompatibleAfterMigration()); }
public Map<String, String> getContent() { if (CollectionUtils.isEmpty(content)) { content = new HashMap<>(); } return content; }
@Test public void test1() { Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull(); }
public List<IssueDto> sort() { String sort = query.sort(); Boolean asc = query.asc(); if (sort != null && asc != null) { return getIssueProcessor(sort).sort(issues, asc); } return issues; }
@Test public void should_sort_by_desc_severity() { IssueDto issue1 = new IssueDto().setKee("A").setSeverity("INFO"); IssueDto issue2 = new IssueDto().setKee("B").setSeverity("BLOCKER"); IssueDto issue3 = new IssueDto().setKee("C").setSeverity("MAJOR"); List<IssueDto> dtoList = newArrayList(issue1, iss...
public static TopicMessageType getMessageType(SendMessageRequestHeader requestHeader) { Map<String, String> properties = MessageDecoder.string2messageProperties(requestHeader.getProperties()); String traFlag = properties.get(MessageConst.PROPERTY_TRANSACTION_PREPARED); TopicMessageType topicMess...
@Test public void testGetMessageTypeAsFifo() { SendMessageRequestHeader requestHeader = new SendMessageRequestHeader(); Map<String, String> map = new HashMap<>(); map.put(MessageConst.PROPERTY_SHARDING_KEY, "shardingKey"); requestHeader.setProperties(MessageDecoder.messageProperties2...
public void execute(InputModuleHierarchy moduleHierarchy) { DefaultInputModule root = moduleHierarchy.root(); // dont apply to root. Root is done by InputProjectProvider for (DefaultInputModule sub : moduleHierarchy.children(root)) { if (!Objects.equals(root.getWorkDir(), sub.getWorkDir())) { ...
@Test public void execute_doesnt_fail_if_nothing_to_clean() { temp.delete(); initializer.execute(hierarchy); }
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) { if (null == source) { return null; } T target = ReflectUtil.newInstanceIfPossible(tClass); copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); return target; }
@Test public void issuesI53O9JTest() { final Map<String, String> map = new HashMap<>(); map.put("statusIdUpdateTime", ""); final WkCrmCustomer customer = new WkCrmCustomer(); BeanUtil.copyProperties(map, customer); assertNull(customer.getStatusIdUpdateTime()); }
static Schema<?> buildSchema(String keySchema, String schema, String keyValueEncodingType) { switch (keyValueEncodingType) { case KEY_VALUE_ENCODING_TYPE_NOT_SET: return buildComponentSchema(schema); case KEY_VALUE_ENCODING_TYPE_SEPARATED: return Schema.Ke...
@Test public void testBuildSchema() { // default assertEquals(SchemaType.BYTES, CmdProduce.buildSchema("string", "bytes", CmdProduce.KEY_VALUE_ENCODING_TYPE_NOT_SET).getSchemaInfo().getType()); // simple key value assertEquals(SchemaType.KEY_VALUE, CmdProduce.buildSchema("string", "...
public static Ip6Prefix valueOf(byte[] address, int prefixLength) { return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); }
@Test public void testToStringIPv6() { Ip6Prefix ipPrefix; ipPrefix = Ip6Prefix.valueOf("1100::/8"); assertThat(ipPrefix.toString(), is("1100::/8")); ipPrefix = Ip6Prefix.valueOf("1111:2222:3333:4444:5555:6666:7777:8885/8"); assertThat(ipPrefix.toString(), is("1100::/8")); ...
@SuppressWarnings("UnstableApiUsage") @Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { final Stream<ColumnName> names = Stream.of(left, right) .flatMap(JoinNode::getPreJoinProjectDataSources) .filter(s -> !sourceName.isPresent() || sourceNa...
@Test public void shouldIncludeSyntheticJoinKeyInResolvedSelectStart() { // Given: when(joinKey.isSynthetic()).thenReturn(true); final JoinNode joinNode = new JoinNode(nodeId, OUTER, joinKey, true, left, right, empty(),"KAFKA"); when(left.resolveSelectStar(any())).thenReturn(Stream.of(...
@Override public void set(String field, String value, Map<String, String[]> data) { if (! include(field, value)) { return; } if (ALWAYS_SET_FIELDS.contains(field) || ALWAYS_ADD_FIELDS.contains(field)) { setAlwaysInclude(field, value, data); return; ...
@Test public void testMinSizeForAlwaysInclude() throws Exception { //test that mimes don't get truncated Metadata metadata = filter(100, 10, 10000, 100, null, true); String mime = getLongestMime().toString(); metadata.set(Metadata.CONTENT_TYPE, mime); assertEquals(mime, meta...
@Transactional(readOnly = true) public UserSyncDto isSignUpAllowed(String phone) { Optional<User> user = userService.readUserByPhone(phone); if (!isExistUser(user)) { log.info("회원가입 이력이 없는 사용자입니다. phone: {}", phone); return UserSyncDto.signUpAllowed(); } if ...
@DisplayName("일반 회원가입 시, 회원 정보가 없으면 {회원 가입 가능, 기존 계정 없음} 응답을 반환한다.") @Test void isSignedUserWhenGeneralReturnFalse() { // given given(userService.readUserByPhone(phone)).willReturn(Optional.empty()); // when UserSyncDto userSync = userGeneralSignService.isSignUpAllowed(phone); ...
public static void checkProjectKey(String keyCandidate) { checkArgument(isValidProjectKey(keyCandidate), MALFORMED_KEY_MESSAGE, keyCandidate, ALLOWED_CHARACTERS_MESSAGE); }
@Test public void checkProjectKey_fail_if_space() { assertThatThrownBy(() -> ComponentKeys.checkProjectKey("ab 12")) .isInstanceOf(IllegalArgumentException.class); }
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof St...
@Test(expected = NullPointerException.class) public void testWithMultipleValueOnlyResults() throws Exception { final TestExtractor extractor = new TestExtractor.Builder() .callback(new Callable<Result[]>() { @Override public Result[] call() throws Exce...
@CanIgnoreReturnValue public Caffeine<K, V> ticker(Ticker ticker) { requireState(this.ticker == null, "Ticker was already set to %s", this.ticker); this.ticker = requireNonNull(ticker); return this; }
@Test public void ticker() { Ticker ticker = new FakeTicker()::read; var builder = Caffeine.newBuilder().ticker(ticker); assertThat(builder.ticker).isSameInstanceAs(ticker); assertThat(builder.build()).isNotNull(); }
public static String fix(final String raw) { if ( raw == null || "".equals( raw.trim() )) { return raw; } MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( raw ); }
@Test public void testAssert1() { final String raw = "insert( foo );"; final String result = "drools.insert( foo );"; assertEqualsIgnoreWhitespace( result, KnowledgeHelperFixerTest.fixer.fix( raw ) ); }
public static void condition(boolean condition, NoArgsConsumer trueConsumer, NoArgsConsumer falseConsumer) { if (condition) { trueConsumer.accept(); } else { falseConsumer.accept(); } }
@Test public void assertCondition() { // init consumer AtomicBoolean checkValue = new AtomicBoolean(false); NoArgsConsumer trueConsumer = () -> checkValue.set(true); NoArgsConsumer falseConsumer = () -> checkValue.set(false); // test trueConsumer run ConditionUtil.con...
@VisibleForTesting RegistryErrorException newRegistryErrorException(ResponseException responseException) { RegistryErrorExceptionBuilder registryErrorExceptionBuilder = new RegistryErrorExceptionBuilder( registryEndpointProvider.getActionDescription(), responseException); if (responseExcep...
@Test public void testNewRegistryErrorException_jsonErrorOutput() { ResponseException httpException = Mockito.mock(ResponseException.class); Mockito.when(httpException.getContent()) .thenReturn( "{\"errors\": [{\"code\": \"MANIFEST_UNKNOWN\", \"message\": \"manifest unknown\"}]}"); Re...
@Override public void upgrade() { if (hasBeenRunSuccessfully()) { LOG.debug("Migration already completed."); return; } final Set<String> dashboardIdToViewId = new HashSet<>(); final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add; ...
@Test @MongoDBFixtures("dashboard_with_no_widgets.json") public void migratesADashboardWithNoWidgets() { this.migration.upgrade(); final MigrationCompleted migrationCompleted = captureMigrationCompleted(); assertThat(migrationCompleted.migratedDashboardIds()).containsExactly("5ddf8ed5b2...
public long updateAndGet(LongUnaryOperator updateFunction) { long prev, next; do { prev = lvVal(); next = updateFunction.applyAsLong(prev); } while (!casVal(prev, next)); return next; }
@Test public void testUpdateAndGet() { PaddedAtomicLong counter = new PaddedAtomicLong(); long value = counter.updateAndGet(operand -> operand + 2); assertEquals(2, value); assertEquals(2, counter.get()); }
public static URI getCanonicalUri(URI uri, int defaultPort) { // skip if there is no authority, ie. "file" scheme or relative uri String host = uri.getHost(); if (host == null) { return uri; } String fqHost = canonicalizeHost(host); int port = uri.getPort(); // short out if already can...
@Test public void testCanonicalUriWithDefaultPort() { URI uri; uri = NetUtils.getCanonicalUri(URI.create("scheme://host"), 123); assertEquals("scheme://host.a.b:123", uri.toString()); uri = NetUtils.getCanonicalUri(URI.create("scheme://host/"), 123); assertEquals("scheme://host.a.b:123/", ur...
public void incQueuePutSize(final String topic, final Integer queueId, final int size) { if (enableQueueStat) { this.statsTable.get(Stats.QUEUE_PUT_SIZE).addValue(buildStatsKey(topic, queueId), size, 1); } }
@Test public void testIncQueuePutSize() { brokerStatsManager.incQueuePutSize(TOPIC, QUEUE_ID, 2); String statsKey = brokerStatsManager.buildStatsKey(TOPIC, String.valueOf(QUEUE_ID)); assertThat(brokerStatsManager.getStatsItem(QUEUE_PUT_SIZE, statsKey).getValue().doubleValue()).isEqualTo(2L);...
public static String getAddress(ECKeyPair ecKeyPair) { return getAddress(ecKeyPair.getPublicKey()); }
@Test public void testGetAddressSmallPublicKey() { byte[] address = Keys.getAddress( Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE)); String expected = Numeric.toHexStringNoPrefix(address); assertEquals(Keys.getAddress("0x1234...
@SuppressWarnings("unchecked") public QueryMetadataHolder handleStatement( final ServiceContext serviceContext, final Map<String, Object> configOverrides, final Map<String, Object> requestProperties, final PreparedStatement<?> statement, final Optional<Boolean> isInternalRequest, f...
@Test public void shouldRunPushQuery_success() { // Given: when(ksqlEngine.executeTransientQuery(any(), any(), anyBoolean())) .thenReturn(transientQueryMetadata); // When: final QueryMetadataHolder queryMetadataHolder = queryExecutor.handleStatement( serviceContext, ImmutableMap.of(),...
public WorkflowInstanceActionResponse unblock( String workflowId, long workflowInstanceId, long workflowRunId, User caller) { WorkflowInstance instance = loadInstanceForAction( workflowId, workflowInstanceId, workflowRunId, Actions.WorkflowInstanceAction.UNBLOCK); LOG.debug("Unblocking...
@Test public void testUnblock() { when(instanceDao.tryUnblockFailedWorkflowInstance(any(), anyLong(), anyLong(), any())) .thenReturn(true); when(instance.getStatus()).thenReturn(WorkflowInstance.Status.FAILED); when(workflowDao.getRunStrategy("test-workflow")) .thenReturn(RunStrategy.creat...
@Override public void run() { // top-level command, do nothing }
@Test public void test_resumeJob_invalidNameOrId() { // When // Then exception.expectMessage("No job with name or id 'invalid' was found"); run("resume", "invalid"); }
public static void initWebRootContext(NacosClientProperties properties) { final String webContext = properties.getProperty(PropertyKeyConst.CONTEXT_PATH); TemplateUtils.stringNotEmptyAndThenExecute(webContext, () -> { UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);...
@Test void testInitWebRootContextWithoutValue() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); InitUtils.initWebRootContext(properties); assertEquals("/nacos", UtilAndComs.webContext); assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); ...
@Override public void putAll(Map<? extends Pair<Integer, StructLike>, ? extends V> otherMap) { otherMap.forEach(this::put); }
@Test public void putAll() { PartitionMap<String> map = PartitionMap.create(SPECS); Map<Pair<Integer, StructLike>, String> otherMap = Maps.newHashMap(); otherMap.put(Pair.of(BY_DATA_SPEC.specId(), Row.of("aaa")), "v1"); otherMap.put(Pair.of(BY_DATA_SPEC.specId(), Row.of("bbb")), "v2"); map.putAll...
public static <R> R runSafely( Block<R, RuntimeException, RuntimeException, RuntimeException> block, CatchBlock catchBlock, FinallyBlock finallyBlock) { return runSafely( block, catchBlock, finallyBlock, RuntimeException.class, RuntimeException.class, ...
@Test public void testRunSafelyTwoExceptions() { CustomCheckedException exc = new CustomCheckedException("test"); Exception suppressedOne = new Exception("test catch suppression"); RuntimeException suppressedTwo = new RuntimeException("test finally suppression"); assertThatThrownBy( () -> ...
public static Checksum newInstance(final String className) { Objects.requireNonNull(className, "className is required!"); if (Crc32.class.getName().equals(className)) { return crc32(); } else if (Crc32c.class.getName().equals(className)) { ret...
@Test void newInstanceReturnsSameInstanceOfCrc32() { assertSame(Crc32.INSTANCE, Checksums.newInstance(Crc32.class.getName())); }
public static JsonToRowWithErrFn withExceptionReporting(Schema rowSchema) { return JsonToRowWithErrFn.forSchema(rowSchema); }
@Test @Category(NeedsRunner.class) public void testParsesErrorRowsDeadLetter() throws Exception { PCollection<String> jsonPersons = pipeline.apply("jsonPersons", Create.of(JSON_PERSON_WITH_ERR)); ParseResult results = jsonPersons.apply(JsonToRow.withExceptionReporting(PERSON_SCHEMA)); PCollec...
@Nullable @Override public RecordAndPosition<E> next() { if (records.hasNext()) { recordAndPosition.setNext(records.next()); return recordAndPosition; } else { return null; } }
@Test void testGetElements() { final String[] elements = new String[] {"1", "2", "3", "4"}; final long initialPos = 1422; final long initialSkipCount = 17; final IteratorResultIterator<String> iter = new IteratorResultIterator<>( Arrays.asList...
public Set<GsonGroup> getGroups(String gitlabUrl, String token) { return Set.copyOf(executePaginatedQuery(gitlabUrl, token, "/groups", resp -> GSON.fromJson(resp, GITLAB_GROUP))); }
@Test public void getGroups_whenCallIsInError_rethrows() throws IOException { String token = "token-toto"; GitlabToken gitlabToken = new GitlabToken(token); when(gitlabPaginatedHttpClient.get(eq(gitlabUrl), eq(gitlabToken), eq("/groups"), any())).thenThrow(new IllegalStateException("exception")); ass...
@Override public void onClick(View v) { switch (v.getId()) { case R.id.quick_keys_popup_close: mKeyboardActionListener.onKey(KeyCodes.CANCEL, null, 0, null, true); break; case R.id.quick_keys_popup_backspace: mKeyboardActionListener.onKey(KeyCodes.DELETE, null, 0, null, true); ...
@Test public void testOnClickMedia() throws Exception { OnKeyboardActionListener keyboardActionListener = Mockito.mock(OnKeyboardActionListener.class); FrameKeyboardViewClickListener listener = new FrameKeyboardViewClickListener(keyboardActionListener); Mockito.verifyZeroInteractions(keyboardActio...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getGlobalConsumerConfigs(final String clientId) { final Map<String, Object> baseConsumerProps = getCommonConsumerConfigs(); // Get global consumer override configs final Map<String, Object> globalConsumerProps = originalsWithPrefi...
@Test public void shouldBeSupportNonPrefixedGlobalConsumerConfigs() { props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> consumerConfigs = streamsConfig.getGlobalConsumerConfigs(groupId); as...
@Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.c...
@Test void testInvokeWithMethodArgumentSizeIsNot3() { Method genericInvoke = GenericService.class.getMethods()[0]; Map<String, Object> person = new HashMap<String, Object>(); person.put("name", "dubbo"); person.put("age", 10); RpcInvocation invocation = new RpcInvocation( ...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return delegate.find(file, listener); } if(cache.isValid(file.getParent())) { final AttributedList<Path> list = cache.get(file.getParen...
@Test public void testFindCaseInsensitive() throws Exception { final PathCache cache = new PathCache(1); final Path directory = new Path("/", EnumSet.of(Path.Type.directory)); final Path file = new Path(directory, "f", EnumSet.of(Path.Type.file)); final CachingFindFeature feature = n...
@Override public void onProjectsDeleted(Set<DeletedProject> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsDeleted(projects))); }
@Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_calls_all_listeners_even_if_one_throws_an_Exception(Set<DeletedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new RuntimeException("Faking listener2 throwing an exception")) ...
public void remove(final T node) { if ( this.firstNode == node ) { removeFirst(); } else if ( this.lastNode == node ) { removeLast(); } else { node.getPrevious().setNext( node.getNext() ); node.getNext().setPrevious( node.getPrevious() ); ...
@Test public void testRemove() { this.list.add( this.node1 ); this.list.add( this.node2 ); this.list.add( this.node3 ); assertThat(this.node1).as("node2 previous should be node1").isSameAs(this.node2.getPrevious()); assertThat(this.node3).as("node2 next should be node3").isS...
public void insertOrUpsertStepInstance(StepInstance instance, boolean inserted) { final StepRuntimeState runtimeState = instance.getRuntimeState(); final Map<StepDependencyType, StepDependencies> dependencies = instance.getDependencies(); final Map<StepOutputsDefinition.StepOutputType, StepOutputs> outputs ...
@Test public void testInsertDuplicateStepInstance() { AssertHelper.assertThrows( "cannot insert the same step instance twice", ApplicationException.class, "BACKEND_ERROR - ERROR: duplicate key value", () -> stepDao.insertOrUpsertStepInstance(si, false)); }
public InetAddress resolve(final String name, final String uriParamName, final boolean isReResolution) { InetAddress resolvedAddress = null; try { resolvedAddress = InetAddress.getByName(name); } catch (final UnknownHostException ignore) { } ...
@Test void resolveResolvesLocalhostAddress() { final String hostName = "localhost"; final String uriParamName = "control"; final boolean isReResolution = true; final InetAddress address = nameResolver.resolve(hostName, uriParamName, isReResolution); assertEquals(InetAdd...
@CheckReturnValue @NonNull public static Observable<Boolean> observePowerSavingState( @NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) { final RxSharedPrefs prefs = AnyApplication.prefs(context); return Observable.combineLatest( prefs ...
@Test public void testControlledByEnabledPrefDefaultFalse() { AtomicReference<Boolean> state = new AtomicReference<>(null); final Observable<Boolean> powerSavingState = PowerSaving.observePowerSavingState( getApplicationContext(), settings_key_power_save_mode_sound_control, ...
@Override public Response toResponse(Throwable e) { if (log.isDebugEnabled()) { log.debug("Uncaught exception in REST call: ", e); } else if (log.isInfoEnabled()) { log.info("Uncaught exception in REST call: {}", e.getMessage()); } if (e instanceof NotFoundExc...
@Test public void testToResponseNotFound() { RestExceptionMapper mapper = new RestExceptionMapper(); Response resp = mapper.toResponse(new NotFoundException()); assertEquals(resp.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); }
@Override public Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt) throws BackgroundException { return this.connected(new Connected<Distribution>() { @Override public Distribution call() throws BackgroundException { retur...
@Test(expected = LoginCanceledException.class) public void testReadMissingCredentials() throws Exception { final Host bookmark = new Host(new TestProtocol(), "myhost.localdomain"); final CustomOriginCloudFrontDistributionConfiguration configuration = new CustomOriginCloudFrontDistributio...
public void checkExecutePrerequisites(final ExecutionContext executionContext) { ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext))); }
@Test void assertCheckExecutePrerequisitesWhenExecuteTruncateInMySQLLocalTransaction() { when(transactionRule.getDefaultType()).thenReturn(TransactionType.LOCAL); ExecutionContext executionContext = new ExecutionContext( new QueryContext(createMySQLTruncateStatementContext(), "", Col...
public static boolean checkpointsMatch( Collection<CompletedCheckpoint> first, Collection<CompletedCheckpoint> second) { if (first.size() != second.size()) { return false; } List<Tuple2<Long, JobID>> firstInterestingFields = new ArrayList<>(first.size()); for (C...
@Test void testCompareCheckpointsWithSameOrder() { CompletedCheckpoint checkpoint1 = new CompletedCheckpoint( new JobID(), 0, 0, 1, new HashMap<>(), ...
public static String subPreGbk(CharSequence str, int len, CharSequence suffix) { return subPreGbk(str, len, true) + suffix; }
@Test public void subPreGbkTest() { // https://gitee.com/dromara/hutool/issues/I4JO2E String s = "华硕K42Intel酷睿i31代2G以下独立显卡不含机械硬盘固态硬盘120GB-192GB4GB-6GB"; String v = CharSequenceUtil.subPreGbk(s, 40, false); assertEquals(39, v.getBytes(CharsetUtil.CHARSET_GBK).length); v = CharSequenceUtil.subPreGbk(s, 40, t...
public MessageId initialize() { try (Reader<byte[]> reader = WorkerUtils.createReader( workerService.getClient().newReader(), workerConfig.getWorkerId() + "-function-assignment-initialize", workerConfig.getFunctionAssignmentTopic(), MessageId.earli...
@Test public void testKubernetesFunctionInstancesRestart() throws Exception { WorkerConfig workerConfig = new WorkerConfig(); workerConfig.setWorkerId("worker-1"); workerConfig.setPulsarServiceUrl(PULSAR_SERVICE_URL); workerConfig.setStateStorageServiceUrl("foo"); workerConf...
public static List<Path> pluginUrls(Path topPath) throws IOException { boolean containsClassFiles = false; Set<Path> archives = new TreeSet<>(); LinkedList<DirectoryEntry> dfs = new LinkedList<>(); Set<Path> visited = new HashSet<>(); if (isArchive(topPath)) { return...
@Test public void testEmptyPluginUrls() throws Exception { assertEquals(Collections.emptyList(), PluginUtils.pluginUrls(pluginPath)); }
public void removeMember(String memberId) { ShareGroupMember oldMember = members.remove(memberId); maybeUpdateSubscribedTopicNamesAndGroupSubscriptionType(oldMember, null); maybeUpdateGroupState(); }
@Test public void testRemoveMember() { ShareGroup shareGroup = createShareGroup("foo"); ShareGroupMember member = shareGroup.getOrMaybeCreateMember("member", true); shareGroup.updateMember(member); assertTrue(shareGroup.hasMember("member")); shareGroup.removeMember("member"...
public int addAndGetPosition(Type type, Block block, int position, long valueHash) { if (values.getPositionCount() >= maxFill) { rehash(); } int bucketId = getBucketId(valueHash, mask); int valuePointer; // look for an empty slot or a slot containing this key ...
@Test public void testUniqueness() { assertEquals(valueStore.addAndGetPosition(type, block, 0, TypeUtils.hashPosition(type, block, 0)), 0); assertEquals(valueStore.addAndGetPosition(type, block, 1, TypeUtils.hashPosition(type, block, 1)), 1); assertEquals(valueStore.addAndGetPosition(typ...
public static byte[] readFixedLengthBytes(byte[] data, int index, int length) { byte[] bytes = new byte[length]; System.arraycopy(data, index, bytes, 0, length); return bytes; }
@Test public void testReadFixedLengthBytes() { Assert.assertArrayEquals(new byte[] {}, ByteHelper.readFixedLengthBytes(new byte[0], 0, 0)); }
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = false; boolean containsNull = false; // Spec. definiti...
@Test void invokeArrayParamEmptyArray() { FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{}), false); }
@Override public <VR> KTable<K, VR> aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator, final Materialized<K, VR, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(ini...
@Test public void shouldThrowNullPointerOnAggregateWhenMaterializedIsNull() { assertThrows(NullPointerException.class, () -> groupedStream.aggregate(MockInitializer.STRING_INIT, MockAggregator.TOSTRING_ADDER, null)); }
public float getStringWidth(String text) throws IOException { byte[] bytes = encode(text); ByteArrayInputStream in = new ByteArrayInputStream(bytes); float width = 0; while (in.available() > 0) { int code = readCode(in); width += getWidth(code...
@Test void testSoftHyphen() throws IOException { String text = "- \u00AD"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (PDDocument doc = new PDDocument()) { PDPage page = new PDPage(); doc.addPage(page); PDFont font1 = new PDT...
public static Number toNumber(Object value, Number defaultValue) { return convertQuietly(Number.class, value, defaultValue); }
@Test public void toNumberTest() { final Object a = "12.45"; final Number number = Convert.toNumber(a); assertEquals(12.45D, number.doubleValue(), 0); }
public static String stripEnd(final String str, final String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.isEm...
@Test public void testStripEnd() { assertNull(StringUtils.stripEnd(null, "ab")); assertEquals("", StringUtils.stripEnd("", "ab")); assertEquals("abc", StringUtils.stripEnd("abc", null)); assertEquals("abc", StringUtils.stripEnd("abc ", null)); assertEquals("abc", StringUtils.stripEnd("abc", ""));...
public ClusterStateBundle getLastClusterStateBundleConverged() { return lastClusterStateBundleConverged; }
@Test void activation_not_sent_if_deferred_activation_is_disabled_in_state_bundle() { var f = StateActivationFixture.withTwoPhaseDisabled(); var cf = f.cf; f.ackStateBundleFromBothDistributors(); // At this point the cluster state shall be considered converged. assertEquals...
public <R> TraceContext.Injector<R> newInjector(Setter<R, String> setter) { if (setter == null) throw new NullPointerException("setter == null"); if (setter instanceof RemoteSetter) { RemoteSetter<?> remoteSetter = (RemoteSetter<?>) setter; switch (remoteSetter.spanKind()) { case CLIENT: ...
@Test void oneFunction_injects_deferred() { DeferredInjector<Object> deferredInjector = (DeferredInjector<Object>) oneFunction.newInjector(setter); for (Kind kind : injectableKinds) { when(request.spanKind()).thenReturn(kind); deferredInjector.inject(context, request); assertThat(one...
@Override public boolean shouldEmitMetric(MetricKeyable metricKeyable) { return selector.test(metricKeyable); }
@Test public void testShouldEmitMetric() { Predicate<? super MetricKeyable> selector = ClientTelemetryUtils.getSelectorFromRequestedMetrics( Collections.singletonList("io.test.metric")); ClientTelemetryEmitter emitter = new ClientTelemetryEmitter(selector, true); assertTrue(emit...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testDecodeByteBuf() { JSONSchema<Foo> jsonSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).withAlwaysAllowNull(false).build()); Foo foo1 = new Foo(); foo1.setField1("foo1"); foo1.setField2("bar1"); foo1.setField4(new Bar()); ...
@Override public Optional<FunctionDefinition> getFunctionDefinition(String name) { final String normalizedName = name.toUpperCase(Locale.ROOT); return Optional.ofNullable(normalizedFunctions.get(normalizedName)); }
@Test void testGetInternalFunction() { assertThat(CoreModule.INSTANCE.getFunctionDefinition("$REPLICATE_ROWS$1")) .hasValueSatisfying( def -> assertThat(def) .asInstanceOf(type(BuiltInFunctionDefi...
@Override public boolean checkVersionConstraint(String version, String constraint) { return StringUtils.isNullOrEmpty(constraint) || "*".equals(constraint) || Version.parse(version).satisfies(constraint); }
@Test void invalidVersion() { assertThrows(ParseException.class, () -> versionManager.checkVersionConstraint("1.0", ">2.0.0")); }
public synchronized <K, V> KStream<K, V> stream(final String topic) { return stream(Collections.singleton(topic)); }
@Test public void shouldAllowReadingFromSameCollectionOfTopics() { builder.stream(asList("topic1", "topic2")); builder.stream(asList("topic2", "topic1")); assertBuildDoesNotThrow(builder); }
static AmqpMessageCoder of() { return new AmqpMessageCoder(); }
@Test public void encodeDecodeTooMuchLargerMessage() throws Exception { thrown.expect(CoderException.class); Message message = Message.Factory.create(); message.setAddress("address"); message.setSubject("subject"); String body = Joiner.on("").join(Collections.nCopies(64 * 1024 * 1024, " ")); m...
public static int checkAsyncBackupCount(int currentBackupCount, int newAsyncBackupCount) { if (currentBackupCount < 0) { throw new IllegalArgumentException("backup-count can't be smaller than 0"); } if (newAsyncBackupCount < 0) { throw new IllegalArgumentException("async...
@Test public void checkAsyncBackupCount() { checkAsyncBackupCount(-1, 0, false); checkAsyncBackupCount(-1, -1, false); checkAsyncBackupCount(0, -1, false); checkAsyncBackupCount(0, 0, true); checkAsyncBackupCount(0, 1, true); checkAsyncBackupCount(1, 1, true); ...
@Override public void onMatch(RelOptRuleCall call) { final Sort sort = call.rel(0); final SortExchange exchange = call.rel(1); final RelMetadataQuery metadataQuery = call.getMetadataQuery(); if (RelMdUtil.checkInputForCollationAndLimit( metadataQuery, exchange.getInput(), sort...
@Test public void shouldMatchLimitNoOffsetYesSortNoSortEnabled() { // Given: RelCollation collation = RelCollations.of(1); SortExchange exchange = PinotLogicalSortExchange.create(_input, RelDistributions.SINGLETON, collation, false, false); Sort sort = LogicalSort.create(exchange, collation, n...
public final void doesNotContainEntry(@Nullable Object key, @Nullable Object value) { checkNoNeedToDisplayBothValues("entries()") .that(checkNotNull(actual).entries()) .doesNotContain(immutableEntry(key, value)); }
@Test public void doesNotContainEntry() { ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever"); assertThat(multimap).doesNotContainEntry("daniel", "ploch"); }
public void createView(View view, boolean replace, boolean ifNotExists) { if (ifNotExists) { relationsStorage.putIfAbsent(view.name(), view); } else if (replace) { relationsStorage.put(view.name(), view); } else if (!relationsStorage.putIfAbsent(view.name(), view)) { ...
@Test public void when_createsView_then_succeeds() { // given View view = view(); given(relationsStorage.putIfAbsent(view.name(), view)).willReturn(true); // when catalog.createView(view, false, false); // then verify(relationsStorage).putIfAbsent(eq(view.na...
static public String map2String(final Map<String, String> tags) { if(tags != null && !tags.isEmpty()) { StringJoiner joined = new StringJoiner(","); for (Object o : tags.entrySet()) { Map.Entry pair = (Map.Entry) o; joined.add(pair.getKey() + "=" + pair.ge...
@Test public void testMap2StringEmpty() { Map<String, String> map = new HashMap<>(); Assert.assertEquals("", InfluxDbPoint.map2String(map)); }
@Override public boolean accept(final Path file, final Local local, final TransferStatus parent) throws BackgroundException { if(local.isFile()) { if(local.exists()) { if(log.isInfoEnabled()) { log.info(String.format("Skip file %s", file)); } ...
@Test public void testAcceptDirectory() throws Exception { SkipFilter f = new SkipFilter(new DisabledDownloadSymlinkResolver(), new NullSession(new Host(new TestProtocol()))); assertTrue(f.accept(new Path("a", EnumSet.of(Path.Type.directory)) { }, new NullLocal("a", "b") ...
@Override public String toJson(Object obj) { return getGson().toJson(obj); }
@Test void testSupported() { Assertions.assertTrue(new GsonImpl().isSupport()); gsonInit.set(g -> Mockito.when(g.toJson((Object) Mockito.any())).thenThrow(new RuntimeException())); Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); gsonInit.set(g -> Moc...
public Optional<Map<String, ParamDefinition>> getDefaultParamsForType(StepType stepType) { Map<String, ParamDefinition> defaults = defaultTypeParams.get(stepType.toString().toLowerCase(Locale.US)); if (defaults != null) { return Optional.of(preprocessParams(defaults)); } else { return Op...
@Test public void testNullStepTypeParams() { assertFalse(defaultParamManager.getDefaultParamsForType(StepType.TITUS).isPresent()); }
public ZipBuilder zipContentsOfMultipleFolders(File destZipFile, boolean excludeRootDir) throws IOException { return new ZipBuilder(this, 0, new FileOutputStream(destZipFile), excludeRootDir); }
@Test void shouldZipMultipleFolderContentsAndExcludeRootDirectory() throws IOException { File folderOne = createDirectoryInTempDir("a-folder1"); FileUtils.writeStringToFile(new File(folderOne, "folder1-file1.txt"), "folder1-file1", UTF_8); FileUtils.writeStringToFile(new File(folderOne, "fol...
@Override public LogicalSchema getSchema() { return getSource().getSchema(); }
@Test public void shouldThrowOnMultiColKeySchema() { // Given: final LogicalSchema multiSchema = LogicalSchema.builder() .keyColumn(ColumnName.of("K"), SqlTypes.INTEGER) .keyColumn(ColumnName.of("K2"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("C1"), SqlTypes.INTEGER) .build...
@Override public ObjectNode encode(MaintenanceDomain md, CodecContext context) { checkNotNull(md, "Maintenance Domain cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(MD_NAME, md.mdId().toString()) .put(MD_NAME_TYPE, md.mdId().nameType()....
@Test public void testEncodeMd4() throws CfmConfigException { MaintenanceDomain md4 = DefaultMaintenanceDomain.builder(MDID4_NONE) .mdLevel(MaintenanceDomain.MdLevel.LEVEL4).build(); ObjectNode node = mapper.createObjectNode(); node.set("md", context.codec(MaintenanceDomain....
@Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { String typeName = type.toString(); TypeElement typeElement = getType(processingEnv, typeName); return buildProperties(processingEnv, typeElem...
@Test void testBuild() {}
@Override public final Object getValue(final int columnIndex, final Class<?> type) throws SQLException { ShardingSpherePreconditions.checkNotContains(INVALID_MEMORY_TYPES, type, () -> new SQLFeatureNotSupportedException(String.format("Get value from `%s`", type.getName()))); Object result = currentR...
@Test void assertGetValueForReader() { assertThrows(SQLFeatureNotSupportedException.class, () -> memoryMergedResult.getValue(1, Reader.class)); }
public static <T> NavigableSet<Point<T>> slowKNearestPoints(Collection<? extends Point<T>> points, Instant time, int k) { checkNotNull(points, "The input collection of Points cannot be null"); checkNotNull(time, "The input time cannot be null"); checkArgument(k >= 0, "k (" + k + ") must be non-n...
@Test public void testKNearestPoints() { //this File file = getResourceFile("Track1.txt"); if (file == null) { fail(); } try { //read a File, convert each Line to a Point and collect the results in a list List<Point<NopHit>> points = Fil...
@SuppressWarnings({"PMD.NullAssignment"}) public void clearRestartFor(RunPolicy runPolicy) { this.currentPolicy = runPolicy; this.restartConfig = null; }
@Test public void testClearRestartFor() { RestartConfig config = RestartConfig.builder() .addRestartNode("foo", 1, "bar") .restartPolicy(RunPolicy.RESTART_FROM_BEGINNING) .downstreamPolicy(RunPolicy.RESTART_FROM_INCOMPLETE) .build(); RunRequest runReques...
public static boolean isReturnTypeFuture(Invocation inv) { Class<?> clazz; if (inv instanceof RpcInvocation) { clazz = ((RpcInvocation) inv).getReturnType(); } else { clazz = getReturnType(inv); } return (clazz != null && CompletableFuture.class.isAssignab...
@Test void testIsReturnTypeFuture() { Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker( URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interfa...
@Override public synchronized boolean checkValid(String clientId, String username, byte[] password) { // Check Username / Password in DB using sqlQuery if (username == null || password == null) { LOG.info("username or password was null"); return false; } Resu...
@Test public void Db_verifyInvalidPassword() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(...
@Override public void deleteFile(String path) { // There is no specific contract about whether delete should fail // and other FileIO providers ignore failure. Log the failure for // now as it is not a required operation for Iceberg. if (!client().delete(BlobId.fromGsUtilUri(path))) { LOG.warn(...
@Test public void testDelete() { String path = "delete/path/data.dat"; storage.create(BlobInfo.newBuilder(TEST_BUCKET, path).build()); // There should be one blob in the bucket assertThat( StreamSupport.stream(storage.list(TEST_BUCKET).iterateAll().spliterator(), false) .c...