focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ...
@Test public void testHistoryServerNotConfigured() throws Exception { //RM doesn't have app report and job History Server is not configured ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate( null, getRMDelegate()); JobStatus jobStatus = clientServiceDelegate.getJobStatus(oldJo...
@ScalarOperator(SUBTRACT) @SqlType(StandardTypes.BIGINT) public static long subtract(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right) { try { return Math.subtractExact(left, right); } catch (ArithmeticException e) { throw ne...
@Test public void testSubtract() { assertFunction("100000000037 - 37", BIGINT, 100000000037L - 37L); assertFunction("37 - 100000000017", BIGINT, 37 - 100000000017L); assertFunction("100000000017 - 37", BIGINT, 100000000017L - 37L); assertFunction("100000000017 - 100000000017", BI...
public Connection connection(Connection connection) { // It is common to implement both interfaces if (connection instanceof XAConnection) { return xaConnection((XAConnection) connection); } return TracingConnection.create(connection, this); }
@Test void connection_wrapsInput() { assertThat(jmsTracing.connection(mock(Connection.class))) .isInstanceOf(TracingConnection.class); }
public static Checksum crc32() { return Crc32.INSTANCE; }
@Test void crc32() { assertSame(Crc32.INSTANCE, Checksums.crc32()); }
public ApplicationBuilder appendParameters(Map<String, String> appendParameters) { this.parameters = appendParameters(parameters, appendParameters); return getThis(); }
@Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); ApplicationBuilder builder = new ApplicationBuilder(); builder.appendParameters(source); Map<String, String> parameters = builde...
@Override public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids)) .orElse(returnNonManagedForAll(groupUuids)); }
@Test public void getGroupUuidToManaged_ifMoreThanOneDelegatesActivated_throws() { Set<ManagedInstanceService> managedInstanceServices = Set.of(new AlwaysManagedInstanceService(), new AlwaysManagedInstanceService()); DelegatingManagedServices delegatingManagedServices = new DelegatingManagedServices(managedIn...
@SuppressWarnings("deprecation") public static void setClasspath(Map<String, String> environment, Configuration conf) throws IOException { boolean userClassesTakesPrecedence = conf.getBoolean(MRJobConfig.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, false); String classpathEnvVar = conf.getBoolean(M...
@Test @Timeout(120000) public void testSetClasspath() throws IOException { Configuration conf = new Configuration(); conf.setBoolean(MRConfig.MAPREDUCE_APP_SUBMISSION_CROSS_PLATFORM, true); Job job = Job.getInstance(conf); Map<String, String> environment = new HashMap<String, String>(); MRApps.s...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { String trackTypeTag = readerWay.getTag("tracktype"); TrackType trackType = TrackType.find(trackTypeTag); if (trackType != MISSING) trackTypeEnc.setEnum(false...
@Test public void testNoNPE() { ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags); assertEquals(TrackType.MISSING, ttEnc.getEnum(false, edgeId, edge...
@GET @Produces(MediaType.APPLICATION_JSON) @Path("{networkId}/hosts") public Response getVirtualHosts(@PathParam("networkId") long networkId) { NetworkId nid = NetworkId.networkId(networkId); Set<VirtualHost> vhosts = vnetService.getVirtualHosts(nid); return ok(encodeArray(VirtualHos...
@Test public void testGetVirtualHostsEmptyArray() { NetworkId networkId = networkId4; expect(mockVnetService.getVirtualHosts(networkId)).andReturn(ImmutableSet.of()).anyTimes(); replay(mockVnetService); WebTarget wt = target(); String location = "vnets/" + networkId.toString...
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComStmtSendLongDataPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_STMT_SEND_LONG_DATA, payload, connectionSession), instanceOf(MySQLComStmtSendLongDataPacket.class)); }
@VisibleForTesting public Optional<ProcessContinuation> run( PartitionMetadata partition, ChildPartitionsRecord record, RestrictionTracker<TimestampRange, Timestamp> tracker, ManualWatermarkEstimator<Instant> watermarkEstimator) { final String token = partition.getPartitionToken(); L...
@Test public void testRestrictionNotClaimed() { final String partitionToken = "partitionToken"; final Timestamp startTimestamp = Timestamp.ofTimeMicroseconds(10L); final PartitionMetadata partition = mock(PartitionMetadata.class); final ChildPartitionsRecord record = new ChildPartitionsRecord(...
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldThrowXsdValidationException_WhenNoRepository() { assertThatThrownBy(() -> xmlLoader.loadConfigHolder(configWithConfigRepos( """ <config-repos> <config-repo pluginId="myplugin"> </config-repo > ...
Map<Class, Object> getSerializers() { return serializers; }
@Test public void testLoad_withParametrizedConstructorAndCompatibilitySwitchOn() { String propName = "hazelcast.compat.serializers.use.default.constructor.only"; String origProperty = System.getProperty(propName); try { System.setProperty(propName, "true"); Serializer...
protected final void ensureCapacity(final int index, final int length) { if (index < 0 || length < 0) { throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length); } final long resultingPosition = index + (long)length; if (resulti...
@Test void ensureCapacityThrowsIndexOutOfBoundsExceptionIfLengthIsNegative() { final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(1); final IndexOutOfBoundsException exception = assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(8, -100)); ...
public void pickSuggestionManually(int index, CharSequence suggestion) { pickSuggestionManually(index, suggestion, mAutoSpace); }
@Test public void testNextWordHappyPath() { mAnySoftKeyboardUnderTest.simulateTextTyping("hello face hello face hello face hello face "); mAnySoftKeyboardUnderTest.simulateTextTyping("hello "); verifySuggestions(true, "face"); mAnySoftKeyboardUnderTest.pickSuggestionManually(0, "face"); TestRxSche...
public static String encode(final String input) { try { final StringBuilder b = new StringBuilder(); final StringTokenizer t = new StringTokenizer(input, "/"); if(!t.hasMoreTokens()) { return input; } if(StringUtils.startsWith(input, St...
@Test public void testEncodeRelativeUri() { assertEquals("a/p", URIEncoder.encode("a/p")); assertEquals("a/p/", URIEncoder.encode("a/p/")); }
public MllpConfiguration getConfiguration() { return configuration; }
@Test public void testCreateEndpointWithDefaultConfigurations() { MllpEndpoint mllpEndpoint = new MllpEndpoint("mllp://dummy", new MllpComponent(), new MllpConfiguration()); assertEquals(5, mllpEndpoint.getConfiguration().getMaxConcurrentConsumers()); }
@Override public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException { try { for(Path file : files) { if(containerService.isContainer(file)) { session.getClient(...
@Test(expected = InteroperabilityException.class) public void testInvalidateContainer() throws Exception { final SwiftDistributionPurgeFeature feature = new SwiftDistributionPurgeFeature(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory))...
void addGetModelForKieBaseMethod(StringBuilder sb) { sb.append( " public java.util.List<Model> getModelsForKieBase(String kieBaseName) {\n"); if (!modelMethod.getKieBaseNames().isEmpty()) { sb.append( " switch (kieBaseName) {\n"); for (String kBase : mod...
@Test public void addGetModelForKieBaseMethodEmptyModelsByKBaseTest() { KieBaseModel kieBaseModel = getKieBaseModel("ModelTest"); Map<String, KieBaseModel> kBaseModels = new HashMap<>(); kBaseModels.put("default-kie", kieBaseModel); ModelSourceClass modelSourceClass = new ModelSource...
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if (!BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly req...
@Test void invokeParamYearMonthDayInvalidDate() { FunctionTestUtil.assertResultError(dateFunction.invoke(2017, 6, 59), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(2017, 59, 12), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFu...
public static <T> Iterator<T> prepend(T prepend, @Nonnull Iterator<? extends T> iterator) { checkNotNull(iterator, "iterator cannot be null."); return new PrependIterator<>(prepend, iterator); }
@Test public void prependNullIterator() { assertThatThrownBy(() -> IterableUtil.prepend(null, null)) .isInstanceOf(NullPointerException.class) .hasMessage("iterator cannot be null."); }
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException { final String httpSessionId = authenticationRequest.getRequest().getSession().getId(); if (authenticationRequest.getFederationName() !...
@Test public void forceLoginWhenMinimumAuthenticationLevelIsSubstantieelTest() throws SamlSessionException, SharedServiceClientException { FederationSession federationSession = new FederationSession(600); federationSession.setAuthLevel(25); authenticationRequest.setMinimumRequestedAuthLevel(...
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious) { if (!type.isOrderable()) { throw new IllegalStateException("Type is not orderable: " + type); } requireNonNull(value, "value is null"); if (type.equals(BIGINT) || type instance...
@Test public void testNextValueForTinyInt() { long minValue = Byte.MIN_VALUE; long maxValue = Byte.MAX_VALUE; assertThat(getAdjacentValue(TINYINT, minValue, false)) .isEqualTo(Optional.of(minValue + 1)); assertThat(getAdjacentValue(TINYINT, minValue + 1, false)) ...
protected String getHttpURL(Exchange exchange, Endpoint endpoint) { Object url = exchange.getIn().getHeader(Exchange.HTTP_URL); if (url instanceof String) { return (String) url; } else { Object uri = exchange.getIn().getHeader(Exchange.HTTP_URI); if (uri insta...
@Test public void testGetHttpURLFromEndpointUri() { Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI); Mockito.when(e...
public void deleteBoardById(final Long boardId, final Long memberId) { Board board = findBoard(boardId); board.validateWriter(memberId); boardRepository.deleteByBoardId(boardId); imageUploader.delete(board.getImages()); Events.raise(new BoardDeletedEvent(boardId)); }
@Test void 게시글_주인이_다르다면_삭제하지_못한다() { // given Board savedBoard = boardRepository.save(게시글_생성_사진없음()); // when & then assertThatThrownBy(() -> boardService.deleteBoardById(savedBoard.getId(), savedBoard.getWriterId() + 1)) .isInstanceOf(WriterNotEqualsException.class)...
@Override public String toString() { return "Counter{value=" + value + '}'; }
@Test public void test_toString() { String s = counter.toString(); assertEquals("Counter{value=0}", s); }
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, MusicContainerResource data) throws Exception { if (data == null) { // Nothing to do re...
@Test public void importTwoPlaylistItemsInDifferentPlaylists() throws Exception { MusicPlaylistItem item1 = createTestPlaylistItem(randomString(), 1); MusicPlaylistItem item2 = createTestPlaylistItem(randomString(), 1); List<MusicPlaylistItem> musicPlaylistItems = List.of(item1, item2); ...
public Map<String, Parameter> getAllParams( Step stepDefinition, WorkflowSummary workflowSummary, StepRuntimeSummary runtimeSummary) { return paramsManager.generateMergedStepParams( workflowSummary, stepDefinition, getStepRuntime(stepDefinition.getType()), runtimeSummary); }
@Test public void testMergeNestedStringMap() { when(this.defaultParamManager.getDefaultStepParams()) .thenReturn( ImmutableMap.of( "nested-default-new", StringMapParamDefinition.builder() .name("nested-default-new") .value...
@Override public YamlProcess swapToYamlConfiguration(final Process data) { YamlProcess result = new YamlProcess(); result.setId(data.getId()); result.setStartMillis(data.getStartMillis()); result.setSql(data.getSql()); result.setDatabaseName(data.getDatabaseName()); r...
@Test void assertSwapToYamlConfiguration() { String processId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString().replace("-", ""); ExecutionGroupReportContext reportContext = new ExecutionGroupReportContext(processId, "foo_db", new Grantee("root", "...
public static boolean isStorage(ServiceCluster cluster) { return ServiceType.STORAGE.equals(cluster.serviceType()); }
@Test public void verifyNonStorageClusterIsNotRecognized() { ServiceCluster cluster = createServiceCluster(new ServiceType("foo")); assertFalse(VespaModelUtil.isStorage(cluster)); }
public DateTimeStamp add(double offsetInDecimalSeconds) { if (Double.isNaN(offsetInDecimalSeconds)) throw new IllegalArgumentException("Cannot add " + Double.NaN); double adjustedTimeStamp = Double.NaN; ZonedDateTime adjustedDateStamp = null; if ( hasTimeStamp()) { ...
@Test void add() { DateTimeStamp a = new DateTimeStamp(.586); double a_ts = a.getTimeStamp(); ZonedDateTime a_dt = a.getDateTime(); DateTimeStamp b = new DateTimeStamp(.586 + .587); assertEquals(b.getTimeStamp(), a.add(.587).getTimeStamp(), .001); assertEquals(a_ts, a...
@Override public Object evaluateLiteralExpression(String rawExpression, String className, List<String> genericClasses) { Object expressionResult = compileAndExecute(rawExpression, new HashMap<>()); Class<Object> requiredClass = loadClass(className, classLoader); if (expressionResult != null ...
@Test public void evaluateLiteralExpression_many() { assertThat(evaluateLiteralExpression("1", Integer.class)).isEqualTo(1); assertThat(evaluateLiteralExpression("\"Value\"", String.class)).isEqualTo("Value"); assertThat(evaluateLiteralExpression("2 * 3", Integer.class)).isEqualTo(6); ...
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, ...
@Test public void testConsumerHeartbeatRequestValidation() { MockPartitionAssignor assignor = new MockPartitionAssignor("range"); GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroupAssignors(Collections.singletonList(assignor)) ...
@Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (tokenQueue.isNextTokenValue(tokenToMatch)) { matchedTokenList.add(tokenQueue.poll()); return true; } return false; }
@Test public void shouldMatch() { Token t1 = new Token("a", 1, 1); Token t2 = new Token("b", 2, 1); TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2))); List<Token> output = mock(List.class); ExactTokenMatcher matcher = new ExactTokenMatcher("a"); assertThat(matcher.matchToken(...
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@SuppressWarnings({"unchecked"}) @Test public void buildsForkedPipeline() throws Exception { final ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider()); final PipelineIR pipelineIR = ConfigCompiler.configToPipelineIR(IRHelpers.toSourceW...
public void init(ScannerReportWriter writer) { File analysisLog = writer.getFileStructure().analysisLog(); try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) { writePlugins(fileWriter); writeBundledAnalyzers(fileWriter); writeGlobalSettings(...
@Test public void shouldOnlyDumpPluginsByDefault() throws Exception { when(pluginRepo.getExternalPluginsInfos()).thenReturn(singletonList(new PluginInfo("xoo").setName("Xoo").setVersion(Version.create("1.0")))); DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create() .setBaseD...
@Override public List<ProductSpuDO> getSpuList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } return productSpuMapper.selectBatchIds(ids); }
@Test void getSpuList() { // 准备参数 ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(RandomUtil.random...
@Override public AuthorityRuleConfiguration swapToObject(final YamlAuthorityRuleConfiguration yamlConfig) { Collection<ShardingSphereUser> users = yamlConfig.getUsers().stream().map(userSwapper::swapToObject).collect(Collectors.toList()); AlgorithmConfiguration provider = algorithmSwapper.swapToObje...
@Test void assertSwapToObjectWithDefaultProvider() { YamlAuthorityRuleConfiguration authorityRuleConfig = new YamlAuthorityRuleConfiguration(); authorityRuleConfig.setUsers(Collections.singletonList(getYamlUser())); AuthorityRuleConfiguration actual = swapper.swapToObject(authorityRuleConfig...
@Override public ExecuteContext after(ExecuteContext context) { RocketMqPullConsumerController.removePullConsumer((DefaultLitePullConsumer) context.getObject()); if (handler != null) { handler.doAfter(context); } return context; }
@Test public void testAfter() { interceptor.after(context); Assert.assertEquals(RocketMqPullConsumerController.getPullConsumerCache().size(), 0); }
@Override public NullsOrderType getDefaultNullsOrderType() { return NullsOrderType.FIRST; }
@Test void assertGetDefaultNullsOrderType() { assertThat(dialectDatabaseMetaData.getDefaultNullsOrderType(), is(NullsOrderType.FIRST)); }
public static String getBaseName(String versionName) throws IOException { Objects.requireNonNull(versionName, "VersionName cannot be null"); int div = versionName.lastIndexOf('@'); if (div == -1) { throw new IOException("No version in key path " + versionName); } return versionName.substring(0...
@Test public void testParseVersionName() throws Exception { assertEquals("/a/b", KeyProvider.getBaseName("/a/b@3")); assertEquals("/aaa", KeyProvider.getBaseName("/aaa@112")); try { KeyProvider.getBaseName("no-slashes"); assertTrue("should have thrown", false); } catch (IOException e) { ...
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBeOfTypeSchemaKStreamWhenDataSourceIsKsqlStream() { // When: realStream = buildStream(node); // Then: assertThat(realStream.getClass(), equalTo(SchemaKStream.class)); }
public static boolean isCompositeURI(URI uri) { String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); if (ssp.indexOf('(') == 0 && checkParenthesis(ssp)) { return true; } return false; }
@Test public void testIsCompositeURINoQueryNoSlashes() throws URISyntaxException { URI[] compositeURIs = new URI[] { new URI("test:(part1://host,part2://(sub1://part,sube2:part))"), new URI("test:(path)/path") }; for (URI uri : compositeURIs) { assertTrue(uri + " must be detected as comp...
@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 shouldThrowIfStoreFetchFails() { // Given: when(cacheBypassFetcher.fetch(any(), any(), any(), any())) .thenThrow(new MaterializationTimeOutException("Boom")); // When: final Exception e = assertThrows( MaterializationException.class, () -> table.get(A_KEY, PA...
public static ExecutionEnvironment createBatchExecutionEnvironment(FlinkPipelineOptions options) { return createBatchExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldDetectMalformedPortBatch() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setRunner(FlinkRunner.class); options.setFlinkMaster("host:p0rt"); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Unparseable port n...
@Override public void write(DataOutput out) throws IOException { String json = GsonUtils.GSON.toJson(this, OptimizeJobV2.class); Text.writeString(out, json); }
@Test public void testSerializeOfOptimizeJob() throws IOException { // prepare file File file = new File(TEST_FILE_NAME); file.createNewFile(); file.deleteOnExit(); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); OptimizeJobV2 optimizeJobV2 =...
@Nullable public PasswordAlgorithm forPassword(String hashedPassword) { for (PasswordAlgorithm passwordAlgorithm : passwordAlgorithms.values()) { if (passwordAlgorithm.supports(hashedPassword)) return passwordAlgorithm; } return null; }
@Test public void testForPasswordShouldReturnNull() throws Exception { when(passwordAlgorithm1.supports(anyString())).thenReturn(false); when(passwordAlgorithm2.supports(anyString())).thenReturn(false); final PasswordAlgorithmFactory passwordAlgorithmFactory = new PasswordAlgorithmFactory(p...
public Uuid directory(int replica) { for (int i = 0; i < replicas.length; i++) { if (replicas[i] == replica) { return directories[i]; } } throw new IllegalArgumentException("Replica " + replica + " is not assigned to this partition."); }
@Test public void testDirectories() { PartitionRegistration partitionRegistration = new PartitionRegistration.Builder(). setReplicas(new int[] {3, 2, 1}). setDirectories(new Uuid[]{ Uuid.fromString("FbRuu7CeQtq5YFreEzg16g"), Uui...
public static <T> RestResponse<T> toRestResponse( final ResponseWithBody resp, final String path, final Function<ResponseWithBody, T> mapper ) { final int statusCode = resp.getResponse().statusCode(); return statusCode == OK.code() ? RestResponse.successful(statusCode, mapper.apply(r...
@Test public void shouldCreateRestResponseFromUnknownResponse() { // Given: when(httpClientResponse.statusCode()).thenReturn(INTERNAL_SERVER_ERROR.code()); when(httpClientResponse.statusMessage()).thenReturn(ERROR_REASON); // When: final RestResponse<KsqlEntityList> restResponse = KsqlCli...
static void setTableInputInformation( TableInput.Builder tableInputBuilder, TableMetadata metadata) { setTableInputInformation(tableInputBuilder, metadata, null); }
@Test public void testSetTableDescription() { String tableDescription = "hello world!"; Map<String, String> tableProperties = ImmutableMap.<String, String>builder() .putAll((tableLocationProperties)) .put(IcebergToGlueConverter.GLUE_DESCRIPTION_KEY, tableDescription) ...
public XAConnectionFactory xaConnectionFactory(XAConnectionFactory xaConnectionFactory) { return TracingXAConnectionFactory.create(xaConnectionFactory, this); }
@Test void xaConnectionFactory_doesntDoubleWrap() { XAConnectionFactory wrapped = jmsTracing.xaConnectionFactory(mock(XAConnectionFactory.class)); assertThat(jmsTracing.xaConnectionFactory(wrapped)) .isSameAs(wrapped); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { try { if(log.isDebugEnabled()) { log.debug("Attempt to list available shares"); } ...
@Test public void testListAllShares() throws Exception { final Path root = Home.ROOT; final AttributedList<Path> result = session.getFeature(ListService.class)/*SMBRootListService*/.list(root, new DisabledListProgressListener()); for(Path f : result) { assertTrue(f.isVolume()); ...
@Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileHighlighting(file, context); } }
@Test public void testExecution() throws IOException { File symbol = new File(baseDir, "src/foo.xoo.highlighting"); FileUtils.write(symbol, "1:1:1:4:k\n2:7:2:10:cd\n\n#comment"); DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo") .setLanguage("xoo") .setModuleBaseDir(b...
@Override public String handlePlaceHolder() { return handlePlaceHolder(inlineExpression); }
@Test void assertHandlePlaceHolder() { String expectdString = "t_${[\"new${1+2}\"]}"; assertThat(createInlineExpressionParser("t_$->{[\"new$->{1+2}\"]}").handlePlaceHolder(), is(expectdString)); assertThat(createInlineExpressionParser("t_${[\"new$->{1+2}\"]}").handlePlaceHolder(), is(expectd...
public static void validate(BugPattern pattern) throws ValidationException { if (pattern == null) { throw new ValidationException("No @BugPattern provided"); } // name must not contain spaces if (CharMatcher.whitespace().matchesAnyOf(pattern.name())) { throw new ValidationException("Name mu...
@Test public void linkTypeCustomAndIncludesLink() throws Exception { @BugPattern( name = "LinkTypeCustomAndIncludesLink", summary = "linkType custom and includes link", explanation = "linkType custom and includes link", severity = SeverityLevel.ERROR, linkType = LinkType.CU...
public JsonElement get() { if (!stack.isEmpty()) { throw new IllegalStateException("Expected one JSON element but was " + stack); } return product; }
@Test public void testEmptyWriter() { JsonTreeWriter writer = new JsonTreeWriter(); assertThat(writer.get()).isEqualTo(JsonNull.INSTANCE); }
@Deprecated public static GeoPoint fromIntString(final String s) { final int commaPos1 = s.indexOf(','); final int commaPos2 = s.indexOf(',', commaPos1 + 1); if (commaPos2 == -1) { return new GeoPoint( Integer.parseInt(s.substring(0, commaPos1)), ...
@Test public void test_toFromString_withoutAltitude() { final GeoPoint in = new GeoPoint(52387524, 4891604); final GeoPoint out = GeoPoint.fromIntString("52387524,4891604"); assertEquals("toFromString without altitude", in, out); }
@ScalarOperator(CAST) @LiteralParameters("x") @SqlType("varchar(x)") public static Slice castToVarchar(@SqlType(StandardTypes.TINYINT) long value) { // todo optimize me return utf8Slice(String.valueOf(value)); }
@Test public void testCastToVarchar() { assertFunction("cast(TINYINT'37' as varchar)", VARCHAR, "37"); assertFunction("cast(TINYINT'17' as varchar)", VARCHAR, "17"); }
@Override public WebSocketExtensionData newRequestData() { return new WebSocketExtensionData( useWebkitExtensionName ? X_WEBKIT_DEFLATE_FRAME_EXTENSION : DEFLATE_FRAME_EXTENSION, Collections.<String, String>emptyMap()); }
@Test public void testDeflateFrameData() { DeflateFrameClientExtensionHandshaker handshaker = new DeflateFrameClientExtensionHandshaker(false); WebSocketExtensionData data = handshaker.newRequestData(); assertEquals(DEFLATE_FRAME_EXTENSION, data.name()); assertTrue(...
public static Double getDouble(Object x) { if (x == null) { return null; } if (x instanceof Double) { return (Double) x; } if (x instanceof String) { String s = x.toString(); if (s == null || s.isEmpty()) { return ...
@Test public void testGetDouble() throws Exception { assertEquals(null, Tools.getDouble(null)); assertEquals(null, Tools.getDouble("")); assertEquals(0.0, Tools.getDouble(0), 0); assertEquals(1.0, Tools.getDouble(1), 0); assertEquals(1.42, Tools.getDouble(1.42), 0); ...
public static String evaluate(final co.elastic.logstash.api.Event event, final String template) throws JsonProcessingException { if (event instanceof Event) { return evaluate((Event) event, template); } else { throw new IllegalStateException("Unknown event concrete class:...
@Test public void TestEpoch() throws IOException { Event event = getTestEvent(); String path = "%{+%s}"; assertEquals("1443657600", StringInterpolation.evaluate(event, path)); }
public ConfigResponse getServerConfig(String dataId, String group, String tenant, long readTimeout, boolean notify) throws NacosException { if (StringUtils.isBlank(group)) { group = Constants.DEFAULT_GROUP; } return this.agent.queryConfig(dataId, group, tenant, readTimeou...
@Test void testGeConfigConfigConflict() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker...
public static LookupDefaultSingleValue create(String valueString, LookupDefaultValue.Type valueType) { requireNonNull(valueString, "valueString cannot be null"); requireNonNull(valueType, "valueType cannot be null"); Object value; try { switch (valueType) { c...
@Test public void createMultiObject() throws Exception { expectedException.expect(IllegalArgumentException.class); LookupDefaultSingleValue.create("{\"hello\":\"world\",\"number\":42}", LookupDefaultSingleValue.Type.OBJECT); }
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testSimpleFunctionDecode() { Function function = new Function( "test", Collections.<Type>emptyList(), Collections.singletonList(new TypeReference<Uint>() {})); assertEquals( Fun...
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if (!BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly req...
@Test void invokeParamYearMonthDayNulls() { FunctionTestUtil.assertResultError(dateFunction.invoke(null, null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(10, null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateF...
@Override public boolean open(final String url) { // Only print out URL console.printf("%n%s", url); return true; }
@Test public void open() { assertTrue(new TerminalBrowserLauncher().open("https://cyberduck.io")); }
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); MEM.putInt(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += INT_SIZE_IN_BYTES; }
@Test(expected = IllegalArgumentException.class) public void testCheckAvailable_negativePos() throws Exception { out.writeInt(-1, 1); }
public static InetAddress getLocalAddress() { return getLocalAddress(null); }
@Test public void testGetLocalAddress() { InetAddress address = NetUtils.getLocalAddress(); Assert.assertNotNull(address); Assert.assertTrue(NetUtils.isValidAddress(address)); try { if(NetUtils.isValidAddress(InetAddress.getLocalHost())){ Assert.assertEqua...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void inUnaryTestStrings() { final String inputExpression = "name in [\"A\"..\"Z...\")"; final BaseNode inNode = parse( inputExpression ); assertThat( inNode).isInstanceOf(InNode.class); assertThat( inNode.getResultType()).isEqualTo(BuiltInType.BOOLEAN); assertThat( inN...
public static SqlDecimal widen(final SqlType t0, final SqlType t1) { final SqlDecimal lDecimal = DecimalUtil.toSqlDecimal(t0); final SqlDecimal rDecimal = DecimalUtil.toSqlDecimal(t1); final int wholePrecision = Math.max( lDecimal.getPrecision() - lDecimal.getScale(), rDecimal.getPrecision(...
@Test public void shouldWidenIntAndLong() { assertThat( DecimalUtil.widen(SqlTypes.BIGINT, SqlTypes.INTEGER), is(SqlTypes.BIGINT_UPCAST_TO_DECIMAL) ); assertThat( DecimalUtil.widen(SqlTypes.INTEGER, SqlTypes.BIGINT), is(SqlTypes.BIGINT_UPCAST_TO_DECIMAL) ); }
protected static void initAndStartAppMaster(final MRAppMaster appMaster, final JobConf conf, String jobUserName) throws IOException, InterruptedException { UserGroupInformation.setConfiguration(conf); // MAPREDUCE-6565: need to set configuration for SecurityUtil. SecurityUtil.setConfiguration(co...
@Test public void testMRAppMasterForDifferentUser() throws IOException, InterruptedException { String applicationAttemptIdStr = "appattempt_1317529182569_0004_000001"; String containerIdStr = "container_1317529182569_0004_000001_1"; String userName = "TestAppMasterUser"; ApplicationAttemptId ap...
public static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition) { if (!isS3SelectPushdownEnabled(session)) { return false; } if (path == null) { return false; } // Hive tab...
@Test public void testShouldNotEnableSelectPushdownWhenInputFormatIsNotSupported() { Storage newStorage = Storage.builder() .setStorageFormat(StorageFormat.create(LazySimpleSerDe.class.getName(), "inputFormat", "outputFormat")) .setLocation("location") .bu...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final B2BucketResponse response = session.getClient().createBucket(containerService.getContainer(folder).getName(), ...
@Test public void testModificationDate() throws Exception { final Path bucket = new Path("/test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final TransferStatus status = new TransferStatus(); final long timestamp = 1509959502930L; status.setModified(timestamp); ...
public long encode(int x, int y) { int EIGHTBITMASK = 0xff; return (MortonTable256[(y >> 8) & EIGHTBITMASK] << 17 | MortonTable256[(x >> 8) & EIGHTBITMASK] << 16 | MortonTable256[y & EIGHTBITMASK] << 1 | MortonTable256[x & EIGHTBITMASK]); }
@Test public void testEncode() { SpatialKeyAlgo algo = new SpatialKeyAlgo(32, new BBox(-180, 180, -90, 90)); long val = algo.encodeLatLon(-24.235345f, 47.234234f); assertEquals("01100110101000111100000110010100", BitUtil.LITTLE.toLastBitString(val, 32)); }
@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 testExpandConnectorsStatus() { when(herder.connectors()).thenReturn(Arrays.asList(CONNECTOR2_NAME, CONNECTOR_NAME)); ConnectorStateInfo connector = mock(ConnectorStateInfo.class); ConnectorStateInfo connector2 = mock(ConnectorStateInfo.class); when(herder.connectorS...
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported())...
@SuppressWarnings("IsInstanceInteger") // test is an intentional trivially true check @Test public void isInstanceOfSuperclass() { assertThat(3).isInstanceOf(Number.class); }
@VisibleForTesting static DateRangeBucket buildDateRangeBuckets(TimeRange timeRange, long searchWithinMs, long executeEveryMs) { final ImmutableList.Builder<DateRange> ranges = ImmutableList.builder(); DateTime from = timeRange.getFrom(); DateTime to; do { // The smallest...
@Test public void testDateRangeBucketWithCatchUpSlidingWindows() { final int processingWindowSizeSec = 120; final int processingHopSizeSec = 60; final DateTime now = DateTime.now(DateTimeZone.UTC); final DateTime from = now; // We are 3 full processingWindows behind f...
@Udf public <T> String toJsonString(@UdfParameter final T input) { return toJson(input); }
@Test public void shouldSerializeDouble() { // When: final String result = udf.toJsonString(123.456d); // Then: assertEquals("123.456", result); }
@Override public int hashCode() { return Objects.hash(taskId, topicPartitions); }
@Test public void shouldBeEqualsIfOnlyDifferInEndOffsets() { final TaskMetadataImpl stillSameDifferEndOffsets = new TaskMetadataImpl( TASK_ID, TOPIC_PARTITIONS, COMMITTED_OFFSETS, mkMap(mkEntry(TP_1, 1000000L), mkEntry(TP_1, 2L)), TIME_CURRENT_IDLI...
public static <T> CompressedSource<T> from(FileBasedSource<T> sourceDelegate) { return new CompressedSource<>(sourceDelegate, CompressionMode.AUTO); }
@Test public void testEmptyGzipProgress() throws IOException { File tmpFile = tmpFolder.newFile("empty.gz"); String filename = tmpFile.toPath().toString(); writeFile(tmpFile, new byte[0], Compression.GZIP); PipelineOptions options = PipelineOptionsFactory.create(); CompressedSource<Byte> source =...
public static double div(float v1, float v2) { return div(v1, v2, DEFAULT_DIV_SCALE); }
@Test public void divBigDecimalTest() { final BigDecimal result = NumberUtil.div(BigDecimal.ZERO, BigDecimal.ONE); assertEquals(BigDecimal.ZERO, result.stripTrailingZeros()); }
@Override protected int rsv(WebSocketFrame msg) { return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame? msg.rsv() | WebSocketExtension.RSV1 : msg.rsv(); }
@Test public void testEmptyFrameCompression() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false)); TextWebSocketFrame emptyFrame = new TextWebSocketFrame(""); assertTrue(encoderChannel.writeOutbound(emptyFrame)); TextWebSocketFrame emp...
@Override public int wipeWritePermOfBroker(final String namesrvAddr, String brokerName) throws RemotingCommandException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException { return defaultMQAdminExtImpl.wipeWritePermOfBroker(name...
@Test public void testWipeWritePermOfBroker() throws InterruptedException, RemotingCommandException, RemotingSendRequestException, RemotingTimeoutException, MQClientException, RemotingConnectException { int result = defaultMQAdminExt.wipeWritePermOfBroker("127.0.0.1:9876", "default-broker"); assertT...
public Cookie decode(String header) { final int headerLen = checkNotNull(header, "header").length(); if (headerLen == 0) { return null; } CookieBuilder cookieBuilder = null; loop: for (int i = 0;;) { // Skip spaces and separators. for (;;) ...
@Test public void testDecodingLongDates() { Calendar cookieDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cookieDate.set(9999, Calendar.DECEMBER, 31, 23, 59, 59); long expectedMaxAge = (cookieDate.getTimeInMillis() - System .currentTimeMillis()) / 1000; St...
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> mapByKey(String key, List<?> list) { Map<K, V> map = new HashMap<>(); if (CollectionUtils.isEmpty(list)) { return map; } try { Class<?> clazz = list.get(0).getClass(); Field field = deepFindField(clazz, key); if (fie...
@Test(expected = BeanUtilsException.class) public void testMapByKeyNotEmptyListThrowsEx() { someAnotherList.add(new KeyClass()); assertNotNull(BeanUtils.mapByKey("wrongKey", someAnotherList)); }
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) { double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9; double toSeconds = to.getEpochSecond() + to.getNano() / 1e9; long linesWritten = 0; BufferedWriter writer = new Buffer...
@Test void logsLimitedToMaxLines() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*")); logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), 2, Optional.of("node2.com")); ass...
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertStreamMessageToAmqpMessageWithAmqpValueBody() throws Exception { ActiveMQStreamMessage outbound = createStreamMessage(); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer(); ...
public OffsetAndMetadata findNextCommitOffset(final String commitMetadata) { boolean found = false; long currOffset; long nextCommitOffset = committedOffset; for (KafkaSpoutMessageId currAckedMsg : ackedMsgs) { // complexity is that of a linear scan on a TreeMap currOffset ...
@Test public void testFindNextCommitOffsetWithMultipleOutOfOrderAcks() { emitAndAckMessage(getMessageId(initialFetchOffset + 1)); emitAndAckMessage(getMessageId(initialFetchOffset)); OffsetAndMetadata nextCommitOffset = manager.findNextCommitOffset(COMMIT_METADATA); assertThat("The n...
@Override public void cleanup() { executor.shutdown(); }
@Test public void cleanupShutsDownExecutor() { factory.cleanup(); assertThat(factory.executor.isShutdown(), is(true)); }
public String generateBadge(String label, String value, Color backgroundValueColor) { int labelWidth = computeWidth(label); int valueWidth = computeWidth(value); Map<String, String> values = ImmutableMap.<String, String>builder() .put(PARAMETER_TOTAL_WIDTH, valueOf(MARGIN * 4 + ICON_WIDTH + labelWidt...
@Test public void generate_badge() { initSvgGenerator(); String result = underTest.generateBadge("label", "10", DEFAULT); checkBadge(result, "label", "10", DEFAULT); }
@Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, MIN_PARAMETER_COUNT, MAX_PARAMETER_COUNT); values = parameters.toArray(new CompoundVariable[parameters.size()]); }
@Test public void testIsVarDefinedError() throws Exception { Assertions.assertThrows( InvalidVariableException.class, () -> isVarDefined.setParameters(params)); }
@Override public int addFirst(V... elements) { return get(addFirstAsync(elements)); }
@Test public void testAddFirstOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.addFirst(1); queue.addFirst(2); queue.addFirst(3); assertThat(queue).containsExactly(3, 2, 1); }
public static String[] parseKey(String groupKey) { StringBuilder sb = new StringBuilder(); String dataId = null; String group = null; String tenant = null; for (int i = 0; i < groupKey.length(); ++i) { char c = groupKey.charAt(i); if ('+' == c) { ...
@Test void testParseKeyForPercentIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("%%%5\u0000??????????????"); // Method is not expected to return due to exception thrown }); // Method is not exp...
public static Set<File> findJsonFiles(File rootDir, Set<File> files) { return findJsonFiles(rootDir, files, (f) -> true); }
@Test public void testFindJsonFiles() throws Exception { Path dir = ResourceUtils.getResourceAsFile("json").toPath(); List<String> jsonFiles; try (Stream<Path> stream = PackageHelper.findJsonFiles(dir)) { jsonFiles = stream .map(PackageHelper::asName) ...
@Override public File getCanonicalFile() { throw new UnsupportedOperationException("Not implemented"); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetCanonicalFile() throws IOException { fs.getFile("nonsuch.txt").getCanonicalFile(); }
@Override public void handle(ContainerLauncherEvent event) { try { eventQueue.put(event); } catch (InterruptedException e) { throw new YarnRuntimeException(e); } }
@Test(timeout = 5000) public void testMyShutdown() throws Exception { LOG.info("in test Shutdown"); AppContext mockContext = mock(AppContext.class); @SuppressWarnings("unchecked") EventHandler<Event> mockEventHandler = mock(EventHandler.class); when(mockContext.getEventHandler()).thenReturn(mockE...
@Override protected CompletableFuture<Void> respondToRequest( ChannelHandlerContext ctx, HttpRequest httpRequest, HandlerRequest<EmptyRequestBody> handlerRequest, RestfulGateway gateway) throws RestHandlerException { final ResourceID taskManagerId ...
@Test void testFileServing() throws Exception { final Time cacheEntryDuration = Time.milliseconds(1000L); final Queue<CompletableFuture<TransientBlobKey>> requestFileUploads = new ArrayDeque<>(1); requestFileUploads.add(CompletableFuture.completedFuture(transientBlobKey1)); final ...
public static List<String> parse(String unixPath) { List<String> pathComponents = new ArrayList<>(); // -1 limit for Guava Splitter behavior: https://errorprone.info/bugpattern/StringSplitter for (String component : unixPath.split("/", -1)) { if (!component.isEmpty()) { pathComponents.add(comp...
@Test public void testParse() { Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("/some/path")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some/path/")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some///path///")...
@Override public SmileResponse<T> handle(Request request, Response response) { byte[] bytes = readResponseBytes(response); String contentType = response.getHeader(CONTENT_TYPE); if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) { return new Smil...
@Test public void testNonSmileResponse() { SmileResponse<User> response = handler.handle(null, TestingResponse.mockResponse(OK, PLAIN_TEXT_UTF_8, "hello")); assertFalse(response.hasValue()); assertNull(response.getException()); assertNull(response.getSmileBytes()); asser...
public static DefaultProcessCommands main(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, true); }
@Test public void main_fails_if_processNumber_is_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES; expectProcessNumberNoValidIAE(() -> { try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { } }, processNumber); }