focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void setConfigAttributes(Object attributes) { clear(); if (attributes == null) { return; } List<Map> attrList = (List<Map>) attributes; for (Map attrMap : attrList) { String type = (String) attrMap.get("artifactTypeValue"); ...
@Test public void shouldLoadArtifactPlans() { HashMap<String, String> artifactPlan1 = new HashMap<>(); artifactPlan1.put(SRC, "blah"); artifactPlan1.put(DEST, "something"); artifactPlan1.put("artifactTypeValue", TestArtifactConfig.TEST_PLAN_DISPLAY_NAME); HashMap<String, Stri...
@Override public void enableTrackScreenOrientation(boolean enable) { }
@Test public void enableTrackScreenOrientation() { mSensorsAPI.enableTrackScreenOrientation(true); }
public boolean isPacketDistinct(@NonNull String originMacAddress, @NonNull byte[] scanRecord) { byte[] macBytes = originMacAddress.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(macBytes.length+scanRecord.length); buffer.put(macBytes); buffer.put(scanRecord); buffer.rewind()...
@Test public void testSecondNonDuplicatePacketIsDistinct() throws Exception { DistinctPacketDetector dpd = new DistinctPacketDetector(); dpd.isPacketDistinct("01:02:03:04:05:06", new byte[] {0x01, 0x02}); boolean secondResult = dpd.isPacketDistinct("01:02:03:04:05:06", new byte[] {0x03, 0x04...
public boolean matches(String comment) { for (String escapedMatcher : escapeMatchers()) { Pattern pattern = Pattern.compile(String.join(escapedMatcher, "\\B", "\\B|\\b", "\\b")); if (pattern.matcher(comment).find()) { return true; } } return fa...
@Test void shouldMatchWordBoundaries() throws Exception { assertThat(new Matcher("!!").matches("!!")).isTrue(); assertThat(new Matcher("ja").matches(" ja")).isTrue(); assertThat(new Matcher("ja").matches("ja ")).isTrue(); assertThat(new Matcher("ja").matches(" ja")).isTrue(); ...
@Override public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final ShareCreationRequestModel options, final PasswordCallback callback) throws BackgroundException { return this.toGuestUrl(file, options, callback); }
@Test public void testDownloadUrlForContainer() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory...
@Override public QueuedCommandStatus enqueueCommand( final CommandId commandId, final Command command, final Producer<CommandId, Command> transactionalProducer ) { final CommandStatusFuture statusFuture = commandStatusMap.compute( commandId, (k, v) -> { if (v == null)...
@Test public void shouldIncludeCommandSequenceNumberInSuccessfulQueuedCommandStatus() { // When: final QueuedCommandStatus commandStatus = commandStore.enqueueCommand(commandId, command, transactionalProducer); // Then: assertThat(commandStatus.getCommandSequenceNumber(), equalTo(recordMetada...
@Override public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final Object options, final PasswordCallback callback) throws BackgroundException { final Host bookmark = session.getHost(); final StringBuilder request = new StringBuilder(String.format("https://%s%s/apps/files_shar...
@Test public void testToDownloadUrlNoPassword() throws Exception { final Path home = new NextcloudHomeFeature(session.getHost()).find(); final Path file = new DAVTouchFeature(new NextcloudWriteFeature(session)).touch(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type...
public synchronized boolean tryUpdatingPreferredReadReplica(TopicPartition tp, int preferredReadReplicaId, LongSupplier timeMs) { final TopicPartitionState state = assignedStateOrNull(tp); ...
@Test public void testTryUpdatingPreferredReadReplica() { state.assignFromUser(Collections.singleton(tp0)); final TopicPartition unassignedPartition = new TopicPartition("unassigned", 0); final int preferredReadReplicaId = 10; final LongSupplier expirationTimeMs = () -> System.curre...
@Override public RecordSet getRecordSet(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorSplit split, List<? extends ColumnHandle> columns) { requireNonNull(split, "partitionChunk is null"); ExampleSplit exampleSplit = (ExampleSplit) split; checkArgument(e...
@Test public void testGetRecordSet() { ExampleRecordSetProvider recordSetProvider = new ExampleRecordSetProvider(new ExampleConnectorId("test")); RecordSet recordSet = recordSetProvider.getRecordSet(ExampleTransactionHandle.INSTANCE, SESSION, new ExampleSplit("test", "schema", "table", dataUri),...
@Override public long get(long key) { return super.get0(key, 0); }
@Test public void testClear() { final long key = random.nextLong(); insert(key); hsa.clear(); assertEquals(NULL_ADDRESS, hsa.get(key)); assertEquals(0, hsa.size()); }
@VisibleForTesting Entity exportNativeEntity(RuleDao ruleDao, EntityDescriptorIds entityDescriptorIds) { final PipelineRuleEntity ruleEntity = PipelineRuleEntity.create( ValueReference.of(ruleDao.title()), ValueReference.of(ruleDao.description()), ValueReferen...
@Test @MongoDBFixtures("PipelineRuleFacadeTest.json") public void exportNativeEntity() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf25034b900a0fdb4e5338", ModelTypes.PIPELINE_RULE_V1); final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor); ...
@Override public Mono<Void> withoutFallback(final ServerWebExchange exchange, final Throwable throwable) { Object error; if (throwable instanceof DegradeException) { exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); error = ShenyuResultWrap.error(exchang...
@Test public void testFlowException() { StepVerifier.create(fallbackHandler.withoutFallback(exchange, new FlowException(""))).expectSubscription().verifyComplete(); }
public static void uncheck(RunnableWithExceptions t) { try { t.run(); } catch (Exception exception) { throwAsUnchecked(exception); } }
@Test public void test_uncheck_exception_thrown_by_method() { Class clazz1 = uncheck(() -> Class.forName("java.lang.String")); Class clazz2 = uncheck(Class::forName, "java.lang.String"); }
@SuppressWarnings("ShouldNotSubclass") public final ThrowableSubject hasCauseThat() { // provides a more helpful error message if hasCauseThat() methods are chained too deep // e.g. assertThat(new Exception()).hCT().hCT().... // TODO(diamondm) in keeping with other subjects' behavior this should still NPE...
@Test public void hasCauseThat_instanceOf() { assertThat(new Exception("foobar", new IOException("barfoo"))) .hasCauseThat() .isInstanceOf(IOException.class); }
public static boolean isIP(String addr) { return isIPv4(addr) || isIPv6(addr); }
@Test void testIsIP() { assertTrue(InternetAddressUtil.isIP("[::1]")); assertTrue(InternetAddressUtil.isIP("127.0.0.1")); assertFalse(InternetAddressUtil.isIP("er34234")); assertFalse(InternetAddressUtil.isIP("127.100.19")); }
public static void checkValidWriteSchema(GroupType schema) { schema.accept(new TypeVisitor() { @Override public void visit(GroupType groupType) { if (groupType.getFieldCount() <= 0) { throw new InvalidSchemaException("Cannot write a schema with an empty group: " + groupType); }...
@Test public void testWriteCheckNestedGroupType() { TypeUtil.checkValidWriteSchema(Types.buildMessage() .repeatedGroup() .required(INT32) .named("a") .optional(BINARY) .as(UTF8) .named("b") .named("valid_group") .named("valid_message")); TestTyp...
@Override protected void getInfo(List<List<Comparable>> infos) { String progress = FeConstants.NULL_STRING; if (jobState == JobState.RUNNING && getBatchTask() != null) { progress = getBatchTask().getFinishedTaskNum() + "/" + getBatchTask().getTaskNum(); } for (IndexSchem...
@Test public void testGetInfo() throws Exception { LakeTable table = createTable(connectContext, "CREATE TABLE t1(c0 INT) DUPLICATE KEY(c0) DISTRIBUTED BY HASH(c0) " + "BUCKETS 2 PROPERTIES('fast_schema_evolution'='true')"); AlterJobV2 job = mustAlterTable(table, "ALTER TABLE t1 ADD ...
public boolean contains(K value) { return (includeLower ? low.compareTo(value) <= 0 : low.compareTo(value) < 0) && (includeUpper ? up.compareTo(value) >= 0 : up.compareTo(value) > 0); }
@Test public void testContains() { assertTrue(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(20)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(1000)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false)...
@Override public Boolean mSet(Map<byte[], byte[]> tuple) { if (isQueueing() || isPipelined()) { for (Entry<byte[], byte[]> entry: tuple.entrySet()) { write(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue()); } return...
@Test public void testMSet() { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); for (Map.Entry<byte[], byte[]> entry : map.entrySet()) { ass...
public boolean isAdmin(Admin admin) { return !isSecurityEnabled() || noAdminsConfigured() || adminsConfig.isAdmin(admin, rolesConfig.memberRoles(admin)); }
@Test public void shouldNotCareIfValidUserInRoleOrUser() throws Exception { SecurityConfig security = security(passwordFileAuthConfig(), admins(role("role2"))); assertThat(security.isAdmin(new AdminUser(new CaseInsensitiveString("chris"))), is(true)); assertThat(security.isAdmin(new AdminUse...
@Override public boolean equals(Object obj) { if (obj instanceof DateTimeStamp) { DateTimeStamp other = (DateTimeStamp) obj; if (this.hasDateStamp()) return this.getDateTime().equals(other.getDateTime()) && (this.getTimeStamp() == other.getTime...
@Test void testEquals() { DateTimeStamp a = new DateTimeStamp(0.586d); DateTimeStamp b = new DateTimeStamp(0.586d); assertEquals(a,b); assertEquals(b,a); b = new DateTimeStamp(.587); assertNotEquals(a, b); assertNotEquals(b,a); a = new DateTimeStamp("...
@Override public <OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> process( OneInputStreamProcessFunction<T, OUT> processFunction) { validateStates( processFunction.usesStates(), new HashSet<>( Arrays.asList( ...
@Test void testStateErrorWithOneInputStream() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); NonKeyedPartitionStreamImpl<Integer> stream = new NonKeyedPartitionStreamImpl<>( env, new TestingTransformation<>("t1", Types.INT, 1)); ...
int getMinLonForTile(double lon) { return (int) (Math.floor((180 + lon) / LON_DEGREE) * LON_DEGREE) - 180; }
@Test public void testMinLon() { assertEquals(-60, instance.getMinLonForTile(-59.9)); assertEquals(0, instance.getMinLonForTile(0.9)); }
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatInsufficientIntervalCoveragePreventsMatch() { PredicateSearch search = createPredicateSearch( new byte[]{1, 1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010001), entry(1, 0x000200ff))); ...
public Set<MessageQueue> fetchMessageQueues(String topic) { Set<MessageQueue> mqSet = new HashSet<>(); TopicConfig topicConfig = selectTopicConfig(topic); if (topicConfig != null && topicConfig.getReadQueueNums() > 0) { for (int i = 0; i < topicConfig.getReadQueueNums(); i++) { ...
@Test public void testFetchMessageQueues() { Set<MessageQueue> messageQueues = transactionBridge.fetchMessageQueues(TopicValidator.RMQ_SYS_TRANS_HALF_TOPIC); assertThat(messageQueues.size()).isEqualTo(1); }
@Override public Future<Void> notifyCheckpointAbortAsync( long checkpointId, long latestCompletedCheckpointId) { return notifyCheckpointOperation( () -> { if (latestCompletedCheckpointId > 0) { notifyCheckpointComplete(latestCompletedCh...
@Test void testSavepointSuspendAbortedAsync() { assertThatThrownBy( () -> testSyncSavepointWithEndInput( (streamTask, abortCheckpointId) -> streamTask.notifyCheckpo...
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((variables == null) ? 0 : variables.hashCode()); return result; }
@Test public void testHashCode() { UnmodifiableJMeterVariables otherUnmodifiables = new UnmodifiableJMeterVariables(vars); assertThat(unmodifiables.hashCode(), CoreMatchers.is(otherUnmodifiables.hashCode())); }
Selector unwrappedSelector() { return unwrappedSelector; }
@Test public void testInterruptEventLoopThread() throws Exception { EventLoopGroup group = new NioEventLoopGroup(1); final NioEventLoop loop = (NioEventLoop) group.next(); try { Selector selector = loop.unwrappedSelector(); assertTrue(selector.isOpen()); ...
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void string() { Schema.Type type = Schema.Type.STRING; Schema simple = SchemaBuilder.builder().stringType(); Schema expected = primitive(type, simple); Schema built1 = SchemaBuilder.builder().stringBuilder().prop("p", "v").endString(); assertEquals(expected, built1); }
public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { ...
@Test public void testFileSize() { setter.setProperty("fs", "2 kb"); assertEquals(2 * 1024, house.getFs().getSize()); }
public static KeyStore newStoreCopyContent(KeyStore originalKeyStore, char[] currentPassword, final char[] newPassword) throws GeneralSecurityException, IOException { if (newPassword == null) { throw new Il...
@Test void testThrowsExceptionIfNewPasswordIsNull() throws Exception { KeyStore originalKeyStore = KeyStore.getInstance(PKCS12); assertThrows(IllegalArgumentException.class, () -> KeystoreUtils.newStoreCopyContent(originalKeyStore, "nvmd".toCharArray(), null)); }
@SuppressWarnings("unchecked") public static <T> boolean containsAny(T[] array, T... values) { for (T value : values) { if (contains(array, value)) { return true; } } return false; }
@Test public void containsAnyTest() { Integer[] a = {1, 2, 3, 4, 3, 6}; boolean contains = ArrayUtil.containsAny(a, 4, 10, 40); assertTrue(contains); contains = ArrayUtil.containsAny(a, 10, 40); assertFalse(contains); }
@Override public File exportDumpOf(ProjectDescriptor descriptor) { String fileName = slugify(descriptor.getKey()) + DUMP_FILE_EXTENSION; return new File(exportDir, fileName); }
@Test public void exportDumpOf_slugifies_project_key() { assertThat(underTest.exportDumpOf(descriptorWithUglyKey)) .isEqualTo(new File(dataDir, "governance/project_dumps/export/so-me-a9c-key.zip")); }
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldCoerceFieldValues() { // Given: final Map<String, Object> anOrder = new HashMap<>(AN_ORDER); anOrder.put("orderId", 1); // <-- int, rather than required long in ORDER_SCHEMA. final byte[] bytes = serializeJson(anOrder); // When: final Object result = deserializer.dese...
public static String normalizeUri(String uri) throws URISyntaxException { // try to parse using the simpler and faster Camel URI parser String[] parts = CamelURIParser.fastParseUri(uri); if (parts != null) { // we optimized specially if an empty array is returned if (part...
@Test public void testNormalizeEndpointUriWithUserInfoSpecialSign() throws Exception { String out1 = URISupport.normalizeUri("ftp://us%40r:t%st@localhost:21000/tmp3/camel?foo=us@r"); assertEquals("ftp://us%40r:t%25st@localhost:21000/tmp3/camel?foo=us%40r", out1); String out2 = URISupport.no...
@Override public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException { if (FORWARDING_CTRL_TBLS.contains(piTableId)) { return treatmentInterpreter.mapForwardingTreatment(treatment, piTableId); } else if (PRE_NEXT_CTRL_TBLS.cont...
@Test public void testNextTreatmentSimpleOutput() throws Exception { TrafficTreatment treatment = DefaultTrafficTreatment.builder() .setOutput(PORT_1) .build(); PiAction mappedAction = interpreter.mapTreatment( treatment, FabricConstants.FABRIC_INGRESS...
public void maybeTriggerWakeup() { final AtomicBoolean throwWakeupException = new AtomicBoolean(false); pendingTask.getAndUpdate(task -> { if (task == null) { return null; } else if (task instanceof WakeupFuture) { throwWakeupException.set(true); ...
@Test public void testManualTriggerWhenWakeupNotCalled() { assertDoesNotThrow(() -> wakeupTrigger.maybeTriggerWakeup()); }
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) { Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>(); for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) { Map<String, ...
@Test public void testNullPartition() { Map<String, Object> offset = new HashMap<>(); offset.put(SinkUtils.KAFKA_OFFSET_KEY, 100); Map<Map<String, ?>, Map<String, ?>> partitionOffsets = new HashMap<>(); partitionOffsets.put(null, offset); ConnectException e = assertThrows(Con...
public static CsvMapper createCsvMapper() { final CsvMapper csvMapper = new CsvMapper(); registerModules(csvMapper); return csvMapper; }
@Test void testCsvMapperDateTimeSupportedEnabled() throws Exception { final CsvMapper mapper = JacksonMapperFactory.createCsvMapper(); final String instantString = "2022-08-07T12:00:33.107787800Z"; final Instant instant = Instant.parse(instantString); final String instantCsv = Strin...
@Override public String getName() { return ACTION_NAME; }
@Test void testGetName() { assertEquals("search_web", searchWebAction.getName()); }
public static Permission getPermission(String name, String serviceName, String... actions) { PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName); if (permissionFactory == null) { throw new IllegalArgumentException("No permissions found for service: " + serviceName);...
@Test public void getPermission_NamespaceService() { Permission permission = ActionConstants.getPermission("foo", UserCodeNamespaceService.SERVICE_NAME); assertNotNull(permission); assertTrue(permission instanceof UserCodeNamespacePermission); }
@Override public Table getTable(String dbName, String tblName) { JDBCTableName jdbcTable = new JDBCTableName(null, dbName, tblName); return tableInstanceCache.get(jdbcTable, k -> { try (Connection connection = getConnection()) { ResultSet c...
@Test public void testCacheTableId() { try { JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource); Table table1 = jdbcMetadata.getTable("test", "tbl1"); columnResult.beforeFirst(); Table table2 = jdbcMetadata.getTable("test", "tbl1")...
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfIncorrectString() { IpPrefix ipPrefix; String fromString; fromString = "NoSuchIpPrefix"; ipPrefix = IpPrefix.valueOf(fromString); }
public synchronized String createDataset(String region) throws BigQueryResourceManagerException { // Check to see if dataset already exists, and throw error if it does if (dataset != null) { throw new IllegalStateException( "Dataset " + datasetId + " already exists for project " + projectId + "...
@Test public void testCreateDatasetShouldThrowErrorWhenDatasetCreateFails() { when(bigQuery.create(any(DatasetInfo.class))).thenThrow(RuntimeException.class); assertThrows( BigQueryResourceManagerException.class, () -> testManager.createDataset(DATASET_ID)); }
@Override public boolean accept(final Path source, final Local local, final TransferStatus parent) { return true; }
@Test public void testAcceptDirectoryNew() throws Exception { final HashMap<Path, Path> files = new HashMap<>(); final Path source = new Path("a", EnumSet.of(Path.Type.directory)); files.put(source, new Path("a", EnumSet.of(Path.Type.directory))); AbstractCopyFilter f = new Overwrite...
public Iterable<ConsumerRecord<byte[], byte[]>> getNewCommands(final Duration timeout) { final Iterable<ConsumerRecord<byte[], byte[]>> iterable = commandConsumer.poll(timeout); final List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>(); if (iterable != null) { for (ConsumerRecord<byte[],...
@Test public void shouldNotGetCommandsWhenCommandTopicCorruptionWhenBackingUp() { // Given: when(commandConsumer.poll(any(Duration.class))).thenReturn(consumerRecords); doNothing().doThrow(new CommandTopicCorruptionException("error")).when(commandTopicBackup).writeRecord(any()); // When: final It...
public boolean add(@Nonnull T toAdd) { addInternal(toAdd); return toAdd.getInternalIndex() == getHeadElementIndex(); }
@Test void testAdd() { HeapPriorityQueue<TestElement> priorityQueue = newPriorityQueue(1); final List<TestElement> testElements = Arrays.asList(new TestElement(4711L, 42L), new TestElement(815L, 23L)); testElements.sort( (l, r) -> getTestElementPriorityCompa...
@Override public void write(int b) { ensureAvailable(1); buffer[pos++] = (byte) (b); }
@Test(expected = IndexOutOfBoundsException.class) public void testWriteForBOffLen_negativeLen() { out.write(TEST_DATA, 0, -3); }
@Override public void selectInstances(Map<Integer, List<InstanceConfig>> poolToInstanceConfigsMap, InstancePartitions instancePartitions) { int numPools = poolToInstanceConfigsMap.size(); Preconditions.checkState(numPools != 0, "No pool qualified for selection"); int tableNameHash = Math.abs(_table...
@Test public void testPoolsWhenOneMorePoolAddedAndOneMoreReplicaGroupsNeeded() throws JsonProcessingException { //@formatter:off String existingPartitionsJson = "{\n" + " \"instancePartitionsName\": \"0f97dac8-4123-47c6-9a4d-b8ce039c5ea5_OFFLINE\",\n" + " \"partitionToInstancesMap\...
public static String[] parseKey(String groupKey) { StringBuilder sb = new StringBuilder(); String dataId = null; String group = null; String tenant = null; for (int i = 0; i < groupKey.length(); ++i) { char c = groupKey.charAt(i); if ('+' == c) { ...
@Test void testParseKeyForPlusIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("+"); // Method is not expected to return due to exception thrown }); // Method is not expected to return due to exc...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void testRootArgs() throws Exception { String testExpression = "#root.args[0]"; String firstArgument = "test"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String re...
@Override public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception { List<Class<?>> groups = new ArrayList<>(); Class<?> methodClass = methodClass(methodName); if (Objects.nonNull(methodClass)) { groups.add(methodCl...
@Test public void validate() throws Exception { URL url = URL.valueOf("dubbo://127.0.0.1:20880/org.apache.shenyu" + ".client.apache.dubbo.validation.service.TestService" + "?accepts=500&anyhost=true&application=shenyu-proxy" + "&bind.ip=127.0.0.1&bind.port=208...
public static Write<PubsubMessage> writeMessagesDynamic() { return Write.newBuilder() .setTopicProvider(null) .setTopicFunction(null) .setDynamicDestinations(true) .build(); }
@Test public void testBigMessageBounded() throws IOException { String bigMsg = IntStream.range(0, 100_000).mapToObj(_unused -> "x").collect(Collectors.joining("")); OutgoingMessage msg = OutgoingMessage.of( com.google.pubsub.v1.PubsubMessage.newBuilder() .setData(B...
public Date parseString(String dateString) throws ParseException { if (dateString == null || dateString.isEmpty()) { return null; } Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString); Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString)...
@Test public void testEmpty() throws Exception { // Setup fixture final String testValue = ""; // Execute system under test final Date result = xmppDateTimeFormat.parseString(testValue); // Verify results assertNull(result); }
@Override public void invoke(NamingEvent event) { logInvoke(event); if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) { ((AbstractEventListener) listener).getExecutor().execute(() -> listener.onEvent(event)); } else { ...
@Test public void testAbstractEventListener() { AbstractEventListener listener = mock(AbstractEventListener.class); NamingListenerInvoker listenerInvoker = new NamingListenerInvoker(listener); NamingEvent event = new NamingEvent("serviceName", Collections.emptyList()); listenerInvoke...
public int filterEntriesForConsumer(List<? extends Entry> entries, EntryBatchSizes batchSizes, SendMessageInfo sendMessageInfo, EntryBatchIndexesAcks indexesAcks, ManagedCursor cursor, boolean isReplayRead, Consumer consumer) { return filterEntriesForConsumer(null, 0, entries, batchSizes...
@Test public void testFilterEntriesForConsumerOfNullElement() { List<Entry> entries = new ArrayList<>(); entries.add(null); SendMessageInfo sendMessageInfo = SendMessageInfo.getThreadLocal(); EntryBatchSizes batchSizes = EntryBatchSizes.get(entries.size()); int size = this....
static BlockStmt getSimpleSetPredicateVariableDeclaration(final String variableName, final SimpleSetPredicate simpleSetPredicate) { final MethodDeclaration methodDeclaration = SIMPLESET_PREDICATE_TEMPLATE.getMethodsByName(GETKIEPMMLSIMPLESETPREDICATE).get(0).clone(); final BlockStmt simp...
@Test void getSimpleSetPredicateVariableDeclaration() throws IOException { String variableName = "variableName"; Array.Type arrayType = Array.Type.STRING; List<String> values = getStringObjects(arrayType, 4); SimpleSetPredicate simpleSetPredicate = getSimpleSetPredicate(values, array...
@VisibleForTesting public ProcessContinuation run( RestrictionTracker<OffsetRange, Long> tracker, OutputReceiver<PartitionRecord> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, InitialPipelineState initialPipelineState) throws Exception { LOG.debug("DNP: Watermark: "...
@Test public void testProcessMergeNewPartitionsMissingParent() throws Exception { // Avoid 0 and multiples of 2 so that we can specifically test just reading new partitions. OffsetRange offsetRange = new OffsetRange(1, Long.MAX_VALUE); when(tracker.currentRestriction()).thenReturn(offsetRange); when(t...
public void setProtectedTargets(String... targets) { handler.setProtectedTargets(Arrays.copyOf(targets, targets.length)); }
@Test void addsProtectedTargets() { environment.setProtectedTargets("/woo"); assertThat(handler.getProtectedTargets()).contains("/woo"); }
@Override public AppResponse process(Flow flow, AppSessionRequest request) { if (appSession.getRegistrationId() == null) { return new NokResponse(); } Map<String, String> result = digidClient.getExistingAccount(appSession.getRegistrationId(), appSession.getLanguage()); ...
@Test void processExistingAccountTest(){ when(digidClientMock.getExistingAccount(1337L, "NL")).thenReturn(Map.of( lowerUnderscore(STATUS), "PENDING", lowerUnderscore(ACCOUNT_ID), "1" )); AppResponse appResponse = checkExistingAccount.process(flowMock, null); ...
public Set<Long> calculateUsers(DelegateExecution execution, int level) { Assert.isTrue(level > 0, "level 必须大于 0"); // 获得发起人 ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId()); Long startUserId = NumberUtils.parseLong(processInst...
@Test public void testCalculateUsers_noDept() { // 准备参数 DelegateExecution execution = mockDelegateExecution(1L); // mock 方法(startUser) AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L)); when(adminUserApi.getUser(eq(1L))).thenReturn(success...
@Override public String format(final Date input, final TimeZone zone) { return ISO8601Utils.format(input, true, zone); }
@Test public void testPrint() { assertEquals("2022-11-04T12:43:42.654+01:00", new ISO8601DateFormatter().format(1667562222654L, TimeZone.getTimeZone("Europe/Zurich"))); assertEquals("2022-11-04T11:43:42.654Z", new ISO8601DateFormatter().format(1667562222654L, TimeZone.getTimeZone("UTC"))); }
@Override protected boolean isTokenAboutToExpire() { if (tokenFetchTime == -1 || super.isTokenAboutToExpire()) { return true; } // In case of, any clock skew issues, refresh token. long elapsedTimeSinceLastTokenRefreshInMillis = System.currentTimeMillis() - tokenFetchTime; boolean e...
@Test public void testTokenStartsAsExpired() { WorkloadIdentityTokenProvider provider = new WorkloadIdentityTokenProvider( AUTHORITY, TENANT_ID, CLIENT_ID, TOKEN_FILE); Assertions.assertThat(provider.isTokenAboutToExpire()) .describedAs("Token should start as expired") .isTrue(); }
void generateDecodeCodeForAMessage(Map<String, MessageDecoderMethod> msgDecodeCode, Queue<Descriptors.Descriptor> queue, Set<String> fieldsToRead) { Descriptors.Descriptor descriptor = queue.remove(); String fullyQualifiedMsgName = ProtoBufUtils.getFullJavaName(descriptor); int varNum = 1; if (msg...
@Test public void testGenerateDecodeCodeForAMessageForAllFieldsToRead() throws URISyntaxException, IOException { MessageCodeGen messageCodeGen = new MessageCodeGen(); Queue<Descriptors.Descriptor> queue = new ArrayDeque<>(); Map<String, MessageCodeGen.MessageDecoderMethod> msgDecodeC...
ProcessId processId() { return processId; }
@Test public void shouldSetProcessId() { assertEquals(PID_1, new ClientState(PID_1, 1).processId()); assertEquals(PID_2, new ClientState(PID_2, mkMap()).processId()); assertEquals(PID_3, new ClientState(PID_3, 1, mkMap()).processId()); assertNull(new ClientState().processId()); }
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test @Category(ValidatesRunner.class) public void testCreateWithVoidType() throws Exception { PCollection<Void> output = p.apply(Create.of((Void) null, (Void) null)); PAssert.that(output).containsInAnyOrder((Void) null, (Void) null); p.run(); }
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) { if (CollectionUtils.isEmpty(remoteInstances)) { return ClusterHealthStatus.unHealth("can't get the instance list"); } if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) { List<RemoteInstance...
@Test public void healthWithSelfAndNodes() { List<RemoteInstance> remoteInstances = new ArrayList<>(); remoteInstances.add(new RemoteInstance(new Address("192.168.0.1", 8899, true))); remoteInstances.add(new RemoteInstance(new Address("192.168.0.2", 8899, false))); ClusterHealthStatu...
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存 public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) { // 1. 无数据权限 if (CollUtil.isEmpty(rules)) { return Collections.emptyList(); } // 2. 未配置,则默认开启 D...
@Test public void testGetDataPermissionRule_02() { // 准备参数 String mappedStatementId = randomString(); // 调用 List<DataPermissionRule> result = dataPermissionRuleFactory.getDataPermissionRule(mappedStatementId); // 断言 assertSame(rules, result); }
@Override public void process(Exchange exchange) throws Exception { JsonElement json = getBodyAsJsonElement(exchange); String operation = exchange.getIn().getHeader(CouchDbConstants.HEADER_METHOD, String.class); if (ObjectHelper.isEmpty(operation)) { Response<DocumentResult> save...
@Test void testStringBodyIsConvertedToJsonTree() throws Exception { when(msg.getMandatoryBody()).thenReturn("{ \"name\" : \"coldplay\" }"); when(client.save(any())).thenAnswer(new Answer<Response>() { @Override public Response answer(InvocationOnMock invocation) { ...
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowStatement) { return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s...
@Test void assertCreateWithSelectPgNamespaceAndPgClass() { SQLStatement sqlStatement = parseSQL(SELECT_PG_CLASS_AND_PG_NAMESPACE); SelectStatementContext selectStatementContext = mock(SelectStatementContext.class); when(selectStatementContext.getSqlStatement()).thenReturn((SelectStatement) s...
private static SSLFactory createSSLFactory(TlsConfig tlsConfig, boolean insecureMode) { return createSSLFactory( tlsConfig.getKeyStoreType(), tlsConfig.getKeyStorePath(), tlsConfig.getKeyStorePassword(), tlsConfig.getTrustStoreType(), tlsConfig.getTrustStorePath(), tlsConfig.getTrustStorePassword(),...
@Test public void createSslFactoryInInsecureMode() { SecureRandom secureRandom = new SecureRandom(); SSLFactory sslFactory = RenewableTlsUtils.createSSLFactory(KEYSTORE_TYPE, TLS_KEYSTORE_FILE_PATH, PASSWORD, TRUSTSTORE_TYPE, TLS_TRUSTSTORE_FILE_PATH, PASSWORD, "TLS", secureRandom, false, true); ...
@VisibleForTesting static Collection<FailureEnricher> filterInvalidEnrichers( final Set<FailureEnricher> failureEnrichers) { final Map<String, Set<Class<?>>> enrichersByKey = new HashMap<>(); failureEnrichers.forEach( enricher -> enricher.getOutput...
@Test public void testGetValidatedEnrichers() { // create two enrichers with non-overlapping keys final FailureEnricher firstEnricher = new TestEnricher("key1"); final FailureEnricher secondEnricher = new TestEnricher("key2"); final Set<FailureEnricher> enrichers = n...
private Collector createCollector(List<MapperConfig> mapperConfigs) { return new DropwizardExports( metricRegistry, new PrometheusMetricFilter(mapperConfigs), new CustomMappingSampleBuilder(mapperConfigs) ); }
@Test void testCreateCollector() { when(prometheusMappingFilesHandlerProvider.get()).thenReturn(prometheusMappingFilesHandler); when(prometheusMappingFilesHandler.getMapperConfigs()).thenReturn(Collections.singletonList(new MapperConfig( "org.graylog2.plugin.streams.Stream.*.StreamRu...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseCorrectLambdaForTypeSpecificCollections() { // Given: givenFunctions( function(EXPECTED, -1, MAP1, LAMBDA_BI_FUNCTION_STRING) ); // When: final KsqlScalarFunction fun1 = udfIndex.getFunction( ImmutableList.of( SqlArgument.of(MAP1_ARG), ...
@BuildStep @Record(ExecutionTime.RUNTIME_INIT) void findRecurringJobAnnotationsAndScheduleThem(RecorderContext recorderContext, CombinedIndexBuildItem index, BeanContainerBuildItem beanContainer, JobRunrRecurringJobRecorder recorder, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) throws NoSuchMeth...
@Test void producesJobRunrRecurringJobsFinderIfJobSchedulerIsEnabled() throws NoSuchMethodException { RecorderContext recorderContext = mock(RecorderContext.class); CombinedIndexBuildItem combinedIndex = mock(CombinedIndexBuildItem.class); when(combinedIndex.getIndex()).thenReturn(mock(Index...
int preferredLocalParallelism() { if (options.containsKey(SqlConnector.OPTION_PREFERRED_LOCAL_PARALLELISM)) { return Integer.parseInt(options.get(SqlConnector.OPTION_PREFERRED_LOCAL_PARALLELISM)); } return StreamKafkaP.PREFERRED_LOCAL_PARALLELISM; }
@Test @Parameters(method = "preferredLocalParallelisms") public void when_preferredLocalParallelism_isDefined_then_parseInt(String plp, Integer expected, boolean shouldThrow) { KafkaTable table = new KafkaTable( null, null, null, null, null, null, null, Map.of(OPTION_PREF...
@SuppressWarnings("unchecked") public static <K, V> V getWithDefault(final Map<K, ? extends Object> map, final K key, final V defaultValue, final Class<V> valueClass) { final Object actualValu...
@Test(expectedExceptions = IllegalArgumentException.class) public void testNullArgument() { MapUtil.getWithDefault(_subjectMap, "subMap", null); MapUtil.getWithDefault(_subjectMap, "subMap_default", null); }
@Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ActingPrincipal that = (ActingPrincipal) o; if ( isAnonymous() != that.isAnonymous() ) { return false; } return getName() !...
@Test public void equals() throws Exception { principal1 = new ActingPrincipal( "suzy" ); principal2 = new ActingPrincipal( "joe" ); assertFalse( principal1.equals( principal2 ) ); assertFalse( principal1.equals( ActingPrincipal.ANONYMOUS ) ); principal2 = new ActingPrincipal( "suzy" ); ass...
@Override public String[] split(String text) { if (splitContraction) { text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not"); text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not"); text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not"); f...
@Test public void testTokenizeHyphen() { System.out.println("tokenize hyphen"); String text = "On a noncash basis for the quarter, the bank reported a " + "loss of $7.3 billion because of a $10.4 billion write-down " + "in the value of its credit card unit, attributed...
public static Document parseXml(final InputStream is) throws Exception { return parseXml(is, null); }
@Test public void testParse() throws Exception { InputStream fis = Files.newInputStream(Paths.get("src/test/resources/org/apache/camel/util/camel-context.xml")); Document dom = XmlLineNumberParser.parseXml(fis); assertNotNull(dom); NodeList list = dom.getElementsByTagName("beans"); ...
public static ObjectNode generateAnnotObjectNode(ChartModel cm) { ObjectNode node = MAPPER.createObjectNode(); for (ChartModel.Annot a : cm.getAnnotations()) { node.put(a.key(), a.valueAsString()); } return node; }
@Test public void annot() { ChartModel cm = new ChartModel(FOO, BAR); cm.addAnnotation("dev1", "of:0000000000000001"); cm.addAnnotation("dev2", "of:0000000000000002"); ObjectNode node = ChartUtils.generateAnnotObjectNode(cm); Assert.assertEquals("wrong results", NODE_AS_STRI...
@Override public ByteBuf writeZero(int length) { if (length == 0) { return this; } ensureWritable(length); int wIndex = writerIndex; checkIndex0(wIndex, length); int nLong = length >>> 3; int nBytes = length & 7; for (int i = nLong; i > 0...
@Test public void testWriteZero() { try { buffer.writeZero(-1); fail(); } catch (IllegalArgumentException e) { // Expected } buffer.clear(); while (buffer.isWritable()) { buffer.writeByte((byte) 0xFF); } buffer...
public List<BackgroundDataWithIndex> getBackgroundDataWithIndex() { return toScesimDataWithIndex(BackgroundDataWithIndex::new); }
@Test public void getBackgroundDataWithIndex() { List<BackgroundDataWithIndex> backgroundDatas = background.getBackgroundDataWithIndex(); assertThat(backgroundDatas).hasSameSizeAs(background.getUnmodifiableData()); BackgroundDataWithIndex backgroundData = backgroundDatas.get(0); ...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") @Test public void shouldNotThrowIfTopicDoesExist() { // Given: final CreateStream statement = new CreateStream(SOME_NAME, ONE_KEY_ONE_VALUE, false, true, withProperties, false); // When: createSourceFactory.createStreamCommand(st...
public ApiMessageAndVersion toRecord(Uuid topicId, int partitionId, ImageWriterOptions options) { PartitionRecord record = new PartitionRecord(). setPartitionId(partitionId). setTopicId(topicId). setReplicas(Replicas.toList(replicas)). setIsr(Replicas.toList(isr))...
@Test public void testRecordRoundTrip() { PartitionRegistration registrationA = new PartitionRegistration.Builder(). setReplicas(new int[]{1, 2, 3}). setDirectories(DirectoryId.migratingArray(3)). setIsr(new int[]{1, 2}).setRemovingReplicas(new int[]{1}).setLeader(1).setL...
@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 testSearchRomantic() { System.out.println("search 'romantic'"); Iterator<Relevance> hits = corpus.search(new BM25(), "romantic"); int n = 0; while (hits.hasNext()) { n++; Relevance hit = hits.next(); System.out.println(hit.text + ...
@CanIgnoreReturnValue @VisibleForTesting DirectoryEntry remove(Name name) { int index = bucketIndex(name, table.length); DirectoryEntry prev = null; DirectoryEntry entry = table[index]; while (entry != null) { if (name.equals(entry.name())) { if (prev != null) { prev.next = ...
@Test public void testRemove() { dir.put(entry("foo")); dir.put(entry("bar")); dir.remove(Name.simple("foo")); assertThat(dir.entryCount()).isEqualTo(3); assertThat(ImmutableSet.copyOf(dir)) .containsExactly( entry("bar"), new DirectoryEntry(dir, Name.SELF, dir), ...
public BigtableConfig withInstanceId(ValueProvider<String> instanceId) { checkArgument(instanceId != null, "Instance Id of BigTable can not be null"); return toBuilder().setInstanceId(instanceId).build(); }
@Test public void testWithInstanceId() { assertEquals(INSTANCE_ID.get(), config.withInstanceId(INSTANCE_ID).getInstanceId().get()); thrown.expect(IllegalArgumentException.class); config.withInstanceId(null); }
void snapshot(final PendingServiceMessageTracker tracker, final ErrorHandler errorHandler) { final int length = MessageHeaderEncoder.ENCODED_LENGTH + PendingMessageTrackerEncoder.BLOCK_LENGTH; final long nextServiceSessionId = correctNextServiceSessionId(tracker, errorHandler); idleStrategy...
@Test void snapshotPendingServiceMessageTracker() { final int offset = 108; final int length = MessageHeaderEncoder.ENCODED_LENGTH + PendingMessageTrackerEncoder.BLOCK_LENGTH; final int serviceId = 6; final PendingServiceMessageTracker pendingServiceMessageTracker = new PendingSe...
@Override public void updateIngress(Ingress ingress) { checkNotNull(ingress, ERR_NULL_INGRESS); checkArgument(!Strings.isNullOrEmpty(ingress.getMetadata().getUid()), ERR_NULL_INGRESS_UID); k8sIngressStore.updateIngress(ingress); log.info(String.format(MSG_INGRESS, i...
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredIngress() { target.updateIngress(INGRESS); }
@Override public void checkBeforeUpdate(final DropEncryptRuleStatement sqlStatement) { if (!sqlStatement.isIfExists()) { checkToBeDroppedEncryptTableNames(sqlStatement); } }
@Test void assertCheckSQLStatementWithoutToBeDroppedRule() { EncryptRule rule = mock(EncryptRule.class); when(rule.getConfiguration()).thenReturn(new EncryptRuleConfiguration(Collections.emptyList(), Collections.emptyMap())); executor.setRule(rule); assertThrows(MissingRequiredRuleEx...
public static String getVersion(Class<?> clazz) { String version = clazz.getPackage().getImplementationVersion(); if (version != null) return version; return getManifestAttributeValue(clazz, "Bundle-Version"); }
@Test void jobRunrVersion() { assertThat(JarUtils.getVersion(JobRunr.class)) .satisfiesAnyOf( val -> assertThat(val).isEqualTo("1.0.0-SNAPSHOT"), val -> assertThat(val).matches("(\\d)+.(\\d)+.(\\d)+(-.*)?") ); }
@Override public ProcessorSlotChain build() { ProcessorSlotChain chain = new DefaultProcessorSlotChain(); List<ProcessorSlot> sortedSlotList = SpiLoader.of(ProcessorSlot.class).loadInstanceListSorted(); for (ProcessorSlot slot : sortedSlotList) { if (!(slot instanceof AbstractLi...
@Test public void testBuild() { DefaultSlotChainBuilder builder = new DefaultSlotChainBuilder(); ProcessorSlotChain slotChain = builder.build(); assertNotNull(slotChain); // Verify the order of slot AbstractLinkedProcessorSlot<?> next = slotChain.getNext(); assertTru...
private <T> T accept(Expression<T> expr) { return expr.accept(this); }
@Test public void testLesser() throws Exception { assertThat(Expr.Lesser.create( Expr.NumberValue.create(1), Expr.NumberValue.create(2) ).accept(new BooleanNumberConditionsVisitor())) .isTrue(); assertThat(Expr.Lesser.create( Expr.NumberValue....
@Override public COMMIT3Response commit(XDR xdr, RpcInfo info) { SecurityHandler securityHandler = getSecurityHandler(info); RpcCall rpcCall = (RpcCall) info.header(); int xid = rpcCall.getXid(); SocketAddress remoteAddress = info.remoteAddress(); return commit(xdr, info.channel(), xid, securityHa...
@Test(timeout = 120000) public void testEncryptedReadWrite() throws Exception { final int len = 8192; final Path zone = new Path("/zone"); hdfs.mkdirs(zone); dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH); final byte[] buffer = new byte[len]; for (int i = 0; i < len; i++) { bu...
public CompletableFuture<AckResult> changeInvisibleTime(ProxyContext ctx, ReceiptHandle handle, String messageId, String groupName, String topicName, long invisibleTime, long timeoutMillis) { CompletableFuture<AckResult> future = new CompletableFuture<>(); try { this.validateReceiptH...
@Test public void testChangeInvisibleTime() throws Throwable { ReceiptHandle handle = create(createMessageExt(MixAll.RETRY_GROUP_TOPIC_PREFIX + TOPIC, "", 0, 3000)); assertNotNull(handle); ArgumentCaptor<ChangeInvisibleTimeRequestHeader> requestHeaderArgumentCaptor = ArgumentCaptor.forClass...
@Override public Map<String, List<TopicPartition>> assignPartitions(Map<String, List<PartitionInfo>> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> assignments = super.assignPartitions(partitionsP...
@Test public void testUniformSubscriptionTransferOwnershipListIsRight() { this.replicationFactor = 1; this.numBrokerRacks = 2; this.hasConsumerRack = true; Map<String, List<PartitionInfo>> partitionsPerTopic = new HashMap<>(); partitionsPerTopic.put(topic1, partitionInfos(top...
@Override protected void removeRange(int fromIndex, int toIndex) { if (fromIndex == toIndex) { return; } notifyRemoval(fromIndex, toIndex - fromIndex); super.removeRange(fromIndex, toIndex); }
@Test public void testRemoveRange() { modelList.removeRange(0, 2); assertEquals(1, modelList.size()); verify(observer).onItemRangeRemoved(0, 2); }
public static long hash64(byte[] data) { return hash64(data, 1337); }
@Test @Disabled public void bulkHashing64Test() { String[] strArray = getRandomStringArray(); long startCity = System.currentTimeMillis(); for (String s : strArray) { CityHash.hash64(s.getBytes()); } long endCity = System.currentTimeMillis(); long startMetro = System.currentTimeMillis(); for (String...
@Override public BulkheadConfig getBulkheadConfig() { return config; }
@Test public void testCreateWithDefaults() { Bulkhead bulkhead = Bulkhead.ofDefaults("test"); assertThat(bulkhead).isNotNull(); assertThat(bulkhead.getBulkheadConfig()).isNotNull(); assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()) .isEqualTo(DEFAULT_MAX_C...