focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public NearCachePreloaderConfig setStoreInitialDelaySeconds(int storeInitialDelaySeconds) { this.storeInitialDelaySeconds = checkPositive("storeInitialDelaySeconds", storeInitialDelaySeconds); return this; }
@Test(expected = IllegalArgumentException.class) public void setStoreInitialDelaySeconds_withZero() { config.setStoreInitialDelaySeconds(0); }
public static OutputStream string2OutputStream(final String string, final String charsetName) { if (string == null || isSpace(charsetName)) return null; try { return bytes2OutputStream(string.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { e.printStackT...
@Test public void string2OutputStreamInputQuestionsReturnNull() { Assert.assertNull( ConvertKit.string2OutputStream("\u0000\u0000\u0000???????????????????", "") ); }
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { return unmarshal(exchange, (Object) stream); }
@Test public void testJsonApiUnmarshall() throws Exception { Class<?>[] formats = { MyBook.class, MyAuthor.class }; JsonApiDataFormat jsonApiDataFormat = new JsonApiDataFormat(MyBook.class, formats); String jsonApiInput = this.generateTestDataAsString(); Exchange exchange = new Def...
@Override public Optional<String> getLocalHadoopConfigurationDirectory() { final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR); if (StringUtils.isNotBlank(hadoopConfDirEnv)) { return Optional.of(hadoopConfDirEnv); } final String hadoopHomeEnv = S...
@Test void testGetLocalHadoopConfigurationDirectoryReturnEmptyWhenHadoopEnvIsNotSet() throws Exception { runTestWithEmptyEnv( () -> { final Optional<String> optional = testingKubernetesParameters.getLocalHadoopConfigurationDirectory...
@Override public void configure(Map<String, ?> configs) { super.configure(configs); configureSamplingInterval(configs); configurePrometheusAdapter(configs); configureQueryMap(configs); }
@Test public void testGetSamplesSuccess() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(PROMETHEUS_SERVER_ENDPOINT_CONFIG, "http://kafka-cluster-1.org:9090"); addCapacityConfig(config); Set<String> topics = new HashSet<>(Arrays.asList(TEST_TOPIC, TEST_T...
@SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Flowable.class)).isTrue(); assertThat(rxJava2BulkheadAspectExt.canHandleReturnType(Single.class)).isTrue(); }
@Override public ImportResult importItem( UUID id, IdempotentImportExecutor idempotentExecutor, TokensAndUrlAuthData authData, MailContainerResource data) throws Exception { // Lazy init the request for all labels in the destination account, since it may not be needed // Mapping of la...
@Test public void importMessage() throws Exception { MailContainerResource resource = new MailContainerResource(null, Collections.singletonList(MESSAGE_MODEL)); ImportResult result = googleMailImporter.importItem(JOB_ID, executor, null, resource); // Getting list of labels from Google verify...
@Override public void clear() { cache.clear(); }
@Test public void testClear() throws Exception { EventLoopGroup group = new DefaultEventLoopGroup(1); try { EventLoop loop = group.next(); final DefaultDnsCnameCache cache = new DefaultDnsCnameCache(); cache.cache("x.netty.io", "mapping.netty.io", 100000, loop); ...
@Override public SyntheticSourceReader createReader(PipelineOptions pipelineOptions) { return new SyntheticSourceReader(this); }
@Test public void testIncreasingProgress() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); testSourceOptions.progressShape = ProgressShape.LINEAR; SyntheticBoundedSource source = new SyntheticBoundedSource(testSourceOptions); BoundedSource.BoundedReader<KV<byte[], byte[]>...
public static String getDatabaseName(final SQLStatement sqlStatement, final String currentDatabaseName) { Optional<DatabaseSegment> databaseSegment = sqlStatement instanceof FromDatabaseAvailable ? ((FromDatabaseAvailable) sqlStatement).getDatabase() : Optional.empty(); return databaseSegment.map(option...
@Test void assertDatabaseNameWhenAvailableInSQLStatement() { FromDatabaseAvailable sqlStatement = mock(FromDatabaseAvailable.class, withSettings().extraInterfaces(SQLStatement.class)); DatabaseSegment databaseSegment = mock(DatabaseSegment.class, RETURNS_DEEP_STUBS); when(databaseSegment.get...
@Override public V putIfAbsent(K k, V v) { return mInternalMap.putIfAbsent(new IdentityObject<>(k), v); }
@Test public void putIfAbsent() { String t = new String("test"); assertNull(mMap.putIfAbsent(t, "v1")); assertEquals(1, mMap.size()); assertEquals("v1", mMap.get(t)); assertFalse(mMap.containsKey("test")); assertEquals("v1", mMap.putIfAbsent(t, "v2")); assertEquals("v1", mMap.get(t)); }
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfByteArrayTooLongPrefixLengthIPv4() { Ip4Prefix ipPrefix; byte[] value; value = new byte[] {1, 2, 3, 4}; ipPrefix = Ip4Prefix.valueOf(value, 33); }
@SuppressWarnings("MethodLength") static void dissectCommand( final DriverEventCode code, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { final int encodedLength = dissectLogHeader(CONTEXT, code, buffer, offset, builder); builder.append(": "); ...
@Test void dissectCommandUnknown() { final DriverEventCode eventCode = SEND_CHANNEL_CREATION; internalEncodeLogHeader(buffer, 0, 5, 5, () -> 1_000_000_000L); dissectCommand(eventCode, buffer, 0, builder); assertEquals("[1.000000000] " + CONTEXT + ": " + eventCode.name() + " [5/...
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) { NewExternalIssue newExternalIssue = sensorContext.newExternalIssue(); newExternalIssue.type(DEFAULT_TYPE); newExternalIssue.engineId(driverName); newExte...
@Test public void mapResult_concatResultMessageAndLocationMessageForIssue() { Location location = new Location().withMessage(new Message().withText("Location message")); result.withLocations(List.of(location)); resultMapper.mapResult(DRIVER_NAME, WARNING, WARNING, result); verify(newExternalIssueLoc...
public static LabelSelectorBuilder<?> builder() { return new LabelSelectorBuilder<>(); }
@Test void builderTest() { var labelSelector = LabelSelector.builder() .eq("a", "v1") .in("b", "v2", "v3") .build(); assertThat(labelSelector.toString()) .isEqualTo("a equal v1, b IN (v2, v3)"); }
public static Builder builder() { return new Builder(); }
@Test public void embeddedUdp() { final ByteBuf pcapBuffer = Unpooled.buffer(); final ByteBuf payload = Unpooled.wrappedBuffer("Meow".getBytes()); InetSocketAddress serverAddr = new InetSocketAddress("1.1.1.1", 1234); InetSocketAddress clientAddr = new InetSocketAddress("2.2.2.2", 3...
public static Validator validRegex() { return (name, val) -> { if (!(val instanceof List)) { throw new IllegalArgumentException("validator should only be used with " + "LIST of STRING defs"); } final StringBuilder regexBuilder = new StringBuilder(); for (Object item : (L...
@Test public void shouldThrowOnNoRegexList() { // Given: final Validator validator = ConfigValidators.validRegex(); // When: final Exception e = assertThrows( IllegalArgumentException.class, () -> validator.ensureValid("propName", "*.*") ); // Then: assertThat(e.getMessag...
@Override public String getName() { return FUNCTION_NAME; }
@Test public void testCastNullColumn() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("cast(%s AS INT)", INT_SV_NULL_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); Assert.assertTrue(transformFunction insta...
@ExecuteOn(TaskExecutors.IO) @Get(uri = "/{executionId}") @Operation(tags = {"Executions"}, summary = "Get an execution") public Execution get( @Parameter(description = "The execution id") @PathVariable String executionId ) { return executionRepository .findById(tenantService...
@Test void restartFromTaskId() throws Exception { final String flowId = "restart_with_inputs"; final String referenceTaskId = "instant"; // Run execution until it ends Execution parentExecution = runnerUtils.runOne(null, TESTS_FLOW_NS, flowId, null, (flow, execution1) -> flowIO.type...
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not f...
@Test public void testStaticMemberRejoinWithUnknownMemberIdAndChangeOfProtocolWhileSelectProtocolUnchangedPersistenceFailure() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceR...
@VisibleForTesting void validateRoleDuplicate(String name, String code, Long id) { // 0. 超级管理员,不允许创建 if (RoleCodeEnum.isSuperAdmin(code)) { throw exception(ROLE_ADMIN_CODE_ERROR, code); } // 1. 该 name 名字被其它角色所使用 RoleDO role = roleMapper.selectByName(name); ...
@Test public void testValidateRoleDuplicate_codeDuplicate() { // mock 数据 RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setCode("code")); roleMapper.insert(roleDO); // 准备参数 String code = "code"; // 调用,并断言异常 assertServiceException(() -> roleService.validateRo...
public Plan validateReservationSubmissionRequest( ReservationSystem reservationSystem, ReservationSubmissionRequest request, ReservationId reservationId) throws YarnException { String message; if (reservationId == null) { message = "Reservation id cannot be null. Please try again specifying " ...
@Test public void testSubmitReservationInvalidPlan() { ReservationSubmissionRequest request = createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3); when(rSystem.getPlan(PLAN_NAME)).thenReturn(null); Plan plan = null; try { plan = rrValidator.validateReservationSubmissionRequ...
public Optional<ContentPackInstallation> findById(ObjectId id) { final ContentPackInstallation installation = dbCollection.findOneById(id); return Optional.ofNullable(installation); }
@Test @MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json") public void findById() { final ObjectId objectId = new ObjectId("5b4c935b4b900a0000000001"); final Optional<ContentPackInstallation> contentPacks = persistenceService.findById(objectId); assertThat(contentPacks...
public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KTableHolder<K> right, final StreamTableJoin<K> join, final RuntimeBuildContext buildContext, final JoinedFactory joinedFactory ) { final Formats leftFormats = join.getInternalFormats(); final QueryConte...
@Test public void shouldBuildLeftSerdeCorrectly() { // Given: givenInnerJoin(SYNTH_KEY); // When: join.build(planBuilder, planInfo); // Then: final QueryContext leftCtx = QueryContext.Stacker.of(CTX).push("Left").getQueryContext(); verify(buildContext).buildValueSerde(FormatInfo.of(Forma...
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) { final int length = counterNames.length; if (counterKinds.length != length || counterDeltas.length != length) { throw new AssertionError("array lengths do not match"); } for (int i = 0; i < length; ++i)...
@Test public void testSingleCounterMultipleDeltas() throws Exception { String[] names = {"sum_counter", "sum_counter"}; String[] kinds = {"sum", "sum"}; long[] deltas = {122, 78}; counters.importCounters(names, kinds, deltas); counterSet.extractUpdates(false, mockUpdateExtractor); verify(mock...
@Override public boolean test(Pickle pickle) { if (expressions.isEmpty()) { return true; } List<String> tags = pickle.getTags(); return expressions.stream() .allMatch(expression -> expression.evaluate(tags)); }
@Test void list_of_empty_tag_predicates_matches_pickle_with_any_tags() { Pickle pickle = createPickleWithTags("@FOO"); TagPredicate predicate = createPredicate("", ""); assertTrue(predicate.test(pickle)); }
@Override public void onMessage(Message<E> message) { messageListener.onMessage(message); }
@Test public void onMessage() { MessageListener<String> listener = createMessageListenerMock(); ReliableMessageListenerAdapter<String> adapter = new ReliableMessageListenerAdapter<>(listener); Message<String> message = new Message<>("foo", "foo", System.currentTimeMillis(), null); a...
@Override public Optional<String> resolveQueryFailure(QueryStats controlQueryStats, QueryException queryException, Optional<QueryObjectBundle> test) { if (!test.isPresent()) { return Optional.empty(); } // Decouple from com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OP...
@Test public void testUnresolvedNonBucketed() { createTable.set(format("CREATE TABLE %s (x varchar, ds varchar) WITH (partitioned_by = ARRAY[\"ds\"])", TABLE_NAME)); getFailureResolver().resolveQueryFailure(CONTROL_QUERY_STATS, HIVE_TOO_MANY_OPEN_PARTITIONS_EXCEPTION, Optional.of(TEST_BUNDLE)); ...
@Override public void execute(Exchange exchange) throws SmppException { SubmitMulti[] submitMulties = createSubmitMulti(exchange); List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length); for (SubmitMulti submitMulti : submitMulties) { SubmitMultiResult result; ...
@Test public void executeWithOptionalParameter() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange...
@Override String getMethodName(Invoker invoker, Invocation invocation, String prefix) { return DubboUtils.getMethodResourceName(invoker, invocation, prefix); }
@Test public void testMethodFlowControlAsync() { Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne(); Invoker invoker = DubboTestUtil.getDefaultMockInvoker(); when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString()); initFlowRule(consumerFilter....
@Override @SuppressWarnings("unchecked") public <T> List<List<T>> toLists(DataTable dataTable, Type itemType) { requireNonNull(dataTable, "dataTable may not be null"); requireNonNull(itemType, "itemType may not be null"); if (dataTable.isEmpty()) { return emptyList(); ...
@Test void to_lists_of_unknown_type__throws_exception() { DataTable table = parse("", " | firstName | lastName | birthDate |", " | Annie M. G. | Schmidt | 1911-03-20 |", " | Roald | Dahl | 1916-09-13 |", " | Astrid | Lindgren | 1907-11-14 |"...
public DataSchema getResultDataSchema() { return _resultDataSchema; }
@Test public void testLiteralTypeHandling() { QueryContext queryContext = QueryContextConverterUtils .getQueryContext("SELECT COUNT(*), 1 FROM testTable GROUP BY d1"); DataSchema dataSchema = new DataSchema(new String[]{"d1", "count(*)"}, new ColumnDataType[]{ColumnDataType.INT, ColumnDataType...
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException { return buildFunction(functionDefinition, true); }
@Test public void testBuildFunctionTransaction() throws Exception { AbiDefinition functionDefinition = new AbiDefinition( false, Arrays.asList(new NamedType("param", "uint8")), "functionName", Col...
@Override public KeyVersion createKey(final String name, final byte[] material, final Options options) throws IOException { return doOp(new ProviderCallable<KeyVersion>() { @Override public KeyVersion call(KMSClientProvider provider) throws IOException { return provider.createKey(name, m...
@Test public void testLoadBalancingWithFailure() throws Exception { Configuration conf = new Configuration(); KMSClientProvider p1 = mock(KMSClientProvider.class); when(p1.createKey(Mockito.anyString(), Mockito.any(Options.class))) .thenReturn( new KMSClientProvider.KMSKeyVersion("p1",...
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_addNonexistentResourceWithPath_then_throwsException() { // Given String path = Paths.get("/i/do/not/exist").toString(); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an existing, readable file: " + path); ...
private void printQueries( final List<RunningQuery> queries, final String type, final String operation ) { if (!queries.isEmpty()) { writer().println(String.format( "%n%-20s%n%-20s", "Queries that " + operation + " from this " + type, "------------------------...
@Test public void testPrintQueries() { // Given: final List<RunningQuery> queries = new ArrayList<>(); queries.add( new RunningQuery( "select * from t1 emit changes", Collections.singleton("Test"), Collections.singleton("Test topic"), new QueryId("0"), queryStatusCount, KsqlConstants.K...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testOldStyleResourcesSeparatedBySpacesInvalidUppercaseUnits() throws Exception { String value = "2 vcores 5120 MB 555 GB"; expectUnparsableResource(value); parseResourceConfigValue(value); }
@VisibleForTesting List<LogFile> applyBundleSizeLogFileLimit(List<LogFile> allLogs) { final ImmutableList.Builder<LogFile> truncatedLogFileList = ImmutableList.builder(); // Always collect the in-memory log and the newest on-disk log file // Keep collecting until we pass LOG_COLLECTION_SIZE...
@Test public void testLogSizeLimiterWithSpaceForOneZippedFile() { final List<LogFile> fullLoglist = List.of( new LogFile("memory", "server.mem.log", 500, Instant.now()), new LogFile("0", "server.log", 50 * 1024 * 1024, Instant.now()), new LogFile("1", "server....
@Override public int hashCode() { StringBuilder stringBuilder = new StringBuilder(); for (Entry<String, Object> entry : getAllLocalProperties().entrySet()) { stringBuilder.append(entry.getKey()).append(entry.getValue()); } return Objects.hashCode(poolClassName, stringBuil...
@Test void assertDifferentHashCodeWithDifferentProperties() { assertThat(new DataSourcePoolProperties(MockedDataSource.class.getName(), createUserProperties("foo")).hashCode(), not(new DataSourcePoolProperties(MockedDataSource.class.getName(), createUserProperties("bar")).hashCode())); }
public Map<String, List<String>> parameters() { if (params == null) { params = decodeParams(uri, pathEndIdx(), charset, maxParams, semicolonIsNormalChar); } return params; }
@Test public void testExcludeFragment() { // a 'fragment' after '#' should be cuted (see RFC 3986) assertEquals("a", new QueryStringDecoder("?a#anchor").parameters().keySet().iterator().next()); assertEquals("b", new QueryStringDecoder("?a=b#anchor").parameters().get("a").get(0)); as...
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException( "The level of the root logger cannot be set to null"); } level = newLevel; if (newLe...
@Test public void testEnabled_All() throws Exception { root.setLevel(Level.ALL); checkLevelThreshold(loggerTest, Level.ALL); }
public void setAgility(int wizard, int amount) { wizards[wizard].setAgility(amount); }
@Test void testSetAgility() { var wizardNumber = 0; var bytecode = new int[5]; bytecode[0] = LITERAL.getIntValue(); bytecode[1] = wizardNumber; bytecode[2] = LITERAL.getIntValue(); bytecode[3] = 50; // agility amount bytecode[4] = SET_AGILITY.getIntValue(); var ...
@Override public Map<String, String> getAddresses() { AwsCredentials credentials = awsCredentialsProvider.credentials(); List<String> taskAddresses = emptyList(); if (!awsConfig.anyOfEc2PropertiesConfigured()) { taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credenti...
@Test public void getAddressesForEC2Client() { // given AwsConfig awsConfig = AwsConfig.builder().setDiscoveryMode(DiscoveryMode.Client).build(); awsEcsClient = new AwsEcsClient(CLUSTER, awsConfig, awsEcsApi, awsEc2Api, awsMetadataApi, awsCredentialsProvider); Map<String, String> exp...
@Override public Subscriber<Exchange> subscriber(String uri) { try { String uuid = context.getUuidGenerator().generateUuid(); RouteBuilder.addRoutes(context, rb -> rb.from("reactive-streams:" + uuid).to(uri)); return streamSubscriber(uuid); } catch (Exception e) ...
@Test public void testSubscriber() throws Exception { context.start(); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:reactor").to("mock:result"); } }); Flowable.just(1, 2, 3).subscribe(crs....
public boolean isEmpty() { return map.isEmpty(); }
@Test public void shouldReportEmpty() { assertThat(map.isEmpty()).isTrue(); }
public static Object toBeamObject(Value value, boolean verifyValues) { return toBeamObject(value, toBeamType(value.getType()), verifyValues); }
@Test public void testZetaSqlValueToJavaObject() { assertEquals( ZetaSqlBeamTranslationUtils.toBeamObject(TEST_VALUE, TEST_FIELD_TYPE, true), TEST_ROW); }
public static DynamicVoter parse(String input) { input = input.trim(); int atIndex = input.indexOf("@"); if (atIndex < 0) { throw new IllegalArgumentException("No @ found in dynamic voter string."); } if (atIndex == 0) { throw new IllegalArgumentException(...
@Test public void testFailedToParseDirectoryId2() { assertEquals("Failed to parse directory ID in dynamic voter string.", assertThrows(IllegalArgumentException.class, () -> DynamicVoter.parse("5@[2001:4860:4860::8888]:8020:")). getMessage()); }
@Override protected Mono<Boolean> doMatcher(final ServerWebExchange exchange, final WebFilterChain chain) { String path = exchange.getRequest().getURI().getRawPath(); return Mono.just(paths.contains(path)); }
@Test public void testDoMatcher() { ServerWebExchange webExchange = MockServerWebExchange.from(MockServerHttpRequest .post("http://localhost:8080/fallback/hystrix")); Mono<Boolean> filter = fallbackFilter.doMatcher(webExchange, webFilterChain); StepVer...
public int seriesCount() { return seriesSet.size(); }
@Test public void testSeriesCount() { cm = new ChartModel(FOO, BAR, ZOO); assertEquals("Wrong series count", 3, cm.seriesCount()); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final Storage.Buckets.Get request ...
@Test(expected = NotfoundException.class) public void testDeletedWithMarker() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new GoogleStorageTouchFeature(session).touch(new Path(container, new Alphanumeri...
protected Bootstrap bootstrap() { return bootstrap; }
@Test public void testBootstrap() { final SimpleChannelPool pool = new SimpleChannelPool(new Bootstrap(), new CountingChannelPoolHandler()); try { // Checking for the actual bootstrap object doesn't make sense here, since the pool uses a copy with a // modified channel handl...
@Override public ConsumerGroupMetadata groupMetadata() { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); return groupMetadata.get().get(); } finally { release(); } }
@Test public void testGroupMetadataAfterCreationWithGroupIdIsNotNullAndGroupInstanceIdSet() { final String groupId = "consumerGroupA"; final String groupInstanceId = "groupInstanceId1"; final Properties props = requiredConsumerConfigAndGroupId(groupId); props.put(ConsumerConfig.GROUP...
public static String convertFromActiveMQDestination(Object value) { return convertFromActiveMQDestination(value, false); }
@Test public void testConvertFromActiveMQDestination() { String result = StringToListOfActiveMQDestinationConverter.convertFromActiveMQDestination(null); assertNull(result); }
public void detectAndResolve() { createTopologyGraph(); }
@TestTemplate void testDetectAndResolve() { // P = InputProperty.DamBehavior.PIPELINED, E = InputProperty.DamBehavior.END_INPUT // P100 = PIPELINED + priority 100 // // 0 --------(P0)----> 1 --(P0)-----------> 7 // \ \-(P0)-> 2 -(P0)--/ // \-----...
@Override public void reset() { resetCount++; super.reset(); initEvaluatorMap(); initCollisionMaps(); root.recursiveReset(); resetTurboFilterList(); cancelScheduledTasks(); fireOnReset(); resetListenersExceptResetResistant(); resetStatusListeners(); }
@Test public void resetTest() { Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); Logger a = lc.getLogger("a"); Logger ab = lc.getLogger("a.b"); ab.setLevel(Level.WARN); root.setLevel(Level.INFO); lc.reset(); assertEquals(Level.DEBUG, root.getEffectiveLevel()); assertTrue(root.isD...
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(...
@Test // 无数据权限时 public void testGetExpression_noDeptDataPermission() { try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock = mockStatic(SecurityFrameworkUtils.class)) { // 准备参数 String tableName = "t_user"; Alias tableAlias = new Alias...
public AmazonInfo build() { return new AmazonInfo(Name.Amazon.name(), metadata); }
@Test public void payloadWithNameBeforeMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"name\": \"Amazon\"," + " \"metadata\": {" + " \"instance-id\": \"i-12345\"" ...
@SuppressWarnings("unchecked") public static List<Object> asList(final Object key) { final Optional<Windowed<Object>> windowed = key instanceof Windowed ? Optional.of((Windowed<Object>) key) : Optional.empty(); final Object naturalKey = windowed .map(Windowed::key) .orElse(key...
@Test public void shouldConvertWindowedKeyToList() { // Given: final Windowed<GenericKey> key = new Windowed<>( GenericKey.genericKey(10), new TimeWindow(1000, 2000) ); // When: final List<?> result = KeyUtil.asList(key); // Then: assertThat(result, is(ImmutableList.of(10...
public boolean canUserViewTemplates(CaseInsensitiveString username, List<Role> roles, boolean isGroupAdministrator) { for (PipelineTemplateConfig templateConfig : this) { if (hasViewAccessToTemplate(templateConfig, username, roles, isGroupAdministrator)) { return true; } ...
@Test public void shouldReturnFalseIfUserCannotViewAtLeastOneTemplate() { CaseInsensitiveString templateViewUser = new CaseInsensitiveString("template-view"); TemplatesConfig templates = configForUserWhoCanViewATemplate(); assertThat(templates.canUserViewTemplates(templateViewUser, null, fa...
public List<IssueDto> getTaintIssuesOnly(List<IssueDto> issues) { return filterTaintIssues(issues, true); }
@Test public void test_getTaintIssuesOnly() { List<IssueDto> taintIssues = underTest.getTaintIssuesOnly(getIssues()); assertThat(taintIssues).hasSize(6); assertThat(taintIssues.get(0).getKey()).isEqualTo("taintIssue1"); assertThat(taintIssues.get(1).getKey()).isEqualTo("taintIssue2"); assertThat(...
protected BaseNode parse(String input) { return input.isEmpty() || input.isBlank() ? getNullNode() : parseNotEmptyInput(input); }
@Test void parse_emptyString() { assertThat(rangeFunction.parse("")).withFailMessage("Check ``").isInstanceOf(NullNode.class); }
public String computerId() { return parseString(token(14)); }
@Test public void testCenterSampleWithNonIntegerComputerId() { CenterRadarHit rh = new CenterRadarHit(SAMPLE_3); NopTestUtils.triggerLazyParsing(rh); assertEquals("25F", rh.computerId()); }
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test @SuppressWarnings("unchecked") public void testDecodeDynamicStructStaticArray() { String rawInput = "0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000060" ...
@Override public Consumer createConsumer(Processor aProcessor) throws Exception { // validate that all of the endpoint is configured properly if (getMonitorType() != null) { if (!isPlatformServer()) { throw new IllegalArgumentException(ERR_PLATFORM_SERVER); }...
@Test public void noStringToCompare() throws Exception { JMXEndpoint ep = context.getEndpoint( "jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string&observedAttribute=foo", JMXEndpoint.class); try { ep.createConsumer(null); ...
@Override public boolean match(Message msg, StreamRule rule) { Object rawField = msg.getField(rule.getField()); if (rawField == null) { return rule.getInverted(); } if (rawField instanceof String) { String field = (String) rawField; Boolean resul...
@Test public void testInvertedNulledFieldMatch() throws Exception { String fieldName = "sampleField"; StreamRule rule = getSampleRule(); rule.setField(fieldName); rule.setType(StreamRuleType.PRESENCE); rule.setInverted(true); Message message = getSampleMessage(); ...
public OAuthBearerToken token() { return token; }
@Test public void testToken() { OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback(); callback.token(TOKEN); assertSame(TOKEN, callback.token()); assertNull(callback.errorCode()); assertNull(callback.errorDescription()); assertNull(callback.errorUri()); ...
public static String beanToXml(Object bean) { return beanToXml(bean, CharsetUtil.CHARSET_UTF_8, true); }
@Test public void beanToXmlTest() { SchoolVo schoolVo = new SchoolVo(); schoolVo.setSchoolName("西安市第一中学"); schoolVo.setSchoolAddress("西安市雁塔区长安堡一号"); SchoolVo.RoomVo roomVo = new SchoolVo.RoomVo(); roomVo.setRoomName("101教室"); roomVo.setRoomNo("101"); schoolVo.setRoom(roomVo); assertEquals(xmlStr, JAX...
@JsonCreator public static MessageCountRotationStrategyConfig create(@JsonProperty(TYPE_FIELD) String type, @JsonProperty("max_docs_per_index") @Min(1) int maxDocsPerIndex) { return new AutoValue_MessageCountRotationStrategyConfig(type, maxDocsPerI...
@Test public void testCreate() throws Exception { final MessageCountRotationStrategyConfig config = MessageCountRotationStrategyConfig.create(1000); assertThat(config.maxDocsPerIndex()).isEqualTo(1000); }
public Value parseWithOffsetInJsonPointer(String json, String offsetInJsonPointer) { return this.delegate.parseWithOffsetInJsonPointer(json, offsetInJsonPointer); }
@Test public void testParseWithPointer2() throws Exception { final JsonParser parser = new JsonParser(); final Value msgpackValue = parser.parseWithOffsetInJsonPointer("{\"a\": [{\"b\": 1}, {\"b\": 2}]}", "/a/1/b"); assertEquals(2, msgpackValue.asIntegerValue().asInt()); }
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testAlign() { run("align.feature"); match(fr.result.getVariables(), "{ configSource: 'normal', functionFromKarateBase: '#notnull', text: 'hello bar world' , cats: '#notnull', myJson: {}}}"); }
public MetaStoreInitListener(Configuration config){ this.conf = config; }
@Test public void testMetaStoreInitListener() throws Exception { // DummyMetaStoreInitListener's onInit will be called at HMSHandler // initialization, and set this to true Assert.assertTrue(DummyMetaStoreInitListener.wasCalled); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, String.valueOf(Path.DELIMITER)); }
@Test public void testListPlaceholderDot() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path placeholder = new S3Dire...
public boolean satisfies(final Distribution distribution, final String expression) { return this.distribution().equals(distribution) && version().satisfies(expression); }
@Test void satisfies() { final SearchVersion searchVersion = SearchVersion.create(SearchVersion.Distribution.ELASTICSEARCH, ver("5.1.4")); assertThat(searchVersion.satisfies(SearchVersion.Distribution.ELASTICSEARCH, "^5.0.0")).isTrue(); assertThat(searchVersion.satisfies(SearchVersion.Distri...
public static Range<Comparable<?>> safeIntersection(final Range<Comparable<?>> range, final Range<Comparable<?>> connectedRange) { try { return range.intersection(connectedRange); } catch (final ClassCastException ex) { Class<?> clazz = getRangeTargetNumericType(range, connectedR...
@Test void assertSafeIntersectionForBigDecimal() { Range<Comparable<?>> range = Range.upTo(new BigDecimal("2331.23211"), BoundType.CLOSED); Range<Comparable<?>> connectedRange = Range.open(135.13F, 45343.23F); Range<Comparable<?>> newRange = SafeNumberOperationUtils.safeIntersection(range, c...
@Override public void checkCanSetUser(Identity identity, AccessControlContext context, Optional<Principal> principal, String userName) { requireNonNull(principal, "principal is null"); requireNonNull(userName, "userName is null"); if (!principalUserMatchRules.isPresent()) { ...
@Test public void testCanSetUserOperations() throws IOException { TransactionManager transactionManager = createTestTransactionManager(); AccessControlManager accessControlManager = newAccessControlManager(transactionManager, "catalog_principal.json"); try { accessControlMan...
public static Serializable decode(final ByteBuf byteBuf) { int valueType = byteBuf.readUnsignedByte() & 0xff; StringBuilder result = new StringBuilder(); decodeValue(valueType, 1, byteBuf, result); return result.toString(); }
@Test void assertDecodeLargeJsonArray() { List<JsonEntry> jsonEntries = new LinkedList<>(); jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, null, 0x00007fff)); jsonEntries.add(new JsonEntry(JsonValueTypes.INT16, null, 0x00008000)); ByteBuf payload = mockJsonArrayByteBuf(jsonEntri...
public static boolean checkUserInfo( IUser user ) { return !StringUtils.isBlank( user.getLogin() ) && !StringUtils.isBlank( user.getName() ); }
@Test public void checkUserInfo_BothAreMeaningful() { assertTrue( RepositoryCommonValidations.checkUserInfo( user( "login", "name" ) ) ); }
public void publishRemoved(Cache<K, V> cache, K key, V value) { publish(cache, EventType.REMOVED, key, /* hasOldValue */ true, /* oldValue */ value, /* newValue */ value, /* quiet */ false); }
@Test public void publishRemoved() { var dispatcher = new EventDispatcher<Integer, Integer>(Runnable::run); registerAll(dispatcher); dispatcher.publishRemoved(cache, 1, 2); verify(removedListener, times(4)).onRemoved(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatch...
@Override public String symmetricEncryptType() { return "AES"; }
@Test public void symmetricEncryptType() { SAECEncrypt ecEncrypt = new SAECEncrypt(); Assert.assertEquals("AES", ecEncrypt.symmetricEncryptType()); }
public int run() throws IOException { String[] header = new String[]{"Address", "State", "Start Time", "Last Heartbeat Time", "Version", "Revision"}; try { List<ProxyStatus> allProxyStatus = mMetaMasterClient.listProxyStatus(); int liveCount = 0; int lostCount = 0; int maxAddres...
@Test public void listProxyInstancesLongName() throws IOException { List<ProxyStatus> longInfoList = prepareInfoListLongName(); Mockito.when(mMetaMasterClient.listProxyStatus()) .thenReturn(longInfoList); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStr...
@Override public Object merge(T mergingValue, T existingValue) { if (existingValue == null) { return null; } return existingValue.getRawValue(); }
@Test public void merge_existingValuePresent() { MapMergeTypes existing = mergingValueWithGivenValue(EXISTING); MapMergeTypes merging = mergingValueWithGivenValue(MERGING); assertEquals(EXISTING, mergePolicy.merge(merging, existing)); }
@Override public String toString() { return StrUtil.NULL; }
@Test public void parseNullTest(){ JSONObject bodyjson = JSONUtil.parseObj("{\n" + " \"device_model\": null,\n" + " \"device_status_date\": null,\n" + " \"imsi\": null,\n" + " \"act_date\": \"2021-07-23T06:23:26.000+00:00\"}"); assertEquals(JSONNull.class...
public void byteOrder(final ByteOrder byteOrder) { if (null == byteOrder) { throw new IllegalArgumentException("byteOrder cannot be null"); } this.byteOrder = byteOrder; }
@Test void shouldReadUtf() throws Throwable { final UnsafeBuffer buffer = toUnsafeBuffer( (out) -> { out.writeLong(0); out.writeUTF("zażółć gęślą jaźń北查爾斯頓"); out.writeLong(0); }); final DirectBufferDataInput da...
@Nullable DockerCredentialHelper getCredentialHelperFor(String registry) { List<Predicate<String>> registryMatchers = getRegistryMatchersFor(registry); Map.Entry<String, String> firstCredHelperMatch = findFirstInMapByKey(dockerConfigTemplate.getCredHelpers(), registryMatchers); if (firstCredHelpe...
@Test public void testGetCredentialHelperFor_correctSuffixMatching() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigT...
@Override public long selectNextWorker() throws NonRecoverableException { ComputeNode worker; worker = getNextWorker(availableID2ComputeNode, DefaultSharedDataWorkerProvider::getNextComputeNodeIndex); if (worker == null) { reportWorkerNotFoundException(); } Preco...
@Test public void testSelectNextWorker() throws UserException { HostBlacklist blockList = SimpleScheduler.getHostBlacklist(); blockList.hostBlacklist.clear(); SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo(); List<Long> availList = prepareNo...
@Override public void serialize(Asn1OutputStream out, Class<? extends Object> type, Object instance, Asn1ObjectMapper mapper) throws IOException { writeFields(mapper, out, type, instance); }
@Test public void shouldSerializeWithOptional() { assertArrayEquals( new byte[] { (byte) 0x81, 1, 0x01, (byte) 0x82, 1, 0x02, (byte) 0x83, 1, 0x03 }, serialize(new SetConverter(), Set.class, new Set(1, 2, 3)) ); }
@Override public String getDescription() { return "time: " + time + ", threshold_type: " + thresholdType.toString().toLowerCase(Locale.ENGLISH) + ", threshold: " + threshold + ", grace: " + grace + ", repeat notifications: " + repeatNotifications; }
@Test public void testConstructor() throws Exception { final Map<String, Object> parameters = getParametersMap(0, 0, MessageCountAlertCondition.ThresholdType.MORE, 0); final MessageCountAlertCondition messageCountAlertCondition = getMessageCountAlertCondition(parameters, alertConditionTitle); ...
@Override public ScheduledExecutor getScheduledExecutor() { return internalScheduledExecutor; }
@Test void testScheduleRunnable() throws Exception { final OneShotLatch latch = new OneShotLatch(); final long delay = 100L; final long start = System.nanoTime(); ScheduledFuture<?> scheduledFuture = pekkoRpcService .getScheduledExecutor() ...
public static void applyDataChangeEvent(DataChangeEvent event) { ValuesTable table = globalTables.get(event.tableId()); Preconditions.checkNotNull(table, event.tableId() + " is not existed"); table.applyDataChangeEvent(event); LOG.info("apply DataChangeEvent: " + event); }
@Test public void testApplyDataChangeEvent() { List<String> results = new ArrayList<>(); results.add("default.default.table1:col1=1;col2=1"); results.add("default.default.table1:col1=2;col2=2"); results.add("default.default.table1:col1=3;col2=3"); Assert.assertEquals(results,...
public static UTypeVarIdent create(CharSequence name) { return new AutoValue_UTypeVarIdent(StringName.of(name)); }
@Test public void serialization() { SerializableTester.reserializeAndAssert(UTypeVarIdent.create("E")); }
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void preDecrement() { assertUnifiesAndInlines("--foo", UUnary.create(Kind.PREFIX_DECREMENT, fooIdent)); }
@Override public BundleData getBundleDataOrDefault(final String bundle) { BundleData bundleData = null; try { Optional<BundleData> optBundleData = pulsarResources.getLoadBalanceResources().getBundleDataResources().getBundleData(bundle).join(); if (optBundl...
@Test(dataProvider = "isV1") public void testBundleDataDefaultValue(boolean isV1) throws Exception { final String cluster = "use"; final String tenant = "my-tenant"; final String namespace = "my-ns"; NamespaceName ns = isV1 ? NamespaceName.get(tenant, cluster, namespace) : NamespaceN...
String storeSink() { return storeSink; }
@Test public void testStoreSinkIsQuoted() { Queries queries = new Queries(mapping, idColumn, columnMetadata); String result = queries.storeSink(); assertEquals("SINK INTO \"mymapping\" (\"id\", \"name\", \"address\") VALUES (?, ?, ?)", result); }
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test public void testMergeAclEntriesMultipleNewBeforeExisting() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "diana", READ)) .add(aclEntry(ACCESS, GROUP, READ_EXECUTE)) .add(aclEnt...
protected HttpUriRequest setupConnection(final String method, final String bucketName, final String objectKey, final Map<String, String> requestParameters) throws S3ServiceException { return this.setupConnection(HTTP_METHOD.valueOf(method), bucketName, objectKey, req...
@Test public void testSetupConnectionVirtualHost() throws Exception { final RequestEntityRestStorageService service = new RequestEntityRestStorageService(virtualhost, new HttpConnectionPoolBuilder(virtualhost.getHost(), new ThreadLocalHostnameDelegatingTrustManager(new DisabledX509TrustManag...
@Override public void close() throws IOException { if(close.get()) { log.warn(String.format("Skip double close of stream %s", this)); return; } try { if(buffer.size() > 0) { proxy.write(buffer.toByteArray()); } // Re...
@Test public void testCopy1() throws Exception { final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20); final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768); final byte[] content = RandomUtils.nextBytes(40500); out.write(content, 0, 32...
public static boolean isLazyFailedWritesCleanPolicy(Configuration conf) { // get all keys with alternatives as strings from Hudi's ConfigProperty List<String> allKeys = new ArrayList<>(); allKeys.add(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.key()); allKeys.addAll(HoodieCleanConfig.FAILED_WRITES_CL...
@Test void testIsLazyFailedWritesCleanPolicy() { Configuration conf = new Configuration(); // add any parameter conf.set(FlinkOptions.CLEAN_ASYNC_ENABLED, true); // add value for FAILED_WRITES_CLEANER_POLICY using default key conf.setString(HoodieCleanConfig.FAILED_WRITES_CLEANER_POLICY.key(), Hoo...
private static VerificationResult verifyChecksums(String expectedDigest, String actualDigest, boolean caseSensitive) { if (expectedDigest == null) { return VerificationResult.NOT_PROVIDED; } if (actualDigest == null) { return VerificationResult.NOT_COMPUTED; } ...
@Test public void noOverlapForComputedAndProvidedChecksums() { final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums( new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, null), buildEntryWithExpectedChecksums(null, null, EMPTY_SHA512), new File("exam...
public static <K, V> Read<K, V> read() { return new AutoValue_KafkaIO_Read.Builder<K, V>() .setTopics(new ArrayList<>()) .setTopicPartitions(new ArrayList<>()) .setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN) .setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES) ...
@Test public void testUnboundedSourceWithExplicitPartitions() { int numElements = 1000; String topic = "test"; List<String> topics = ImmutableList.of(topic); String bootStrapServer = "none"; KafkaIO.Read<byte[], Long> reader = KafkaIO.<byte[], Long>read() .withBootstrapServer...
void portAddedHelper(DeviceEvent event) { log.debug("Instance port {} is detected from {}", event.port().annotations().value(PORT_NAME), event.subject().id()); // we check the existence of openstack port, in case VM creation // event comes before port creation ...
@Test public void testProcessPortAddedForNewAddition() { org.onosproject.net.Port port = new DefaultPort(DEV2, P1, true, ANNOTATIONS); DeviceEvent event = new DeviceEvent(DeviceEvent.Type.PORT_ADDED, DEV2, port); target.portAddedHelper(event); HostId hostId = HostId.hostId(HOST_MAC...