focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Future<RestResponse> restRequest(RestRequest request) { return restRequest(request, new RequestContext()); }
@Test(groups = {"small"}, dataProvider = "allCombinations3x") @SuppressWarnings("deprecation") public void testRequestTimeoutAllowed(boolean isHigherThanDefault, boolean ignoreTimeoutIfHigher, int expectedTimeout) throws Exception { LoadBalancerSimulator.ClockedExecutor clockedExecutor = new LoadBalancerSimul...
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testReplaceOldValueSuccess() { RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple"); map.put(new SimpleKey("1"), new SimpleValue("2")); boolean res = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3")); Assertio...
@Override public MapperResult getTenantIdList(MapperContext context) { return new MapperResult( "SELECT tenant_id FROM config_info WHERE tenant_id != '" + NamespaceUtil.getNamespaceDefaultId() + "' GROUP BY tenant_id OFFSET " + context.getStartRow() + " ROWS ...
@Test void testGetTenantIdList() { MapperResult mapperResult = configInfoMapperByDerby.getTenantIdList(context); assertEquals(mapperResult.getSql(), "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id OFFSET " + startRow + " ROWS FETCH NEXT " ...
public String workersStatus() { StringBuilder sb = new StringBuilder(); for (TaskExecuteWorker worker : executeWorkers) { sb.append(worker.status()).append('\n'); } return sb.toString(); }
@Test void testWorkersStatus() { assertEquals("TEST_0%1, pending tasks: 0\n", executeTaskExecuteEngine.workersStatus()); }
@Override @Deprecated @SuppressWarnings("unchecked") public <T extends Number> Counter<T> counter(String name, Class<T> type, Unit unit) { if (Integer.class.equals(type)) { return (Counter<T>) new DefaultCounter(unit).asIntCounter(); } if (Long.class.equals(type)) { return (Counter<T>) ne...
@Test public void longCounterNullCheck() { assertThatThrownBy(() -> new DefaultMetricsContext().counter("name", Long.class, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid count unit: null"); }
public static Map<TopicPartition, ListOffsetsResultInfo> fetchEndOffsets(final Collection<TopicPartition> partitions, final Admin adminClient) { if (partitions.isEmpty()) { return Collections.emptyMap(); } r...
@Test public void fetchEndOffsetsShouldReturnEmptyMapIfPartitionsAreEmpty() { final Admin adminClient = mock(AdminClient.class); assertTrue(fetchEndOffsets(emptySet(), adminClient).isEmpty()); }
@Override public CheckpointStateToolset createTaskOwnedCheckpointStateToolset() { if (fileSystem instanceof PathsCopyingFileSystem) { return new FsCheckpointStateToolset( taskOwnedStateDirectory, (PathsCopyingFileSystem) fileSystem); } else { return new No...
@Test void testNotDuplicationCheckpointStateToolset() throws Exception { CheckpointStorageAccess checkpointStorage = createCheckpointStorage(randomTempPath(), true); assertThat(checkpointStorage.createTaskOwnedCheckpointStateToolset()) .isInstanceOf(NotDuplicatingCheckpointStateTools...
@Override public ConfigOperateResult insertOrUpdateBetaCas(final ConfigInfo configInfo, final String betaIps, final String srcIp, final String srcUser) { if (findConfigInfo4BetaState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()) == null) { return addConfigInf...
@Test void testInsertOrUpdateBetaCasOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; //mock exist beta ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper(); mockedConfigInfoStateWrapper.setDa...
public static boolean isMultipart(DiscFilterRequest request) { if (request == null) { return false; } String contentType = request.getContentType(); if (contentType == null) { return false; } String[] parts = Pattern.compile(";").split(contentTy...
@Test void testIsMultipart() { URI uri = URI.create("http://localhost:8080/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data"); DiscFilterRequest request = n...
@Override public String[] getHelp() { if (expression != null) { return expression.getHelp(); } return null; }
@Test public void getHelp() { String[] help = new String[] { "Help 1", "Help 2", "Help 3" }; when(expr.getHelp()).thenReturn(help); assertArrayEquals(help, test.getHelp()); verify(expr).getHelp(); verifyNoMoreInteractions(expr); }
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfEmptyString() { Ip4Prefix ipPrefix; String fromString; fromString = ""; ipPrefix = Ip4Prefix.valueOf(fromString); }
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 testLeaveLargeAlone() { final String original = "yeah yeah yeah minsert( xxx ) this is a long() thing Person (name=='drools') modify a thing"; final String result = KnowledgeHelperFixerTest.fixer.fix( original ); assertEqualsIgnoreWhitespace( original, ...
public int compareNodePositions() { if(beginPath.length == 0 && endPath.length == 0) return 0; if(beginPath.length == 0) return -1; if(endPath.length == 0) return 1; return Integer.compare(beginPath[0], endPath[0]); }
@Test public void compareParentToDescendantNode(){ final NodeModel parent = root(); final NodeModel node1 = new NodeModel("node1", map); parent.insert(node1); final int compared = new NodeRelativePath(parent, node1).compareNodePositions(); assertTrue(compared < 0); }
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schemas to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVi...
@Test public void testVisit12() { String s12 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": " + "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}"; Ass...
public SpanInScope withSpanInScope(@Nullable Span span) { return new SpanInScope(currentTraceContext.newScope(span != null ? span.context() : null)); }
@Test void withSpanInScope() { Span current = tracer.newTrace(); try (SpanInScope scope = tracer.withSpanInScope(current)) { assertThat(tracer.currentSpan()) .isEqualTo(current); assertThat(tracer.currentSpanCustomizer()) .isNotEqualTo(current) .isNotEqualTo(NoopSpanCustomiz...
@Override public IndexedFieldProvider<Class<?>> getIndexedFieldProvider() { return entityType -> { IndexDescriptor indexDescriptor = getIndexDescriptor(entityType); if (indexDescriptor == null) { return CLASS_NO_INDEXING; } return new SearchFieldIndexingMetadata...
@Test public void testRecognizeAnalyzedField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isAnalyzed(new String[]{"description"})).isTrue(); }
@Override protected InputStream openObjectInputStream( long position, int bytesToRead) { GSObject object; try { object = mClient.getObject(mBucketName, mPath, null, null, null, null, position, position + bytesToRead - 1); } catch (ServiceException e) { String errorMessage = Str...
@Test public void openObjectInputStream() throws Exception { GSObject object = Mockito.mock(GSObject.class); BufferedInputStream objectInputStream = Mockito.mock(BufferedInputStream.class); Mockito.when(mClient.getObject(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mocki...
public static FuryBuilder builder() { return new FuryBuilder(); }
@Test public void testSerializePackageLevelBean() { Fury fury = Fury.builder() .withLanguage(Language.JAVA) .withCodegen(false) .requireClassRegistration(false) .build(); PackageLevelBean o = new PackageLevelBean(); o.f1 = 10; o.f2 = 1; serDe...
@Override @SuccessResponse(statuses = { HttpStatus.S_204_NO_CONTENT }) @ServiceErrors(INVALID_PERMISSIONS) @ParamError(code = INVALID_ID, parameterNames = { "albumEntryId" }) public UpdateResponse update(CompoundKey key, AlbumEntry entity) { long photoId = (Long) key.getPart("photoId"); long albumId =...
@Test(expectedExceptions = RestLiServiceException.class) public void testBadUpdatePhotoId() { // photo 100 doesn't exist CompoundKey key = new CompoundKey().append("photoId", 100L).append("albumId", 1L); AlbumEntry entry = new AlbumEntry().setAddTime(4); _entryRes.update(key, entry); }
public static List<String> extractLinks(String content) { if (content == null || content.length() == 0) { return Collections.emptyList(); } List<String> extractions = new ArrayList<>(); final Matcher matcher = LINKS_PATTERN.matcher(content); while (matcher.find()) { ...
@Test public void testExtractLinksFtp() { List<String> links = RegexUtils.extractLinks("Test with ftp://www.nutch.org is it found? " + "What about www.google.com at ftp://www.google.de"); assertTrue(links.size() == 2, "Url not found!"); assertEquals("ftp://www.nutch.org", li...
public void removeState(HttpRequest request, HttpResponse response) { response.addCookie(newCookieBuilder(request).setName(CSRF_STATE_COOKIE).setValue(null).setHttpOnly(false).setExpiry(0).build()); }
@Test public void remove_state() { underTest.removeState(request, response); verify(response).addCookie(cookieArgumentCaptor.capture()); Cookie cookie = cookieArgumentCaptor.getValue(); assertThat(cookie.getValue()).isNull(); assertThat(cookie.getMaxAge()).isZero(); }
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) { return decorateTextWithHtml(text, decorationDataHolder, null, null); }
@Test public void should_support_crlf_line_breaks() { String crlfCodeSample = "/**" + CR_END_OF_LINE + LF_END_OF_LINE + "* @return metric generated by the decorator" + CR_END_OF_LINE + LF_END_OF_LINE + "*/" + CR_END_OF_LINE + LF_END_OF_LINE + "@DependedUpon" + CR_END_OF_LINE + LF_EN...
static ApiError validateQuotaKeyValue( Map<String, ConfigDef.ConfigKey> validKeys, String key, double value ) { // Ensure we have an allowed quota key ConfigDef.ConfigKey configKey = validKeys.get(key); if (configKey == null) { return new ApiError(Errors.I...
@Test public void testValidateQuotaKeyValueForValidRequestPercentage() { assertEquals(ApiError.NONE, ClientQuotaControlManager.validateQuotaKeyValue( VALID_CLIENT_ID_QUOTA_KEYS, "request_percentage", 56.62367)); }
public static MemorySegment wrapCopy(byte[] bytes, int start, int end) throws IllegalArgumentException { checkArgument(end >= start); checkArgument(end <= bytes.length); MemorySegment copy = allocateUnpooledSegment(end - start); copy.put(0, bytes, start, copy.size()); ...
@Test void testWrapPartialCopy() { byte[] data = {1, 2, 3, 5, 6}; MemorySegment segment = MemorySegmentFactory.wrapCopy(data, 0, data.length / 2); byte[] exp = new byte[segment.size()]; arraycopy(data, 0, exp, 0, exp.length); assertThat(segment.getHeapMemory()).containsExactl...
@Override public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) throws InvalidRequestEventException { // Expect the HTTP method and context to be populated. If they are not, we are handling an // uns...
@Test void readRequest_validAwsProxy_populatedRequest() { AwsProxyRequest request = new AwsProxyRequestBuilder("/path", "GET").header(TEST_HEADER_KEY, TEST_HEADER_VALUE).build(); try { HttpServletRequest servletRequest = reader.readRequest(request, null, null, ContainerConfig.defaultConf...
public void persistDatabaseNameListenerAssisted(final ListenerAssisted listenerAssisted) { repository.persistEphemeral(ListenerAssistedNodePath.getDatabaseNameNodePath(listenerAssisted.getDatabaseName()), YamlEngine.marshal(listenerAssisted)); }
@Test void assertPersistDatabaseNameListenerAssisted() { new ListenerAssistedPersistService(repository).persistDatabaseNameListenerAssisted(new ListenerAssisted("foo_db", ListenerAssistedType.CREATE_DATABASE)); verify(repository).persistEphemeral("/listener_assisted/foo_db", "databaseName: foo_db" +...
@Override public List<FileEntriesLayer> createLayers() throws IOException { // Clear the exploded-artifact root first if (Files.exists(targetExplodedJarRoot)) { MoreFiles.deleteRecursively(targetExplodedJarRoot, RecursiveDeleteOption.ALLOW_INSECURE); } // Add dependencies layers. List<FileE...
@Test public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_SINGLE_DEPENDENCY_JAR).toURI()); Path destDir = temporaryFolder.getRoot().toPath(); StandardExplodedProcessor standardExplodedModeProcessor = new Stan...
@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 shouldIncludePathForErrorsInObjectFieldsValue() { // Given: final Map<String, Object> value = new HashMap<>(AN_ORDER); value.put("ordertime", true); final byte[] bytes = serializeJson(value); // When: final Exception e = assertThrows( SerializationException.class, ...
public static <T> int indexOfSub(T[] array, T[] subArray) { return indexOfSub(array, 0, subArray); }
@Test public void indexOfSubTest2() { Integer[] a = {0x12, 0x56, 0x34, 0x56, 0x78, 0x9A}; Integer[] b = {0x56, 0x78}; int i = ArrayUtil.indexOfSub(a, b); assertEquals(3, i); }
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Namespaces differ") public void testMergeDifferentNamespace() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("namespace", "Different"); SinkConfigUt...
public void addAt(long offset, VoterSet voters) { Optional<LogHistory.Entry<VoterSet>> lastEntry = votersHistory.lastEntry(); if (lastEntry.isPresent() && lastEntry.get().offset() >= 0) { // If the last voter set comes from the replicated log then the majorities must overlap. // ...
@Test void testAddAt() { Map<Integer, VoterSet.VoterNode> voterMap = VoterSetTest.voterMap(IntStream.of(1, 2, 3), true); VoterSet staticVoterSet = VoterSet.fromMap(new HashMap<>(voterMap)); VoterSetHistory votersHistory = new VoterSetHistory(staticVoterSet); assertThrows( ...
public static <E> List<E> ensureImmutable(List<E> list) { if (list.isEmpty()) return Collections.emptyList(); // Faster to make a copy than check the type to see if it is already a singleton list if (list.size() == 1) return Collections.singletonList(list.get(0)); if (isImmutable(list)) return list; ...
@Test void ensureImmutable_convertsToUnmodifiableList() { List<Long> list = new ArrayList<>(); list.add(1L); list.add(2L); assertThat(Lists.ensureImmutable(list).getClass().getSimpleName()) .startsWith("Unmodifiable"); }
@NonNull public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) { Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi...
@Test public void testPermutorForRule_size_asc() { Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.SIZE_SMALL_LARGE); List<FeedItem> itemList = getTestList(); assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting permutor.reorder(itemList); ass...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); final Integer offset = readTimeZone(data, 0); if (offset == null) { onInvalidDataReceived(device, data); return; } if (offset == -128) { onUnknownTimeZoneRece...
@Test public void onTimeZoneReceived_invalid() { final Data data = new Data(new byte[] { 60 }); callback.onDataReceived(null, data); assertTrue(invalidData); }
public static boolean verify(@Nonnull UserModel currentUser, @Nonnull CertificateMetadata edsMetadata) { logger.info("Trying to match via user attributes and bin & taxCode..."); Map<String, List<String>> attrs = currentUser.getAttributes(); String bin = edsMetadata.getBin(), taxCode = edsMetadat...
@Test public void testVerifyValidData() { CertificateMetadata metadata = new CertificateMetadata(); metadata.withBin("BIN_VALUE"); metadata.withTaxCode("TAX_CODE_VALUE"); UserModel user = Mockito.mock(UserModel.class); HashMap<String, List<String>> attributes = new HashMap<>...
public static Class<?> resolvePrimitiveClassName(String name) { Class<?> result = null; // Most class names will be quite long, considering that they // SHOULD sit in a package, so a length check is worthwhile. if (name != null && name.length() <= 8) { // Could be a primitive...
@Test void testResolvePrimitiveClassName() { assertThat(ClassUtils.resolvePrimitiveClassName("boolean") == boolean.class, is(true)); assertThat(ClassUtils.resolvePrimitiveClassName("byte") == byte.class, is(true)); assertThat(ClassUtils.resolvePrimitiveClassName("char") == char.class, is(tru...
public void println( LogMessageInterface logMessage, LogLevel channelLogLevel ) { String subject = logMessage.getSubject(); if ( !logMessage.getLevel().isVisible( channelLogLevel ) ) { return; // not for our eyes. } if ( subject == null ) { subject = DEFAULT_LOG_SUBJECT; } // Are...
@Test public void testPrintlnWithNullLogChannelFileWriterBuffer() { LoggingBuffer loggingBuffer = mock( LoggingBuffer.class ); kettleLogStoreMockedStatic.when( KettleLogStore::getAppender ).thenReturn( loggingBuffer ); logChannel.println( logMsgInterface, LogLevel.BASIC ); verify( logChFileWriterBuff...
public MailConfiguration getConfiguration() { if (configuration == null) { configuration = new MailConfiguration(getCamelContext()); } return configuration; }
@Test public void testTo() { MailEndpoint endpoint = checkEndpoint("smtp://james@myhost:25/?password=secret&to=someone@outthere.com&folderName=XXX"); MailConfiguration config = endpoint.getConfiguration(); assertEquals("smtp", config.getProtocol(), "getProtocol()"); a...
public Map<String, String> mergeOptions( MergingStrategy mergingStrategy, Map<String, String> sourceOptions, Map<String, String> derivedOptions) { Map<String, String> options = new HashMap<>(); if (mergingStrategy != MergingStrategy.EXCLUDING) { options.pu...
@Test void mergeOptions() { Map<String, String> sourceOptions = new HashMap<>(); sourceOptions.put("offset", "1"); sourceOptions.put("format", "json"); Map<String, String> derivedOptions = new HashMap<>(); derivedOptions.put("format.ignore-errors", "true"); Map<Stri...
public static MountTo to(final String target) { return new MountTo(checkNotNullOrEmpty(target, "Target should not be null")); }
@Test public void should_mount_dir_to_uri() throws Exception { server.mount(MOUNT_DIR, to("/dir")); running(server, () -> assertThat(helper.get(remoteUrl("/dir/dir.response")), is("response from dir"))); }
public Collection<PlanCoordinator> coordinators() { return Collections.unmodifiableCollection(mCoordinators.values()); }
@Test public void testPurgeCount() throws Exception { PlanTracker tracker = new PlanTracker(10, 0, 5, mMockWorkflowTracker); assertEquals("tracker should be empty", 0, tracker.coordinators().size()); fillJobTracker(tracker, 10); finishAllJobs(tracker); addJob(tracker, 100); assertEquals(6, tra...
public void returnFury(Fury fury) { Objects.requireNonNull(fury); try { lock.lock(); idleCacheQueue.add(fury); activeCacheNumber.decrementAndGet(); furyCondition.signalAll(); } catch (Exception e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e); } finall...
@Test public void testReturnFury() { Function<ClassLoader, Fury> furyFactory = getFuryFactory(); Fury fury = furyFactory.apply(getClass().getClassLoader()); ClassLoaderFuryPooled pooled = getPooled(4, 8, furyFactory); pooled.returnFury(fury); }
@VisibleForTesting void validateDictTypeUnique(Long id, String type) { if (StrUtil.isEmpty(type)) { return; } DictTypeDO dictType = dictTypeMapper.selectByType(type); if (dictType == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if...
@Test public void testValidateDictTypeUnique_success() { // 调用,成功 dictTypeService.validateDictTypeUnique(randomLongId(), randomString()); }
public static String readToString(String file) throws IOException { return readToString(Paths.get(file)); }
@Test public void testReadToString() throws IOException, URISyntaxException { String content = IOKit.readToString(IOKitTest.class.getResourceAsStream("/application.properties")); Assert.assertTrue(StringKit.isNotBlank(content)); content = IOKit.readToString(Paths.get(IOKitTest.class.getReso...
public synchronized ApplicationDescription saveApplication(InputStream stream) { try (InputStream ais = stream) { byte[] cache = toByteArray(ais); InputStream bis = new ByteArrayInputStream(cache); boolean plainXml = isPlainXml(cache); ApplicationDescription desc...
@Test public void savePlainApp() throws IOException { InputStream stream = getClass().getResourceAsStream("app.xml"); ApplicationDescription app = aar.saveApplication(stream); validate(app); stream.close(); }
@Override public boolean contains(double lat, double lon) { return lat <= maxLat && lat >= minLat && lon <= maxLon && lon >= minLon; }
@Test public void testContains() { assertTrue(new BBox(1, 2, 0, 1).contains(new BBox(1, 2, 0, 1))); assertTrue(new BBox(1, 2, 0, 1).contains(new BBox(1.5, 2, 0.5, 1))); assertFalse(new BBox(1, 2, 0, 0.5).contains(new BBox(1.5, 2, 0.5, 1))); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final BoxApiClient client = new BoxApiClient(session.getClient()); final HttpGet request = new HttpGet(String.format("%s/files/%s/cont...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final TransferStatus status = new TransferStatus(); new BoxReadFeature(session, fileid).read(new Path(new DefaultHomeFinderService(sess...
@Override public Object execute(String command, byte[]... args) { for (Method method : this.getClass().getDeclaredMethods()) { if (method.getName().equalsIgnoreCase(command) && Modifier.isPublic(method.getModifiers()) && (method.getParameterTypes().len...
@Test public void testExecute() { Long s = (Long) connection.execute("ttl", "key".getBytes()); assertThat(s).isEqualTo(-2); connection.execute("flushDb"); }
public static LogCollector<ShenyuRequestLog> getInstance() { return INSTANCE; }
@Test public void testAbstractLogCollector() throws Exception { KafkaLogCollector.getInstance().start(); Field field1 = AbstractLogCollector.class.getDeclaredField("started"); field1.setAccessible(true); Assertions.assertEquals(field1.get(KafkaLogCollector.getInstance()).toString(), ...
@Override public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds, final DescribeConsumerGroupsOptions options) { SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future = Descri...
@Test public void testDescribeConsumerGroups() throws Exception { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); // Retriable FindCoordinatorResponse errors should be retried ...
@Override public boolean test(Pickle pickle) { if (expressions.isEmpty()) { return true; } List<String> tags = pickle.getTags(); return expressions.stream() .allMatch(expression -> expression.evaluate(tags)); }
@Test void single_tag_predicate_matches_pickle_with_same_single_tag() { Pickle pickle = createPickleWithTags("@FOO"); TagPredicate predicate = createPredicate("@FOO"); assertTrue(predicate.test(pickle)); }
@Override public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) throws Exception { final Object body = requestHttpEntity.getBody(); final Header headers = requestHttpEntity.getHeaders(); replaceDefaultConfig(requestHttpEntity.getHttpCl...
@Test void testExecuteForm() throws Exception { Header header = Header.newInstance(); header.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpClientConfig config = HttpClientConfig.builder().build(); Map<String, String> body = new HashMap<>(); body.put("a", "bo&dy")...
@Override public boolean canHandleReturnType(Class<?> returnType) { return Flux.class.isAssignableFrom(returnType) || Mono.class.isAssignableFrom(returnType); }
@Test public void testCheckTypes() { assertThat(reactorTimeLimiterAspectExt.canHandleReturnType(Mono.class)).isTrue(); assertThat(reactorTimeLimiterAspectExt.canHandleReturnType(Flux.class)).isTrue(); }
public static IpAddress valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new IpAddress(Version.INET, bytes); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfIncorrectString() { IpAddress ipAddress; String fromString = "NoSuchIpAddress"; ipAddress = IpAddress.valueOf(fromString); }
@Override public void doRun() { final DataNodeDto dto = DataNodeDto.Builder.builder() .setId(nodeId.getNodeId()) .setTransportAddress(opensearchBaseUri.get().toString()) .setClusterAddress(opensearchClusterUri.get()) .setDataNodeStatus(processS...
@Test void doRun() { final SimpleNodeId nodeID = new SimpleNodeId("5ca1ab1e-0000-4000-a000-000000000000"); final URI uri = URI.create("http://localhost:9200"); final String cluster = "localhost:9300"; final String datanodeRestApi = "http://localhost:8999"; @SuppressWarnings(...
@Override public BackgroundException map(final String message, final OneDriveAPIException failure, final Path file) { if(failure.getResponseCode() > 0) { switch(failure.getResponseCode()) { case HttpStatus.SC_NOT_FOUND: fileid.cache(file, null); } ...
@Test public void map() { assertTrue(new GraphExceptionMappingService(new GraphFileIdProvider(new OneDriveSession(new Host(new OneDriveProtocol()), new DisabledX509TrustManager(), new DefaultX509KeyManager()))).map( new OneDriveAPIException("The OneDrive API responded with too many redirects...
protected CompletableFuture<Optional<Topic>> loadOrCreatePersistentTopic(final String topic, boolean createIfMissing, Map<String, String> properties, @Nullable TopicPolicies topicPolicies) { final CompletableFuture<Optional<Topic>> topicFuture = FutureUtil.createFutureWithTimeout( Du...
@Test public void testConcurrentLoadTopicExceedLimitShouldNotBeAutoCreated() throws Exception { boolean needDeleteTopic = false; final String namespace = "prop/concurrentLoad"; try { // set up broker disable auto create and set concurrent load to 1 qps. cleanup(); ...
@Override public Reiterator<ShuffleEntry> read( @Nullable ShufflePosition startPosition, @Nullable ShufflePosition endPosition) { return new ShuffleReadIterator(startPosition, endPosition); }
@Test public void readerCanRead() throws Exception { ShuffleEntry e1 = newShuffleEntry(KEY, SKEY, VALUE); ShuffleEntry e2 = newShuffleEntry(KEY, SKEY, VALUE); ArrayList<ShuffleEntry> entries = new ArrayList<>(); entries.add(e1); entries.add(e2); when(batchReader.read(START_POSITION, END_POSITI...
public static DeploymentStrategy deploymentStrategy(io.strimzi.api.kafka.model.common.template.DeploymentStrategy strategy) { return switch (strategy) { case ROLLING_UPDATE -> rollingUpdateStrategy(); case RECREATE -> recreateStrategy(); }; }
@Test public void testDeploymentStrategyRollingUpdate() { DeploymentStrategy strategy = WorkloadUtils.deploymentStrategy(io.strimzi.api.kafka.model.common.template.DeploymentStrategy.ROLLING_UPDATE); assertThat(strategy.getType(), is("RollingUpdate")); assertThat(strategy.getRollingUpdat...
public static <T, K, V> MutableMap<K, V> aggregateInPlaceBy( Iterable<T> iterable, Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Procedure2<? super V, ? super T> mutatingAggregator) { return FJIterate.aggregateInPlaceBy( ...
@Test public void aggregateInPlaceByWithBatchSize() { Procedure2<AtomicInteger, Integer> sumAggregator = AtomicInteger::addAndGet; MutableList<Integer> list = LazyIterate.adapt(Collections.nCopies(100, 1)) .concatenate(Collections.nCopies(200, 2)) .concatenate(Col...
public RuntimeOptionsBuilder parse(Class<?> clazz) { RuntimeOptionsBuilder args = new RuntimeOptionsBuilder(); for (Class<?> classWithOptions = clazz; hasSuperClass( classWithOptions); classWithOptions = classWithOptions.getSuperclass()) { CucumberOptions options = requireNonNul...
@Test void create_with_no_filters() { RuntimeOptions runtimeOptions = parser().parse(NoName.class).build(); assertAll( () -> assertTrue(runtimeOptions.getTagExpressions().isEmpty()), () -> assertTrue(runtimeOptions.getNameFilters().isEmpty()), () -> assertTrue(ru...
public static FromMatchesFilter createFull(Jid address) { return new FromMatchesFilter(address, false); }
@Test public void fullCompareMatchingServiceJid() { FromMatchesFilter filter = FromMatchesFilter.createFull(SERVICE_JID1); Stanza packet = StanzaBuilder.buildMessage().build(); packet.setFrom(SERVICE_JID1); assertTrue(filter.accept(packet)); packet.setFrom(SERVICE_JID2); ...
public static String getViewVersionNode(final String databaseName, final String schemaName, final String viewName, final String version) { return String.join("/", getViewVersionsNode(databaseName, schemaName, viewName), version); }
@Test void assertGetViewVersionNode() { assertThat(ViewMetaDataNode.getViewVersionNode("foo_db", "foo_schema", "foo_view", "0"), is("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/0")); }
@Override public boolean addAll(Collection<? extends E> c) { int numToAdd = c.size(); if (underlying.size() > maxLength - numToAdd) { throw new BoundedListTooLongException("Cannot add another " + numToAdd + " element(s) to the list because it would exceed the maximum leng...
@Test public void testAddAll() { BoundedList<String> list = BoundedList.newArrayBacked(5); list.add("a"); list.add("b"); list.add("c"); assertEquals("Cannot add another 3 element(s) to the list because it would exceed the " + "maximum length of 5", ...
public static Predicate[] acceptVisitor(Predicate[] predicates, Visitor visitor, IndexRegistry indexes) { Predicate[] target = predicates; boolean copyCreated = false; for (int i = 0; i < predicates.length; i++) { Predicate predicate = predicates[i]; if (predicate instanc...
@Test public void acceptVisitor_whenNoChange_thenReturnOriginalArray() { Visitor mockVisitor = mock(Visitor.class); Predicate[] predicates = new Predicate[1]; Predicate predicate = createMockVisitablePredicate(); predicates[0] = predicate; Predicate[] result = VisitorUtils....
public static NamespaceName get(String tenant, String namespace) { validateNamespaceName(tenant, namespace); return get(tenant + '/' + namespace); }
@Test(expectedExceptions = IllegalArgumentException.class) public void namespace_nullTenant() { NamespaceName.get(null, "use", "ns1"); }
@Override public NativeQuerySpec<Record> select(String sql, Object... args) { return new NativeQuerySpecImpl<>(this, sql, args, DefaultRecord::new, false); }
@Test public void testLoadTable() { database .sql() .reactive() .execute(SqlRequests.of("create table \"NATIVE_TEST\"( " + "\"id\" varchar(32) primary key" + ",name varchar(32)" + ...
@InvokeOnHeader(Web3jConstants.ETH_COMPILE_SOLIDITY) void ethCompileSolidity(Message message) throws IOException { String sourceCode = message.getHeader(Web3jConstants.SOURCE_CODE, configuration::getSourceCode, String.class); Request<?, EthCompileSolidity> request = web3j.ethCompileSolidity(sourceCo...
@Test public void ethCompileSolidityTest() throws Exception { EthCompileSolidity response = Mockito.mock(EthCompileSolidity.class); Mockito.when(mockWeb3j.ethCompileSolidity(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getCompi...
@Override public long extractWatermark(IcebergSourceSplit split) { return split.task().files().stream() .map( scanTask -> { Preconditions.checkArgument( scanTask.file().lowerBounds() != null && scanTask.file().lowerBounds().get(eventTimeFie...
@TestTemplate public void testSingle() throws IOException { ColumnStatsWatermarkExtractor extractor = new ColumnStatsWatermarkExtractor(SCHEMA, columnName, TimeUnit.MILLISECONDS); assertThat(extractor.extractWatermark(split(0))) .isEqualTo(MIN_VALUES.get(0).get(columnName).longValue()); }
@Override public AppResponse process(Flow flow, RsPollAppApplicationResultRequest request) throws SharedServiceClientException { checkSwitchesEnabled(); final String activationStatus = appSession.getActivationStatus(); final Long accountId = appSession.getAccountId(); final String ...
@Test public void processRsPollAppApplicationResultTooManyAppsTest() throws SharedServiceClientException { when(sharedServiceClient.getSSConfigInt("Maximum_aantal_DigiD_apps_eindgebruiker")).thenReturn(5); when(switchService.digidAppSwitchEnabled()).thenReturn(true); when(switchService.digid...
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { Optional<ColumnProjection> columnProjection = selectStatementContext.getProjectionsContext().findColumnProjection(columnIndex); if (!columnProjection.is...
@Test void assertGetValueWhenOriginalValueIsNull() throws SQLException { when(mergedResult.getValue(1, Object.class)).thenReturn(null); assertNull(new MaskMergedResult(mockMaskAlgorithmAbsent(), mockSelectStatementContext(), mergedResult).getValue(1, Object.class)); }
static void closeStateManager(final Logger log, final String logPrefix, final boolean closeClean, final boolean eosEnabled, final ProcessorStateManager stateMgr, ...
@Test public void shouldStillWipeStateStoresIfCloseThrowsException() { final File randomFile = new File("/random/path"); when(stateManager.taskId()).thenReturn(taskId); when(stateDirectory.lock(taskId)).thenReturn(true); doThrow(new ProcessorStateException("Close failed")).when(sta...
@Override public void message(final String message) { if(StringUtils.isBlank(message)) { return; } final StringAppender appender = new StringAppender('…'); appender.append(message); // Clear the line and append message. Used instead of \r because the line width ma...
@Test public void testNullMessage() { new TerminalProgressListener().message(null); }
@Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { return getDescriptionInHtml(rule) .map(this::generateSections) .orElse(emptySet()); }
@Test public void parse_with_noncompliant_section_not_removed() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + NONCOMPLIANTCODE + COMPLIANTCODE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(R...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void generatorForwardsSavepointRestoreSettings() { StreamGraph streamGraph = new StreamGraph( new Configuration(), new ExecutionConfig(), new CheckpointConfig(), SavepointRestoreSettings.for...
public long[] getLatencyMax() { return this.defaultMQProducerImpl.getLatencyMax(); }
@Test public void assertGetLatencyMax() { assertNotNull(producer.getLatencyMax()); }
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void lessThan() { assertUnifiesAndInlines( "4 < 17", UBinary.create(Kind.LESS_THAN, ULiteral.intLit(4), ULiteral.intLit(17))); }
public static Class<?> getAssistInterface(Object proxyBean) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { if (proxyBean == null) { return null; } if (!isDubboProxyNa...
@Test public void testGetAssistInterfaceForNotDubboProxy() throws NoSuchFieldException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { assertNull(DubboUtil.getAssistInterface(new ArrayList<>())); }
public int run(String... argv) { if (argv.length == 0) { printUsage(); return -1; } // Sanity check on the number of arguments String cmd = argv[0]; Command command = mCommands.get(cmd); if (command == null) { String[] replacementCmd = getReplacementCmd(cmd); if (replac...
@Test public void commandAliasExists() throws Exception { TestShell shell = new TestShell(); assertEquals(0, shell.run("cmdAlias")); String warningMsg = "WARNING: cmdAlias is not a stable CLI command. It may be removed in the" + " future. Use with caution in scripts. You may use 'cmd -O' instead."...
public static boolean isMatchWithPrefix(final byte[] candidate, final byte[] expected, final int prefixLength) { if (candidate.length != expected.length) { return false; } if (candidate.length == 4) { final int mask = prefixLengthToIpV4Mask(prefixLeng...
@Test void shouldNotMatchIfNotAllBytesWithUnalignedPrefixMatch() { assertFalse(isMatchWithPrefix( asBytes(0b10101010_11111111_00000000_00000000), asBytes(0b10101010_11111111_10000000_00000000), 17)); }
@Override public boolean renameTo(File dest) { // implementing this based on the current storage structure is complex and very expensive. // a redesign is nessesary, especially must be avoid storing paths as key // maybe file name + reference to the parent in metadata and as key is used a uuid, so ...
@Test(expectedExceptions = UnsupportedOperationException.class) public void testRenameTo(){ fs.getFile("file.txt").renameTo(null); }
@GET @Path("{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getConfig(@PathParam("name") String configName) { log.trace(String.format(MESSAGE_CONFIG, QUERY)); final TelemetryConfig config = nullIsNotFound(configService...
@Test public void testUpdateConfigAddressWithModifyOperation() { expect(mockConfigAdminService.getConfig(anyString())) .andReturn(telemetryConfig).once(); mockConfigAdminService.updateTelemetryConfig(telemetryConfig); replay(mockConfigAdminService); final WebTarget w...
@Override public String getType() { return "TIMEOUT"; }
@Test public void verify_message_and_type() { assertThat(underTest.getMessage()).isEqualTo(message); assertThat(underTest.getType()).isEqualTo("TIMEOUT"); }
@JsonCreator public static DeletionRetentionStrategyConfig create(@JsonProperty(TYPE_FIELD) String type, @JsonProperty("max_number_of_indices") @Min(1) int maxNumberOfIndices) { return new AutoValue_DeletionRetentionStrategyConfig(type, maxNumberOfInd...
@Test public void testSerialization() throws JsonProcessingException { final DeletionRetentionStrategyConfig config = DeletionRetentionStrategyConfig.create(25); final ObjectMapper objectMapper = new ObjectMapperProvider().get(); final String json = objectMapper.writeValueAsString(config); ...
public Object stringToKey(String s) { char type = s.charAt(0); switch (type) { case 'S': // this is a String, NOT a Short. For Short see case 'X'. return s.substring(2); case 'I': // This is an Integer return Integer.valueOf(s.substring(2)); ...
@Test(expectedExceptions = CacheException.class) public void testStringToUnknownKey() { keyTransformationHandler.stringToKey("Z:someKey"); }
public static Combine.BinaryCombineDoubleFn ofDoubles() { return new SumDoubleFn(); }
@Test public void testSumDoubleFnInfinity() { testCombineFn( Sum.ofDoubles(), Lists.newArrayList(Double.NEGATIVE_INFINITY, 2.0, 3.0, Double.POSITIVE_INFINITY), Double.NaN); }
@VisibleForTesting static void validateInstancePartitionsTypeMapConfig(TableConfig tableConfig) { if (MapUtils.isEmpty(tableConfig.getInstancePartitionsMap()) || MapUtils.isEmpty( tableConfig.getInstanceAssignmentConfigMap())) { return; } for (InstancePartitionsType instancePartitionsType :...
@Test public void testValidateInstancePartitionsMap() { InstanceAssignmentConfig instanceAssignmentConfig = Mockito.mock(InstanceAssignmentConfig.class); TableConfig tableConfigWithoutInstancePartitionsMap = new TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE_NAME).build(); // Call vali...
@Override public InputStream getJreBinary(String jreFilename) { try { return new FileInputStream("jres/" + jreFilename); } catch (FileNotFoundException fileNotFoundException) { throw new NotFoundException(String.format("Unable to find JRE '%s'", jreFilename)); } }
@Test void getJreBinary_shouldFail_whenFileNotFound() { assertThatThrownBy(() -> jresHandler.getJreBinary("jre1")) .isInstanceOf(NotFoundException.class) .hasMessage("Unable to find JRE 'jre1'"); }
static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) { ParseResult result = new ParseResult(); try { Parser parser = new Parser(new Scanner("ignore", new StringReader(expression))); Java.Atom atom = parser.parseConditionalExpression(); ...
@Test public void testConvertExpression() { NameValidator validVariable = s -> Helper.toUpperCase(s).equals(s) || s.equals("road_class") || s.equals("toll"); ParseResult result = parse("toll == NO", validVariable, k -> ""); assertTrue(result.ok); assertEquals("[toll]", result.guesse...
public short getReplicas() { return replicas == null ? DEFAULT_REPLICAS : replicas; }
@Test public void shouldDefaultIfNoReplicasSupplied() { // Given: // When: final TopicProperties properties = new Builder() .withName("name") .withWithClause(Optional.empty(), Optional.of(1), Optional.empty(), Optional.of((long) 100)) .build(); // Then: assertThat(properti...
@Override @Nullable protected HttpHost determineProxy(HttpHost target, HttpContext context) throws HttpException { for (Pattern nonProxyHostPattern : nonProxyHostPatterns) { if (nonProxyHostPattern.matcher(target.getHostName()).matches()) { return null; } ...
@Test void testHostWithStartWildcardIsMatched() throws Exception { assertThat(routePlanner.determineProxy(new HttpHost("test.example.com"), httpContext)).isNull(); }
@Override public int read() throws IOException { if (this.closed) { throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED); } if (this.partRemaining <= 0 && this.position < this.fileSize) { this.reopen(this.position); } int byteRead = -1; if (this.partRemaining != 0) { ...
@Test public void testRead() throws Exception { final int bufLen = 256; Path readTestFilePath = new Path(this.testRootDir + "/" + "testReadSmallFile.txt"); long fileSize = 5 * Unit.MB; ContractTestUtils.generateTestFile( this.fs, readTestFilePath, fileSize, 256, 255); LOG.info("re...
public boolean isUniqueRoleName(final CaseInsensitiveString roleName) { return Collections.frequency(roleNames(), roleName) <= 1; }
@Test public void isUniqueRoleName_shouldBeTrueIfRolesAreUnique() throws Exception { RolesConfig rolesConfig = new RolesConfig(new RoleConfig(new CaseInsensitiveString("admin")), new RoleConfig(new CaseInsensitiveString("view"))); assertTrue(rolesConfig.isUniqueRoleName(new CaseInse...
public ChannelUriStringBuilder linger(final Long lingerNs) { if (null != lingerNs && lingerNs < 0) { throw new IllegalArgumentException("linger value cannot be negative: " + lingerNs); } this.linger = lingerNs; return this; }
@Test void shouldCopyLingerTimeoutFromChannelUriNegativeValue() { final ChannelUri channelUri = ChannelUri.parse("aeron:udp?linger=-1000"); assertThrows(IllegalArgumentException.class, () -> new ChannelUriStringBuilder().linger(channelUri)); }
public static NodeBadge glyph(String gid) { return new NodeBadge(Status.INFO, true, nonNull(gid), null); }
@Test public void glyphWarnMsg() { badge = NodeBadge.glyph(Status.WARN, GID, MSG); checkFields(badge, Status.WARN, true, GID, MSG); }
public static Object invokeStaticMethod(final Class<?> clazz, final String method) { try { return MethodUtils.invokeStaticMethod(clazz, method); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { LOG.error("", e); } return nul...
@Test public void testInvokeStaticMethod() { final Reflect reflect = new Reflect(); assertEquals("1", ReflectUtils.invokeStaticMethod(reflect.getClass(), "methodStaticA")); assertNull(ReflectUtils.invokeStaticMethod(reflect.getClass(), "methodB")); }
private static String sanitizeDate(int days, int today) { String isPast = today > days ? "ago" : "from-now"; int diff = Math.abs(today - days); if (diff == 0) { return "(date-today)"; } else if (diff < 90) { return "(date-" + diff + "-days-" + isPast + ")"; } return "(date)"; }
@Test public void testSanitizeDate() { assertEquals( Expressions.equal("test", "(date)"), ExpressionUtil.sanitize(Expressions.equal("test", "2022-04-29"))); assertEquals( Expressions.equal("date", "(date)"), ExpressionUtil.sanitize(STRUCT, Expressions.equal("date", "2022-04-29...
public static boolean isMissingTypeArguments(Type type) { if (type instanceof WildcardType wildcardType) { var baseType = wildcardType.getLowerBounds().length > 0 ? wildcardType.getLowerBounds()[0] : wildcardType.getUpperBounds()[0]; return isMissingTypeArguments(ba...
@Test public void isMissingTypeArguments() { assertThat( Reflection.isMissingTypeArguments( Types.parameterizedType(Container.class, Person.class))) .isFalse(); assertThat(Reflection.isMissingTypeArguments(Container.class)).isTrue(); assertThat(Reflection.isMissingTypeA...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeDynamicStruct3() { AbiV2TestFixture.Nazz nazz = new AbiV2TestFixture.Nazz( Collections.singletonList( new AbiV2TestFixture.Nazzy( Arrays.asList( ...
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testForceUnlock() { RLock lock = redisson.getLock("lock"); lock.lock(); lock.forceUnlock(); Assertions.assertFalse(lock.isLocked()); lock = redisson.getLock("lock"); Assertions.assertFalse(lock.isLocked()); }