focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean checkIndexExists( Database database, String schemaName, String tableName, String[] idxFields ) throws KettleDatabaseException { String tablename = database.getDatabaseMeta().getQuotedSchemaTableCombination( schemaName, tableName ); boolean[] exists = new boolean[ idxFields.length]; ...
@Test public void testCheckIndexExists() throws Exception { String expectedSQL = "select i.name table_name, c.name column_name from sysindexes i, sysindexkeys k, syscolumns c where i.name = 'FOO' AND i.id = k.id AND i.id = c.id AND k.colid = c.colid "; // yes, space at the end like in the db...
public static void checkState(boolean isValid, String message) throws IllegalStateException { if (!isValid) { throw new IllegalStateException(message); } }
@Test public void checkStateMessageOnlySupportsStringTypeTemplate() { try { Preconditions.checkState(true, "Test message %d", 12); } catch (IllegalStateException e) { Assert.fail("Should not throw exception when isValid is true"); } try { Preconditions.checkState(false, "Test messag...
@Override protected Collection<Address> getPossibleAddresses() { Iterable<DiscoveryNode> discoveredNodes = checkNotNull(discoveryService.discoverNodes(), "Discovered nodes cannot be null!"); MemberImpl localMember = node.nodeEngine.getLocalMember(); Set<Address> localAddress...
@Test public void test_DiscoveryJoiner_enriches_member_with_public_address_when_advanced_network_used() throws UnknownHostException { DiscoveryJoiner joiner = new DiscoveryJoiner(getNode(hz), service, false); doReturn(discoveryNodes).when(service).discoverNodes(); // the CLIENT p...
@Override public void validate(PipelineOptions options) { delegate().validate(options); }
@Test public void validateDelegates() { @SuppressWarnings("unchecked") PipelineOptions options = mock(PipelineOptions.class); doThrow(RuntimeException.class).when(delegate).validate(options); thrown.expect(RuntimeException.class); forwarding.validate(options); }
@Override public void memberChange(Set<String> addresses) { for (int i = 0; i < 5; i++) { if (this.raftServer.peerChange(jRaftMaintainService, addresses)) { return; } ThreadUtils.sleep(100L); } Loggers.RAFT.warn("peer removal failed"); ...
@Test void testMemberChange() { Set<String> addresses = new HashSet<>(); raftProtocol.memberChange(addresses); verify(serverMock, times(5)).peerChange(jRaftMaintainService, addresses); }
public static String jaasConfig(String moduleName, Map<String, String> options) { StringJoiner joiner = new StringJoiner(" "); for (Entry<String, String> entry : options.entrySet()) { String key = Objects.requireNonNull(entry.getKey()); String value = Objects.requireNonNull(entry...
@Test public void testModuleNameContainsEqualSign() { Map<String, String> options = new HashMap<>(); options.put("key1", "value1"); String moduleName = "Module="; assertThrows(IllegalArgumentException.class, () -> AuthenticationUtils.jaasConfig(moduleName, options)); }
@Override public void deregisterInstance(String serviceName, String ip, int port) throws NacosException { deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); }
@Test void testDeregisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); //when client.deregisterInstance(serviceName, groupName, instance); //then verify(pro...
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final BrickApiClient client = new BrickApiClient(session); if(status.isExists()) { ...
@Test public void testCopyEmptyFile() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new BrickTouchFeature(session).touch(test, new TransferStatus()); final Path copy = n...
public CompletableFuture<InetSocketAddress> resolveAndCheckTargetAddress(String hostAndPort) { int pos = hostAndPort.lastIndexOf(':'); String host = hostAndPort.substring(0, pos); int port = Integer.parseInt(hostAndPort.substring(pos + 1)); if (!isPortAllowed(port)) { return ...
@Test public void shouldAllowAllWithWildcard() throws Exception { BrokerProxyValidator brokerProxyValidator = new BrokerProxyValidator( createMockedAddressResolver("1.2.3.4"), "*" , "*" , "6650"); brokerProxyValidator.resolveAndCheckTar...
public PluginData obtainPluginData(final String pluginName) { return PLUGIN_MAP.get(pluginName); }
@Test public void testObtainPluginData() throws NoSuchFieldException, IllegalAccessException { PluginData pluginData = PluginData.builder().name(mockName1).build(); ConcurrentHashMap<String, PluginData> pluginMap = getFieldByName(pluginMapStr); pluginMap.put(mockName1, pluginData); a...
@Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { boolean useJavaCC = "--useJavaCC".equals(getArg(args, 0, null)); if (args.isEmpty() || args.size() > (useJavaCC ? 3 : 2) || isRequestingHelp(args)) { err.println("Usage: idl2schemata [--useJ...
@Test void splitIdlIntoSchemata() throws Exception { String idl = "src/test/idl/protocol.avdl"; String outdir = "target/test-split"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); List<String> arglist = Arrays.asList(idl, outdir); new IdlToSchemataTool().run(null, null, new PrintStre...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedNoArrowOneStringInvalidDelimiter() { String[] forwardedFields = {"f2,f3,f0"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsSin...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testClusterAuthorizationExceptionInProduceRequest() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(producerId, Er...
@PostMapping("/rule") public ShenyuAdminResult saveRule(@RequestBody @Valid @NotNull final DataPermissionDTO dataPermissionDTO) { return ShenyuAdminResult.success(ShenyuResultMessage.SAVE_SUCCESS, dataPermissionService.createRule(dataPermissionDTO)); }
@Test public void saveRule() throws Exception { DataPermissionDTO dataPermissionDTO = new DataPermissionDTO(); dataPermissionDTO.setDataId("testDataId"); dataPermissionDTO.setUserId("testUserId"); given(this.dataPermissionService.createRule(dataPermissionDTO)).willReturn(1); ...
@Override public boolean tryFence(HAServiceTarget target, String args) { ProcessBuilder builder; String cmd = parseArgs(target.getTransitionTargetHAStatus(), args); if (!Shell.WINDOWS) { builder = new ProcessBuilder("bash", "-e", "-c", cmd); } else { builder = new ProcessBuilder("cmd.exe"...
@Test public void testTargetAsEnvironment() { if (!Shell.WINDOWS) { fencer.tryFence(TEST_TARGET, "echo $target_host $target_port"); Mockito.verify(ShellCommandFencer.LOG).info( Mockito.endsWith("echo $ta...rget_port: dummyhost 1234")); } else { fencer.tryFence(TEST_TARGET, "echo %t...
@Override public void setIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(); } this.readerIndex = readerIndex; this.writerIndex = writerIndex; }
@Test void setIndexBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.setIndex(0, CAPACITY + 1)); }
public List<Metadata> recursiveParserWrapperExample() throws IOException, SAXException, TikaException { Parser p = new AutoDetectParser(); ContentHandlerFactory factory = new BasicContentHandlerFactory(BasicContentHandlerFactory.HANDLER_TYPE.HTML, -1); RecursiveParserWrapper wrapper = new Recur...
@Test public void testRecursiveParserWrapperExample() throws IOException, SAXException, TikaException { List<Metadata> metadataList = parsingExample.recursiveParserWrapperExample(); assertEquals(12, metadataList.size(), "Number of embedded documents + 1 for the container document"); Metadata...
@SafeVarargs public static <T> T[] append(T[] buffer, T... newElements) { if (isEmpty(buffer)) { return newElements; } return insert(buffer, buffer.length, newElements); }
@Test public void appendTest() { String[] a = {"1", "2", "3", "4"}; String[] b = {"a", "b", "c"}; String[] result = ArrayUtil.append(a, b); assertArrayEquals(new String[]{"1", "2", "3", "4", "a", "b", "c"}, result); }
public void createResource(CreateResourceStmt stmt) throws DdlException { Resource resource = Resource.fromStmt(stmt); this.writeLock(); try { String resourceName = stmt.getResourceName(); String typeName = resource.getType().name().toLowerCase(Locale.ROOT); ...
@Test(expected = DdlException.class) public void testAddResourceExist(@Injectable BrokerMgr brokerMgr, @Injectable EditLog editLog, @Mocked GlobalStateMgr globalStateMgr) throws UserException { ResourceMgr mgr = new ResourceMgr(); // add Crea...
public static CountMinSketch merge(CountMinSketch... estimators) throws CMSMergeException { CountMinSketch merged = null; if (estimators != null && estimators.length > 0) { int depth = estimators[0].depth; int width = estimators[0].width; long[] hashA = Arrays.copyOf(...
@Test public void testMergeEmpty() throws CMSMergeException { assertNull(CountMinSketch.merge()); }
public Optional<Throwable> run(String... arguments) { try { if (isFlag(HELP, arguments)) { parser.printHelp(stdOut); } else if (isFlag(VERSION, arguments)) { parser.printVersion(stdOut); } else { final Namespace namespace = pars...
@Test void handlesShortHelpCommands() throws Exception { assertThat(cli.run("-h")) .isEmpty(); assertThat(stdOut) .hasToString(String.format( "usage: java -jar dw-thing.jar [-h] [-v] {check,custom} ...%n" + "%n"...
@Override public int run(String[] argv) { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-safemode".equals(cmd)) { if (argv.length != 2) ...
@Test(timeout = 180000) public void testReportCommand() throws Exception { tearDown(); redirectStream(); // init conf final Configuration dfsConf = new HdfsConfiguration(); ErasureCodingPolicy ecPolicy = SystemErasureCodingPolicies.getByID( SystemErasureCodingPolicies.XOR_2_1_POLICY_ID); ...
@Override public void handleRequestWithRestLiResponse(RestRequest request, RequestContext requestContext, Callback<RestLiResponse> callback) { if (!isMultipart(request, requestContext, callback)) { _restRestLiServer.handleRequestWithRestLiResponse(request, requestContext, callback); } }
@Test(dataProvider = "restOrStream") public void testHandleRequestWithRestLiResponseSuccess(final RestOrStream restOrStream) throws Exception { Status status = new Status(); status.data().put("test", "this is a test"); final StatusCollectionResource statusResource = getMockResource(StatusCollectionReso...
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithEmptyString() { expectFailureWhenTestingThat(asList()).containsExactly(""); assertFailureValue("missing (1)", ""); }
public static void assertAllResultsEqual(Collection<?> objects) throws AssertionError { if (objects.size() == 0 || objects.size() == 1) return; Object[] resultsArray = objects.toArray(); for (int i = 1; i < resultsArray.length; i++) { Object currElement = resultsArray[i]; Object...
@Test public void testAssertAllResultsEqual() { checkAllResults(new Long[]{}, true); checkAllResults(new Long[]{1l}, true); checkAllResults(new Long[]{1l, 1l}, true); checkAllResults(new Long[]{1l, 1l, 1l}, true); checkAllResults(new Long[]{new Long(1), new Long(1)}, true); checkAllResults(new...
public ConnectionDetails getConnectionDetails( IMetaStore metaStore, String key, String name ) { ConnectionProvider<? extends ConnectionDetails> connectionProvider = getConnectionProvider( key ); if ( connectionProvider != null ) { Class<? extends ConnectionDetails> clazz = connectionProvider.getClassType...
@Test public void testSaveConnection() { addOne(); TestConnectionWithBucketsDetails testConnectionDetails1 = (TestConnectionWithBucketsDetails) connectionManager .getConnectionDetails( TestConnectionWithBucketsProvider.SCHEME, CONNECTION_NAME ); assertEquals( CONNECTION_NAME, testConnection...
@Description("round down to nearest integer") @ScalarFunction @SqlType(StandardTypes.BIGINT) public static long floor(@SqlType(StandardTypes.BIGINT) long num) { return num; }
@Test public void testFloor() { assertFunction("floor(TINYINT'123')", TINYINT, (byte) 123); assertFunction("floor(TINYINT'-123')", TINYINT, (byte) -123); assertFunction("floor(CAST(NULL AS TINYINT))", TINYINT, null); assertFunction("floor(SMALLINT'123')", SMALLINT, (short) 123); ...
public static Object serialize(Object bean) throws NullPointerException { return serialize(bean, false); }
@Test public void serialize() { TestJsonBean bean = new TestJsonBean(); boolean error = false; try { Map map = (Map) BeanSerializer.serialize(bean); } catch (Exception e) { error = true; } Assert.assertTrue(error); error = false; ...
@Nonnull public static <C> SourceBuilder<C>.Batch<Void> batch( @Nonnull String name, @Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn ) { return new SourceBuilder<C>(name, createFn).new Batch<>(); }
@Test public void batch_fileSource() throws Exception { // Given File textFile = createTestFile(); // When BatchSource<String> fileSource = SourceBuilder .batch("file-source", x -> fileReader(textFile)) .<String>fillBufferFn((in, buf) -> { ...
public Group getGroup(JID jid) throws GroupNotFoundException { JID groupJID = GroupJID.fromJID(jid); return (groupJID instanceof GroupJID) ? getGroup(((GroupJID)groupJID).getGroupName()) : null; }
@Test public void willUseACacheMiss() { groupCache.put(GROUP_NAME, CacheableOptional.of(null)); try { groupManager.getGroup(GROUP_NAME, false); } catch (final GroupNotFoundException ignored) { verifyNoMoreInteractions(groupProvider); return; } ...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType = null; String colName...
@Test public void testAggregateMultiStatsWhenOnlySomeAvailable() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2", "part3", "part4"); ColumnStatisticsData data1 = new ColStatsBuilder<>(String.class).numNulls(1).numDVs(3).avgColLen(20.0 / 3).maxColLen(13) .hll(S_1, S_2, ...
public OpenConfigComponentHandler addTransceiver(OpenConfigTransceiverHandler transceiver) { augmentedOcPlatformComponent.transceiver(transceiver.getModelObject()); modelObject.addAugmentation(augmentedOcPlatformComponent); return this; }
@Test public void testAddTransceiver() { // test Handler OpenConfigComponentHandler component = new OpenConfigComponentHandler("name", parent); // call addTransceiver OpenConfigTransceiverHandler transceiver = new OpenConfigTransceiverHandler(component); // expected ModelOb...
@Override public AuthLoginRespVO refreshToken(String refreshToken) { OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT); return AuthConvert.INSTANCE.convert(accessTokenDO); }
@Test public void testRefreshToken() { // 准备参数 String refreshToken = randomString(); // mock 方法 OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class); when(oauth2TokenService.refreshAccessToken(eq(refreshToken), eq("default"))) .thenReturn(...
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = false; boolean containsNull = false; // Spec. definiti...
@Test void invokeListParamEmptyList() { FunctionTestUtil.assertResult(anyFunction.invoke(Collections.emptyList()), false); }
public JobBuilder withLabels(String... labels) { return withLabels(asSet(labels)); }
@Test void testWithLabels() { Job job = aJob() .withLabels(Set.of("TestLabel", "Email")) .withDetails(() -> testService.doWorkWithUUID(UUID.randomUUID())) .build(jobDetailsGenerator); assertThat(job) .hasLabels(Set.of("TestLabel", "Ema...
protected ObjectName getJMXObjectName() throws MalformedObjectNameException { if (jmxObjectName == null) { ObjectName on = buildObjectName(); setJMXObjectName(on); } return jmxObjectName; }
@Test public void getJMXObjectNameCached() throws Exception { JMXEndpoint ep = context.getEndpoint("jmx:platform?objectDomain=FooDomain&key.name=theObjectName", JMXEndpoint.class); ObjectName on = ep.getJMXObjectName(); assertNotNull(on); assertSame(on, ep.getJMXObjectName()); }
public ClusterSerdes init(Environment env, ClustersProperties clustersProperties, int clusterIndex) { ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex); log.debug("Configuring serdes for cluster {}", clusterP...
@Test void pluggedSerdesInitializedByLoader() { ClustersProperties.SerdeConfig customSerdeConfig = new ClustersProperties.SerdeConfig(); customSerdeConfig.setName("MyPluggedSerde"); customSerdeConfig.setFilePath("/custom.jar"); customSerdeConfig.setClassName("org.test.MyPluggedSerde"); customSerde...
public Distance altitudeDelta() { double delta = abs(point1.altitude().inFeet() - point2.altitude().inFeet()); return Distance.of(delta, Distance.Unit.FEET); }
@Test public void testAltitudeDelta() { //alt = 2400 Point p1 = NopHit.from("[RH],STARS,A80_B,02/12/2018,18:36:46.667,JIA5545,CRJ9,E,5116,024,157,270,033.63143,-084.33913,1334,5116,22.4031,27.6688,1,O,A,A80,OZZ,OZZ,ATL,1827,ATL,ACT,IFR,,01719,,,,,27L,L,1,,0,{RH}"); //alt = 3400 Point...
@Override public boolean supportsPath(String path) { return path != null && path.startsWith(Constants.HEADER_OSS); }
@Test public void supportsPath() { Assert.assertTrue(mFactory.supportsPath(mOssPath)); assertFalse(mFactory.supportsPath(null)); assertFalse(mFactory.supportsPath("Invalid_Path")); assertFalse(mFactory.supportsPath("hdfs://test-bucket/path")); }
@Override public void submit(VplsOperation vplsOperation) { if (isLeader) { // Only leader can execute operation addVplsOperation(vplsOperation); } }
@Test @Ignore("Test is brittle - revisit") public void testDuplicateOperationInQueue() { VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1, V100H2)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
@Override public void define(Context context) { NewController controller = context.createController("api/user_groups") .setDescription("Manage user groups.") .setSince("5.2"); for (UserGroupsWsAction action : actions) { action.define(controller); } controller.done(); }
@Test public void define_controller() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/user_groups"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertTha...
@Override public Mono<PooledRef<Connection>> acquire() { return new BorrowerMono(this, Duration.ZERO); }
@Test void pendingTimeout() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(); PoolBuilder<Connection, PoolConfig<Connection>> poolBuilder = PoolBuilder.from(Mono.just(Connection.from(channel))) .maxPendingAcquire(10) .sizeBetween(0, 1); Http2Pool http2Pool = po...
@Override public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) { if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) { return resolveRequestConfig(propertyName); } else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX) && !propertyName.starts...
@Test public void shouldFindUnknownStreamsPrefixedConsumerPropertyIfNotStrict() { // Given: final String configName = StreamsConfig.CONSUMER_PREFIX + "custom.interceptor.config"; // Then: assertThat( resolver.resolve(KsqlConfig.KSQL_STREAMS_PREFIX + configName, false), is(unre...
public FEELFnResult<Object> invoke(@ParameterName("list") List list) { if ( list == null || list.isEmpty() ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty")); } else { try { return FEELFnResult.ofResult(C...
@Test void invokeNullArray() { FunctionTestUtil.assertResultError(minFunction.invoke((Object[]) null), InvalidParametersEvent.class); }
@Override public Collection<RequestAndKeys<CoordinatorKey>> buildRequest(int brokerId, Set<CoordinatorKey> groupIds) { validateKeys(groupIds); // When the OffsetFetchRequest fails with NoBatchedOffsetFetchRequestException, we completely disable // the batching end-to-end, including the Find...
@Test public void testBuildRequest() { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler(singleRequestMap, false, logContext); OffsetFetchRequest request = handler.buildBatchedRequest(coordinatorKeys(groupZero)).build(); assertEquals(groupZero, request...
public String[] decodeStringArray(final byte[] parameterBytes, final boolean isBinary) { ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode")); String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8); Collection<String> pa...
@Test void assertParseStringArrayWithNullTextMode() { String[] actual = DECODER.decodeStringArray("{\"a\",\"b\",NULL}".getBytes(), false); assertThat(actual.length, is(3)); assertThat(actual[0], is("a")); assertThat(actual[1], is("b")); assertNull(actual[2]); }
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the re...
@Test public void testPostNewDeploymentBarFileWithTenantId() throws Exception { try { // Create zip with bpmn-file and resource ByteArrayOutputStream zipOutput = new ByteArrayOutputStream(); ZipOutputStream zipStream = new ZipOutputStream(zipOutput); // Add b...
public LocalFileSystem() { this.workingDir = new File(System.getProperty("user.dir")).toURI(); this.homeDir = new File(System.getProperty("user.home")).toURI(); }
@Test void testLocalFilesystem() throws Exception { final File tempdir = new File(TempDirUtils.newFolder(tempFolder), UUID.randomUUID().toString()); final File testfile1 = new File(tempdir, UUID.randomUUID().toString()); final File testfile2 = new File(tempdir, UUID.randomUU...
public PipelineResult run() { return run(defaultOptions); }
@Test @Category(NeedsRunner.class) public void testEmptyPipeline() throws Exception { pipeline.run(); }
public int ceil(int v) { return Boundary.CEIL.apply(find(v)); }
@Test public void ceil() { SortedIntList l = new SortedIntList(5); l.add(1); l.add(3); l.add(5); assertEquals(0, l.ceil(0)); assertEquals(0, l.ceil(1)); assertEquals(1, l.ceil(2)); assertEquals(1, l.ceil(3)); assertEquals(2, l.ceil(4)); ass...
public Collection<Map.Entry<Point, UntypedMetric>> getValuesForMetric(String metricName) { List<Map.Entry<Point, UntypedMetric>> singleMetric = new ArrayList<>(); for (Map.Entry<Identifier, UntypedMetric> entry : values.entrySet()) { if (metricName.equals(entry.getKey().getName())) { ...
@Test final void testGetValuesForMetric() { twoMetricsUniqueDimensions(); Collection<Entry<Point, UntypedMetric>> values = bucket.getValuesForMetric("nalle"); assertEquals(4, values.size()); }
@Override public String telnet(Channel channel, String message) { long size; File file = LoggerFactory.getFile(); StringBuilder buf = new StringBuilder(); if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { ...
@Test void testPrintLog() throws RemotingException { mockChannel = mock(Channel.class); String result = log.telnet(mockChannel, "100"); assertTrue(result.contains("CURRENT LOG APPENDER")); }
@Udf(description = "Returns the cotangent of an INT value") public Double cot( @UdfParameter( value = "value", description = "The value in radians to get the cotangent of." ) final Integer value ) { return cot(value == null ? null : value.doubleValue()); ...
@Test public void shouldHandleNegative() { assertThat(udf.cot(-0.43), closeTo(-2.1804495406685085, 0.000000000000001)); assertThat(udf.cot(-Math.PI), closeTo(8.165619676597685E15, 0.000000000000001)); assertThat(udf.cot(-Math.PI * 2), closeTo(4.0828098382988425E15, 0.000000000000001)); assertThat(udf....
@Override public boolean onTouchEvent(@NonNull MotionEvent nativeMotionEvent) { if (mKeyboard == null) { // I mean, if there isn't any keyboard I'm handling, what's the point? return false; } final int action = nativeMotionEvent.getActionMasked(); final int pointerCount = nativeMotionEven...
@Test public void testWithLongPressOutputRegularPressKeyPressState() { final AnyKeyboard.AnyKey key = findKey('f'); key.longPressCode = 'z'; KeyDrawableStateProvider provider = new KeyDrawableStateProvider( R.attr.key_type_function, R.attr.key_type_action, R.att...
@Override public final int compareTo(final SQLToken sqlToken) { return startIndex - sqlToken.startIndex; }
@Test void assertCompareToEqual() { assertThat(new SQLTokenFixture(0, 10).compareTo(new SQLTokenFixture(0, 10)), is(0)); }
public double getY() { return position.y(); }
@Test public void testGetY() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getY(), EPSILON); }
public String generateSignature() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialSigType"), x509cert.getSigAlgName()); append(builder, NLS.str("certificate.serialSigOID"), x509cert.getSigAlgOID()); return builder.toString(); }
@Test public void decodeRSAKeySignature() { assertThat(certificateManagerRSA.generateSignature()) .contains("SHA256withRSA") .contains("1.2.840.113549.1.1.11"); }
@Override public LogicalSchema getSchema() { return getSource().getSchema(); }
@Test public void shouldSupportMultiRangeExpressionsUsingTableScan() { // Given: when(source.getSchema()).thenReturn(MULTI_KEY_SCHEMA); final Expression expression1 = new ComparisonExpression( Type.GREATER_THAN, new UnqualifiedColumnReferenceExp(ColumnName.of("K1")), new IntegerLiteral(1...
@GET @Operation(summary = "List all active connectors") public Response listConnectors( final @Context UriInfo uriInfo, final @Context HttpHeaders headers ) { if (uriInfo.getQueryParameters().containsKey("expand")) { Map<String, Map<String, Object>> out = new HashMap<>();...
@Test public void testFullExpandConnectors() { when(herder.connectors()).thenReturn(Arrays.asList(CONNECTOR2_NAME, CONNECTOR_NAME)); ConnectorInfo connectorInfo = mock(ConnectorInfo.class); ConnectorInfo connectorInfo2 = mock(ConnectorInfo.class); when(herder.connectorInfo(CONNECTOR2...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldHandleNullKeyForSourceWithKeyField() { // Given: givenSourceStreamWithSchema(BIG_SCHEMA, SerdeFeatures.of(), SerdeFeatures.of()); final ConfiguredStatement<InsertValues> statement = givenInsertValues( allAndPseudoColumnNames(BIG_SCHEMA), ImmutableList.of( ...
public void updateSchema( PartitionSchema schema ) { if ( schema != null && schema.getName() != null ) { stepMeta.getStepPartitioningMeta().setPartitionSchema( schema ); } }
@Test public void metaIsUpdated() { PartitionSchema schema = new PartitionSchema( "1", Collections.<String>emptyList() ); StepPartitioningMeta meta = mock( StepPartitioningMeta.class ); when( stepMeta.getStepPartitioningMeta() ).thenReturn( meta ); settings.updateSchema( schema ); verify( meta )...
@Override public int size() { int size = 0; for (Map<Data, QueryableEntry> resultSet : resultSets) { size += resultSet.size(); } return size; }
@Test public void testAddResultSet_notEmpty() { addEntry(entry(data())); assertThat(result.size()).isEqualTo(1); }
public String getGroup() { return group; }
@Test public void testGetGroup() { // Test the getGroup method assertEquals("Group1", event.getGroup()); }
static Map<Address, List<Shard>> assignShards(Collection<Shard> shards, Collection<Address> addresses) { Map<String, List<String>> assignment = addresses.stream() // host -> [indexShard...] .map(Address::getHost).distinct().collect(toMap(identity(), a -> new ArrayList<>())); Map<String,...
@Test public void given_multipleNodeAddressesOnLocal_when_assignShards_then_shouldAssignSingleShardToEachAddress() throws UnknownHostException { List<Shard> shards = List.of( new Shard("elastic-index", 0, Prirep.p, 10, "STARTED", "127.0.0.1", "127.0.0.1:9200", "node1"), ...
public Optional<LDAPUser> searchUserByPrincipal(LDAPConnection connection, UnboundLDAPConfig config, String principal) throws LDAPException { final String filterString = new MessageFormat(config.userSearchPat...
@Test public void testUserLookup() throws Exception { final UnboundLDAPConfig searchConfig = UnboundLDAPConfig.builder() .userSearchBase("ou=users,dc=example,dc=com") .userSearchPattern("(&(objectClass=posixAccount)(uid={0}))") .userUniqueIdAttribute("entryUUI...
@Override public String toString() { return "RollbackRule with pattern [" + this.exceptionName + "]"; }
@Test public void toStringTest(){ RollbackRule otherRollbackRuleByName = new RollbackRule(Exception.class.getName()); Assertions.assertEquals(otherRollbackRuleByName.toString(), String.format("RollbackRule with pattern [%s]", Exception.class.getName())); }
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Dimension... dimensions) { return defi...
@Test void testInt() { testGeneric(Flags.defineIntFlag("int-id", 2, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 3); }
public URL getInterNodeListener( final Function<URL, Integer> portResolver ) { return getInterNodeListener(portResolver, LOGGER); }
@Test public void shouldThrowIfExplicitInterNodeListenerHasIpv4WildcardAddress() { // Given: final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder() .putAll(MIN_VALID_CONFIGS) .put(ADVERTISED_LISTENER_CONFIG, "https://0.0.0.0:12589") .build() ); ...
@Override protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception { try { if (object instanceof XMLEvent) { final XMLEvent event = (XMLEvent) object; if (event.isStartDocument() || event.isEndDocument()) { r...
@Test public void testMergeStreamClose() throws Exception { List<Object> list = Lists.newArrayList(); streamCloseXmlEventList.forEach(xmlEvent -> { try { xmlMerger.decode(new ChannelHandlerContextAdapter(), xmlEvent, list); } catch (Exception e) { ...
public static byte[] serialize(final Object body) throws IOException { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream); try { outputStream.writeObject(body); ...
@Test public void testSerialisationOfSerializableObject() throws Exception { Object in = new Obj("id", "name"); byte[] expected = PulsarMessageUtils.serialize(in); assertNotNull(expected); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { try { context.proceed(); } catch (EofException e) { LOGGER.debug("Client disconnected while processing and sending response", e); exceptionCounter.i...
@SuppressWarnings("NullAway") @Test void shouldSwallowEofException() throws IOException { MetricRegistry metricRegistry = new MetricRegistry(); EofExceptionWriterInterceptor interceptor = new EofExceptionWriterInterceptor(metricRegistry); WriterInterceptorContext context = mock(WriterInt...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { final IRODSFileSystemAO fs = session.getClient(); final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(file.getAbsolute()); if(!f.exists...
@Test(expected = NotfoundException.class) public void testFindNotFound() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().ge...
@Override public WebSocketExtensionData newRequestData() { HashMap<String, String> parameters = new HashMap<String, String>(4); if (requestedServerNoContext) { parameters.put(SERVER_NO_CONTEXT, null); } if (allowClientNoContext) { parameters.put(CLIENT_NO_CONT...
@Test public void testNormalData() { PerMessageDeflateClientExtensionHandshaker handshaker = new PerMessageDeflateClientExtensionHandshaker(); WebSocketExtensionData data = handshaker.newRequestData(); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name()); assertE...
@Nullable @Override public ResultSubpartition.BufferAndBacklog getNextBuffer() throws IOException { synchronized (lock) { cacheBuffer(); if (cachedBuffers.isEmpty()) { return null; } ResultSubpartition.BufferAndBacklog buffer = cachedBuffe...
@Test void testGetNextBuffer() throws IOException { assertThat(view.peekNextBufferSubpartitionId()).isEqualTo(-1); assertThat(view.getNextBuffer()).isNull(); view0.notifyDataAvailable(); assertThat(view.peekNextBufferSubpartitionId()).isZero(); ResultSubpartition.BufferAndBac...
public void handle(ServletResponse response, Exception ex) throws IOException { if (ex instanceof InterceptException) { if (response instanceof org.eclipse.jetty.server.Response) { String errorData = ObjectMapperFactory .getMapper().writer().writeValueAsString...
@Test @SneakyThrows public void testHandle() { String restriction = "Reach the max tenants [5] restriction"; String internal = "internal exception"; String illegal = "illegal argument exception "; ExceptionHandler handler = new ExceptionHandler(); HttpServletResponse resp...
public double logp(int[] o, int[] s) { if (o.length != s.length) { throw new IllegalArgumentException("The observation sequence and state sequence are not the same length."); } int n = s.length; double p = MathEx.log(pi[s[0]]) + MathEx.log(b.get(s[0], o[0])); for (in...
@Test public void testLogp() { System.out.println("logp"); HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b)); int[] o = {0, 0, 1, 1, 0, 1, 1, 0}; double expResult = -5.609373; double result = hmm.logp(o); assertEquals(expResult, result, 1E-6); }
@VisibleForTesting public int getSignalToContainerFailedRetrieved() { return numSignalToContainerFailedRetrieved.value(); }
@Test public void testSignalToContainerFailed() { long totalBadBefore = metrics.getSignalToContainerFailedRetrieved(); badSubCluster.getSignalContainer(); Assert.assertEquals(totalBadBefore + 1, metrics.getSignalToContainerFailedRetrieved()); }
@Override public SparkPipelineResult run(Pipeline pipeline) { boolean isStreaming = options.isStreaming() || options.as(TestSparkPipelineOptions.class).isForceStreaming(); // Default to using the primitive versions of Read.Bounded and Read.Unbounded. // TODO(https://github.com/apache/beam/issues/...
@Test public void debugBatchPipeline() { PipelineOptions options = contextRule.configure(PipelineOptionsFactory.create()); options.setRunner(SparkRunnerDebugger.class); Pipeline pipeline = Pipeline.create(options); PCollection<String> lines = pipeline.apply(Create.of(Collections.<String>empty...
@Override protected DatanodeDescriptor chooseDataNode(final String scope, final Collection<Node> excludedNode, StorageType type) { // only the code that uses DFSNetworkTopology should trigger this code path. Preconditions.checkArgument(clusterMap instanceof DFSNetworkTopology); DFSNetworkTopology df...
@Test public void testChooseDataNode() { Collection<Node> allNodes = new ArrayList<>(dataNodes.length); Collections.addAll(allNodes, dataNodes); if (placementPolicy instanceof AvailableSpaceBlockPlacementPolicy) { // exclude all datanodes when chooseDataNode, no NPE should be thrown ((Availabl...
@Override public long contains(Collection<T> objects) { return get(containsAsync(objects)); }
@Test public void testNotInitializedOnContains() { Assertions.assertThrows(RedisException.class, () -> { RBloomFilter<String> filter = redisson.getBloomFilter("filter"); filter.contains("32"); }); }
@Override public void execute(String mapName, Predicate predicate, Collection<Integer> partitions, Result result) { RetryableHazelcastException storedException = null; for (Integer partitionId : partitions) { try { partitionScanRunner.run(mapName, predicate, partitionId, ...
@Test public void execute_success() { PartitionScanRunner runner = mock(PartitionScanRunner.class); CallerRunsPartitionScanExecutor executor = new CallerRunsPartitionScanExecutor(runner); Predicate<Object, Object> predicate = Predicates.equal("attribute", 1); QueryResult queryResult ...
public static Autoscaling empty() { return empty(""); }
@Test public void autoscaling_with_unspecified_resources_use_defaults_exclusive() { var min = new ClusterResources( 2, 1, NodeResources.unspecified()); var max = new ClusterResources( 6, 1, NodeResources.unspecified()); var fixture = DynamicProvisioningTester.fixture() ...
public Schema find(String name, String namespace) { Schema.Type type = PRIMITIVES.get(name); if (type != null) { return Schema.create(type); } String fullName = fullName(name, namespace); Schema schema = getNamedSchema(fullName); if (schema == null) { schema = getNamedSchema(name); ...
@Test public void primitivesAreNotCached() { EnumSet<Schema.Type> primitives = EnumSet.complementOf(EnumSet.of(Schema.Type.RECORD, Schema.Type.ENUM, Schema.Type.FIXED, Schema.Type.UNION, Schema.Type.ARRAY, Schema.Type.MAP)); ParseContext context = new ParseContext(); for (Schema.Type type : primi...
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i...
@Test public void testRemoveDupesDupeIsNotFirstNoRecycle() throws Exception { ArrayList<CharSequence> list = new ArrayList<>( Arrays.<CharSequence>asList("typed", "something", "duped", "duped", "something")); Assert.assertEquals(0, mStringPool.size()); IMEUtil.removeDupes(list, mStri...
@Override public String getScheme() { return uri.getScheme(); }
@Test public void testGetScheme() throws Exception { Configuration config = new Configuration(); try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) { fs.initialize(new URI("s3a://test-bucket/table"), config); assertEquals(fs.getScheme(), "s3a"); } ...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testSeekBeforeException() { buildFetcher(OffsetResetStrategy.NONE, new ByteArrayDeserializer(), new ByteArrayDeserializer(), 2, IsolationLevel.READ_UNCOMMITTED); assignFromUser(mkSet(tp0)); subscriptions.seek(tp0, 1); assertEquals(1, sendFetches());...
@Override protected void runOneIteration() { monitor.debug(() -> "JobMetadata.isInitialized(): " + JobMetadata.isInitialized()); if (JobMetadata.isInitialized()) { if (stopwatch.elapsed(TimeUnit.SECONDS) > credsTimeoutSeconds) { UUID jobId = JobMetadata.getJobId(); markJobTimedOut(jobId)...
@Test public void pollingLifeCycle() throws Exception { when(asymmetricKeyGenerator.generate()).thenReturn(TEST_KEY_PAIR); // Initial state assertThat(JobMetadata.isInitialized()).isFalse(); // Run once with no data in the database jobPollingService.runOneIteration(); assertThat(JobMetadata....
public int allocate(final String label) { return allocate(label, DEFAULT_TYPE_ID); }
@Test void shouldMapAllocatedCounters() { manager.allocate("def"); final int id = manager.allocate("abc"); final ReadablePosition reader = new UnsafeBufferPosition(valuesBuffer, id); final Position writer = new UnsafeBufferPosition(valuesBuffer, id); final long expectedV...
@Override public String getFirstNodeValue(String value) { long hash = super.hash(value); System.out.println("value=" + value + " hash = " + hash); return sortArrayMap.firstNodeValue(hash); }
@Test public void getFirstNodeValue() { AbstractConsistentHash map = new SortArrayMapConsistentHash() ; List<String> strings = new ArrayList<String>(); for (int i = 0; i < 10; i++) { strings.add("127.0.0." + i) ; } String process = map.process(strings,"zhangsan")...
public void convertQueueHierarchy(FSQueue queue) { List<FSQueue> children = queue.getChildQueues(); final String queueName = queue.getName(); emitChildQueues(queueName, children); emitMaxAMShare(queueName, queue); emitMaxParallelApps(queueName, queue); emitMaxAllocations(queueName, queue); ...
@Test public void testQueueMaxChildCapacityNotSupported() { converter = builder.build(); expectedException.expect(UnsupportedPropertyException.class); expectedException.expectMessage("test"); Mockito.doThrow(new UnsupportedPropertyException("test")) .when(ruleHandler).handleMaxChildCapacity(); ...
@Override public List<TableIdentifier> listTables(Namespace namespace) { if (!namespaceExists(namespace)) { throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace); } return fetch( row -> JdbcUtil.stringToTableIdentifier( row.getString(JdbcU...
@Test public void testListTables() { TableIdentifier tbl1 = TableIdentifier.of("db", "tbl1"); TableIdentifier tbl2 = TableIdentifier.of("db", "tbl2"); TableIdentifier tbl3 = TableIdentifier.of("db", "tbl2", "subtbl2"); TableIdentifier tbl4 = TableIdentifier.of("db", "ns1", "tbl3"); TableIdentifier...
public static String humanReadableBytes(Locale locale, long bytes) { int unit = 1024; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = String.valueOf("KMGTPE".charAt(exp - 1)); return String.format(loc...
@Test public void testHumanReadableBytesNullLocale() { assertEquals("1.3 KB", StringHelper.humanReadableBytes(null, 1280)); }
public static void updateKeyForBlobStore(Map<String, Object> conf, BlobStore blobStore, CuratorFramework zkClient, String key, NimbusInfo nimbusDetails) { try { // Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForB...
@Test public void testUpdateKeyForBlobStore_noMatch() { zkClientBuilder.withExists(BLOBSTORE_KEY, true); zkClientBuilder.withGetChildren(BLOBSTORE_KEY, "localhost:1111-1"); when(nimbusDetails.getHost()).thenReturn("no match"); BlobStoreUtils.updateKeyForBlobStore(conf, blobStore, zkC...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemCounter that = (ItemCounter) o; if (!map.equals(that.map)) { return false; } ...
@Test public void testEquals_returnsTrueOnSameInstance() { assertTrue(counter.equals(counter)); }
@Deprecated public static RowMutationInformation of(MutationType mutationType, long sequenceNumber) { checkArgument(sequenceNumber >= 0, "sequenceNumber must be non-negative"); return new AutoValue_RowMutationInformation( mutationType, null, Long.toHexString(sequenceNumber)); }
@Test public void givenTooManySegments_throws() { IllegalArgumentException error = assertThrows( IllegalArgumentException.class, () -> RowMutationInformation.of(RowMutationInformation.MutationType.UPSERT, "0/0/0/0/0")); assertEquals( "changeSequenceNumbe...
@VisibleForTesting static void configureSslEngineFactory( final KsqlConfig config, final SslEngineFactory sslFactory ) { sslFactory .configure(config.valuesWithPrefixOverride(KsqlConfig.KSQL_SCHEMA_REGISTRY_PREFIX)); }
@Test public void shouldPickUpPrefixedSslConfig() { // Given: final KsqlConfig config = config( "ksql.schema.registry." + SslConfigs.SSL_PROTOCOL_CONFIG, "SSLv3" ); final Map<String, Object> expectedConfigs = defaultConfigs(); expectedConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, "SSLv3"); ...
@Override public RetrievableStateHandle<T> addAndLock(String pathInZooKeeper, T state) throws PossibleInconsistentStateException, Exception { checkNotNull(pathInZooKeeper, "Path in ZooKeeper"); checkNotNull(state, "State"); final String path = normalizePath(pathInZooKeeper); ...
@Test void testFailingAddWithPossiblyInconsistentState() { final TestingLongStateHandleHelper stateHandleProvider = new TestingLongStateHandleHelper(); CuratorFramework client = spy(getZooKeeperClient()); when(client.inTransaction()).thenThrow(new RuntimeException("Expected test Exception."...
@Override public List<SnowflakeIdentifier> listSchemas(SnowflakeIdentifier scope) { StringBuilder baseQuery = new StringBuilder("SHOW SCHEMAS"); String[] queryParams = null; switch (scope.type()) { case ROOT: // account-level listing baseQuery.append(" IN ACCOUNT"); break; ...
@SuppressWarnings("unchecked") @Test public void testListSchemasInAccount() throws SQLException { when(mockResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false); when(mockResultSet.getString("database_name")) .thenReturn("DB_1") .thenReturn("DB_1") .t...
public Optional<User> login(String nameOrEmail, String password) { if (nameOrEmail == null || password == null) { return Optional.empty(); } User user = userDAO.findByName(nameOrEmail); if (user == null) { user = userDAO.findByEmail(nameOrEmail); } if (user != null && !user.isDisabled()) { boolean...
@Test void apiLoginShouldPerformPostLoginActivitiesIfUserFoundFromApikeyLookupNotDisabled() { Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser); userService.login("apikey"); Mockito.verify(postLoginActivities).executeFor(normalUser); }
static String abbreviate(String cmd, int len) { if (cmd.length() > len && len >= 5) { int firstHalf = (len - 3) / 2; int rem = len - firstHalf - 3; return cmd.substring(0, firstHalf) + "..." + cmd.substring(cmd.length() - rem); } else { return cmd; } }
@Test public void testCommandAbbreviation() { assertEquals("a...f", ShellCommandFencer.abbreviate("abcdef", 5)); assertEquals("abcdef", ShellCommandFencer.abbreviate("abcdef", 6)); assertEquals("abcdef", ShellCommandFencer.abbreviate("abcdef", 7)); assertEquals("a...g", ShellCommandFencer.abbreviate(...