focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
protected static List<LastOpenedDTO> filterForExistingIdAndCapAtMaximum(final LastOpenedForUserDTO loi, final GRN grn, final long max) { return loi.items().stream().filter(i -> !i.grn().equals(grn)).limit(max - 1).toList(); }
@Test public void testCapAtMaximumMinusOneSoYouCanAddANewElement() { var list = List.of( new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "1"), DateTime.now(DateTimeZone.UTC)), new LastOpenedDTO(grnRegistry.newGRN(GRNTypes.DASHBOARD, "2"), DateTime.now(DateTimeZone.UT...
private Set<Long> getUnavailableBeIdsInGroup(SystemInfoService infoService, ColocateTableIndex colocateIndex, GroupId groupId) { Set<Long> backends = colocateIndex.getBackendsByGroup(groupId); Set<Long> unavailableBeIds = Sets.newHashSet(); for (L...
@Test public void testGetUnavailableBeIdsInGroup() { GroupId groupId = new GroupId(10000, 10001); List<Long> allBackendsInGroup = Lists.newArrayList(1L, 2L, 3L, 4L, 5L); List<List<Long>> backendsPerBucketSeq = new ArrayList<>(); backendsPerBucketSeq.add(allBackendsInGroup); C...
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testNonEmptyResponseWithVoidResponseType() throws Exception { int statusCode = Response.Status.OK.getStatusCode(); Request req = mock(Request.class); ContentResponse resp = mock(ContentResponse.class); when(resp.getContentAsString()).thenReturn(toJsonString(TEST_DTO...
@VisibleForTesting void validateParentMenu(Long parentId, Long childId) { if (parentId == null || ID_ROOT.equals(parentId)) { return; } // 不能设置自己为父菜单 if (parentId.equals(childId)) { throw exception(MENU_PARENT_ERROR); } MenuDO menu = menuMapper...
@Test public void testValidateParentMenu_parentNotExist() { // 调用,并断言异常 assertServiceException(() -> menuService.validateParentMenu(randomLongId(), null), MENU_PARENT_NOT_EXISTS); }
public static <T> Key<T> newKey(String name) { return new Key<>(name); }
@Test void newKeyFailsOnNull() { assertThrows(NullPointerException.class, () -> SessionContext.newKey(null)); }
static ParseResult parse(final int javaMajorVersion, final BufferedReader br) throws IOException { final ParseResult result = new ParseResult(); int lineNumber = 0; while (true) { final String line = br.readLine(); lineNumber++; if (line == null) { ...
@Test public void testParseOptionVersionRange() throws IOException { JvmOptionsParser.ParseResult res = JvmOptionsParser.parse(11, asReader("10-11:-XX:+UseConcMarkSweepGC")); verifyOptions("Option must be present for Java 11", "-XX:+UseConcMarkSweepGC", res); res = JvmOptionsParser.parse(14...
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamIsNull() { FunctionTestUtil.assertResultError(startsFunction.invoke((Comparable) null, new RangeImpl()), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(startsFunction.invoke("a", null), InvalidParametersEvent.class); }
public static EndpointResponse mapException(final Throwable exception) { if (exception instanceof KsqlRestException) { final KsqlRestException restException = (KsqlRestException) exception; return restException.getResponse(); } return EndpointResponse.create() .status(INTERNAL_SERVER_ERR...
@Test public void shouldReturnCorrectResponseForUnspecificException() { final EndpointResponse response = OldApiUtils .mapException(new Exception("error msg")); assertThat(response.getEntity(), instanceOf(KsqlErrorMessage.class)); final KsqlErrorMessage errorMessage = (KsqlErrorMessage) response.g...
static boolean isTableUsingInstancePoolAndReplicaGroup(@Nonnull TableConfig tableConfig) { boolean status = true; Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = tableConfig.getInstanceAssignmentConfigMap(); if (instanceAssignmentConfigMap != null) { for (InstanceAssignmentConfig i...
@Test public void testNoIACOfflineTable() { TableConfig tableConfig = new TableConfig("table", TableType.OFFLINE.name(), new SegmentsValidationAndRetentionConfig(), new TenantConfig("DefaultTenant", "DefaultTenant", null), new IndexingConfig(), new TableCustomConfig(null), null, nu...
String prependInstruction(String text, Context context) { if (prependQuery != null && !prependQuery.isEmpty() && context.getDestination().startsWith("query")) { return prependQuery + " " + text; } if (prependDocument != null && !prependDocument.isEmpty()){ return prependD...
@Test public void testPrepend() { var context = new Embedder.Context("schema.indexing"); String input = "This is a test"; var embedder = getNormalizePrefixdEmbedder(); var result = embedder.prependInstruction(input, context); assertEquals("This is a document: This is a test",...
Config targetConfig(Config sourceConfig, boolean incremental) { // If using incrementalAlterConfigs API, sync the default property with either SET or DELETE action determined by ConfigPropertyFilter::shouldReplicateSourceDefault later. // If not using incrementalAlterConfigs API, sync the default proper...
@Test @Deprecated public void testConfigPropertyFilteringWithAlterConfigs() { MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"), new DefaultReplicationPolicy(), x -> true, new DefaultConfigPropertyFilter()); List<ConfigEntry> entr...
@Override public Endpoint<Http2RemoteFlowController> remote() { return remoteEndpoint; }
@Test public void clientRemoteIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception { incrementAndGetStreamShouldRespectOverflow(client.remote(), MAX_VALUE - 1); }
@Override public ExportResult<MediaContainerResource> export(UUID jobId, AD authData, Optional<ExportInformation> exportInfo) throws Exception { ExportResult<PhotosContainerResource> per = exportPhotos(jobId, authData, exportInfo); if (per.getThrowable().isPresent()) { return new ExportResult<>(pe...
@Test public void shouldHandleOnlyPhotos() throws Exception { MediaContainerResource mcr = new MediaContainerResource(albums, photos, null); ExportResult<MediaContainerResource> exp = new ExportResult<>(ResultType.END, mcr); Optional<ExportInformation> ei = Optional.of(new ExportInformation(null, mcr)); ...
public static CreateSourceAsProperties from(final Map<String, Literal> literals) { try { return new CreateSourceAsProperties(literals, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" ); throw new ...
@Test public void shouldThrowOnInvalidTimestampFormat() { // When: final Exception e = assertThrows( KsqlException.class, () -> from( of(TIMESTAMP_FORMAT_PROPERTY, new StringLiteral("invalid"))) ); // Then: assertThat(e.getMessage(), containsString("Invalid datetime fo...
@Override public Dictionary buildDictionary(VirtualColumnContext context) { FieldSpec fieldSpec = context.getFieldSpec(); switch (fieldSpec.getDataType().getStoredType()) { case INT: return new ConstantValueIntDictionary((int) fieldSpec.getDefaultNullValue()); case LONG: return new...
@Test public void testBuildDictionary() { VirtualColumnContext virtualColumnContext = new VirtualColumnContext(SV_INT, 1); Dictionary dictionary = new DefaultNullValueVirtualColumnProvider().buildDictionary(virtualColumnContext); assertEquals(dictionary.getClass(), ConstantValueIntDictionary.class); a...
@Udf(description = "Returns the cosine of an INT value") public Double cos( @UdfParameter( value = "value", description = "The value in radians to get the cosine of." ) final Integer value ) { return cos(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNull() { assertThat(udf.cos((Integer) null), is(nullValue())); assertThat(udf.cos((Long) null), is(nullValue())); assertThat(udf.cos((Double) null), is(nullValue())); }
public static boolean isPowerOfTwo(long n) { return (n > 0) && ((n & (n - 1)) == 0); }
@Test public void isPowerOfTwoTest() { assertFalse(NumberUtil.isPowerOfTwo(-1)); assertTrue(NumberUtil.isPowerOfTwo(16)); assertTrue(NumberUtil.isPowerOfTwo(65536)); assertTrue(NumberUtil.isPowerOfTwo(1)); assertFalse(NumberUtil.isPowerOfTwo(17)); }
@Override public TsunamiConfig loadConfig() { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Map<String, Object> rawYamlData = yaml.load(configFileReader()); return TsunamiConfig.fromYamlData(rawYamlData); }
@Test public void loadConfig_whenYamlFileNotFound_usesEmptyConfig() { TsunamiConfig tsunamiConfig = new YamlConfigLoader().loadConfig(); assertThat(tsunamiConfig.getRawConfigData()).isEmpty(); }
public static Optional<Object[]> coerceParams(Class<?> currentIdxActualParameterType, Class<?> expectedParameterType, Object[] actualParams, int i) { Object actualObject = actualParams[i]; Optional<Object> coercedObject = coerceParam(currentIdxActualParameterType, expectedParameterType, ...
@Test void coerceParamsCollectionToArrayConverted() { Object item = "TESTED_OBJECT"; Object value = Collections.singleton(item); Object[] actualParams1 = {value, "NOT_DATE"}; Optional<Object[]> retrieved = CoerceUtil.coerceParams(Set.class, String.class, actualParams1, 0); as...
@Override public SelJodaDateTimeZone field(SelString field) { String fieldName = field.getInternalVal(); if ("UTC".equals(fieldName)) { return new SelJodaDateTimeZone(DateTimeZone.UTC); } throw new UnsupportedOperationException(type() + " DO NOT support accessing field: " + field); }
@Test public void testField() { SelType res = one.field(SelString.of("UTC")); assertEquals("DATETIME_ZONE: UTC", res.type() + ": " + res); }
public String getRealMaximumTimeout() { return Const.trim( environmentSubstitute( getMaximumTimeout() ) ); }
@Test public void testGetRealMaximumTimeout() { JobEntryDelay entry = new JobEntryDelay(); assertTrue( Utils.isEmpty( entry.getRealMaximumTimeout() ) ); entry.setMaximumTimeout( " 1" ); assertEquals( "1", entry.getRealMaximumTimeout() ); entry.setVariable( "testValue", " 20" ); entry.setMaxi...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatExplainQuery() { final String statementString = "EXPLAIN foo;"; final Statement statement = parseSingle(statementString); final String result = SqlFormatter.formatSql(statement); assertThat(result, is("EXPLAIN \nFOO")); }
long importPhotos( Collection<PhotoModel> photos, GPhotosUpload gPhotosUpload) throws Exception { return gPhotosUpload.uploadItemsViaBatching( photos, this::importPhotoBatch); }
@Test public void importPhotoInTempStoreFailure() throws Exception { PhotoModel photoModel = new PhotoModel( PHOTO_TITLE, IMG_URI, PHOTO_DESCRIPTION, JPEG_MEDIA_TYPE, "oldPhotoID1", OLD_ALBUM_ID, true); Mockito.when(g...
public static Builder route() { return new RouterFunctionBuilder(); }
@Test void andRoute() { RouterFunction<ServerResponse> routerFunction1 = request -> Optional.empty(); RequestPredicate requestPredicate = request -> true; RouterFunction<ServerResponse> result = routerFunction1.andRoute(requestPredicate, this::handlerMethod); assertThat(result).isNotNull(); Optional<? exte...
public void validateLoginName() throws ValidationException { validate(Validator.presenceValidator("Login name field must be non-blank."), getName()); }
@Test void shouldValidateWhenLoginNameExists() throws Exception { user = new User("bob", new String[]{"Jez,Pavan"}, "user@mail.com", true); user.validateLoginName(); }
public static AztecCode encode(String data) { return encode(data.getBytes(StandardCharsets.ISO_8859_1)); }
@Test public void testAztecWriter() throws Exception { testWriter("Espa\u00F1ol", null, 25, true, 1); // Without ECI (implicit ISO-8859-1) testWriter("Espa\u00F1ol", ISO_8859_1, 25, true, 1); // Explicit ISO-8859-1 testWriter("\u20AC 1 sample data.", WINDOWS_1252, 25, true, 2...
public void addReceiptHandle(ProxyContext context, Channel channel, String group, String msgID, MessageReceiptHandle messageReceiptHandle) { ConcurrentHashMapUtils.computeIfAbsent(this.receiptHandleGroupMap, new ReceiptHandleGroupKey(channel, group), k -> new ReceiptHandleGroup()).put(msgID, message...
@Test public void testClientOffline() { ArgumentCaptor<ConsumerIdsChangeListener> listenerArgumentCaptor = ArgumentCaptor.forClass(ConsumerIdsChangeListener.class); Mockito.verify(consumerManager, Mockito.times(1)).appendConsumerIdsChangeListener(listenerArgumentCaptor.capture()); Channel ch...
@Override public List<HivePartitionName> refreshTable(String hiveDbName, String hiveTblName, boolean onlyCachedPartitions) { DatabaseTableName databaseTableName = DatabaseTableName.of(hiveDbName, hiveTblName); tableNameLockMap.putIfAbsent(databaseTable...
@Test public void testRefreshTable() { new Expectations(metastore) { { metastore.getTable(anyString, "notExistTbl"); minTimes = 0; Throwable targetException = new NoSuchObjectException("no such obj"); Throwable e = new InvocationTar...
public List<VespaService> getMonitoringServices(String service) { if (service.equalsIgnoreCase(ALL_SERVICES)) return services; List<VespaService> myServices = new ArrayList<>(); for (VespaService s : services) { log.log(FINE, () -> "getMonitoringServices. service=" + ser...
@Test public void services_can_be_retrieved_from_monitoring_name() { List<VespaService> dummyServices = List.of( new DummyService(0, "dummy/id/0"), new DummyService(1, "dummy/id/1")); VespaServices services = new VespaServices(dummyServices); assertEquals(2, ...
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks, final Map<TaskId, Set<TopicPartition>> standbyTasks) { log.info("Handle new assignment with:\n" + "\tNew active tasks: {}\n" + "\tNew standby tasks: {}\n" +...
@Test public void shouldRemoveUnusedFailedStandbyTaskFromStateUpdaterAndCloseDirty() { final StandbyTask standbyTaskToClose = standbyTask(taskId02, taskId02ChangelogPartitions) .inState(State.RUNNING) .withInputPartitions(taskId02Partitions).build(); final TasksRegistry tasks...
@Override public Object get(PropertyKey key) { return get(key, ConfigurationValueOptions.defaults()); }
@Test public void initConfWithExtenstionProperty() throws Exception { try (Closeable p = new SystemPropertyRule("alluxio.master.journal.ufs.option.a.b.c", "foo").toResource()) { resetConf(); assertEquals("foo", mConfiguration.get(Template.MASTER_JOURNAL_UFS_OPTION_PROPERTY ...
@Override public double dot(SGDVector other) { if (other.size() != size) { throw new IllegalArgumentException("Can't dot two vectors of different lengths, this = " + size + ", other = " + other.size()); } else if (other instanceof SparseVector) { double score = 0.0; ...
@Test public void overlappingDot() { SparseVector a = generateVectorA(); SparseVector b = generateVectorB(); assertEquals(a.dot(b), b.dot(a), 1e-10); assertEquals(-15.0, a.dot(b), 1e-10); }
public String convert(Object o) { StringBuilder buf = new StringBuilder(); Converter<Object> p = headTokenConverter; while (p != null) { buf.append(p.convert(o)); p = p.getNext(); } return buf.toString(); }
@Test public void convertMultipleDates() { Calendar cal = Calendar.getInstance(); cal.set(2003, 4, 20, 17, 55); FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM, aux}/%d{yyyy.MM.dd}.txt", context); assertEquals("foo-2003.05/2003.05.20.txt", fnp.convert(cal.getTime())); }
public static <T> T loadWithSecrets(Map<String, Object> map, Class<T> clazz, SourceContext sourceContext) { return loadWithSecrets(map, clazz, secretName -> sourceContext.getSecret(secretName)); }
@Test public void testDefaultValue() { // test required field. Assert.expectThrows(IllegalArgumentException.class, () -> IOConfigUtils.loadWithSecrets(new HashMap<>(), TestDefaultConfig.class, new TestSinkContext())); // test all default value. Map<String, Object> ...
public static long readInt64(ByteBuffer buf) throws BufferUnderflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).getLong(); }
@Test public void testReadInt64() { assertEquals(258L, ByteUtils.readInt64(new byte[]{2, 1, 0, 0, 0, 0, 0, 0}, 0)); assertEquals(258L, ByteUtils.readInt64(new byte[]{2, 1, 0, 0, 0, 0, 0, 0, 3, 4}, 0)); assertEquals(772L, ByteUtils.readInt64(new byte[]{1, 2, 4, 3, 0, 0, 0, 0, 0, 0}, 2)); ...
static public boolean notMarkedWithNoAutoStart(Object o) { if (o == null) { return false; } Class<?> clazz = o.getClass(); NoAutoStart a = clazz.getAnnotation(NoAutoStart.class); return a == null; }
@Test public void markedWithNoAutoStart() { DoNotAutoStart o = new DoNotAutoStart(); assertFalse(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); }
public Collection<Task> createTasks(final Consumer<byte[], byte[]> consumer, final Map<TaskId, Set<TopicPartition>> tasksToBeCreated) { final List<Task> createdTasks = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> newTaskAndPartitions : tas...
@Test public void shouldThrowStreamsExceptionOnErrorCloseThreadProducerIfEosV2Enabled() { properties.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2); mockClientSupplier.setApplicationIdForProducer("appId"); createTasks(); mockClientSupplier.producers.get...
public static String loadClassWithBackwardCompatibleCheck(String className) { return PLUGINS_BACKWARD_COMPATIBLE_CLASS_NAME_MAP.getOrDefault(className, className); }
@Test public void testBackwardCompatible() { Assert.assertEquals(PluginManager .loadClassWithBackwardCompatibleCheck("org.apache.pinot.core.realtime.stream.SimpleAvroMessageDecoder"), "org.apache.pinot.plugin.inputformat.avro.SimpleAvroMessageDecoder"); Assert.assertEquals(PluginManager ...
@Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { return false; }
@Test public void hasProjectUuidPermission() { assertThat(githubWebhookUserSession.hasEntityUuidPermission("perm", "project")).isFalse(); }
public static String getFullGcsPath(String... pathParts) { checkArgument(pathParts.length != 0, "Must provide at least one path part"); checkArgument( stream(pathParts).noneMatch(Strings::isNullOrEmpty), "No path part can be null or empty"); return String.format("gs://%s", String.join("/", pathPart...
@Test public void testGetFullGcsPathOneEmptyValue() { assertThrows( IllegalArgumentException.class, () -> ArtifactUtils.getFullGcsPath("bucket", "", "dir2", "file")); }
@Override public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) { ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new); String columnName = shardingValue.getColumnName(); ...
@SuppressWarnings({"unchecked", "rawtypes"}) @Test void assertDoShardingWithRangeShardingConditionValue() { List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3"); Collection<String> actual = inlineShardingAlgorithm.doSharding(availableTargetNames, ...
@Override public NullsOrderType getDefaultNullsOrderType() { return NullsOrderType.FIRST; }
@Test void assertGetDefaultNullsOrderType() { assertThat(dialectDatabaseMetaData.getDefaultNullsOrderType(), is(NullsOrderType.FIRST)); }
@Override public void executeSystemTask(WorkflowSystemTask systemTask, String taskId, int callbackTime) { try { Task task = executionDAOFacade.getTaskById(taskId); if (task == null) { LOG.error("TaskId: {} could not be found while executing SystemTask", taskId); return; } L...
@Test public void testExecuteSystemTaskThrowUnexpectedException() { String workflowId = "workflow-id"; String taskId = "task-id-1"; Task maestroTask = new Task(); maestroTask.setTaskType(Constants.MAESTRO_TASK_NAME); maestroTask.setReferenceTaskName("maestroTask"); maestroTask.setWorkflowInst...
public Collection<String> getUsedConversionClasses(Schema schema) { Collection<String> result = new HashSet<>(); for (Conversion<?> conversion : getUsedConversions(schema)) { result.add(conversion.getClass().getCanonicalName()); } return result; }
@Test void getUsedConversionClassesForNullableLogicalTypesInArray() throws Exception { SpecificCompiler compiler = createCompiler(); final Schema schema = new Schema.Parser().parse( "{\"type\":\"record\",\"name\":\"NullableLogicalTypesArray\",\"namespace\":\"org.apache.avro.codegentest.testdata\",\"d...
public static void displayWelcomeMessage( final int consoleWidth, final PrintWriter writer ) { final String[] lines = { "", "===========================================", "= _ _ ____ ____ =", "= | | _____ __ _| | _ \\| __ ) =", ...
@Test public void shouldFlushWriterWhenOutputtingLongMessage() { // When: WelcomeMsgUtils.displayWelcomeMessage(80, mockPrintWriter); // Then: Mockito.verify(mockPrintWriter).flush(); }
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testUnsupportedBetweenOperandEmptyLeaves() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); final SearchArgument arg = new MockSearchArgument( builder .startAnd() .between("salary", PredicateLeaf.Type.LONG, 9000L, 1500...
@SafeVarargs public static Optional<Predicate<Throwable>> createExceptionsPredicate( Predicate<Throwable> exceptionPredicate, Class<? extends Throwable>... exceptions) { return PredicateCreator.createExceptionsPredicate(exceptions) .map(predicate -> exceptionPredicate == null ? p...
@Test public void buildComplexRecordExceptionsPredicate() { Predicate<Throwable> exceptionPredicate = t -> t instanceof IOException; Predicate<Throwable> predicate = PredicateCreator .createExceptionsPredicate(exceptionPredicate, RuntimeException.class) .orElseThrow(); ...
@Override public void updateArticle(ArticleUpdateReqVO updateReqVO) { // 校验存在 validateArticleExists(updateReqVO.getId()); // 校验分类存在 validateArticleCategoryExists(updateReqVO.getCategoryId()); // 更新 ArticleDO updateObj = ArticleConvert.INSTANCE.convert(updateReqVO); ...
@Test public void testUpdateArticle_notExists() { // 准备参数 ArticleUpdateReqVO reqVO = randomPojo(ArticleUpdateReqVO.class); // 调用, 并断言异常 assertServiceException(() -> articleService.updateArticle(reqVO), ARTICLE_NOT_EXISTS); }
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldNotParseAsArrayWithoutCommas() { SchemaAndValue schemaAndValue = Values.parseString("[0 1 2]"); assertEquals(Type.STRING, schemaAndValue.schema().type()); assertEquals("[0 1 2]", schemaAndValue.value()); }
public ServiceInfo processServiceInfo(String json) { ServiceInfo serviceInfo = JacksonUtils.toObj(json, ServiceInfo.class); serviceInfo.setJsonFromServer(json); return processServiceInfo(serviceInfo); }
@Test void testProcessServiceInfoForOlder() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); List<Instance> hosts = new ArrayList<>(); hosts.add(instance1); hosts.add...
@VisibleForTesting ImmutableList<AggregationKeyResult> extractValues(PivotResult pivotResult) throws EventProcessorException { final ImmutableList.Builder<AggregationKeyResult> results = ImmutableList.builder(); // Example PivotResult structures. The row value "key" is composed of: "metric/<functio...
@Test public void testExtractValuesWithoutGroupBy() throws Exception { final long WINDOW_LENGTH = 30000; final AbsoluteRange timerange = AbsoluteRange.create(DateTime.now(DateTimeZone.UTC).minusSeconds(3600), DateTime.now(DateTimeZone.UTC)); final SeriesSpec seriesCount = Count.builder().id(...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } return FEELFnResult.ofResult( BigDecimal.valueOf( list.size() ) ); }
@Test void invokeParamListNonEmpty() { FunctionTestUtil.assertResult(countFunction.invoke(Arrays.asList(1, 2, "test")), BigDecimal.valueOf(3)); }
@Override public Object decrypt(final Object cipherValue, final AlgorithmSQLContext algorithmSQLContext) { return cryptographicAlgorithm.decrypt(cipherValue); }
@Test void assertDecryptNullValue() { assertNull(encryptAlgorithm.decrypt(null, mock(AlgorithmSQLContext.class))); }
public static Matches matches(String regex) { return matches(regex, 0); }
@Test @Category(NeedsRunner.class) public void testMatchesName() { PCollection<String> output = p.apply(Create.of("a", "x xxx", "x yyy", "x zzz")) .apply(Regex.matches("x (?<namedgroup>[xyz]*)", "namedgroup")); PAssert.that(output).containsInAnyOrder("xxx", "yyy", "zzz"); p.run(); ...
static ResourceMethodConfigElement parse(RestLiMethodConfig.ConfigType configType, String key, Object value) throws ResourceMethodConfigParsingException { ParsingErrorListener errorListener = new ParsingErrorListener(); ANTLRInputStream input = new ANTLRInputStream(key); ResourceMethodKeyLexer l...
@Test(dataProvider = "invalidConfigs", expectedExceptions = {ResourceMethodConfigParsingException.class}) public void testInvalidTimeoutConfigParsing(RestLiMethodConfig.ConfigType configType, String configKey, Object configVal...
public List<JobVertex> getVerticesSortedTopologicallyFromSources() throws InvalidProgramException { // early out on empty lists if (this.taskVertices.isEmpty()) { return Collections.emptyList(); } List<JobVertex> sorted = new ArrayList<JobVertex>(this.taskVertice...
@Test public void testTopologicalSort2() { try { JobVertex source1 = new JobVertex("source1"); JobVertex source2 = new JobVertex("source2"); JobVertex root = new JobVertex("root"); JobVertex l11 = new JobVertex("layer 1 - 1"); JobVertex l12 = new J...
public static Date parseDate2(String datetimeStr) { if (StringUtils.isEmpty(datetimeStr)) { return null; } try { datetimeStr = datetimeStr.trim(); int len = datetimeStr.length(); if (datetimeStr.contains("-") && datetimeStr.contains(":") && datetim...
@PrepareForTest(StringUtils.class) @Test public void parseDate2InputNotNullOutputNull2() throws Exception { // Setup mocks PowerMockito.mockStatic(StringUtils.class); // Arrange final String datetimeStr = "1a 2b 3c"; final Method isEmptyMethod = DTUMemberMatcher.method(StringUtils.clas...
@Override public Object toConnectRow(final Object ksqlData) { if (!(ksqlData instanceof Struct)) { return ksqlData; } final Schema schema = getSchema(); final Struct struct = new Struct(schema); Struct originalData = (Struct) ksqlData; Schema originalSchema = originalData.schema(); ...
@Test public void shouldTransformStructWithDefaultValue() { // Given: final Schema schema = SchemaBuilder.struct() .field("f1", SchemaBuilder.OPTIONAL_STRING_SCHEMA) .field("f2", SchemaBuilder.OPTIONAL_INT32_SCHEMA) .field("f3", SchemaBuilder.int64().defaultValue(123L)) .build(...
public CompletableFuture<Void> handlePullQuery( final ServiceContext serviceContext, final PullPhysicalPlan pullPhysicalPlan, final ConfiguredStatement<Query> statement, final RoutingOptions routingOptions, final PullQueryWriteStream pullQueryQueue, final CompletableFuture<Void> shou...
@Test public void forwardingError_throwsError() { // Given: locate(location5); when(ksqlClient.makeQueryRequest(eq(node2.location()), any(), any(), any(), any(), any(), any())) .thenThrow(new RuntimeException("Network Error")); // When: CompletableFuture<Void> future = haRouting.handlePul...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testGoodStateParameterSuperclassStateType() throws Exception { DoFnSignatures.getSignature( new DoFn<KV<String, Integer>, Long>() { @StateId("my-id") private final StateSpec<CombiningState<Integer, int[], Integer>> state = StateSpecs.combining(Sum.ofInt...
public Collection<PluginUpdateAggregate> aggregate(@Nullable Collection<PluginUpdate> pluginUpdates) { if (pluginUpdates == null || pluginUpdates.isEmpty()) { return Collections.emptyList(); } Map<Plugin, PluginUpdateAggregateBuilder> builders = new HashMap<>(); for (PluginUpdate pluginUpdate : p...
@Test public void aggregates_groups_pluginUpdate_per_plugin_key() { Collection<PluginUpdateAggregator.PluginUpdateAggregate> aggregates = underTest.aggregate(ImmutableList.of( createPluginUpdate("key1"), createPluginUpdate("key1"), createPluginUpdate("key0"), createPluginUpdate("key2"), ...
public DataTable subTable(int fromRow, int fromColumn) { return subTable(fromRow, fromColumn, height(), width()); }
@Test void subTable_throws_for_invalid_from_to_row() { DataTable table = createSimpleTable(); assertThrows(IllegalArgumentException.class, () -> table.subTable(2, 0, 1, 1)); }
public Image getIcon(String pluginId) { return getVersionedSecretsExtension(pluginId).getIcon(pluginId); }
@Test void getIcon_shouldDelegateToVersionedExtension() { SecretsExtensionV1 secretsExtensionV1 = mock(SecretsExtensionV1.class); Map<String, VersionedSecretsExtension> secretsExtensionMap = Map.of("1.0", secretsExtensionV1); extension = new SecretsExtension(pluginManager, extensionsRegistry...
@Override public List<DictDataDO> getDictDataList(Integer status, String dictType) { List<DictDataDO> list = dictDataMapper.selectListByStatusAndDictType(status, dictType); list.sort(COMPARATOR_TYPE_AND_SORT); return list; }
@Test public void testGetDictDataList() { // mock 数据 DictDataDO dictDataDO01 = randomDictDataDO().setDictType("yunai").setSort(2) .setStatus(CommonStatusEnum.ENABLE.getStatus()); dictDataMapper.insert(dictDataDO01); DictDataDO dictDataDO02 = randomDictDataDO().setDict...
public static void validate( FederationPolicyInitializationContext policyContext, String myType) throws FederationPolicyInitializationException { if (myType == null) { throw new FederationPolicyInitializationException( "The myType parameter" + " should not be null."); } if (pol...
@Test public void correcInit() throws Exception { FederationPolicyInitializationContextValidator.validate(context, MockPolicyManager.class.getCanonicalName()); }
@Override public void onProjectsDeleted(Set<DeletedProject> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsDeleted(projects))); }
@Test public void onProjectsDeleted_throws_NPE_if_set_is_null_even_if_no_listeners() { assertThatThrownBy(() -> underTestNoListeners.onProjectsDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); }
@Override public String toString() { StringBuilder builder = new StringBuilder(); boolean isFirstLine = true; for (Item entry : entries.values()) { if (isFirstLine) { isFirstLine = false; } else { builder.append("\n"); } builder.append(entry); } return bui...
@Test public void testPathToString() { assertEquals("root string", "[]", DisplayData.Path.root().toString()); assertEquals("single component", "[a]", DisplayData.Path.absolute("a").toString()); assertEquals("hierarchy", "[a/b/c]", DisplayData.Path.absolute("a", "b", "c").toString()); }
@Override public String getDisplayName() { return ARRAY + "(" + elementType.getDisplayName() + ")"; }
@Test public void testDisplayName() { ArrayType type = new ArrayType(BOOLEAN); assertEquals(type.getDisplayName(), "array(boolean)"); }
public static boolean areKerberosCredentialsValid( UserGroupInformation ugi, boolean useTicketCache) { Preconditions.checkState(isKerberosSecurityEnabled(ugi)); // note: UGI::hasKerberosCredentials inaccurately reports false // for logins based on a keytab (fixed in Hadoop 2.6.1, se...
@Test public void testShouldReturnTrueIfTicketCacheIsNotUsed() { UserGroupInformation.setConfiguration( getHadoopConfigWithAuthMethod(AuthenticationMethod.KERBEROS)); UserGroupInformation user = createTestUser(AuthenticationMethod.KERBEROS); boolean result = HadoopUtils.areK...
public String getEcosystem(DefCveItem cve) { final List<Reference> references = Optional.ofNullable(cve) .map(DefCveItem::getCve) .map(CveItem::getReferences) .orElse(null); if (Objects.nonNull(references)) { for (Reference r : references) { ...
@Test public void testGetEcosystemMustHandleNullCve() { // Given UrlEcosystemMapper mapper = new UrlEcosystemMapper(); DefCveItem cveItem = new DefCveItem(); // When String output = mapper.getEcosystem(cveItem); // Then assertNull(output); }
public K getKeyInternal() { return key; }
@Test public void testGetKeyInternal() { assertEquals(0, replicatedRecord.getHits()); assertEquals("key", replicatedRecord.getKeyInternal()); assertEquals(0, replicatedRecord.getHits()); }
@POST @Path("/select-idp") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response postSelectIdp( @CookieParam("session_id") String sessionId, @FormParam("identityProvider") String identityProvider) { var redirect = authService.selectedIdentityProvider(new SelectedIdpRequest(sess...
@Test void selectIdp_passParams() { var sessionId = IdGenerator.generateID(); var selectedIdpIssuer = "https://aok-testfalen.example.com"; var idpRedirect = URI.create(selectedIdpIssuer).resolve("/auth/login"); var authService = mock(AuthService.class); when(authService.selectedIdentityProvide...
@ExecuteOn(TaskExecutors.IO) @Post(uri = "/replay/by-ids") @Operation(tags = {"Executions"}, summary = "Create new executions from old ones. Keep the flow revision") @ApiResponse(responseCode = "200", description = "On success", content = {@Content(schema = @Schema(implementation = BulkResponse.class))}) ...
@Test void replayByIds() throws TimeoutException { Execution execution1 = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested"); Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested"); assertThat(execution1.getState().isTerminated(), is(...
@SuppressWarnings("unchecked") @VisibleForTesting Schema<T> initializeSchema() throws ClassNotFoundException { if (StringUtils.isEmpty(this.pulsarSinkConfig.getTypeClassName())) { return (Schema<T>) Schema.BYTES; } Class<?> typeArg = Reflections.loadClass(this.pulsarSinkConf...
@Test public void testInitializeSchema() throws Exception { PulsarClient pulsarClient = getPulsarClient(); // generic record type (no serde and no schema type) PulsarSinkConfig pulsarSinkConfig = getPulsarConfigs(); pulsarSinkConfig.setSerdeClassName(null); pulsarSinkConfig....
public static ReplaceFirst replaceFirst(String regex, String replacement) { return replaceFirst(Pattern.compile(regex), replacement); }
@Test @Category(NeedsRunner.class) public void testReplaceFirst() { PCollection<String> output = p.apply(Create.of("xjx", "yjy", "zjz")).apply(Regex.replaceFirst("[xyz]", "new")); PAssert.that(output).containsInAnyOrder("newjx", "newjy", "newjz"); p.run(); }
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@Test void testAbstractAndInterfaceTypes() { // interface RichMapFunction<String, ?> function = new RichMapFunction<String, Testable>() { private static final long serialVersionUID = 1L; @Override public Testable map(Strin...
@Udtf public <T> List<List<T>> cube(final List<T> columns) { if (columns == null) { return Collections.emptyList(); } return createAllCombinations(columns); }
@Test public void shouldHandleOneNull() { // Given: final Object[] oneNull = {1, null}; // When: final List<List<Object>> result = cubeUdtf.cube(Arrays.asList(oneNull)); // Then: assertThat(result.size(), is(2)); assertThat(result.get(0), is(Arrays.asList(null, null))); assertThat(re...
public static File generate(String content, int width, int height, File targetFile) { String extName = FileUtil.extName(targetFile); switch (extName) { case QR_TYPE_SVG: String svg = generateAsSvg(content, new QrConfig(width, height)); FileUtil.writeString(svg, targetFile, StandardCharsets.UTF_8); br...
@Test @Disabled public void generateToFileTest() { final QrConfig qrConfig = QrConfig.create() .setForeColor(Color.BLUE) .setBackColor(new Color(0,200,255)) .setWidth(0) .setHeight(0).setMargin(1); final File qrFile = QrCodeUtil.generate("https://hutool.cn/", qrConfig, FileUtil.touch("d:/test/asci...
@Override public AuthorizationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { Capabilities capabilities = capabilities(descriptor.id()); PluggableInstanceSettings authConfigSettings = authConfigSettings(descriptor.id()); PluggableInstanceSettings roleSettings = roleSettings(descri...
@Test public void shouldBuildPluginInfoWithAuthSettings() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); List<PluginConfiguration> pluginConfigurations = List.of( new PluginConfiguration("username", new Metadata(true, false)), ne...
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException { try { String[] s; if (suffix == null || suffix.isBlank()) { s = new String[]{prefix, "tmp"}; // see File.createTempFile - tmp is used if suffix is null ...
@Issue("JENKINS-48227") @Test public void testCreateTempDir() throws IOException, InterruptedException { final File srcFolder = temp.newFolder("src"); final FilePath filePath = new FilePath(srcFolder); FilePath x = filePath.createTempDir("jdk", "dmg"); FilePath y = filePath.crea...
public static String calculateMemoryWithDefaultOverhead(String memory) { long memoryMB = convertToBytes(memory) / M; long memoryOverheadMB = Math.max((long) (memoryMB * 0.1f), MINIMUM_OVERHEAD); return (memoryMB + memoryOverheadMB) + "Mi"; }
@Test void testExceptionMaxLong() { assertThrows(NumberFormatException.class, () -> { K8sUtils.calculateMemoryWithDefaultOverhead("10000000Tb"); }); }
public boolean containsPK(List<String> cols) { if (cols == null) { return false; } List<String> pk = getPrimaryKeyOnlyName(); if (pk.isEmpty()) { return false; } //at least contain one pk if (cols.containsAll(pk)) { return tr...
@Test public void testContainsPKWithNoMatch() { List<String> cols = Collections.singletonList("other"); assertFalse(tableMeta.containsPK(cols)); }
@Override public ConsumerBuilder<T> maxAcknowledgmentGroupSize(int messageNum) { checkArgument(messageNum > 0, "acknowledgementsGroupSize needs to be > 0"); conf.setMaxAcknowledgmentGroupSize(messageNum); return this; }
@Test public void testMaxAcknowledgmentGroupSizeInvalid() { try { consumerBuilderImpl.maxAcknowledgmentGroupSize(0); fail("Should throw exception"); } catch (IllegalArgumentException e) { // expect exception assertEquals(e.getMessage(), "acknowledgemen...
@Override public void run() { if (!ignoreListenShutdownHook && destroyed.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info("Run shutdown hook now."); } doDestroy(); } }
@Test public void testDestoryNoModuleManagedExternally() { boolean hasModuleManagedExternally = false; for (ModuleModel moduleModel : applicationModel.getModuleModels()) { if (moduleModel.isLifeCycleManagedExternally()) { hasModuleManagedExternally = true; ...
public static HazelcastSqlOperatorTable instance() { return INSTANCE; }
@Test public void testNoOverride() { Map<BiTuple<String, SqlSyntax>, SqlOperator> map = new HashMap<>(); for (SqlOperator operator : HazelcastSqlOperatorTable.instance().getOperatorList()) { BiTuple<String, SqlSyntax> key = BiTuple.of(operator.getName(), operator.getSyntax()); ...
public List<String> targetedUrls(final UUID aci) { final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration(); final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream() .filter(config -> config.getEnrolledAcis().contains(a...
@Test public void testExplicitEnrollment() throws JsonProcessingException { final String configString = """ captcha: scoreFloor: 1.0 turn: secret: bloop uriConfigs: - uris: - enrolled.org weight: 0 enrolledAcis: ...
private static String randomString(Random random, char[] alphabet, int numRandomChars) { // The buffer most hold the size of the requested number of random chars and the chunk separators ('-'). int bufferSize = numRandomChars + ((numRandomChars - 1) / RANDOM_STRING_CHUNK_SIZE); CharBuffer charBu...
@Test(expected = NegativeArraySizeException.class) public void testNegativeArraySizeException() { // Boundary test StringUtils.randomString(-1); }
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test public void testValueOfStringIPv4() { Ip4Address ipAddress; ipAddress = Ip4Address.valueOf("1.2.3.4"); assertThat(ipAddress.toString(), is("1.2.3.4")); ipAddress = Ip4Address.valueOf("0.0.0.0"); assertThat(ipAddress.toString(), is("0.0.0.0")); ipAddress = Ip4...
public Future<KafkaVersionChange> reconcile() { return getVersionFromController() .compose(i -> getPods()) .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testDowngradeFailsWithNewProtocolVersions(VertxTestContext context) { String oldKafkaVersion = KafkaVersionTestUtils.LATEST_KAFKA_VERSION; String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.LATEST_PROTOCOL_VERSION; String oldLogMessageFormatVersion = KafkaVersionT...
public static Value convertBoxedJavaType(Object boxed) { if (boxed == null) { return null; } final Class<?> clazz = boxed.getClass(); if (clazz == String.class) { return new StringValue((String) boxed); } else if (clazz == Integer.class) { re...
@Test void testJavaToValueConversion() { assertThat(JavaToValueConverter.convertBoxedJavaType(null)).isNull(); assertThat(JavaToValueConverter.convertBoxedJavaType("123Test")) .isEqualTo(new StringValue("123Test")); assertThat(JavaToValueConverter.convertBoxedJavaType((byte)...
@Override public WindowStoreIterator<V> backwardFetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { Objects.requireNonNull(key, "key can't be null"); final L...
@Test public void shouldFindValueForKeyWhenMultiStoresBackwards() { final ReadOnlyWindowStoreStub<String, String> secondUnderlying = new ReadOnlyWindowStoreStub<>(WINDOW_SIZE); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingWindowStore.put("key-one", "value-one...
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assert...
@Override public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) { if (requestData == null) { return super.handle(targetName, instances, null); } if (!shouldHandle(instances)) { return instances; } List<Object> r...
@Test public void testGetTargetInstancesWithOneInstance() { List<Object> instances = new ArrayList<>(); ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0"); instances.add(instance1); Map<String, List<String>> header = new HashMap<>(); ...
public CredentialRetriever googleApplicationDefaultCredentials() { return () -> { try { if (imageReference.getRegistry().endsWith("gcr.io") || imageReference.getRegistry().endsWith("docker.pkg.dev")) { GoogleCredentials googleCredentials = googleCredentialsProvider.get(); ...
@Test public void testGoogleApplicationDefaultCredentials_adcNotPresent() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = new CredentialRetrieverFactory( ImageReference.of("awesome.gcr.io", "repository", null), mockLogger, ...
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } try { TemporalAccessor parsed = FEEL_TIME.parse(val); i...
@Test void invokeStringParamNoOffset() { FunctionTestUtil.assertResult(timeFunction.invoke("10:15:06"), LocalTime.of(10, 15, 6)); }
public NearCachePreloaderConfig setStoreInitialDelaySeconds(int storeInitialDelaySeconds) { this.storeInitialDelaySeconds = checkPositive("storeInitialDelaySeconds", storeInitialDelaySeconds); return this; }
@Test(expected = IllegalArgumentException.class) public void setStoreInitialDelaySeconds_withNegative() { config.setStoreInitialDelaySeconds(-1); }
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator411() { UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks:/")); assertTrue(urlValidator.isValid("http://example.rocks:0/")); assertTrue(urlValidator.isValid("http://example.rocks:65535/")); ass...
public void timePasses() { if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); } else { changeStateTo(new PeacefulState(this)); } }
@Test void testTimePasses() { final var mammoth = new Mammoth(); mammoth.observe(); assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); assertEquals(1, appender.getLogSize()); mammoth.timePasses(); assertEquals("The mammoth gets angry!", appender.getLastMessage()); ...
synchronized boolean tryToMoveTo(State to) { boolean res = false; State currentState = state; if (TRANSITIONS.get(currentState).contains(to)) { this.state = to; res = true; } LOG.debug("{} tryToMoveTo from {} to {} => {}", Thread.currentThread().getName(), currentState, to, res); ret...
@Test public void STOPPED_is_not_allowed_from_RESTARTING() { assertThat(newNodeLifecycle(RESTARTING).tryToMoveTo(STOPPED)).isFalse(); }
public Connector newConnector(String connectorClassOrAlias) { Class<? extends Connector> klass = connectorClass(connectorClassOrAlias); return newPlugin(klass); }
@Test public void shouldThrowIfNoDefaultConstructor() { assertThrows(ConnectException.class, () -> plugins.newConnector( TestPlugin.BAD_PACKAGING_NO_DEFAULT_CONSTRUCTOR_CONNECTOR.className() )); }