focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
private void announceBackgroundJobServer() { final BackgroundJobServerStatus serverStatus = backgroundJobServer.getServerStatus(); storageProvider.announceBackgroundJobServer(serverStatus); determineIfCurrentBackgroundJobServerIsMaster(); lastSignalAlive = serverStatus.getLastHeartbeat()...
@Test void otherServersDoZookeepingAndBecomeMasterIfMasterCrashes() { final BackgroundJobServerStatus master = anotherServer(); storageProvider.announceBackgroundJobServer(master); backgroundJobServer.start(); await().atMost(TWO_SECONDS) .untilAsserted(() -> assertT...
public boolean isComplete() { return !ruleMetaData.getRules().isEmpty() && !resourceMetaData.getStorageUnits().isEmpty(); }
@Test void assertIsNotCompleteWithoutRule() { ResourceMetaData resourceMetaData = new ResourceMetaData(Collections.singletonMap("ds", new MockedDataSource())); RuleMetaData ruleMetaData = new RuleMetaData(Collections.emptyList()); assertFalse(new ShardingSphereDatabase("foo_db", mock(Databas...
@InvokeOnHeader(Web3jConstants.ETH_UNINSTALL_FILTER) void ethUninstallFilter(Message message) throws IOException { BigInteger filterId = message.getHeader(Web3jConstants.FILTER_ID, configuration::getFilterId, BigInteger.class); Request<?, EthUninstallFilter> request = web3j.ethUninstallFilter(filter...
@Test public void ethUninstallFilterTest() throws Exception { EthUninstallFilter response = Mockito.mock(EthUninstallFilter.class); Mockito.when(mockWeb3j.ethUninstallFilter(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.isUninst...
@Override public Port getPort(DeviceId deviceId, PortNumber portNumber) { Map<PortNumber, Port> ports = devicePorts.get(deviceId); return ports == null ? null : ports.get(portNumber); }
@Test public final void testGetPort() { putDevice(DID1, SW1); putDevice(DID2, SW1); List<PortDescription> pds = Arrays.asList( DefaultPortDescription.builder().withPortNumber(P1).isEnabled(true).build(), DefaultPortDescription.builder().withPortNumber(P2).isEn...
public <T extends VFSConnectionDetails> boolean test( @NonNull ConnectionManager manager, @NonNull T details, @Nullable VFSConnectionTestOptions options ) throws KettleException { if ( options == nul...
@Test public void testTestReturnsTrueWhenRootPathIsValid() throws KettleException { assertTrue( vfsConnectionManagerHelper.test( connectionManager, vfsConnectionDetails, getTestOptionsCheckRootPath() ) ); }
@Override public Blob getBlob(final int columnIndex) throws SQLException { return (Blob) mergeResultSet.getValue(columnIndex, Blob.class); }
@Test void assertGetBlobWithColumnIndex() throws SQLException { Blob blob = mock(Blob.class); when(mergeResultSet.getValue(1, Blob.class)).thenReturn(blob); assertThat(shardingSphereResultSet.getBlob(1), is(blob)); }
public static boolean isExpiration(String token) { try { return getTokenBody(token).getExpiration().before(new Date()); } catch (ExpiredJwtException e) { return true; } }
@Test public void isExpiration() { boolean isExpiration = JwtTokenUtil.isExpiration(token); Assert.isTrue(!isExpiration); }
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unl...
@Test void nextSpan_should_not_clear_other_headers() throws JMSException { message.setIntProperty("foo", 1); jmsTracing.nextSpan(message); assertThat(message.getIntProperty("foo")).isEqualTo(1); }
public static List<MusicProtocol.MusicPlaylist> convertToAppleMusicPlaylist(Collection<MusicPlaylist> musicPlaylists) { List<MusicProtocol.MusicPlaylist> convertedPlaylists = new ArrayList<>(); for (MusicPlaylist playlist : musicPlaylists) { if (playlist == null) { throw new ...
@Test public void testConvertToAppleMusicPlaylist() { String expectedId1 = "expectedId1"; String expectedTitle1 = "Expected Title 1"; String expectedDescription1 = "Expected Description"; Instant expectedTimeCreated1 = Instant.now(); Instant expectedTimeUpdated1 = expectedTim...
@Override @ManagedOperation(description = "Does the store contain the given key") public boolean contains(String key) { return setOperations.isMember(repositoryName, key); }
@Test public void shoulCheckForMembers() { idempotentRepository.contains(KEY); verify(setOperations).isMember(REPOSITORY, KEY); }
@Override @NonNull public String getId() { return ID; }
@Test public void shouldCreateWithRemoteGitRepo() throws IOException, UnirestException { String accessToken = needsGithubAccessToken(); User user = login(); this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId()); Map resp = createCredentials(user, MapsHelper.of("credenti...
public static <T extends ConfigInstance> T getNewInstance(Class<T> type, String configId, ConfigPayload payload) { T instance; try { ConfigTransformer<?> transformer = new ConfigTransformer<>(type); ConfigInstance.Builder instanceBuilder = transformer.toConfigBuilder(payload); ...
@Test public void testGetNewInstanceErrorMessage() { ConfigPayloadBuilder payloadBuilder = new ConfigPayloadBuilder(); try { ConfigInstanceUtil.getNewInstance(TestNodefsConfig.class, "id0", ConfigPayload.fromBuilder(payloadBuilder)); assert(false); } catch (IllegalArg...
@VisibleForTesting void initializeForeachArtifactRollup( ForeachStepOverview foreachOverview, ForeachStepOverview prevForeachOverview, String foreachWorkflowId) { Set<Long> iterationsToRunInNewRun = foreachOverview.getIterationsToRunFromDetails(prevForeachOverview); WorkflowRollupOve...
@Test public void testGetAggregatedRollupFromIterationsManyEven() { ArgumentCaptor<List<Long>> captor = ArgumentCaptor.forClass(List.class); Set<Long> iterations = LongStream.rangeClosed(1, 10).boxed().collect(Collectors.toSet()); doReturn(Collections.singletonList(new WorkflowRollupOverview())) ...
public static MySqlBinlogSplit filterOutdatedSplitInfos( MySqlBinlogSplit binlogSplit, Tables.TableFilter currentTableFilter) { Map<TableId, TableChange> filteredTableSchemas = binlogSplit.getTableSchemas().entrySet().stream() .filter(entry -> currentTableFilt...
@Test public void filterOutdatedSplitInfos() { Map<TableId, TableChanges.TableChange> tableSchemas = new HashMap<>(); // mock table1 TableId tableId1 = new TableId("catalog1", null, "table1"); TableChanges.TableChange tableChange1 = new TableChanges.TableChange( ...
@Udf public List<Integer> generateSeriesInt( @UdfParameter(description = "The beginning of the series") final int start, @UdfParameter(description = "Marks the end of the series (inclusive)") final int end ) { return generateSeriesInt(start, end, end - start > 0 ? 1 : -1); }
@Test public void shouldThrowIfStepWrongSignInt1() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> rangeUdf.generateSeriesInt(0, 10, -1) ); // Then: assertThat(e.getMessage(), containsString( "GENERATE_SERIES step has wrong sign")); }
public static String getKey(String dataId, String group) { return doGetKey(dataId, group, ""); }
@Test void testGetKeyByThreeParams() { // Act final String actual = GroupKey.getKey(",", ",", "3"); // Assert result assertEquals(",+,+3", actual); }
public Img scale(float scale) { if (scale < 0) { // 自动修正负数 scale = -scale; } final Image srcImg = getValidSrcImg(); // PNG图片特殊处理 if (ImgUtil.IMAGE_TYPE_PNG.equals(this.targetImageType)) { // 修正float转double导致的精度丢失 final double scaleDouble = NumberUtil.toDouble(scale); this.targetImage = ImgUtil...
@Test @Disabled public void scaleTest() { final String downloadFile = "d:/test/1435859438434136064.JPG"; final File file = FileUtil.file(downloadFile); final File fileScale = FileUtil.file(downloadFile + ".scale." + FileTypeUtil.getType(file)); final Image img = ImgUtil.getImage(URLUtil.getURL(file)); ImgU...
@Override public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters, final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) { final long now = System.cur...
@Test public void reportsDoubleGaugeValues() throws Exception { reporter.report(map("gauge", gauge(1.1)), this.map(), this.map(), this.map(), this.map()); final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class); Mockito.verify(influxDb, atLeast...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { String highwayValue = way.getTag("highway"); if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service"))) return; int ...
@Test public void testBusYes() { EdgeIntAccess access = new ArrayEdgeIntAccess(1); ReaderWay way = new ReaderWay(0); way.setTag("motor_vehicle", "no"); way.setTag("highway", "tertiary"); int edgeId = 0; parser.handleWayTags(edgeId, access, way, null); assertFa...
void save(Collection<SinkRecord> sinkRecords) { sinkWriter.save(sinkRecords); }
@Test public void testSave() { when(config.catalogName()).thenReturn("catalog"); try (MockedStatic<KafkaUtils> mockKafkaUtils = mockStatic(KafkaUtils.class)) { ConsumerGroupMetadata consumerGroupMetadata = mock(ConsumerGroupMetadata.class); mockKafkaUtils .when(() -> KafkaUtils.consumer...
public static String stripSuffix(final String value, final String suffix) { if (value == null || suffix == null) { return value; } if (value.endsWith(suffix)) { return value.substring(0, value.length() - suffix.length()); } return value; }
@Test public void shouldStripSuffixes() { assertThat(URISupport.stripSuffix(null, null)).isNull(); assertThat(URISupport.stripSuffix("", null)).isEmpty(); assertThat(URISupport.stripSuffix(null, "")).isNull(); assertThat(URISupport.stripSuffix("", "")).isEmpty(); assertThat(U...
@Override public RouteContext route(final ShardingRule shardingRule) { RouteContext result = new RouteContext(); String dataSourceName = getDataSourceName(shardingRule.getDataSourceNames()); RouteMapper dataSourceMapper = new RouteMapper(dataSourceName, dataSourceName); if (logicTabl...
@Test void assertRoutingForNoTable() { RouteContext actual = new ShardingUnicastRoutingEngine(mock(SQLStatementContext.class), Collections.emptyList(), new ConnectionContext(Collections::emptySet)).route(shardingRule); assertThat(actual.getRouteUnits().size(), is(1)); }
static String buildRedirect(String redirectUri, Map<String, Object> params) { String paramsString = params.entrySet() .stream() .map(e -> e.getKey() + "=" + urlEncode(String.valueOf(e.getValue()))) .colle...
@Test public void testBuildRedirectParam() { String url = OAuth2AuthorizeController.buildRedirect("http://hsweb.me/callback?a=b", Collections.singletonMap("code", "1234")); assertEquals(url,"http://hsweb.me/callback?a=b&code=1234"); }
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void configured_zero_init_progress_time_disables_auto_init_to_down_feature() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .bringEntireClusterUp() .reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.INITIALIZING).setInitProgress(0.5f)); ...
public void writeIntLenenc(final long value) { if (value < 0xfb) { byteBuf.writeByte((int) value); return; } if (value < Math.pow(2D, 16D)) { byteBuf.writeByte(0xfc); byteBuf.writeShortLE((int) value); return; } if (valu...
@Test void assertWriteIntLenencWithOneByte() { new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeIntLenenc(1L); verify(byteBuf).writeByte(1); }
@Override public <KeyT> void onTimer( String timerId, String timerFamilyId, KeyT key, BoundedWindow window, Instant timestamp, Instant outputTimestamp, TimeDomain timeDomain) { Preconditions.checkNotNull(outputTimestamp, "outputTimestamp"); OnTimerArgumentProvider<Ke...
@Test public void testOnTimerExceptionsWrappedAsUserCodeException() { ThrowingDoFn fn = new ThrowingDoFn(); DoFnRunner<String, String> runner = new SimpleDoFnRunner<>( null, fn, NullSideInputReader.empty(), null, null, Collections...
public void moveFactMapping(int oldIndex, int newIndex) { if (oldIndex < 0 || oldIndex >= factMappings.size()) { throw new IndexOutOfBoundsException(new StringBuilder().append("Index ").append(oldIndex) .append(" not found in the list").toStrin...
@Test public void moveFactMappingTest() { ExpressionIdentifier expressionIdentifier2 = ExpressionIdentifier.create("Test expression 2", GIVEN); ExpressionIdentifier expressionIdentifier3 = ExpressionIdentifier.create("Test expression 3", GIVEN); FactMapping factMapping1 = modelDescriptor.add...
public Trans loadTransFromFilesystem( String initialDir, String filename, String jarFilename, Serializable base64Zip ) throws Exception { Trans trans = null; File zip; if ( base64Zip != null && ( zip = decodeBase64ToZipFile( base64Zip, true ) ) != null ) { // update filename to a meaningful, 'ETL-fi...
@Test public void testFilesystemBase64Zip() throws Exception { String fileName = "test.ktr"; File zipFile = new File( getClass().getResource( "testKtrArchive.zip" ).toURI() ); String base64Zip = Base64.getEncoder().encodeToString( FileUtils.readFileToByteArray( zipFile ) ); Trans trans = mockedPanComm...
@Override public boolean ownInsertsAreVisible(final int type) { return false; }
@Test void assertOwnInsertsAreVisible() { assertFalse(metaData.ownInsertsAreVisible(0)); }
@Override public Set<Pair<WorkerInfo, SerializableVoid>> selectExecutors(PersistConfig config, List<WorkerInfo> jobWorkerInfoList, SelectExecutorsContext context) throws Exception { if (jobWorkerInfoList.isEmpty()) { throw new RuntimeException("No worker is available"); } AlluxioURI uri...
@Test public void selectExecutorsTest() throws Exception { AlluxioURI uri = new AlluxioURI("/test"); PersistConfig config = new PersistConfig(uri.getPath(), -1, true, ""); WorkerNetAddress workerNetAddress1 = new WorkerNetAddress().setDataPort(10).setHost("host1"); WorkerIdentity workerIdentity1 = Wo...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldCloseIterator() { // When: table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS); // Then: verify(fetchIterator).close(); }
public static void notNullOrEmpty(String string) { notNullOrEmpty(string, String.format("string [%s] is null or empty", string)); }
@Test public void testNotNull1NotEmpty6() { assertThrows(IllegalArgumentException.class, () -> Precondition.notNullOrEmpty("\t")); }
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull16() { // Arrange final int type = 30; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Write_rows", actual); }
@PostMapping("/token") @PermitAll @Operation(summary = "获得访问令牌", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用") @Parameters({ @Parameter(name = "grant_type", required = true, description = "授权类型", example = "code"), @Parameter(name = "code", description = "授权...
@Test public void testPostAccessToken_refreshToken() { // 准备参数 String granType = OAuth2GrantTypeEnum.REFRESH_TOKEN.getGrantType(); String refreshToken = randomString(); String password = randomString(); HttpServletRequest request = mockRequest("test_client_id", "test_client_s...
protected boolean shouldAnalyze() { if (analyzer instanceof FileTypeAnalyzer) { final FileTypeAnalyzer fileTypeAnalyzer = (FileTypeAnalyzer) analyzer; return fileTypeAnalyzer.accept(dependency.getActualFile()); } return true; }
@Test public void shouldAnalyzeReturnsTrueForNonFileTypeAnalyzers() { AnalysisTask instance = new AnalysisTask(new HintAnalyzer(), null, null, null); boolean shouldAnalyze = instance.shouldAnalyze(); assertTrue(shouldAnalyze); }
public static <T> T clone(T value) { return ObjectMapperWrapper.INSTANCE.clone(value); }
@Test public void cloneDeserializeStepErrorTest() { MyEntity entity = new MyEntity(); entity.setValue("some value"); entity.setPojos(Arrays.asList( createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), createMyPojo("second value", MyType.B, "1...
public static ByteBuffer copy(ByteBuffer src, int start, int end) { return copy(src, ByteBuffer.allocate(end - start)); }
@Test public void copyTest() { byte[] bytes = "AAABBB".getBytes(); ByteBuffer buffer = ByteBuffer.wrap(bytes); ByteBuffer buffer2 = BufferUtil.copy(buffer, ByteBuffer.allocate(5)); assertEquals("AAABB", StrUtil.utf8Str(buffer2)); }
@Override public List<Instance> getAllInstances(String serviceName) throws NacosException { return getAllInstances(serviceName, new ArrayList<>()); }
@Test void testGetAllInstances7() throws NacosException { //given String serviceName = "service1"; List<String> clusterList = Arrays.asList("cluster1", "cluster2"); //when client.getAllInstances(serviceName, clusterList, false); //then verify(proxy, times(1))....
public void add(Boolean bool) { elements.add(bool == null ? JsonNull.INSTANCE : new JsonPrimitive(bool)); }
@Test public void testBooleanPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add(true); jsonArray.add(true); jsonArray.add(false); jsonArray.add(false); jsonArray.add((Boolean) null); jsonArray.add(true); assertThat(jsonArray.toString()).isEqualTo("[true,true,f...
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); ...
@Test void testParagraphTextUnfinishedQuote() { assertThrows(RuntimeException.class, () -> ParagraphTextParser.parse("%spark.pyspark(pool=\"2314234) sc.version"), "Problems by parsing paragraph. Not finished interpreter configuration"); }
public static int getParentOrder(int nodeOrder) { return (nodeOrder - 1) >> 1; }
@Test public void testGetParentOrder() { assertEquals(0, MerkleTreeUtil.getParentOrder(1)); assertEquals(0, MerkleTreeUtil.getParentOrder(2)); assertEquals(1, MerkleTreeUtil.getParentOrder(3)); assertEquals(1, MerkleTreeUtil.getParentOrder(4)); assertEquals(2, MerkleTreeUtil....
public synchronized ListenableFuture<?> waitForMinimumCoordinatorSidecars() { if (currentCoordinatorSidecarCount == 1 || !isCoordinatorSidecarEnabled) { return immediateFuture(null); } SettableFuture<?> future = SettableFuture.create(); coordinatorSidecarSizeFutures.add(...
@Test(timeOut = 10_000) public void testTimeoutWaitingForCoordinatorSidecars() throws InterruptedException { waitForMinimumCoordinatorSidecars(); assertFalse(coordinatorSidecarsTimeout.get()); assertEquals(minCoordinatorSidecarsLatch.getCount(), 1); Thread.sleep(SECON...
public static long toMillis(long day, long hour, long minute, long second, long millis) { try { long value = millis; value = addExact(value, multiplyExact(day, MILLIS_IN_DAY)); value = addExact(value, multiplyExact(hour, MILLIS_IN_HOUR)); value = addExact(valu...
@Test public void testFormat() { assertMillis(0, "0 00:00:00.000"); assertMillis(1, "0 00:00:00.001"); assertMillis(-1, "-0 00:00:00.001"); assertMillis(toMillis(12, 13, 45, 56, 789), "12 13:45:56.789"); assertMillis(toMillis(-12, -13, -45, -56, -789), "-12 13:45:56.789"...
@Override public CompletableFuture<Void> deleteTopicInNameserver(String address, DeleteTopicFromNamesrvRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DEL...
@Test public void assertDeleteTopicInNameserverWithSuccess() throws Exception { setResponseSuccess(null); DeleteTopicFromNamesrvRequestHeader requestHeader = mock(DeleteTopicFromNamesrvRequestHeader.class); CompletableFuture<Void> actual = mqClientAdminImpl.deleteTopicInNameserver(defaultBro...
public static AnnotateImagesFromBytes annotateImagesFromBytes( PCollectionView<Map<ByteString, ImageContext>> contextSideInput, List<Feature> features, long batchSize, int desiredRequestParallelism) { return new AnnotateImagesFromBytes( contextSideInput, features, batchSize, desiredR...
@Test public void shouldConvertByteStringToRequest() { CloudVision.AnnotateImagesFromBytes annotateImagesFromBytes = CloudVision.annotateImagesFromBytes(null, features, 1, 1); AnnotateImageRequest request = annotateImagesFromBytes.mapToRequest(TEST_BYTES, null); assertEquals(1, request.getFeatures...
@Override public Response updateSchedulerConfiguration(SchedConfUpdateInfo mutationInfo, HttpServletRequest hsr) throws AuthorizationException, InterruptedException { // Make Sure mutationInfo is not null. if (mutationInfo == null) { routerMetrics.incrUpdateSchedulerConfigurationFailedRetrieved()...
@Test public void testUpdateSchedulerConfigurationErrorMsg() throws Exception { SchedConfUpdateInfo mutationInfo = new SchedConfUpdateInfo(); LambdaTestUtils.intercept(IllegalArgumentException.class, "Parameter error, the subClusterId is empty or null.", () -> interceptor.updateSchedulerConfig...
@VisibleForTesting static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) { ImmutableSortedMap.Builder<OffsetRange, Integer> rval = ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE); List<OffsetRange> sortedRanges = Lists.newArrayList(ranges); if (...
@Test public void testRangesWithAtMostOneOverlap() { Iterable<OffsetRange> ranges = Arrays.asList(range(0, 6), range(4, 10), range(8, 12)); Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition = computeOverlappingRanges(ranges); assertEquals( ImmutableMap.builder() ...
@Restricted(NoExternalUse.class) public static String extractPluginNameFromIconSrc(String iconSrc) { if (iconSrc == null) { return ""; } if (!iconSrc.contains("plugin-")) { return ""; } String[] arr = iconSrc.split(" "); for (String element :...
@Test public void extractPluginNameFromIconSrcHandlesEmptyString() { String result = Functions.extractPluginNameFromIconSrc(""); assertThat(result, is(emptyString())); }
Mono<ResponseEntity<Void>> delete(UUID id) { return client.delete() .uri(uriBuilder -> uriBuilder.path("/posts/{id}").build(id)) .exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.NO_CONTENT)) { return response.to...
@SneakyThrows @Test public void testDeletePostById() { var id = UUID.randomUUID(); stubFor(delete("/posts/" + id) .willReturn( aResponse() .withStatus(204) ) ); postClient.delete(id) ...
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_convertsToSingletonList() { List<Object> list = new ArrayList<>(); list.add("foo"); assertThat(Lists.ensureImmutable(list).getClass().getSimpleName()) .isEqualTo("SingletonList"); }
public Optional<Object> retrieveSingleValue(final Object jsonObject, final String valueName) { final Map<String, Object> map = objectMapper.convertValue(jsonObject, new TypeReference<>() {}); return Optional.ofNullable(map.get(valueName)); }
@Test void testRetrievesEmptyOptionalOnWrongValueName() { Optional<Object> value = toTest.retrieveSingleValue(new TestJson(42, "ho!"), "carramba!"); assertTrue(value.isEmpty()); }
public static String getName(File file) { return FileNameUtil.getName(file); }
@Test public void getNameTest() { String path = "d:\\aaa\\bbb\\cc\\ddd\\"; String name = FileUtil.getName(path); assertEquals("ddd", name); path = "d:\\aaa\\bbb\\cc\\ddd.jpg"; name = FileUtil.getName(path); assertEquals("ddd.jpg", name); }
@Nonnull @Override public Result addChunk(ByteBuf buffer) { final byte[] readable = new byte[buffer.readableBytes()]; buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes()); final GELFMessage msg = new GELFMessage(readable); final ByteBuf aggregatedBuffer; ...
@Test public void differentIdsDoNotInterfere() { final ByteBuf[] msg1 = createChunkedMessage(4096 + 1, 1024, generateMessageId(1));// 5 chunks; final ByteBuf[] msg2 = createChunkedMessage(4096 + 1, 1024, generateMessageId(2));// 5 chunks; CodecAggregator.Result result1 = null; Codec...
public double p99() { return getLinearInterpolation(0.99); }
@Test public void testP99() { HistogramData histogramData1 = HistogramData.linear(0, 0.2, 50); histogramData1.record(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); assertThat(String.format("%.3f", histogramData1.p99()), equalTo("9.180")); HistogramData histogramData2 = HistogramData.linear(0, 0.02, 50); histogra...
@Override public String convert(ILoggingEvent event) { List<KeyValuePair> kvpList = event.getKeyValuePairs(); if (kvpList == null || kvpList.isEmpty()) { return CoreConstants.EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < kvpList.siz...
@Test public void smoke() { event.addKeyValuePair(new KeyValuePair("a", "b")); event.addKeyValuePair(new KeyValuePair("k", "v")); String result = converter.convert(event); assertEquals("a=\"b\" k=\"v\"", result); }
@Override public long getBlockIdByIndex(int blockIndex) throws BlockInfoException { if (blockIndex < 0 || blockIndex >= mBlocks.size()) { throw new BlockInfoException( "blockIndex " + blockIndex + " is out of range. File blocks: " + mBlocks.size()); } return mBlocks.get(blockIndex); }
@Test public void getBlockIdByIndex() throws Exception { MutableInodeFile inodeFile = createInodeFile(1); List<Long> blockIds = new ArrayList<>(); final int NUM_BLOCKS = 3; for (int i = 0; i < NUM_BLOCKS; i++) { blockIds.add(inodeFile.getNewBlockId()); } for (int i = 0; i < NUM_BLOCKS; i...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithColumnLabel() throws SQLException { when(mergeResultSet.getValue(1, Object.class)).thenReturn("object_value"); assertThat(shardingSphereResultSet.getObject("label"), is("object_value")); }
public ConnectionFactory connectionFactory(ConnectionFactory connectionFactory) { // It is common to implement both interfaces if (connectionFactory instanceof XAConnectionFactory) { return (ConnectionFactory) xaConnectionFactory((XAConnectionFactory) connectionFactory); } return TracingConnection...
@Test void connectionFactory_doesntDoubleWrap() { ConnectionFactory wrapped = jmsTracing.connectionFactory(mock(ConnectionFactory.class)); assertThat(jmsTracing.connectionFactory(wrapped)) .isSameAs(wrapped); }
public void visit(Entry entry) { final AFreeplaneAction action = new EntryAccessor().getAction(entry); if (action != null) { final EntryAccessor entryAccessor = new EntryAccessor(); String accelerator = entryAccessor.getAccelerator(entry); if(accelerator != null) { map.setDefaultAccelerator(action, acc...
@Test public void givenEntryWithoutAccelerator_doesNotSetOwnDefaultAccelerator() { Entry actionEntry = new Entry(); final AFreeplaneAction action = mock(AFreeplaneAction.class); new EntryAccessor().setAction(actionEntry, action); IAcceleratorMap map = mock(IAcceleratorMap.class); final AcceleratorBuilder ac...
@Override public int readUnsignedMedium() { checkReadableBytes0(3); int v = _getUnsignedMedium(readerIndex); readerIndex += 3; return v; }
@Test public void testReadUnsignedMediumAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().readUnsignedMedium(); } }); }
static String toRegularExpression(String glob) { StringBuilder output = new StringBuilder("^"); boolean literal = true; boolean processingGroup = false; for (int i = 0; i < glob.length(); ) { char c = glob.charAt(i++); switch (c) { case '?': ...
@Test public void testToRegularExpression() { assertNull(GlobComponent.toRegularExpression("blah")); assertNull(GlobComponent.toRegularExpression("")); assertNull(GlobComponent.toRegularExpression("does not need a regex, actually")); assertEquals("^\\$blah.*$", GlobComponent.toRegula...
public void check(AccessResource checkedAccess, AccessResource ownedAccess) { PlainAccessResource checkedPlainAccess = (PlainAccessResource) checkedAccess; PlainAccessResource ownedPlainAccess = (PlainAccessResource) ownedAccess; if (ownedPlainAccess.isAdmin()) { // admin user don't...
@Test public void testCheck_withDefaultPermissions_shouldPass() { PlainAccessResource checkedAccess = new PlainAccessResource(); checkedAccess.setRequestCode(Permission.SUB); checkedAccess.addResourceAndPerm("topic1", Permission.PUB); PlainAccessResource ownedAccess = new PlainAccess...
@Override @Nullable public Object convert(@Nullable String value) { if (isNullOrEmpty(value)) { return null; } LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone); final DateTimeFormatter form...
@Test public void convertUsesCustomLocale() throws Exception { final Converter c = new DateConverter(config("dd/MMM/YYYY HH:mm:ss Z", null, "de-DE")); final DateTime dateTime = (DateTime) c.convert("11/März/2017 15:10:48 +0200"); assertThat(dateTime).isEqualTo("2017-03-11T13:10:48.000Z"); ...
public static int checkGreaterThanOrEqual(int n, int expected, String name) { if (n < expected) { throw new IllegalArgumentException(name + ": " + n + " (expected: >= " + expected + ')'); } return n; }
@Test(expected = IllegalArgumentException.class) public void checkGreaterThanOrEqualMustFailIfArgumentIsLessThanExpected() { RangeUtil.checkGreaterThanOrEqual(0, 1, "var"); }
@Override protected void handlePut(final String listenTo, final ClusterProperties discoveryProperties) { if (discoveryProperties != null) { ActivePropertiesResult pickedPropertiesResult = pickActiveProperties(discoveryProperties); ClusterInfoItem newClusterInfoItem = new ClusterInfoItem( ...
@Test(dataProvider = "getConfigsWithFailoutProperties") public void testWithFailoutConfigs(ClusterProperties stableConfigs, FailoutProperties clusterFailoutProperties) { ClusterLoadBalancerSubscriberFixture fixture = new ClusterLoadBalancerSubscriberFixture(); fixture.getMockSubscriber(false).handlePut(CLUS...
@Override public String update(List<String> columns, List<String> where) { StringBuilder sql = new StringBuilder(); String method = "UPDATE "; sql.append(method); sql.append(getTableName()).append(" ").append("SET "); for (int i = 0; i < columns.size(); i++) { St...
@Test void testUpdate() { String sql = abstractMapper.update(Arrays.asList("id", "name"), Arrays.asList("id")); assertEquals("UPDATE tenant_info SET id = ?,name = ? WHERE id = ?", sql); }
@Override public ConsumerRecords<K, V> poll(final Duration timeout) { Timer timer = time.timer(timeout); acquireAndEnsureOpen(); try { kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs()); if (subscriptions.hasNoSubscriptionOrUserAssignment()) { ...
@Test @SuppressWarnings("deprecation") public void testPollLongThrowsException() { consumer = newConsumer(); Exception e = assertThrows(UnsupportedOperationException.class, () -> consumer.poll(0L)); assertEquals("Consumer.poll(long) is not supported when \"group.protocol\" is \"consumer\...
public static void install() { installBasic(); installLight(); installSemiBold(); }
@Test void testFont() { FlatInterFont.install(); testFont( FlatInterFont.FAMILY, Font.PLAIN, 13 ); testFont( FlatInterFont.FAMILY, Font.ITALIC, 13 ); testFont( FlatInterFont.FAMILY, Font.BOLD, 13 ); testFont( FlatInterFont.FAMILY, Font.BOLD | Font.ITALIC, 13 ); testFont( FlatInterFont.FAMILY_LIGHT, Font....
public static String generateTransactionHashHexEncoded( RawTransaction rawTransaction, Credentials credentials) { return Numeric.toHexString(generateTransactionHash(rawTransaction, credentials)); }
@Test public void testGenerateEip155TransactionHash() { assertEquals( generateTransactionHashHexEncoded( TransactionEncoderTest.createContractTransaction(), (byte) 1, SampleKeys.CREDENTIALS), ("0x568c7f69...
@VisibleForTesting static MemoryMonitor forTest( GCStatsProvider gcStatsProvider, long sleepTimeMillis, int shutDownAfterNumGCThrashing, boolean canDumpHeap, double gcThrashingPercentagePerPeriod, @Nullable String uploadFilePath, File localDumpFolder) { return new MemoryM...
@Test public void disableMemoryMonitor() throws Exception { MemoryMonitor disabledMonitor = MemoryMonitor.forTest(provider, 10, 0, true, 100.0, null, localDumpFolder); Thread disabledMonitorThread = new Thread(disabledMonitor); disabledMonitorThread.start(); // Monitor thread should stop quic...
public static String generateNewWalletFile(String password, File destinationDirectory) throws CipherException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException { return g...
@Test public void testGenerateNewWalletFile() throws Exception { String fileName = WalletUtils.generateNewWalletFile(PASSWORD, tempDir); testGeneratedNewWalletFile(fileName); }
static Map<String, String> parseConfig(byte[] byteConfig) { String config = new String(byteConfig, StandardCharsets.US_ASCII); Map<String, String> configMap = Util.parseMap(config); Map<String, String> serverMap = new HashMap<>(configMap.size() - 1); for (Map.Entry<String, String> ent...
@Test public void testParseConfig() { String config = "server.1=my-cluster-zookeeper-0.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181\n" + "server.2=my-cluster-zookeeper-1.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181\n...
@Udf public String concatWS( @UdfParameter(description = "Separator string and values to join") final String... inputs) { if (inputs == null || inputs.length < 2) { throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments."); } final String separator = inputs[0...
@Test public void shouldConcatBytes() { assertThat(udf.concatWS(ByteBuffer.wrap(new byte[] {1}), ByteBuffer.wrap(new byte[] {2}), ByteBuffer.wrap(new byte[] {3})), is(ByteBuffer.wrap(new byte[] {2, 1, 3}))); }
public TokenResponse exchangePkceCode( URI tokenEndpoint, String code, String redirectUri, String clientId, String codeVerifier) { var body = UrlFormBodyBuilder.create() .param("grant_type", "authorization_code") .param("redirect_uri", redirectUri) .param("client_i...
@Test void exchangePkceCode(WireMockRuntimeInfo wm) { var body = """ { "access_token" : null, "token_type" : "Bearer", "expires_in" : 3600, "id_token" : "eyJraWQiOiIxZTlnZGs3IiwiYWxnIjoiUl..." } """ .getBytes(StandardChar...
@Override public synchronized int read(long pos, byte[] b, int start, int len) throws IOException { this.pos = (int) pos; return read(b, start, len); }
@Test void randomReads() throws Exception { Random random = new Random(19820210); int length = random.nextInt(SIZE) + 1; byte[] data = new byte[length]; random.nextBytes(data); Input in = new InputBytes(data); for (int i = 0; i < COUNT; i++) { int p = random.nextInt(length); int ...
@Override protected CompletableFuture<JobVertexBackPressureInfo> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { metricFetcher.update(); final JobID jobId = request.getPathParameter(JobIDPathPar...
@Test void testAbsentBackPressure() throws Exception { final Map<String, String> pathParameters = new HashMap<>(); pathParameters.put( JobIDPathParameter.KEY, TEST_JOB_ID_BACK_PRESSURE_STATS_ABSENT.toString()); pathParameters.put(JobVertexIdPathParameter.KEY, new JobVertexID(...
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException { // set URL if set in authnRequest final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL(); if (authnAcsURL != null) { ...
@Test void resolveAcsUrlWithIndex1InMultiAcsMetadata() throws SamlValidationException { AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class); authnRequest.setAssertionConsumerServiceIndex(1); AuthenticationRequest authenticationRequest = new AuthenticationRequest();...
@Override public ZFrame pop() { return frames.poll(); }
@Test public void testPop() { ZMsg msg = new ZMsg(); assertThat(msg.popString(), nullValue()); }
public Map<String, LdapContextFactory> getContextFactories() { if (contextFactories == null) { contextFactories = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { initMultiLdapConfiguration(serverKeys); } else { ...
@Test public void testContextFactoriesWithSingleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( generateSingleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(1); }
public float add(int i, int j, float b) { return A[index(i, j)] += b; }
@Test public void testAdd() { System.out.println("add"); float[][] A = { { 0.7220180f, 0.07121225f, 0.6881997f}, {-0.2648886f, -0.89044952f, 0.3700456f}, {-0.6391588f, 0.44947578f, 0.6240573f} }; float[][] B = { {0.688...
public void run() { status = GameStatus.RUNNING; Thread gameThread = new Thread(this::processGameLoop); gameThread.start(); }
@Test void testRun() { gameLoop.run(); Assertions.assertEquals(GameStatus.RUNNING, gameLoop.status); }
public static void applyLocaleToContext(@NonNull Context context, @Nullable String localeString) { final Locale forceLocale = LocaleTools.getLocaleForLocaleString(localeString); final Configuration configuration = context.getResources().getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.J...
@SuppressLint("UseSdkSuppress") @RequiresApi(api = Build.VERSION_CODES.N) @Test @Config(sdk = Build.VERSION_CODES.N) public void testSetAndResetValueAPI24() { Assert.assertEquals( "English (United States)", mContext.getResources().getConfiguration().locale.getDisplayName()); Assert.asser...
@Override public DescribeClientQuotasResult describeClientQuotas(ClientQuotaFilter filter, DescribeClientQuotasOptions options) { KafkaFutureImpl<Map<ClientQuotaEntity, Map<String, Double>>> future = new KafkaFutureImpl<>(); final long now = time.milliseconds(); runnable.call(new Call("desc...
@Test public void testDescribeClientQuotas() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); final String value = "value"; Map<ClientQuotaEntity, Map<String, Double>> responseData = ...
public static GoPluginBundleDescriptor parseXML(InputStream pluginXml, BundleOrPluginFileDetails bundleOrPluginJarFile) throws IOException, JAXBException, XMLStreamException, SAXException { return parseXML(pluginXml, bundleOrPluginJarFile.file().getAbsolutePat...
@Test void shouldValidatePluginVersion() throws IOException { try (InputStream pluginXml = IOUtils.toInputStream("<go-plugin version=\"10\"></go-plugin>", StandardCharsets.UTF_8)) { JAXBException e = assertThrows(JAXBException.class, () -> GoPluginDescriptorParser.parseXML(plugin...
@Override public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileAnonymousRequest request) { final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier()); if (targetIdentifier.identityType() != IdentityT...
@Test void getVersionedProfileVersionNotFound() { final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH); when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey)); when(account.isUnrestrictedUnidentifiedAccess())...
public static XPathExpression buildXPathMatcherFromRules(String rules) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); WritableNamespaceContext nsContext = new WritableNamespaceContext(); // Parse SoapUI rules for getting namespaces and expression to evaluate. ...
@Test void testBuildXPathMatcherFromRulesFunction() { String rules = "declare namespace ser='http://www.example.com/hello';\n" + "concat(//ser:sayHello/title/text(),' ',//ser:sayHello/name/text())"; String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ...
public boolean hasAnyMethodHandlerAnnotation() { return !operationsWithHandlerAnnotation.isEmpty(); }
@Test public void testHandlerInFunctionalInterfaceWithMethodReference() { MyClass myClass = new MyClass(); MyHandlerInterface mhi = (MyHandlerInterface) myClass::myOtherMethod; BeanInfo info = new BeanInfo(context, mhi.getClass()); assertTrue(info.hasAnyMethodHandlerAnnotation()); ...
public void writeBytes(final byte[] value) { byteBuf.writeBytes(value); }
@Test void assertWriteBytes() { new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeBytes("value".getBytes()); verify(byteBuf).writeBytes("value".getBytes()); }
@Override public void commit() { if (context == null || context.isEmpty()) { return; } LOGGER.info("Commit started"); if (context.containsKey(UnitActions.INSERT.getActionValue())) { commitInsert(); } if (context.containsKey(UnitActions.MODIFY.getActionValue())) { commitModif...
@Test void shouldNotWriteToDbIfNothingToCommit() { var weaponRepository = new ArmsDealer(new HashMap<>(), weaponDatabase); weaponRepository.commit(); verifyNoMoreInteractions(weaponDatabase); }
public @CheckForNull String readLink() throws IOException { return null; }
@Issue("JENKINS-26810") @Test public void readLink() throws Exception { assumeFalse(Functions.isWindows()); File root = tmp.getRoot(); FilePath rootF = new FilePath(root); rootF.child("plain").write("", null); rootF.child("link").symlinkTo("physical", TaskListener.NULL); ...
@Override public DataSerializableFactory createFactory() { return new Factory(); }
@Test(expected = IllegalArgumentException.class) public void testInvalidType() { MetricsDataSerializerHook hook = new MetricsDataSerializerHook(); hook.createFactory().create(999); }
public CacheConfig<K, V> setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount); return this; }
@Test(expected = IllegalArgumentException.class) public void setAsyncBackupCount_whenTooLarge() { CacheConfig config = new CacheConfig(); config.setAsyncBackupCount(200); //max allowed is 6.. }
public static String toJson(FileScanTask fileScanTask) { Preconditions.checkArgument(fileScanTask != null, "Invalid scan task: null"); return JsonUtil.generate(generator -> toJson(fileScanTask, generator), false); }
@Test public void unsupportedTask() { FileScanTask mockTask = Mockito.mock(FileScanTask.class); assertThatThrownBy(() -> ScanTaskParser.toJson(mockTask)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining( "Unsupported task type: org.apache.iceberg.FileScanTas...
public static String getDefaultContextPath() { return defaultContextPath; }
@Test void testGetDefaultContextPath() { String defaultVal = ParamUtil.getDefaultContextPath(); assertEquals(defaultContextPath, defaultVal); String expect = "test"; ParamUtil.setDefaultContextPath(expect); assertEquals(expect, ParamUtil.getDefaultContextPath()); ...
public static boolean containsWildcard(String regex) { return (regex.contains("?") || regex.contains("*")); }
@Test void testContainsWildcard() { assertFalse(RegexParser.containsWildcard("test")); assertTrue(RegexParser.containsWildcard("?")); assertTrue(RegexParser.containsWildcard("*")); }
@Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("ip", ipAddress) .add("timestamp", timestamp) .add("lease", leasePeriod) .add("assignmentStatus", assignmentStatus) .add("subnetMask", subne...
@Test public void testToString() { assertThat(stats1.toString(), is(stats1.toString())); }
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 testNormalizeEndpointUri() throws Exception { String out1 = URISupport.normalizeUri("smtp://localhost?username=davsclaus&password=secret"); String out2 = URISupport.normalizeUri("smtp://localhost?password=secret&username=davsclaus"); assertEquals(out1, out2); out1 ...
public List<DataRecord> merge(final List<DataRecord> dataRecords) { Map<DataRecord.Key, DataRecord> result = new HashMap<>(); dataRecords.forEach(each -> { if (PipelineSQLOperationType.INSERT == each.getType()) { mergeInsert(each, result); } else if (PipelineSQLOp...
@Test void assertDeleteBeforeDelete() { DataRecord beforeDataRecord = mockDeleteDataRecord(1, 1, 1); DataRecord afterDataRecord = mockDeleteDataRecord(1, 1, 1); assertThrows(PipelineUnexpectedDataRecordOrderException.class, () -> groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRec...
@SuppressWarnings("unchecked") public static synchronized <T extends Cache> T createCache(String name) { T cache = (T) caches.get(name); if (cache != null) { return cache; } cache = (T) cacheFactoryStrategy.createCache(name); log.info("Created cache [" + cacheFac...
@Test public void testCacheRecreation() throws Exception { // Setup test fixture. final String name = "unittest-cache-recreation"; // Execute system under test. final Cache resultA = CacheFactory.createCache(name); final Cache resultB = CacheFactory.createCache(name); ...
public static Builder builder(Type type) { return new Builder(type); }
@Test public void build_without_key_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setUuid("ABCD").build()) .isInstanceOf(NullPointerException.class); }